supconloss.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import paddle
  2. from paddle import nn
  3. class SupConLoss(nn.Layer):
  4. """Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
  5. It also supports the unsupervised contrastive loss in SimCLR"""
  6. def __init__(self,
  7. views=16,
  8. temperature=0.07,
  9. contrast_mode='all',
  10. base_temperature=0.07,
  11. normalize_feature=True):
  12. super(SupConLoss, self).__init__()
  13. self.temperature = paddle.to_tensor(temperature)
  14. self.contrast_mode = contrast_mode
  15. self.base_temperature = paddle.to_tensor(base_temperature)
  16. self.num_ids = None
  17. self.views = views
  18. self.normalize_feature = normalize_feature
  19. def forward(self, features, labels, mask=None):
  20. """Compute loss for model. If both `labels` and `mask` are None,
  21. it degenerates to SimCLR unsupervised loss:
  22. https://arxiv.org/pdf/2002.05709.pdf
  23. Args:
  24. features: hidden vector of shape [bsz, n_views, ...].
  25. labels: ground truth of shape [bsz].
  26. mask: contrastive mask of shape [bsz, bsz], mask_{i,j}=1 if sample j
  27. has the same class as sample i. Can be asymmetric.
  28. Returns:
  29. A loss scalar.
  30. """
  31. features = features["features"]
  32. if self.num_ids is None:
  33. self.num_ids = int(features.shape[0] / self.views)
  34. if self.normalize_feature:
  35. features = 1. * features / (paddle.expand_as(
  36. paddle.norm(
  37. features, p=2, axis=-1, keepdim=True), features) + 1e-12)
  38. features = features.reshape([self.num_ids, self.views, -1])
  39. labels = labels.reshape([self.num_ids, self.views])[:, 0]
  40. if len(features.shape) < 3:
  41. raise ValueError('`features` needs to be [bsz, n_views, ...],'
  42. 'at least 3 dimensions are required')
  43. if len(features.shape) > 3:
  44. features = features.reshape(
  45. [features.shape[0], features.shape[1], -1])
  46. batch_size = features.shape[0]
  47. if labels is not None and mask is not None:
  48. raise ValueError('Cannot define both `labels` and `mask`')
  49. elif labels is None and mask is None:
  50. mask = paddle.eye(batch_size, dtype='float32')
  51. elif labels is not None:
  52. labels = labels.reshape([-1, 1])
  53. if labels.shape[0] != batch_size:
  54. raise ValueError(
  55. 'Num of labels does not match num of features')
  56. mask = paddle.cast(
  57. paddle.equal(labels, paddle.t(labels)), 'float32')
  58. else:
  59. mask = paddle.cast(mask, 'float32')
  60. contrast_count = features.shape[1]
  61. contrast_feature = paddle.concat(
  62. paddle.unbind(
  63. features, axis=1), axis=0)
  64. if self.contrast_mode == 'one':
  65. anchor_feature = features[:, 0]
  66. anchor_count = 1
  67. elif self.contrast_mode == 'all':
  68. anchor_feature = contrast_feature
  69. anchor_count = contrast_count
  70. else:
  71. raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
  72. # compute logits
  73. anchor_dot_contrast = paddle.divide(
  74. paddle.matmul(anchor_feature, paddle.t(contrast_feature)),
  75. self.temperature)
  76. # for numerical stability
  77. logits_max = paddle.max(anchor_dot_contrast, axis=1, keepdim=True)
  78. logits = anchor_dot_contrast - logits_max.detach()
  79. # tile mask
  80. mask = paddle.tile(mask, [anchor_count, contrast_count])
  81. logits_mask = 1 - paddle.eye(batch_size * anchor_count)
  82. mask = mask * logits_mask
  83. # compute log_prob
  84. exp_logits = paddle.exp(logits) * logits_mask
  85. log_prob = logits - paddle.log(
  86. paddle.sum(exp_logits, axis=1, keepdim=True))
  87. # compute mean of log-likelihood over positive
  88. mean_log_prob_pos = paddle.sum((mask * log_prob),
  89. axis=1) / paddle.sum(mask, axis=1)
  90. # loss
  91. loss = -(self.temperature / self.base_temperature) * mean_log_prob_pos
  92. loss = paddle.mean(loss.reshape([anchor_count, batch_size]))
  93. return {"SupConLoss": loss}