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

Add DebiasedMultipleNegativesRankingLoss to the losses #3148

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Corrected errors in DebiasedMultipleNegativesRankingLoss.py
ilanaliouchouche committed Jan 8, 2025
commit 2d03076aad8dd5e510ea17d89cdad910053412e3
Original file line number Diff line number Diff line change
@@ -6,12 +6,15 @@
import torch
from torch import Tensor, nn

import numpy as np

from sentence_transformers import util
from sentence_transformers.SentenceTransformer import SentenceTransformer

from collections import defaultdict

class DebiasedMultipleNegativesRankingLoss(nn.Module):
def __init__(self, model: SentenceTransformer, scale: float = 20.0, similarity_fct=util.cos_sim, tau_plus: float = 0.01) -> None:
def __init__(self, model: SentenceTransformer, scale: float = 1.0, similarity_fct=util.cos_sim, tau_plus: float = 0.1) -> None:
"""
This loss is a debiased version of the `MultipleNegativesRankingLoss` loss that addresses the inherent sampling bias in the negative examples.
@@ -110,23 +113,19 @@ def forward(self, sentence_features: Iterable[dict[str, Tensor]], labels: Tensor

# Compute the mask to remove the similarity of the anchor to the positive candidate.
batch_size = scores.size(0)
mask = torch.ones_like(scores, dtype=torch.bool) # (batch_size, batch_size * (1 + num_negatives))
mask = torch.zeros_like(scores, dtype=torch.bool) # (batch_size, batch_size * (1 + num_negatives))
positive_indices = torch.arange(0, batch_size, device=scores.device)
mask[positive_indices, positive_indices] = False
mask[positive_indices, positive_indices] = True

# Get the similarity of the anchor to the negative candidates.
neg_exp = torch.exp(scores.masked_fill(mask, float("-inf"))).sum(dim=-1) # (batch_size,)
Copy link
Author

@ilanaliouchouche ilanaliouchouche Jan 8, 2025

Choose a reason for hiding this comment

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

Here, there is an error in my code. The masked_fill method replaces all the True locations in the mask, so ultimately we have pos_exp = neg_exp when computing the positives. This results in g being negative (because tau_plus << 1 - tau_plus). For each a i , g is replaced by exp ( scale ) (hence no learning).

Changes made:

  • Line 113: replaced the ones_like function with zeros_like.
  • Line 115: replaced mask[positive_indices, positive_indices] = False with mask[positive_indices, positive_indices] = True.

Tested, and gradient descent is now active; the loss is no longer stuck at 0. I still need to run some additional tests (the loss behaves differently depending on whether cos_sim or dot_score is used).

# Get the similarity of the anchor to the positive candidate.
pos_exp = torch.exp(torch.gather(scores, -1, positive_indices.unsqueeze(1)).squeeze())
# (batch_size,)

# Compute the g estimator with the exponential of the similarities.
N_neg = scores.size(1) - 1 # Number of negatives
g = torch.clamp((1 / (1 - self.tau_plus)) * ((neg_exp / N_neg) - (self.tau_plus * pos_exp)),
min=torch.exp(-torch.tensor(self.scale)))
# (batch_size,)

# Compute the final debiased loss.
min=np.exp(-self.scale))
loss = - torch.log(pos_exp / (pos_exp + N_neg * g)).mean()

return loss