File size: 7,091 Bytes
7f4f2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import torch
import torch.nn as nn
import torch.nn.functional as F
import config


class ContrastiveLoss_simcse(nn.Module):
    """SimCSE loss"""

    def __init__(self):
        super(ContrastiveLoss_simcse, self).__init__()
        self.temperature = config.temperature

    def forward(self, feature_vectors, labels):
        normalized_features = F.normalize(
            feature_vectors, p=2, dim=0
        )  # normalize along columns

        # Identify indices for each label
        anchor_indices = (labels == 0).nonzero().squeeze(dim=1)
        positive_indices = (labels == 1).nonzero().squeeze(dim=1)
        negative_indices = (labels == 2).nonzero().squeeze(dim=1)

        # Extract tensors based on labels
        anchor = normalized_features[anchor_indices]
        positives = normalized_features[positive_indices]
        negatives = normalized_features[negative_indices]
        pos_and_neg = torch.cat([positives, negatives])

        denominator = torch.sum(
            torch.exp(
                torch.div(
                    torch.matmul(anchor, torch.transpose(pos_and_neg, 0, 1)),
                    self.temperature,
                )
            )
        )

        numerator = torch.exp(
            torch.div(
                torch.matmul(anchor, torch.transpose(positives, 0, 1)),
                self.temperature,
            )
        )

        loss = -torch.log(
            torch.div(
                numerator,
                denominator,
            )
        )

        return loss


class ContrastiveLoss_simcse_w(nn.Module):
    """SimCSE loss with weighting."""

    def __init__(self):
        super(ContrastiveLoss_simcse_w, self).__init__()
        self.temperature = config.temperature

    def forward(self, feature_vectors, labels, scores):
        normalized_features = F.normalize(
            feature_vectors, p=2, dim=0
        )  # normalize along columns

        # Identify indices for each label
        anchor_indices = (labels == 0).nonzero().squeeze(dim=1)
        positive_indices = (labels == 1).nonzero().squeeze(dim=1)
        negative_indices = (labels == 2).nonzero().squeeze(dim=1)

        pos_scores = scores[positive_indices].float()
        normalized_neg_scores = F.normalize(
            scores[negative_indices].float(), p=2, dim=0
        )  # l2-norm
        normalized_neg_scores += 1
        scores = torch.cat([pos_scores, normalized_neg_scores])

        # Extract tensors based on labels
        anchor = normalized_features[anchor_indices]
        positives = normalized_features[positive_indices]
        negatives = normalized_features[negative_indices]
        pos_and_neg = torch.cat([positives, negatives])

        denominator = torch.sum(
            torch.exp(
                scores
                * torch.div(
                    torch.matmul(anchor, torch.transpose(pos_and_neg, 0, 1)),
                    self.temperature,
                )
            )
        )

        numerator = torch.exp(
            torch.div(
                torch.matmul(anchor, torch.transpose(positives, 0, 1)),
                self.temperature,
            )
        )

        loss = -torch.log(
            torch.div(
                numerator,
                denominator,
            )
        )

        return loss


class ContrastiveLoss_samp(nn.Module):
    """Supervised contrastive loss without weighting."""

    def __init__(self):
        super(ContrastiveLoss_samp, self).__init__()
        self.temperature = config.temperature

    def forward(self, feature_vectors, labels):
        # Normalize feature vectors
        normalized_features = F.normalize(
            feature_vectors, p=2, dim=0
        )  # normalize along columns

        # Identify indices for each label
        anchor_indices = (labels == 0).nonzero().squeeze(dim=1)
        positive_indices = (labels == 1).nonzero().squeeze(dim=1)
        negative_indices = (labels == 2).nonzero().squeeze(dim=1)

        # Extract tensors based on labels
        anchor = normalized_features[anchor_indices]
        positives = normalized_features[positive_indices]
        negatives = normalized_features[negative_indices]
        pos_and_neg = torch.cat([positives, negatives])

        pos_cardinal = positives.shape[0]

        denominator = torch.sum(
            torch.exp(
                torch.div(
                    torch.matmul(anchor, torch.transpose(pos_and_neg, 0, 1)),
                    self.temperature,
                )
            )
        )

        sum_log_ent = torch.sum(
            torch.log(
                torch.div(
                    torch.exp(
                        torch.div(
                            torch.matmul(anchor, torch.transpose(positives, 0, 1)),
                            self.temperature,
                        )
                    ),
                    denominator,
                )
            )
        )

        scale = -1 / pos_cardinal

        return scale * sum_log_ent


class ContrastiveLoss_samp_w(nn.Module):
    """Supervised contrastive loss with weighting."""

    def __init__(self):
        super(ContrastiveLoss_samp_w, self).__init__()
        self.temperature = config.temperature

    def forward(self, feature_vectors, labels, scores):
        # Normalize feature vectors
        normalized_features = F.normalize(
            feature_vectors, p=2, dim=0
        )  # normalize along columns

        # Identify indices for each label
        anchor_indices = (labels == 0).nonzero().squeeze(dim=1)
        positive_indices = (labels == 1).nonzero().squeeze(dim=1)
        negative_indices = (labels == 2).nonzero().squeeze(dim=1)

        # Normalize score vector
        num_skip = len(positive_indices) + 1
        pos_scores = scores[: (num_skip - 1)].float()  # exclude anchor
        normalized_neg_scores = F.normalize(
            scores[num_skip:].float(), p=2, dim=0
        )  # l2-norm
        normalized_neg_scores += 1
        scores = torch.cat([pos_scores, normalized_neg_scores])

        # Extract tensors based on labels
        anchor = normalized_features[anchor_indices]
        positives = normalized_features[positive_indices]
        negatives = normalized_features[negative_indices]
        pos_and_neg = torch.cat([positives, negatives])

        pos_cardinal = positives.shape[0]

        denominator = torch.sum(
            torch.exp(
                scores
                * torch.div(
                    torch.matmul(anchor, torch.transpose(pos_and_neg, 0, 1)),
                    self.temperature,
                )
            )
        )

        sum_log_ent = torch.sum(
            torch.log(
                torch.div(
                    torch.exp(
                        torch.div(
                            torch.matmul(anchor, torch.transpose(positives, 0, 1)),
                            self.temperature,
                        )
                    ),
                    denominator,
                )
            )
        )

        scale = -1 / pos_cardinal

        return scale * sum_log_ent