From f1e4b4f468c91dabe8b4dc1f983bb8044981d313 Mon Sep 17 00:00:00 2001 From: flyingdoubleG <53119724+flyingdoubleG@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:06:19 +0800 Subject: [PATCH] fix(loss): upsample InfoNCE hard negatives from the negatives only With hard_negatives set, groups with fewer negatives are padded by sampling `choice(range(negatives)) + 1`. A group is laid out as [anchor, positive, negatives...], so that offset samples indices 1..negatives: it can pick the positive and never picks the last negative. A group with a single negative is always padded with copies of the positive, which then appears as its own negative and caps the loss below at log(1 + copies). Offset by 2, as ms-swift does. Co-Authored-By: Claude Opus 5.5 --- src/twinkle/loss/infonce.py | 4 ++-- tests/loss/test_infonce.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 tests/loss/test_infonce.py diff --git a/src/twinkle/loss/infonce.py b/src/twinkle/loss/infonce.py index cb9465113..6eacd4aa3 100644 --- a/src/twinkle/loss/infonce.py +++ b/src/twinkle/loss/infonce.py @@ -63,8 +63,8 @@ def _parse_multi_negative_sentences(sentences: torch.Tensor, if negatives > hard_negatives: split_part = split_part[:hard_negatives + 2] elif negatives < hard_negatives: - # upsample negatives with replacement; skip index 0 (positive) - selected = np.random.choice(list(range(negatives)), size=hard_negatives - negatives, replace=True) + 1 + # upsample negatives with replacement; skip index 0 (anchor) and 1 (positive) + selected = np.random.choice(list(range(negatives)), size=hard_negatives - negatives, replace=True) + 2 split_part = torch.cat((split_part, split_part[selected]), dim=0) split_tensors.append(split_part) return split_tensors diff --git a/tests/loss/test_infonce.py b/tests/loss/test_infonce.py new file mode 100644 index 000000000..d0eee4fe7 --- /dev/null +++ b/tests/loss/test_infonce.py @@ -0,0 +1,28 @@ +# Copyright (c) ModelScope Contributors. All rights reserved. +"""Tests for InfonceLoss.""" +import torch + +from twinkle.loss import InfonceLoss +from twinkle.loss.infonce import _parse_multi_negative_sentences + + +def test_hard_negative_upsampling_never_picks_anchor_or_positive(): + # Two groups laid out as anchor, positive, negatives: [a0, p0, n0] and [a1, p1, n1, n1']. + sentences = torch.arange(7, dtype=torch.float32).unsqueeze(-1) + labels = torch.tensor([1, 0, 0, 1, 0, 0, 0]) + groups = _parse_multi_negative_sentences(sentences, labels, hard_negatives=4) + for group, negatives in zip(groups, ({2.0}, {5.0, 6.0})): + assert group.shape[0] == 2 + 4 + assert set(group[2:, 0].tolist()) <= negatives + + +def test_hard_negative_upsampling_keeps_the_loss_of_duplicated_negatives(): + # One negative padded to three copies: the loss equals CE over [positive, neg, neg, neg]. + torch.manual_seed(0) + anchor, positive, negative = torch.randn(3, 4) + sentences = torch.stack([anchor, positive, negative]) + loss_fn = InfonceLoss(temperature=1.0, use_batch=False, hard_negatives=3) + loss = loss_fn({'labels': torch.tensor([1, 0, 0])}, {'embeddings': sentences})['loss'] + logits = torch.stack([anchor @ positive] + [anchor @ negative] * 3) + expected = -torch.log_softmax(logits, dim=0)[0] + torch.testing.assert_close(loss, expected)