vqperceptual.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from taming.modules.losses.lpips import LPIPS
  5. from taming.modules.discriminator.model import NLayerDiscriminator, weights_init
  6. class DummyLoss(nn.Module):
  7. def __init__(self):
  8. super().__init__()
  9. def adopt_weight(weight, global_step, threshold=0, value=0.):
  10. if global_step < threshold:
  11. weight = value
  12. return weight
  13. def hinge_d_loss(logits_real, logits_fake):
  14. loss_real = torch.mean(F.relu(1. - logits_real))
  15. loss_fake = torch.mean(F.relu(1. + logits_fake))
  16. d_loss = 0.5 * (loss_real + loss_fake)
  17. return d_loss
  18. def vanilla_d_loss(logits_real, logits_fake):
  19. d_loss = 0.5 * (
  20. torch.mean(torch.nn.functional.softplus(-logits_real)) +
  21. torch.mean(torch.nn.functional.softplus(logits_fake)))
  22. return d_loss
  23. class VQLPIPSWithDiscriminator(nn.Module):
  24. def __init__(self, disc_start, codebook_weight=1.0, pixelloss_weight=1.0,
  25. disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0,
  26. perceptual_weight=1.0, use_actnorm=False, disc_conditional=False,
  27. disc_ndf=64, disc_loss="hinge"):
  28. super().__init__()
  29. assert disc_loss in ["hinge", "vanilla"]
  30. self.codebook_weight = codebook_weight
  31. self.pixel_weight = pixelloss_weight
  32. self.perceptual_loss = LPIPS().eval()
  33. self.perceptual_weight = perceptual_weight
  34. self.discriminator = NLayerDiscriminator(input_nc=disc_in_channels,
  35. n_layers=disc_num_layers,
  36. use_actnorm=use_actnorm,
  37. ndf=disc_ndf
  38. ).apply(weights_init)
  39. self.discriminator_iter_start = disc_start
  40. if disc_loss == "hinge":
  41. self.disc_loss = hinge_d_loss
  42. elif disc_loss == "vanilla":
  43. self.disc_loss = vanilla_d_loss
  44. else:
  45. raise ValueError(f"Unknown GAN loss '{disc_loss}'.")
  46. print(f"VQLPIPSWithDiscriminator running with {disc_loss} loss.")
  47. self.disc_factor = disc_factor
  48. self.discriminator_weight = disc_weight
  49. self.disc_conditional = disc_conditional
  50. def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
  51. if last_layer is not None:
  52. nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
  53. g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
  54. else:
  55. nll_grads = torch.autograd.grad(nll_loss, self.last_layer[0], retain_graph=True)[0]
  56. g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0]
  57. d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
  58. d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
  59. d_weight = d_weight * self.discriminator_weight
  60. return d_weight
  61. def forward(self, codebook_loss, inputs, reconstructions, optimizer_idx,
  62. global_step, last_layer=None, cond=None, split="train"):
  63. rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())
  64. if self.perceptual_weight > 0:
  65. p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())
  66. rec_loss = rec_loss + self.perceptual_weight * p_loss
  67. else:
  68. p_loss = torch.tensor([0.0])
  69. nll_loss = rec_loss
  70. #nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
  71. nll_loss = torch.mean(nll_loss)
  72. # now the GAN part
  73. if optimizer_idx == 0:
  74. # generator update
  75. if cond is None:
  76. assert not self.disc_conditional
  77. logits_fake = self.discriminator(reconstructions.contiguous())
  78. else:
  79. assert self.disc_conditional
  80. logits_fake = self.discriminator(torch.cat((reconstructions.contiguous(), cond), dim=1))
  81. g_loss = -torch.mean(logits_fake)
  82. try:
  83. d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer)
  84. except RuntimeError:
  85. assert not self.training
  86. d_weight = torch.tensor(0.0)
  87. disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
  88. loss = nll_loss + d_weight * disc_factor * g_loss + self.codebook_weight * codebook_loss.mean()
  89. log = {"{}/total_loss".format(split): loss.clone().detach().mean(),
  90. "{}/quant_loss".format(split): codebook_loss.detach().mean(),
  91. "{}/nll_loss".format(split): nll_loss.detach().mean(),
  92. "{}/rec_loss".format(split): rec_loss.detach().mean(),
  93. "{}/p_loss".format(split): p_loss.detach().mean(),
  94. "{}/d_weight".format(split): d_weight.detach(),
  95. "{}/disc_factor".format(split): torch.tensor(disc_factor),
  96. "{}/g_loss".format(split): g_loss.detach().mean(),
  97. }
  98. return loss, log
  99. if optimizer_idx == 1:
  100. # second pass for discriminator update
  101. if cond is None:
  102. logits_real = self.discriminator(inputs.contiguous().detach())
  103. logits_fake = self.discriminator(reconstructions.contiguous().detach())
  104. else:
  105. logits_real = self.discriminator(torch.cat((inputs.contiguous().detach(), cond), dim=1))
  106. logits_fake = self.discriminator(torch.cat((reconstructions.contiguous().detach(), cond), dim=1))
  107. disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
  108. d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
  109. log = {"{}/disc_loss".format(split): d_loss.clone().detach().mean(),
  110. "{}/logits_real".format(split): logits_real.detach().mean(),
  111. "{}/logits_fake".format(split): logits_fake.detach().mean()
  112. }
  113. return d_loss, log