-
Notifications
You must be signed in to change notification settings - Fork 12
/
loss.py
27 lines (21 loc) · 867 Bytes
/
loss.py
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
import torch
import torch.nn as nn
class BarlowTwinsLoss(torch.nn.Module):
def __init__(self, device, lambda_param=5e-3):
super(BarlowTwinsLoss, self).__init__()
self.lambda_param = lambda_param
self.device = device
def forward(self, z_a: torch.Tensor, z_b: torch.Tensor):
# normalize repr. along the batch dimension
z_a_norm = (z_a - z_a.mean(0)) / z_a.std(0) # NxD
z_b_norm = (z_b - z_b.mean(0)) / z_b.std(0) # NxD
N = z_a.size(0)
D = z_a.size(1)
# cross-correlation matrix
c = torch.mm(z_a_norm.T, z_b_norm) / N # DxD
# loss
c_diff = (c - torch.eye(D,device=self.device)).pow(2) # DxD
# multiply off-diagonal elems of c_diff by lambda
c_diff[~torch.eye(D, dtype=bool)] *= self.lambda_param
loss = c_diff.sum()
return loss