Skip to content

Fix tensor-parallel gradient scaling in Top-K KL distillation - #2988

Merged
kevalmorabia97 merged 5 commits into
NVIDIA:mainfrom
wiederse:codex/fix-topk-kl-tp-gradients
Oct 26, 2026
Merged

kevalmorabia97 merged 5 commits into
NVIDIA:mainfrom
wiederse:codex/fix-topk-kl-tp-gradients

Conversation

@wiederse

@wiederse wiederse commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

With Top-K logits distillation and tensor parallelism enabled, each TP rank evaluates the same global KL loss. The autograd all-gather and full-vocabulary normalizer all-reduce sum gradients from these replicated losses, multiplying student gradients by the TP size even though the reported loss is correct.

Scale only the Top-K loss's backward contribution by 1 / TP. Forward loss values, loss-balancer weights, and dense KL behavior remain unchanged. Extend the existing ghost-token reference test to compare each vocabulary shard's gradients against a full-vocabulary reference, including Top-P truncation, non-default temperature, and reverse KL.

Usage

No API or command-line changes. Existing logit_kl_topk / --logit_kl_top_k configurations automatically receive the corrected gradients.

Testing

  • A800/NCCL: 13 focused tests passed at each of TP=1, TP=2, and TP=4 (39 total), including real Megatron model forward/backward and the distributed gradient-reference tests.
  • Negative control: restoring the original loss implementation makes all 3 gradient-reference cases fail at TP=2, at the gradient assertions.
  • CPU/Gloo: 14 focused numerical tests passed, using a temporary TP=1/2/4 worker fixture; repeated successfully on this isolated PR branch.
  • pre-commit run --files modelopt/torch/distill/plugins/megatron.py tests/gpu_megatron/torch/distill/plugins/test_distill_megatron.py CHANGELOG.rst: passed.
  • A800 TP=2 forward/backward microbenchmark: BF16 logits, sequence length 4096, global vocabulary 32768, K=256, 3 warmups and 10 measured iterations. Peak allocated memory was unchanged at 1,086,358,528 bytes per rank; measured time was 8.44 ms before / 7.81 ms after. This short run checks overhead and does not establish a speedup.
  • Full training convergence was not evaluated.

GPU test selection:

python -m pytest tests/gpu_megatron/torch/distill/plugins/test_distill_megatron.py \
  -k 'logits_kl_loss or logits_kl_losses_temperature_scaling or topk_logits_kl_loss' \
  -q -o addopts=''

Run with 1, 2, or 4 visible GPUs.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ API and forward loss values are unchanged; incorrect TP gradient scaling is corrected.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A.
  • Did you write any new necessary tests?: ✅ Extended the existing reference test with distributed gradient assertions and parameterized cases.
  • Did you update Changelog?: ✅.
  • Did you get Claude approval on this PR?: ❌ Not run; this PR is a draft.

Additional Information

No additional dependencies or communication collectives.

Summary by CodeRabbit

  • Bug Fixes
    • Corrected Megatron Top-K/Top-P distillation gradient scaling when tensor parallelism is enabled. Reported loss values remain unchanged, while gradients are now scaled consistently across tensor-parallel ranks.
  • Tests
    • Expanded coverage across tensor-parallel workers, including top-P truncation, reverse KL, and temperature scaling. Tests also compare shard-level gradients with a full-vocabulary reference and verify probability-mass normalization.

@copy-pr-bot

copy-pr-bot Bot commented Oct 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between fd93cec and e02c3f2.

Files selected for processing: 3
  • CHANGELOG.rst
  • modelopt/torch/distill/plugins/megatron.py
  • tests/gpu_megatron/torch/distill/plugins/test_distill_megatron.py
Files skipped from review as they are similar to previous changes: 1
  • CHANGELOG.rst

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

Walkthrough

Megatron Top-K/Top-P distillation now divides loss gradients by the tensor-parallel size when multiple ranks are active, without changing the reported loss. A distributed test compares shard losses and student gradients with a full-vocabulary reference across several configurations.

Changes: Distillation gradient scaling

Layer / File(s) Summary
Scale gradients and validate distributed loss
modelopt/torch/distill/plugins/megatron.py, tests/gpu_megatron/torch/distill/plugins/test_distill_megatron.py, CHANGELOG.rst
For multiple tensor-parallel ranks, the loss adjustment scales gradients by the inverse of the tensor-parallel size while preserving the reported loss. Distributed tests compare shard losses and gradients with a full-vocabulary reference across top-P, reverse-KL, and temperature settings. The changelog records the fix.

Priority: Normal

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Merge Risk: Minimal · up to e02c3

The change corrects Top-K distillation gradients without changing reported losses, and the distributed reference test covers the scaling error. It is ready to merge after normal checks.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Fix tensor-parallel gradient scaling in Top-K KL distillation" names the main change: the Top-K KL loss now scales its backward gradient by 1/TP to correct gradients replicated across tenso…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The PR changes only modelopt/torch/distill/plugins/megatron.py, one changelog entry, and tests. The modelopt addition only applies backward gradient scaling. Added Python lines contain no unsa…
Full details: Title check

Explanation

The title "Fix tensor-parallel gradient scaling in Top-K KL distillation" names the main change: the Top-K KL loss now scales its backward gradient by 1/TP to correct gradients replicated across tensor-parallel ranks. The changeset adds this scaling in TopLogitsKLLoss.forward, and the test changes check gradient shards against a full-vocabulary reference under tensor parallelism. The title is concise, specific, and free of file lists or vague terms. The changelog and test updates are supporting changes that the title does not need to cover.

Full details: Security Anti-Patterns

Explanation

PASS. The PR changes only modelopt/torch/distill/plugins/megatron.py, one changelog entry, and tests. The modelopt addition only applies backward gradient scaling. Added Python lines contain no unsafe torch.load, numpy.load(..., allow_pickle=True), hardcoded trust_remote_code=True, external-input eval()/exec(), or # nosec. The diff adds no pyproject.toml or requirements dependencies.

Full details: Docstring Coverage

Explanation

Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@wiederse
wiederse marked this pull request as ready for review October 24, 2026 10:38
@wiederse
wiederse requested review from a team as code owners October 24, 2026 10:38

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot review (gpt-6.1-sol) — DM the bot to share feedback.

LGTM: backward-only scaling corrects replicated TP gradients without changing forward losses; the justified reference-test rewrite needs human sign-off.

Needs action:

  • Confirm the test rewrite in tests/gpu_megatron/torch/distill/plugins/test_distill_megatron.py: it retains forward and probability-mass checks while adding shard-gradient comparisons, Top-P truncation, temperature scaling, and reverse KL.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/claude review

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test 5ec737a

@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 79.15%. Comparing base (607263d) to head (e02c3f2).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
modelopt/torch/distill/plugins/megatron.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2988      +/-   ##
==========================================
+ Coverage   77.50%   79.15%   +1.65%     
==========================================
  Files         661      661              
  Lines       74949    74951       +2     
==========================================
+ Hits        58086    59331    +1245     
+ Misses      16863    15620    -1243     
Flag Coverage Δ
examples-diffusers 19.90% <0.00%> (-0.01%) ⬇️
examples-gpt-oss 13.44% <0.00%> (-0.01%) ⬇️
examples-hf_ptq 23.34% <0.00%> (-0.04%) ⬇️
examples-llm_distill 13.52% <0.00%> (-0.01%) ⬇️
examples-llm_eval 17.17% <0.00%> (-0.01%) ⬇️
examples-llm_qat 17.34% <0.00%> (-0.03%) ⬇️
examples-llm_sparsity 16.76% <0.00%> (-0.01%) ⬇️
examples-megatron_bridge 26.48% <50.00%> (-0.22%) ⬇️
examples-specdec_bench 13.23% <0.00%> (-0.01%) ⬇️
examples-speculative_decoding 17.42% <0.00%> (-0.07%) ⬇️
examples-torch_onnx 21.21% <0.00%> (-0.03%) ⬇️
examples-torch_trt 15.15% <0.00%> (-0.01%) ⬇️
examples-vllm_serve 17.38% <0.00%> (-0.01%) ⬇️
gpu 59.00% <50.00%> (+7.96%) ⬆️
regression 15.04% <0.00%> (-0.01%) ⬇️
unit 61.16% <0.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@claude

claude Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Claude review — PR #2988

Scope: full review (trigger comment was a bare /claude review). 3 changed files, all reviewed: modelopt/torch/distill/plugins/megatron.py, tests/gpu_megatron/torch/distill/plugins/test_distill_megatron.py, CHANGELOG.rst.

Findings: CRITICAL: 0 · IMPORTANT: 0 · SUGGESTION: 3 (all test-only, all posted inline)

The fix is correct — I verified the 1/tp_size factor rather than assuming it

The claim is that every TP rank computes the same global Top-K loss, and the autograd collectives then sum tp_size identical gradients. Traced end to end:

  • dist_nn.functional.all_gather backward is reduce_scatter(cat(grad_outputs)). Because every rank runs an identical graph over identically-gathered values, grad_outputs[r] is bit-identical on all ranks, so rank r receives exactly tp_size × its local gradient.
  • dist_nn.functional.all_reduce inside _tp_logsumexp backward is all_reduce(SUM) of the grad — again tp_size × local. Crucially, logits_max is .detach()ed before its (non-autograd) MAX all-reduce, so it does not add a second, unscaled path.
  • Both paths from loss back to predictions (via student_lse, and via gather → all_gather) cross exactly one collective, so the inflation factor is uniformly tp_size. A single scale on the loss is therefore exactly right, not an approximation — and skipping it at tp_size == 1 is correct since no collective runs.
  • loss.detach() + (loss - loss.detach()) / tp_size is bit-exact in the forward: loss - loss.detach() is exactly 0.0.

Dense LogitsKLLoss is correctly left alone, which is the part most likely to look like a missed case. It returns post_forward(loss, tp_reduce=True) on a partial per-shard vocab sum, so the sum over ranks really is the global loss and the summing autograd semantics are the intended ones there. TopLogitsKLLoss returns tp_reduce=False on an already-global loss — that asymmetry is precisely the bug. Root cause, not side effect.

Loss-balancer claim checked: LogitsAndIntermediatesLossBalancer derives dynamic_scale from logits_loss.detach() / intermediate_loss.detach(), so the preserved forward value keeps the balancer's weighting byte-identical. The intended consequence — the logits term's gradient now shrinks tp_size × relative to the never-inflated intermediate/LM terms — is the correction itself.

Test quality: the rewrite is a genuine strengthening, not a weakening. It keeps the original forward and K+1 probability-mass assertions (now keep-masked) and adds a real full-vocab gradient reference per shard. The reference correctly computes the Top-P mask from the teacher before the reverse swap, matching the implementation, and omitting the min_keep term is safe since top_p > 0 always keeps top-1. Global-Top-K recovery from per-rank local Top-K candidates is sound at every tested size. The author's negative control (reverting the loss change fails all 3 cases at TP=2) is the right evidence per CONTRIBUTING's "each fix has a test that fails without it".

Suggestions (non-blocking)

  1. vocab=16 vs torch.chunk(size) — torch.chunk means "chunks of ceil(n/size)", not "size equal parts". On a 5-GPU runner rank 4 hits IndexError; on 6 GPUs ranks disagree on local_top_k and all_gather sees mismatched shapes. Latent only (1/2/4/8 all divide 16), but the failure mode is opaque. Suggest vocab=4 * size.
  2. Unreachable torch.device("cpu") fallback — dist_workers is an NCCL pool, so this is dead code left over from the temporary Gloo fixture.
  3. dist_workers sizes to torch.cuda.device_count() — on a 1-GPU runner size == 1, the tp_size > 1 branch is skipped and all three cases pass vacuously. dist_workers_size_2 skips loudly instead.

Two minor notes not worth their own threads: the Top-P reference masking is now the third hand-written copy in this file (alongside test_topk_logits_kl_loss_top_p_masks_tail's reference() and test_logits_kl_losses_temperature_scaling) and could be consolidated; and the CHANGELOG entry is accurate, but users with existing TP>1 logit_kl_topk runs may appreciate the explicit hint that effective gradient magnitude drops by TP, so LR / kd_loss_alpha may need retuning.

Risk

Low. Five added source lines guarded by tp_size > 1, no API / config / modelopt_state / export surface touched, forward values provably unchanged, and the one behavioral change is the intended correction. All three suggestions are test hygiene and none affect shipped behavior.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude review passed — no blocking issues found. LGTM

@wiederse
wiederse requested a review from cjluo-nv October 25, 2026 15:28

@kevalmorabia97 kevalmorabia97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Root cause confirmed in the code: the Top-K path's dist_nn.functional.all_gather and _tp_logsumexp's dist_nn.functional.all_reduce sum the gradient of the replicated loss across TP ranks, so scaling only the backward by 1 / tp_size is correct. loss - loss.detach() is exactly 0 in the forward, so the reported loss and loss-balancer weights are unchanged, and the dense LogitsKLLoss is untouched. The rewrite of the ghost-token reference test is justified: the forward and probability-mass checks are kept and shard-gradient checks are added (Top-P, temperature, reverse KL). I did not run the GPU tests; the PR reports TP=1/2/4 passing and the negative control failing.

Minor, non-blocking:

  • The PR body still says "this PR is a draft"; it is ready for review.
  • Anyone who tuned the learning rate under the previously inflated TP gradients will see a change; the changelog entry already says gradients change.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test aed85b5

kevalmorabia97 and others added 2 commits October 27, 2026 00:05
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Signed-off-by: Keval Morabia <[email protected]>
Use equal vocab shards so torch.chunk never splits unevenly, and request
dist_workers_size_2 so a single-GPU run skips instead of passing without
entering the tp_size > 1 branch.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test e02c3f2

@kevalmorabia97
kevalmorabia97 enabled auto-merge (squash) October 26, 2026 18:39
@kevalmorabia97
kevalmorabia97 merged commit 8fef214 into NVIDIA:main Oct 26, 2026
52 checks passed
kevalmorabia97 added a commit that referenced this pull request Oct 28, 2026
#2928 #2885 #2908 #2929 #2950 #2972 #2877 #2951 #2816 #3005 #3012 #2971 #3015 #3006 #3026 #2988 #3028 #1860 #3030 #2612 #3033 #2653 #2599 #2655 #2618 #2868 #3032 #3027 #2869 #2984 #2975 #2345 #3020 #2997 (#3072)

## Cherry-picked PRs

- #2817
- #2671
- #2892
- #2876
- #2910
- #2911
- #2919
- #2904
- #2937
- #2928
- #2885
- #2908
- #2929
- #2950
- #2972
- #2877
- #2951
- #2816
- #3005
- #3012
- #2971
- #3015
- #3006
- #3026
- #2988
- #3028
- #1860
- #3030
- #2612
- #3033
- #2653
- #2599
- #2655
- #2618
- #2868
- #3032
- #3027
- #2869
- #2984
- #2975
- #2345
- #3020
- #2997

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Diffusion exports now offer more control over attention-quantizer
metadata and preserve sparse-attention settings in a format compatible
with downstream tooling.
* Model loading better handles select bundled model implementations, and
Docker guidance now covers writable CUDA-extension cache locations.
* **Bug Fixes**
* Improved reliability for model export and checkpoint saving,
quantization across devices, ONNX processing, and calibration.
* Temporary TensorRT and autotuning artifacts now use private
directories by default.
* **Documentation**
* Updated installation guidance, compatibility notes, and links;
corrected typos across guides and examples.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Chad Voegele <[email protected]>
Signed-off-by: Rohan Joshi <[email protected]>
Signed-off-by: LinCanNerd <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
Signed-off-by: weimingc <[email protected]>
Signed-off-by: Noey Yang <[email protected]>
Signed-off-by: Kai Xu <[email protected]>
Signed-off-by: Zhehao Hu <[email protected]>
Signed-off-by: noeyy-mino <[email protected]>
Signed-off-by: joe-nv <[email protected]>
Signed-off-by: yingguo-trt <[email protected]>
Signed-off-by: Shengliang Xu <[email protected]>
Signed-off-by: Chenjie Luo <[email protected]>
Signed-off-by: anmaurya001 <[email protected]>
Signed-off-by: Connor Baker <[email protected]>
Signed-off-by: wiederse <[email protected]>
Signed-off-by: Vu Dinh <[email protected]>
Signed-off-by: Pratik Gandhi <[email protected]>
Signed-off-by: Michael Rusu <[email protected]>
Signed-off-by: Michael-Rusu <[email protected]>
Signed-off-by: namgyu-youn <[email protected]>
Signed-off-by: Sylvester Kaczmarek <[email protected]>
Signed-off-by: Javier de Jesus <[email protected]>
Signed-off-by: javierdejesusda <[email protected]>
Signed-off-by: Zhiyu Cheng <[email protected]>
Signed-off-by: Juhi Mittal <[email protected]>
Signed-off-by: Dmitry Rantovov <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
Co-authored-by: Chad Voegele <[email protected]>
Co-authored-by: LinCanNerd <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Keval Morabia <[email protected]>
Co-authored-by: Wei-Ming Chen <[email protected]>
Co-authored-by: noeyy-mino <[email protected]>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: kaix-nv <[email protected]>
Co-authored-by: Zhehao Hu <[email protected]>
Co-authored-by: joe <[email protected]>
Co-authored-by: yingguo-trt <[email protected]>
Co-authored-by: Shengliang Xu <[email protected]>
Co-authored-by: Chenjie Luo <[email protected]>
Co-authored-by: anmaurya001 <[email protected]>
Co-authored-by: Connor Baker <[email protected]>
Co-authored-by: Jiao Mingyang <[email protected]>
Co-authored-by: Vu Dinh <[email protected]>
Co-authored-by: Pratik Gandhi <[email protected]>
Co-authored-by: Michael R <[email protected]>
Co-authored-by: Michael-Rusu <[email protected]>
Co-authored-by: namgyu-youn <[email protected]>
Co-authored-by: Sylvester Kaczmarek <[email protected]>
Co-authored-by: Javier De Jesus <[email protected]>
Co-authored-by: Zhiyu <[email protected]>
Co-authored-by: Juhi Mittal <[email protected]>
Co-authored-by: Dmitry Rantovov <[email protected]>
Co-authored-by: h-guo18 <[email protected]>
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 28, 2026
@wiederse
wiederse deleted the codex/fix-topk-kl-tp-gradients branch November 1, 2026 13:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-0.48.0 cherry-pick-done Added by bot once PR is cherry-picked to the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants