loss.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. from fastai import *
  2. from fastai.core import *
  3. from fastai.torch_core import *
  4. from fastai.callbacks import hook_outputs
  5. import torchvision.models as models
  6. class FeatureLoss3(nn.Module):
  7. def __init__(self, layer_wgts=[5,15,2]):
  8. super().__init__()
  9. self.m_feat = models.vgg16_bn(True).features.cuda().eval()
  10. requires_grad(self.m_feat, False)
  11. blocks = [i-1 for i,o in enumerate(children(self.m_feat)) if isinstance(o,nn.MaxPool2d)]
  12. layer_ids = blocks[2:5]
  13. self.loss_features = [self.m_feat[i] for i in layer_ids]
  14. self.hooks = hook_outputs(self.loss_features, detach=False)
  15. self.wgts = layer_wgts
  16. self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))]
  17. self.base_loss = F.l1_loss
  18. def _make_features(self, x, clone=False):
  19. self.m_feat(x)
  20. return [(o.clone() if clone else o) for o in self.hooks.stored]
  21. def forward(self, input, target):
  22. out_feat = self._make_features(target, clone=True)
  23. in_feat = self._make_features(input)
  24. self.feat_losses = [self.base_loss(input,target)]
  25. self.feat_losses += [self.base_loss(f_in, f_out)*w
  26. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  27. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  28. return sum(self.feat_losses)
  29. def __del__(self): self.hooks.remove()
  30. class FeatureLoss2(nn.Module):
  31. def __init__(self, layer_wgts=[20,70,10]):
  32. super().__init__()
  33. self.m_feat = models.vgg16_bn(True).features.cuda().eval()
  34. requires_grad(self.m_feat, False)
  35. blocks = [i-1 for i,o in enumerate(children(self.m_feat)) if isinstance(o,nn.MaxPool2d)]
  36. layer_ids = blocks[2:5]
  37. self.loss_features = [self.m_feat[i] for i in layer_ids]
  38. self.hooks = hook_outputs(self.loss_features, detach=False)
  39. self.wgts = layer_wgts
  40. self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))]
  41. self.base_loss = F.l1_loss
  42. def _make_features(self, x, clone=False):
  43. self.m_feat(x)
  44. return [(o.clone() if clone else o) for o in self.hooks.stored]
  45. def forward(self, input, target):
  46. out_feat = self._make_features(target, clone=True)
  47. in_feat = self._make_features(input)
  48. self.feat_losses = [self.base_loss(input,target)]
  49. self.feat_losses += [self.base_loss(f_in, f_out)*w
  50. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  51. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  52. return sum(self.feat_losses)
  53. def __del__(self): self.hooks.remove()
  54. #"Before activations" in ESRGAN paper
  55. class FeatureLoss(nn.Module):
  56. def __init__(self, layer_wgts=[5,15,2]):
  57. super().__init__()
  58. self.m_feat = models.vgg16_bn(True).features.cuda().eval()
  59. requires_grad(self.m_feat, False)
  60. blocks = [i-2 for i,o in enumerate(children(self.m_feat)) if isinstance(o,nn.MaxPool2d)]
  61. layer_ids = blocks[2:5]
  62. self.loss_features = [self.m_feat[i] for i in layer_ids]
  63. self.hooks = hook_outputs(self.loss_features, detach=False)
  64. self.wgts = layer_wgts
  65. self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))]
  66. self.base_loss = F.l1_loss
  67. def _make_features(self, x, clone=False):
  68. self.m_feat(x)
  69. return [(o.clone() if clone else o) for o in self.hooks.stored]
  70. def forward(self, input, target):
  71. out_feat = self._make_features(target, clone=True)
  72. in_feat = self._make_features(input)
  73. self.feat_losses = [self.base_loss(input,target)]
  74. self.feat_losses += [self.base_loss(f_in, f_out)*w
  75. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  76. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  77. return sum(self.feat_losses)
  78. def __del__(self): self.hooks.remove()
  79. class PretrainFeatureLoss(nn.Module):
  80. def __init__(self, layer_wgts=[5,15,2], gram_wgt:float=5e3):
  81. super().__init__()
  82. self.gram_wgt = gram_wgt
  83. self.m_feat = models.vgg16_bn(True).features.cuda().eval()
  84. requires_grad(self.m_feat, False)
  85. blocks = [i-2 for i,o in enumerate(children(self.m_feat)) if isinstance(o,nn.MaxPool2d)]
  86. layer_ids = blocks[2:5]
  87. self.loss_features = [self.m_feat[i] for i in layer_ids]
  88. self.hooks = hook_outputs(self.loss_features, detach=False)
  89. self.wgts = layer_wgts
  90. self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))]
  91. self.base_loss = F.l1_loss
  92. def _gram_matrix(self, x:torch.Tensor):
  93. n,c,h,w = x.size()
  94. x = x.view(n, c, -1)
  95. return (x @ x.transpose(1,2))/(c*h*w)
  96. def _make_features(self, x, clone=False):
  97. self.m_feat(x)
  98. return [(o.clone() if clone else o) for o in self.hooks.stored]
  99. def forward(self, input, target):
  100. out_feat = self._make_features(target, clone=True)
  101. in_feat = self._make_features(input)
  102. self.feat_losses = [self.base_loss(input,target)]
  103. self.feat_losses += [self.base_loss(self._gram_matrix(f_in), self._gram_matrix(f_out))*w**2 * self.gram_wgt
  104. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  105. self.feat_losses += [self.base_loss(f_in, f_out)*w
  106. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  107. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  108. return sum(self.feat_losses)
  109. def __del__(self): self.hooks.remove()
  110. #Includes wasserstein loss
  111. class WassFeatureLoss(nn.Module):
  112. def __init__(self, layer_wgts=[5,15,2], wass_wgts=[3.0,0.7,0.01]):
  113. super().__init__()
  114. self.m_feat = models.vgg16_bn(True).features.cuda().eval()
  115. requires_grad(self.m_feat, False)
  116. blocks = [i-1 for i,o in enumerate(children(self.m_feat)) if isinstance(o,nn.MaxPool2d)]
  117. layer_ids = blocks[2:5]
  118. self.loss_features = [self.m_feat[i] for i in layer_ids]
  119. self.hooks = hook_outputs(self.loss_features, detach=False)
  120. self.wgts = layer_wgts
  121. self.wass_wgts = wass_wgts
  122. self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))] + [f'wass_{i}' for i in range(len(layer_ids))]
  123. self.base_loss = F.l1_loss
  124. def _make_features(self, x, clone=False):
  125. self.m_feat(x)
  126. return [(o.clone() if clone else o) for o in self.hooks.stored]
  127. def _calc_2_moments(self, tensor):
  128. chans = tensor.shape[1]
  129. tensor = tensor.view(1, chans, -1)
  130. n = tensor.shape[2]
  131. mu = tensor.mean(2)
  132. tensor = (tensor - mu[:,:,None]).squeeze(0)
  133. #Prevents nasty bug that happens very occassionally- divide by zero. Why such things happen?
  134. if n == 0: return None, None
  135. cov = torch.mm(tensor, tensor.t()) / float(n)
  136. return mu, cov
  137. def _get_style_vals(self, tensor):
  138. mean, cov = self._calc_2_moments(tensor)
  139. if mean is None:
  140. return None, None, None
  141. eigvals, eigvects = torch.symeig(cov, eigenvectors=True)
  142. eigroot_mat = torch.diag(torch.sqrt(eigvals.clamp(min=0)))
  143. root_cov = torch.mm(torch.mm(eigvects, eigroot_mat), eigvects.t())
  144. tr_cov = eigvals.clamp(min=0).sum()
  145. return mean, tr_cov, root_cov
  146. def _calc_l2wass_dist(self, mean_stl, tr_cov_stl, root_cov_stl, mean_synth, cov_synth):
  147. tr_cov_synth = torch.symeig(cov_synth, eigenvectors=True)[0].clamp(min=0).sum()
  148. mean_diff_squared = (mean_stl - mean_synth).pow(2).sum()
  149. cov_prod = torch.mm(torch.mm(root_cov_stl, cov_synth), root_cov_stl)
  150. var_overlap = torch.sqrt(torch.symeig(cov_prod, eigenvectors=True)[0].clamp(min=0)+1e-8).sum()
  151. dist = mean_diff_squared + tr_cov_stl + tr_cov_synth - 2*var_overlap
  152. return dist
  153. def _single_wass_loss(self, pred, targ):
  154. mean_test, tr_cov_test, root_cov_test = targ
  155. mean_synth, cov_synth = self._calc_2_moments(pred)
  156. loss = self._calc_l2wass_dist(mean_test, tr_cov_test, root_cov_test, mean_synth, cov_synth)
  157. return loss
  158. def forward(self, input, target):
  159. out_feat = self._make_features(target, clone=True)
  160. in_feat = self._make_features(input)
  161. self.feat_losses = [self.base_loss(input,target)]
  162. self.feat_losses += [self.base_loss(f_in, f_out)*w
  163. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  164. styles = [self._get_style_vals(i) for i in out_feat]
  165. if styles[0][0] is not None:
  166. self.feat_losses += [self._single_wass_loss(f_pred, f_targ)*w
  167. for f_pred, f_targ, w in zip(in_feat, styles, self.wass_wgts)]
  168. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  169. return sum(self.feat_losses)
  170. def __del__(self): self.hooks.remove()