fix(loss): compensate InfoNCE gradients for DDP averaging - #10081
Open
taking-lying-flat wants to merge 1 commit into
Open
fix(loss): compensate InfoNCE gradients for DDP averaging#10081taking-lying-flat wants to merge 1 commit into
taking-lying-flat wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR type
PR information
With
INFONCE_USE_BATCH=True, each HF/DDP rank computes the same global mean InfoNCE loss after gathering embeddings, but retains the computation graph only for its own embeddings. DDP then averages these local gradient contributions, making the parameter gradient smaller than the full-batch reference by the data-parallel size even though the loss values match.Compensate the backward gradient by the number of gathered DP embedding shards while preserving the reported loss through a detached value. The scale remains one without cross-rank batch negatives. Using the gathered shard count avoids including SP/TP ranks in the compensation. This change is limited to the HF path; Megatron behavior is unchanged.
Only six production-code lines are added in
swift/loss/embedding.py.Experiment results
Real two-process CPU DDP with a linear encoder and the production InfoNCE implementation:
All 21 local comparison cases passed: seven configurations across world/DP sizes 2/2, 4/2 and 2/1. Coverage includes equal and variable negative counts, QQ/DD with fake-negative masking, disabled batch negatives, and gradient accumulation. The subgroup cases validate DP group selection without running a sequence-parallel model. Maximum gradient error against the reference was below
6.71e-8.All applicable pre-commit checks passed. Validation scripts remain outside the repository.