-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloss.py
More file actions
executable file
·51 lines (36 loc) · 1.45 KB
/
Copy pathloss.py
File metadata and controls
executable file
·51 lines (36 loc) · 1.45 KB
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
import torch
import torch.nn as nn
import torch.nn.functional as F
class ContrastiveLoss(nn.Module):
def __init__(self, temp=0.5, normalize= False):
super().__init__()
self.temp = temp
self.normalize = normalize
def forward(self,xi,xj):
z1 = F.normalize(xi, dim=1)
z2 = F.normalize(xj, dim=1)
N, Z = z1.shape
device = z1.device
representations = torch.cat([z1, z2], dim=0)
similarity_matrix = torch.mm(representations, representations.T)
# create positive matches
l_pos = torch.diag(similarity_matrix, N)
r_pos = torch.diag(similarity_matrix, -N)
positives = torch.cat([l_pos, r_pos]).view(2 * N, 1)
# print(positives)
# get the values of every pair that's a mismatch
diag = torch.eye(2*N, dtype=torch.bool, device=device)
diag[N:,:N] = diag[:N,N:] = diag[:N,:N]
negatives = similarity_matrix[~diag].view(2*N, -1)
logits = torch.cat([positives, negatives], dim=1)
logits /= self.temp
labels = torch.zeros(2*N, device=device, dtype=torch.int64)
loss = F.cross_entropy(logits, labels, reduction='sum')
return (loss / (2 * N))
if __name__ == "__main__":
main = torch.rand(4,256)
augm = torch.rand(4,256)
# print((main*augm).shape)
# print(torch.sum(main * augm, dim = -1))
loss = ContrastiveLoss()
loss(main,augm)