vqperceptual.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import torch
  2. from torch import nn
  3. import torch.nn.functional as F
  4. from einops import repeat
  5. from taming.modules.discriminator.model import NLayerDiscriminator, weights_init
  6. from taming.modules.losses.lpips import LPIPS
  7. from taming.modules.losses.vqperceptual import hinge_d_loss, vanilla_d_loss
  8. def hinge_d_loss_with_exemplar_weights(logits_real, logits_fake, weights):
  9. assert weights.shape[0] == logits_real.shape[0] == logits_fake.shape[0]
  10. loss_real = torch.mean(F.relu(1. - logits_real), dim=[1,2,3])
  11. loss_fake = torch.mean(F.relu(1. + logits_fake), dim=[1,2,3])
  12. loss_real = (weights * loss_real).sum() / weights.sum()
  13. loss_fake = (weights * loss_fake).sum() / weights.sum()
  14. d_loss = 0.5 * (loss_real + loss_fake)
  15. return d_loss
  16. def adopt_weight(weight, global_step, threshold=0, value=0.):
  17. if global_step < threshold:
  18. weight = value
  19. return weight
  20. def measure_perplexity(predicted_indices, n_embed):
  21. # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py
  22. # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally
  23. encodings = F.one_hot(predicted_indices, n_embed).float().reshape(-1, n_embed)
  24. avg_probs = encodings.mean(0)
  25. perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp()
  26. cluster_use = torch.sum(avg_probs > 0)
  27. return perplexity, cluster_use
  28. def l1(x, y):
  29. return torch.abs(x-y)
  30. def l2(x, y):
  31. return torch.pow((x-y), 2)
  32. class VQLPIPSWithDiscriminator(nn.Module):
  33. def __init__(self, disc_start, codebook_weight=1.0, pixelloss_weight=1.0,
  34. disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0,
  35. perceptual_weight=1.0, use_actnorm=False, disc_conditional=False,
  36. disc_ndf=64, disc_loss="hinge", n_classes=None, perceptual_loss="lpips",
  37. pixel_loss="l1"):
  38. super().__init__()
  39. assert disc_loss in ["hinge", "vanilla"]
  40. assert perceptual_loss in ["lpips", "clips", "dists"]
  41. assert pixel_loss in ["l1", "l2"]
  42. self.codebook_weight = codebook_weight
  43. self.pixel_weight = pixelloss_weight
  44. if perceptual_loss == "lpips":
  45. print(f"{self.__class__.__name__}: Running with LPIPS.")
  46. self.perceptual_loss = LPIPS().eval()
  47. else:
  48. raise ValueError(f"Unknown perceptual loss: >> {perceptual_loss} <<")
  49. self.perceptual_weight = perceptual_weight
  50. if pixel_loss == "l1":
  51. self.pixel_loss = l1
  52. else:
  53. self.pixel_loss = l2
  54. self.discriminator = NLayerDiscriminator(input_nc=disc_in_channels,
  55. n_layers=disc_num_layers,
  56. use_actnorm=use_actnorm,
  57. ndf=disc_ndf
  58. ).apply(weights_init)
  59. self.discriminator_iter_start = disc_start
  60. if disc_loss == "hinge":
  61. self.disc_loss = hinge_d_loss
  62. elif disc_loss == "vanilla":
  63. self.disc_loss = vanilla_d_loss
  64. else:
  65. raise ValueError(f"Unknown GAN loss '{disc_loss}'.")
  66. print(f"VQLPIPSWithDiscriminator running with {disc_loss} loss.")
  67. self.disc_factor = disc_factor
  68. self.discriminator_weight = disc_weight
  69. self.disc_conditional = disc_conditional
  70. self.n_classes = n_classes
  71. def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
  72. if last_layer is not None:
  73. nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
  74. g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
  75. else:
  76. nll_grads = torch.autograd.grad(nll_loss, self.last_layer[0], retain_graph=True)[0]
  77. g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0]
  78. d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
  79. d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
  80. d_weight = d_weight * self.discriminator_weight
  81. return d_weight
  82. def forward(self, codebook_loss, inputs, reconstructions, optimizer_idx,
  83. global_step, last_layer=None, cond=None, split="train", predicted_indices=None):
  84. if not exists(codebook_loss):
  85. codebook_loss = torch.tensor([0.]).to(inputs.device)
  86. #rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())
  87. rec_loss = self.pixel_loss(inputs.contiguous(), reconstructions.contiguous())
  88. if self.perceptual_weight > 0:
  89. p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())
  90. rec_loss = rec_loss + self.perceptual_weight * p_loss
  91. else:
  92. p_loss = torch.tensor([0.0])
  93. nll_loss = rec_loss
  94. #nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
  95. nll_loss = torch.mean(nll_loss)
  96. # now the GAN part
  97. if optimizer_idx == 0:
  98. # generator update
  99. if cond is None:
  100. assert not self.disc_conditional
  101. logits_fake = self.discriminator(reconstructions.contiguous())
  102. else:
  103. assert self.disc_conditional
  104. logits_fake = self.discriminator(torch.cat((reconstructions.contiguous(), cond), dim=1))
  105. g_loss = -torch.mean(logits_fake)
  106. try:
  107. d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer)
  108. except RuntimeError:
  109. assert not self.training
  110. d_weight = torch.tensor(0.0)
  111. disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
  112. loss = nll_loss + d_weight * disc_factor * g_loss + self.codebook_weight * codebook_loss.mean()
  113. log = {"{}/total_loss".format(split): loss.clone().detach().mean(),
  114. "{}/quant_loss".format(split): codebook_loss.detach().mean(),
  115. "{}/nll_loss".format(split): nll_loss.detach().mean(),
  116. "{}/rec_loss".format(split): rec_loss.detach().mean(),
  117. "{}/p_loss".format(split): p_loss.detach().mean(),
  118. "{}/d_weight".format(split): d_weight.detach(),
  119. "{}/disc_factor".format(split): torch.tensor(disc_factor),
  120. "{}/g_loss".format(split): g_loss.detach().mean(),
  121. }
  122. if predicted_indices is not None:
  123. assert self.n_classes is not None
  124. with torch.no_grad():
  125. perplexity, cluster_usage = measure_perplexity(predicted_indices, self.n_classes)
  126. log[f"{split}/perplexity"] = perplexity
  127. log[f"{split}/cluster_usage"] = cluster_usage
  128. return loss, log
  129. if optimizer_idx == 1:
  130. # second pass for discriminator update
  131. if cond is None:
  132. logits_real = self.discriminator(inputs.contiguous().detach())
  133. logits_fake = self.discriminator(reconstructions.contiguous().detach())
  134. else:
  135. logits_real = self.discriminator(torch.cat((inputs.contiguous().detach(), cond), dim=1))
  136. logits_fake = self.discriminator(torch.cat((reconstructions.contiguous().detach(), cond), dim=1))
  137. disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
  138. d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
  139. log = {"{}/disc_loss".format(split): d_loss.clone().detach().mean(),
  140. "{}/logits_real".format(split): logits_real.detach().mean(),
  141. "{}/logits_fake".format(split): logits_fake.detach().mean()
  142. }
  143. return d_loss, log