Switch to unified view

a b/algorithms/loss/supcon_loss.py
1
"""
2
Taken from: https://github.com/HobbitLong/SupContrast
3
Author: Yonglong Tian (yonglong@mit.edu)
4
Date: May 07, 2020
5
6
"""
7
8
import torch
9
import torch.nn as nn
10
11
12
class SupConLoss(nn.Module):
13
    """Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
14
    It also supports the unsupervised contrastive loss in SimCLR"""
15
    def __init__(self, temperature=0.07, contrast_mode='all',
16
                 base_temperature=0.07):
17
        super(SupConLoss, self).__init__()
18
        self.temperature = temperature
19
        self.contrast_mode = contrast_mode
20
        self.base_temperature = base_temperature
21
22
    def forward(self, features, labels=None, mask=None):
23
        """Compute loss for model. If both `labels` and `mask` are None,
24
        it degenerates to SimCLR unsupervised loss:
25
        https://arxiv.org/pdf/2002.05709.pdf
26
27
        Args:
28
            features: hidden vector of shape [bsz, n_views, ...].
29
            labels: ground truth of shape [bsz].
30
            mask: contrastive mask of shape [bsz, bsz], mask_{i,j}=1 if sample j
31
                has the same class as sample i. Can be asymmetric.
32
        Returns:
33
            A loss scalar.
34
        """
35
        device = (torch.device('cuda')
36
                  if features.is_cuda
37
                  else torch.device('cpu'))
38
39
        if len(features.shape) < 3:
40
            raise ValueError('`features` needs to be [bsz, n_views, ...],'
41
                             'at least 3 dimensions are required')
42
        if len(features.shape) > 3:
43
            features = features.view(features.shape[0], features.shape[1], -1)
44
45
        batch_size = features.shape[0]
46
        if labels is not None and mask is not None:
47
            raise ValueError('Cannot define both `labels` and `mask`')
48
        elif labels is None and mask is None:
49
            mask = torch.eye(batch_size, dtype=torch.float32).to(device)
50
        elif labels is not None:
51
            labels = labels.contiguous().view(-1, 1)
52
            if labels.shape[0] != batch_size:
53
                raise ValueError('Num of labels does not match num of features')
54
            mask = torch.eq(labels, labels.T).float().to(device)
55
        else:
56
            mask = mask.float().to(device)
57
58
        contrast_count = features.shape[1]
59
        contrast_feature = torch.cat(torch.unbind(features, dim=1), dim=0)
60
        if self.contrast_mode == 'one':
61
            anchor_feature = features[:, 0]
62
            anchor_count = 1
63
        elif self.contrast_mode == 'all':
64
            anchor_feature = contrast_feature
65
            anchor_count = contrast_count
66
        else:
67
            raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
68
69
        # compute logits
70
        anchor_dot_contrast = torch.div(
71
            torch.matmul(anchor_feature, contrast_feature.T),
72
            self.temperature)
73
        # for numerical stability
74
        logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)
75
        logits = anchor_dot_contrast - logits_max.detach()
76
77
        # tile mask
78
        mask = mask.repeat(anchor_count, contrast_count)
79
        # mask-out self-contrast cases
80
        logits_mask = torch.scatter(
81
            torch.ones_like(mask),
82
            1,
83
            torch.arange(batch_size * anchor_count).view(-1, 1).to(device),
84
            0
85
        )
86
        mask = mask * logits_mask
87
88
        # compute log_prob
89
        exp_logits = torch.exp(logits) * logits_mask
90
        log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
91
92
        # compute mean of log-likelihood over positive
93
        mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)
94
95
        # loss
96
        loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos
97
        loss = loss.view(anchor_count, batch_size).mean()
98
99
        return loss