Switch to unified view

a b/opengait/modeling/losses/supconloss.py
1
'''
2
Modifed fromhttps://github.com/BNU-IVC/FastPoseGait/blob/main/fastposegait/modeling/losses/supconloss.py
3
'''
4
5
import torch.nn as nn
6
import torch
7
from .base import BaseLoss, gather_and_scale_wrapper
8
9
10
class SupConLoss_Re(BaseLoss):
11
    def __init__(self, temperature=0.01):
12
        super(SupConLoss_Re, self).__init__()
13
        self.train_loss = SupConLoss(temperature=temperature)
14
15
    @gather_and_scale_wrapper
16
    def forward(self, features, labels=None, mask=None):
17
        loss = self.train_loss(features, labels)
18
        self.info.update({
19
            'loss': loss.detach().clone()})
20
        return loss, self.info
21
22
23
class SupConLoss_Lp(BaseLoss):
24
    def __init__(self, temperature=0.01):
25
        super(SupConLoss_Lp, self).__init__()
26
        self.train_loss = SupConLoss(
27
            temperature=temperature, base_temperature=temperature, reduce_zero=True, p=2)
28
29
    @gather_and_scale_wrapper
30
    def forward(self, features, labels=None, mask=None):
31
        loss = self.train_loss(features.unsqueeze(1), labels)
32
        self.info.update({
33
            'loss': loss.detach().clone()})
34
        return loss, self.info
35
36
37
class SupConLoss(nn.Module):
38
    """Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
39
    It also supports the unsupervised contrastive loss in SimCLR"""
40
41
    def __init__(self, temperature=0.01, contrast_mode='all',
42
                 base_temperature=0.07, reduce_zero=False, p=None):
43
        super(SupConLoss, self).__init__()
44
        self.temperature = temperature
45
        self.contrast_mode = contrast_mode
46
        self.base_temperature = base_temperature
47
        self.reduce_zero = reduce_zero
48
        self.p = p
49
50
    def forward(self, features, labels=None, mask=None):
51
        """Compute loss for model. If both `labels` and `mask` are None,
52
        it degenerates to SimCLR unsupervised loss:
53
        https://arxiv.org/pdf/2002.05709.pdf
54
        Args:
55
            features: hidden vector of shape [bsz, n_views, ...].
56
            labels: ground truth of shape [bsz].
57
            mask: contrastive mask of shape [bsz, bsz], mask_{i,j}=1 if sample j
58
                has the same class as sample i. Can be asymmetric.
59
        Returns:
60
            A loss scalar.
61
        """
62
        device = (torch.device('cuda')
63
                  if features.is_cuda
64
                  else torch.device('cpu'))
65
66
        if len(features.shape) < 3:
67
            raise ValueError('`features` needs to be [bsz, n_views, ...],'
68
                             'at least 3 dimensions are required')
69
        if len(features.shape) > 3:
70
            features = features.view(features.shape[0], features.shape[1], -1)
71
72
        batch_size = features.shape[0]
73
        if labels is not None and mask is not None:
74
            raise ValueError('Cannot define both `labels` and `mask`')
75
        elif labels is None and mask is None:
76
            mask = torch.eye(batch_size, dtype=torch.float32).to(device)
77
        elif labels is not None:
78
            labels = labels.contiguous().view(-1, 1)
79
            if labels.shape[0] != batch_size:
80
                raise ValueError('Num of labels does not match num of features')
81
            mask = torch.eq(labels, labels.T).float().to(device)
82
        else:
83
            mask = mask.float().to(device)
84
85
        contrast_count = features.shape[1]
86
        contrast_feature = torch.cat(torch.unbind(features, dim=1), dim=0)
87
        if self.contrast_mode == 'one':
88
            anchor_feature = features[:, 0]
89
            anchor_count = 1
90
        elif self.contrast_mode == 'all':
91
            anchor_feature = contrast_feature
92
            anchor_count = contrast_count
93
        else:
94
            raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
95
96
        # compute distance mat
97
        if self.p is None:
98
            mat = torch.matmul(
99
                anchor_feature, contrast_feature.T)
100
        else:
101
            anchor_feature = torch.nn.functional.normalize(
102
                anchor_feature, p=self.p, dim=1)
103
            contrast_feature = torch.nn.functional.normalize(
104
                contrast_feature, p=self.p, dim=1)
105
            mat = -torch.cdist(
106
                anchor_feature, contrast_feature, p=self.p)
107
        mat = mat/self.temperature
108
        # for numerical stability
109
        logits_max, _ = torch.max(mat, dim=1, keepdim=True)
110
        logits = mat - logits_max.detach()
111
112
        # tile mask
113
        mask = mask.repeat(anchor_count, contrast_count)
114
        # mask-out self-contrast cases
115
        logits_mask = torch.scatter(
116
            torch.ones_like(mask),
117
            1,
118
            torch.arange(batch_size * anchor_count).view(-1, 1).to(device),
119
            0
120
        )
121
        mask = mask * logits_mask
122
123
        # compute log_prob
124
        exp_logits = torch.exp(logits) * logits_mask
125
        log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
126
127
        # compute mean of log-likelihood over positive
128
        mean_log_prob_pos = (mask * log_prob).sum(1) / \
129
            (mask.sum(1)+torch.finfo(mat.dtype).tiny)
130
        # loss
131
        loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos
132
        if self.reduce_zero:
133
            loss = loss[loss > 0]
134
135
        return loss.mean()