Skip to content

fix(loss): compensate InfoNCE gradients for DDP averaging - #10081

Open
taking-lying-flat wants to merge 1 commit into
modelscope:mainfrom
taking-lying-flat:fix/infonce-dp-grad-scaling
Open

fix(loss): compensate InfoNCE gradients for DDP averaging#10081
taking-lying-flat wants to merge 1 commit into
modelscope:mainfrom
taking-lying-flat:fix/infonce-dp-grad-scaling

Conversation

@taking-lying-flat

Copy link
Copy Markdown
Contributor

PR type

  • Bug Fix
  • New Feature
  • Document Updates
  • More Models or Datasets Support

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:

Measurement Before After
Distributed loss 0.8853394985 0.8853394985
Full-batch reference loss 0.8853394985 0.8853394985
DDP / reference gradient ratio 0.5 1.0

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.

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