Skip to content

Group batches by label for SupConLoss and the BatchTriplet losses - #663

Open
danielkorat wants to merge 1 commit into
huggingface:mainfrom
danielkorat:fix-group-by-label-sampler
Open

danielkorat wants to merge 1 commit into
huggingface:mainfrom
danielkorat:fix-group-by-label-sampler

Conversation

@danielkorat

Copy link
Copy Markdown
Contributor

Hello!

Heads up, this PR was AI-generated.

Pull Request overview

  • Fix GROUP_BY_LABEL never being applied for SupConLoss and the four BatchTriplet losses
  • Add a regression test

Details

Since #554 (v1.1.0), Trainer.train_embeddings checks the loss like this:

self.st_trainer.loss = loss
if loss in (
    losses.BatchAllTripletLoss,
    ...
    SupConLoss,
):
    self.st_trainer.args.batch_sampler = BatchSamplers.GROUP_BY_LABEL

loss here is the instance returned by get_dataset, while the tuple holds classes, so the condition is always False and these losses train on plain random batches. They mine positives inside each batch, so a label that appears only once in a batch leaves that sample without a positive. For SupConLoss this is a 0/0, the loss becomes NaN, and the NaN weights then make the classification head fail. The fix compares args.loss, as get_dataset already does a few lines below.

Reproducer (6 classes, 4 samples each, batches of 8):

from datasets import Dataset

from setfit import SetFitModel, Trainer, TrainingArguments
from setfit.losses import SupConLoss

labels = [label for label in range(6) for _ in range(4)]
dataset = Dataset.from_dict({"text": [f"sample {i}" for i in range(len(labels))], "label": labels})
model = SetFitModel.from_pretrained("sentence-transformers/paraphrase-albert-small-v2")
args = TrainingArguments(loss=SupConLoss, batch_size=8, num_epochs=1, logging_steps=1, report_to="none")
trainer = Trainer(model=model, args=args, train_dataset=dataset)
trainer.train()
main this PR
st_trainer.args.batch_sampler BatchSamplers.BATCH_SAMPLER BatchSamplers.GROUP_BY_LABEL
logged embedding_loss per step 0.0, 0.0, 0.0 1.45, 1.55, 1.44
trainer.train() ValueError: Input X contains NaN. finishes

The logged 0.0 hides the problem: with the default logging_nan_inf_filter=True, transformers leaves non-finite losses out of the logged value. With few classes (e.g. binary) a label rarely appears only once in a batch, so the bug mostly shows up as fewer in-batch positives than intended, without any error.

Tests

test_trainer_groups_batches_by_label_for_in_batch_losses trains each of the five losses on a 6-class dataset and asserts that GROUP_BY_LABEL is set. It fails for all five on main and passes with the fix.

Check Result
pytest tests/test_trainer.py (Python 3.12.14, macOS, torch 2.14.1, transformers 5.18.0, sentence-transformers 6.1.0) 40 passed, 3 skipped
make style && make quality (Python 3.9, black 25.11.0, as in the quality workflow) no changes, passes

🤖 Generated with Claude Code

Trainer.train_embeddings compared the loss instance against a tuple of
loss classes, so the check was always False and GROUP_BY_LABEL was never
set. SupConLoss and the four BatchTriplet losses trained on random
batches, where a label can appear only once; SupConLoss then returns NaN
and fitting the head fails with 'Input X contains NaN'. Compare
args.loss, as get_dataset already does.
@danielkorat

Copy link
Copy Markdown
Contributor Author

Hi @tomaarsen 👋

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant