Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MACL(Model Aware Contrastive learning ) Loss Function #1757

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions lightly/loss/macl_loss.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import torch
import torch.nn as nn
import torch.nn.functional as F

class MACLLoss(nn.Module):
def __init__(self, temperature=0.1, alpha=0.5, A_0=0):
super().__init__()
self.t_0 = temperature
self.alpha = alpha
self.A_0 = A_0
Comment on lines +6 to +10
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def __init__(self, temperature=0.1, alpha=0.5, A_0=0):
super().__init__()
self.t_0 = temperature
self.alpha = alpha
self.A_0 = A_0
def __init__(self, temperature: float = 0.1, alpha: float = 0.5, A_0: float = 0):
super().__init__()
self.temperature = temperature
self.alpha = alpha
self.A_0 = A_0

Could you also add a short docstring that describes what the loss does, what the parameters are, and add a reference to the paper that introduced the loss? You can follow the example here:

class NTXentLoss(nn.Module):

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok i will add the loss doc also


def mask_correlated_samples(self, batch_size):
N = 2 * batch_size
mask = torch.ones((N, N), dtype=bool)
mask = mask.fill_diagonal_(0)
for i in range(batch_size):
mask[i, batch_size + i] = 0
mask[batch_size + i, i] = 0
return mask

def forward(self, z0, z1):
"""
Args:
z0: first view embeddings
z1: second view embeddings
"""
# Normalize embeddings
z0 = F.normalize(z0, dim=-1, p=2)
z1 = F.normalize(z1, dim=-1, p=2)

# Concatenate embeddings
out = torch.cat([z0, z1], dim=0)
batch_size = z0.shape[0]
n_samples = len(out)

# Compute similarity matrix
cov = out @ out.T

# Get positive and negative pairs
mask = self.mask_correlated_samples(batch_size).to(out.device)
Abhishekjha3515 marked this conversation as resolved.
Show resolved Hide resolved
neg = cov.masked_select(mask).view(n_samples, -1)

# Get positive pairs from upper and lower diagonals
u_b = torch.diag(cov, batch_size)
l_b = torch.diag(cov, -batch_size)
pos = torch.cat([u_b, l_b], dim=0).reshape(n_samples, 1)

# Calculate model-aware temperature
A = torch.mean(pos.detach())
t = self.t_0 * (1 + self.alpha * (A - self.A_0))

# Calculate logits and loss
logits = torch.cat([pos, neg], dim=1)
P = torch.softmax(logits/t, dim=1)[:, 0]
V = 1 / (1 - P)
loss = -V.detach() * torch.log(P)

return loss.mean()