loss.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 FeatureLoss(nn.Module):
  7. def __init__(self, layer_wgts=[20,70,10]):
  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. #Includes wasserstein loss
  31. class WassFeatureLoss(nn.Module):
  32. def __init__(self, layer_wgts=[5,15,2], wass_wgts=[3.0,0.7,0.01]):
  33. super().__init__()
  34. self.m_feat = models.vgg16_bn(True).features.cuda().eval()
  35. requires_grad(self.m_feat, False)
  36. blocks = [i-1 for i,o in enumerate(children(self.m_feat)) if isinstance(o,nn.MaxPool2d)]
  37. layer_ids = blocks[2:5]
  38. self.loss_features = [self.m_feat[i] for i in layer_ids]
  39. self.hooks = hook_outputs(self.loss_features, detach=False)
  40. self.wgts = layer_wgts
  41. self.wass_wgts = wass_wgts
  42. self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))] + [f'wass_{i}' for i in range(len(layer_ids))]
  43. self.base_loss = F.l1_loss
  44. def _make_features(self, x, clone=False):
  45. self.m_feat(x)
  46. return [(o.clone() if clone else o) for o in self.hooks.stored]
  47. def _calc_2_moments(self, tensor):
  48. chans = tensor.shape[1]
  49. tensor = tensor.view(1, chans, -1)
  50. n = tensor.shape[2]
  51. mu = tensor.mean(2)
  52. tensor = (tensor - mu[:,:,None]).squeeze(0)
  53. #Prevents nasty bug that happens very occassionally- divide by zero. Why such things happen?
  54. if n == 0: return None, None
  55. cov = torch.mm(tensor, tensor.t()) / float(n)
  56. return mu, cov
  57. def _get_style_vals(self, tensor):
  58. mean, cov = self._calc_2_moments(tensor)
  59. if mean is None:
  60. return None, None, None
  61. eigvals, eigvects = torch.symeig(cov, eigenvectors=True)
  62. eigroot_mat = torch.diag(torch.sqrt(eigvals.clamp(min=0)))
  63. root_cov = torch.mm(torch.mm(eigvects, eigroot_mat), eigvects.t())
  64. tr_cov = eigvals.clamp(min=0).sum()
  65. return mean, tr_cov, root_cov
  66. def _calc_l2wass_dist(self, mean_stl, tr_cov_stl, root_cov_stl, mean_synth, cov_synth):
  67. tr_cov_synth = torch.symeig(cov_synth, eigenvectors=True)[0].clamp(min=0).sum()
  68. mean_diff_squared = (mean_stl - mean_synth).pow(2).sum()
  69. cov_prod = torch.mm(torch.mm(root_cov_stl, cov_synth), root_cov_stl)
  70. var_overlap = torch.sqrt(torch.symeig(cov_prod, eigenvectors=True)[0].clamp(min=0)+1e-8).sum()
  71. dist = mean_diff_squared + tr_cov_stl + tr_cov_synth - 2*var_overlap
  72. return dist
  73. def _single_wass_loss(self, pred, targ):
  74. mean_test, tr_cov_test, root_cov_test = targ
  75. mean_synth, cov_synth = self._calc_2_moments(pred)
  76. loss = self._calc_l2wass_dist(mean_test, tr_cov_test, root_cov_test, mean_synth, cov_synth)
  77. return loss
  78. def forward(self, input, target):
  79. out_feat = self._make_features(target, clone=True)
  80. in_feat = self._make_features(input)
  81. self.feat_losses = [self.base_loss(input,target)]
  82. self.feat_losses += [self.base_loss(f_in, f_out)*w
  83. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  84. styles = [self._get_style_vals(i) for i in out_feat]
  85. if styles[0][0] is not None:
  86. self.feat_losses += [self._single_wass_loss(f_pred, f_targ)*w
  87. for f_pred, f_targ, w in zip(in_feat, styles, self.wass_wgts)]
  88. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  89. return sum(self.feat_losses)
  90. def __del__(self): self.hooks.remove()