contperceptual.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import torch
  2. import torch.nn as nn
  3. from taming.modules.losses.vqperceptual import * # TODO: taming dependency yes/no?
  4. class LPIPSWithDiscriminator(nn.Module):
  5. def __init__(self, disc_start, logvar_init=0.0, kl_weight=1.0, pixelloss_weight=1.0,
  6. disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0,
  7. perceptual_weight=1.0, use_actnorm=False, disc_conditional=False,
  8. disc_loss="hinge"):
  9. super().__init__()
  10. assert disc_loss in ["hinge", "vanilla"]
  11. self.kl_weight = kl_weight
  12. self.pixel_weight = pixelloss_weight
  13. self.perceptual_loss = LPIPS().eval()
  14. self.perceptual_weight = perceptual_weight
  15. # output log variance
  16. self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)
  17. self.discriminator = NLayerDiscriminator(input_nc=disc_in_channels,
  18. n_layers=disc_num_layers,
  19. use_actnorm=use_actnorm
  20. ).apply(weights_init)
  21. self.discriminator_iter_start = disc_start
  22. self.disc_loss = hinge_d_loss if disc_loss == "hinge" else vanilla_d_loss
  23. self.disc_factor = disc_factor
  24. self.discriminator_weight = disc_weight
  25. self.disc_conditional = disc_conditional
  26. def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
  27. if last_layer is not None:
  28. nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
  29. g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
  30. else:
  31. nll_grads = torch.autograd.grad(nll_loss, self.last_layer[0], retain_graph=True)[0]
  32. g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0]
  33. d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
  34. d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
  35. d_weight = d_weight * self.discriminator_weight
  36. return d_weight
  37. def forward(self, inputs, reconstructions, posteriors, optimizer_idx,
  38. global_step, last_layer=None, cond=None, split="train",
  39. weights=None):
  40. rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())
  41. if self.perceptual_weight > 0:
  42. p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())
  43. rec_loss = rec_loss + self.perceptual_weight * p_loss
  44. nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar
  45. weighted_nll_loss = nll_loss
  46. if weights is not None:
  47. weighted_nll_loss = weights*nll_loss
  48. weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]
  49. nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
  50. kl_loss = posteriors.kl()
  51. kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
  52. # now the GAN part
  53. if optimizer_idx == 0:
  54. # generator update
  55. if cond is None:
  56. assert not self.disc_conditional
  57. logits_fake = self.discriminator(reconstructions.contiguous())
  58. else:
  59. assert self.disc_conditional
  60. logits_fake = self.discriminator(torch.cat((reconstructions.contiguous(), cond), dim=1))
  61. g_loss = -torch.mean(logits_fake)
  62. if self.disc_factor > 0.0:
  63. try:
  64. d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer)
  65. except RuntimeError:
  66. assert not self.training
  67. d_weight = torch.tensor(0.0)
  68. else:
  69. d_weight = torch.tensor(0.0)
  70. disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
  71. loss = weighted_nll_loss + self.kl_weight * kl_loss + d_weight * disc_factor * g_loss
  72. log = {"{}/total_loss".format(split): loss.clone().detach().mean(), "{}/logvar".format(split): self.logvar.detach(),
  73. "{}/kl_loss".format(split): kl_loss.detach().mean(), "{}/nll_loss".format(split): nll_loss.detach().mean(),
  74. "{}/rec_loss".format(split): rec_loss.detach().mean(),
  75. "{}/d_weight".format(split): d_weight.detach(),
  76. "{}/disc_factor".format(split): torch.tensor(disc_factor),
  77. "{}/g_loss".format(split): g_loss.detach().mean(),
  78. }
  79. return loss, log
  80. if optimizer_idx == 1:
  81. # second pass for discriminator update
  82. if cond is None:
  83. logits_real = self.discriminator(inputs.contiguous().detach())
  84. logits_fake = self.discriminator(reconstructions.contiguous().detach())
  85. else:
  86. logits_real = self.discriminator(torch.cat((inputs.contiguous().detach(), cond), dim=1))
  87. logits_fake = self.discriminator(torch.cat((reconstructions.contiguous().detach(), cond), dim=1))
  88. disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
  89. d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
  90. log = {"{}/disc_loss".format(split): d_loss.clone().detach().mean(),
  91. "{}/logits_real".format(split): logits_real.detach().mean(),
  92. "{}/logits_fake".format(split): logits_fake.detach().mean()
  93. }
  94. return d_loss, log