Skip to content

Prune invalid positive pairs before forming batch-all triplets - #4029

Merged
tomaarsen merged 2 commits into
huggingface:mainfrom
ayoubchikri:perf/prune-invalid-positive-triplets
Sep 16, 2026
Merged

tomaarsen merged 2 commits into
huggingface:mainfrom
ayoubchikri:perf/prune-invalid-positive-triplets

Conversation

@ayoubchikri

Copy link
Copy Markdown
Contributor

BatchAllTripletLoss builds a B × B × B loss tensor before masking invalid anchor-positive pairs. With two samples per label, only B of those B² pairs are valid.

Select valid anchor-positive pairs first, then compare each with the batch's negatives. This preserves all valid triplets, the hinge and the positive-triplet denominator. Intermediate storage scales with B × P, where P is the number of valid anchor-positive pairs; it is quadratic for paired labels, but can still be cubic for large label groups.

Measured: CPU PyTorch 2.2.2, one thread, 256 examples × 32 dimensions, two examples per label: median loss forward/backward 245 → 2.39 ms over five runs. Unique additional storage saved for backward falls 101.3 → 0.99 MB, excluding inputs. This measures the loss only, not encoder throughput or peak GPU memory. Losses match within tolerance and gradients are bitwise identical across nine benchmark configurations.

Validation: 25 tests pass locally and on Linux PyTorch 2.8. The new memory regression fails on upstream; reference comparisons cover uneven groups, ties, missing positives/negatives, both distance metrics and dtypes, and three SGD updates. Official pre-commit hooks pass. Linux run on the exact commit.

@tomaarsen

Copy link
Copy Markdown
Member

Hello!

Thanks for this! This is a useful improvement alongside #4026. With 256 examples and two samples per label on an RTX 3090, additional peak tensor memory dropped from about 209 MiB to 3 MiB, and forward/backward took roughly half the time.

I've inlined anchor_negative_dist so the temporary can be released earlier. Keeping it alive actually increased peak memory for heavily imbalanced batches. I also removed the commented-out calculations.

Similar to #4026, I've removed the redundant SGD test and float64 parametrization. The original ties case had zero gradients throughout, so I've replaced it with an explicit check of the hinge gradient at zero.

  • Tom Aarsen

@tomaarsen
tomaarsen enabled auto-merge (squash) September 16, 2026 15:29
@tomaarsen
tomaarsen merged commit 6b50c78 into huggingface:main Sep 16, 2026
10 checks passed
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.

2 participants