Repository navigation
perf(loss): avoid full-vocab student log-softmax in same-vocab top-k KD - #3314
Conversation
_direct_topk_kl materialized the all-gathered [B, T, V] fp32 student log-probs (vocab_parallel_full_log_softmax) and then used only the K teacher top-k columns, renormalized within the subset. The subset renormalization cancels the full-vocab partition function, so the same loss is computed exactly by gathering the K columns of the raw logits and applying log_softmax within the subset: the dominant intermediate drops from [B, T, V] (2.32 GiB/sample at T=4096, V=151936, plus the autograd-saved copy and a TP all-gather of the vocab axis) to [B, T, K] (1 MiB at K=64). Adds vocab_parallel_gather_columns: a differentiable TP-aware gather of a shared 1-D column set, reusing gather_logits_at_global_indices (its mask + all_reduce(SUM) construction keeps gradients on the owning shard) with uniform mcore vocab sharding, mirroring vocab_parallel_full_log_softmax's assumptions. Equivalence pinned by tests: forward and gradients match the previous formulation at multiple temperatures, and the no-TP gather path is covered directly. Addresses NVIDIA-NeMo#3272 Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Tianyi Zhang <[email protected]>
…ank group Runs the production sharded-gather code per rank (patched world/rank/ all_reduce) and validates the summed result equals the full-logits column slice, with each shard's backward receiving exactly its own columns' gradients. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Tianyi Zhang <[email protected]>
CUDA measurements + a real 2-rank TP runFollow-up to the CPU numbers above, on an
Peak memory is a flat 3.50× at every length. The cost is also flat in Real 2-rank tensor parallel. The TP test in this PR uses an emulated group, so the collective never actually executes. Re-ran it with two real processes on a real gloo
The 64 columns split 35/29 across the ranks, so the |
yuki-97
left a comment
There was a problem hiding this comment.
@tianyi-zhang-02 thanks for the contribution! @RayenTian @avenkateshha could you help review?
|
Overall LGTM. Would please update the branch then we can trigger CI? @tianyi-zhang-02 |
|
Branch is updated — merged current main, no conflicts, and the submodule pointers match now. On the wandb curve: I don't have one from a real distillation run, and honestly I don't think it'd tell you much, since the two formulations are the same function. But that's an argument rather than data, so I ran it. Same student head, same init, same data, 2000 AdamW steps across 3 seeds, only the student-term formulation swapped (V=151,936, K=64, T=2.0, bf16 logits, 4090): Step 0 is bitwise identical, and main against itself is bitwise identical too (verified over 300 steps), so everything below is the formulation and not run-to-run noise. Two things come out of it, and the second is the one worth knowing. The loss gap is bounded — median 3.8e-6, with the last quarter coming out 0.47-0.52x the first across all three seeds. Final losses agree to five figures (0.011366 vs 0.011364). The weights do drift apart, though. Relative ||dw|| reaches ~2.4e-4 after 2000 steps and grows roughly like t^0.9, so it's steady accumulation rather than anything explosive. At identical weights the two formulations agree to round-off (forward 9.5e-7, gradient rel-L2 2.0e-5 on the top-K columns at full vocab); once you actually optimize, those small gradient differences put the two runs on nearby-but-distinct trajectories. It's the same class of drift you'd get from anything else that perturbs floating-point results — a different GPU count, non-deterministic kernels, a different reduction order — but I'd rather flag it than have you find it. I also swept K in {8, 64, 256} x T in {1.0, 2.0} x 2 seeds. Worst case over those 13 runs was 4.4e-5 absolute and 8.8e-4 relative on the loss, and it shrinks as K grows. One thing I should've mentioned earlier: |
|
Thanks a lot for experiences results!Triggered CI. |
|
/ok to test 4fa15ea |
@RayenTian, there was an error processing your request: See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/ |
|
/ok to test 4fa15ea |
@RayenTian, there was an error processing your request: See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/ |
|
/ok to test 63e0485 |

What does this PR do ?
_direct_topk_kl(same-vocab top-k KD inCrossTokenizerDistillationLossFn) materialized the all-gathered full-vocab[B, T, V]fp32 student log-probs viavocab_parallel_full_log_softmax, then used only the K teacher top-k columns, renormalized within the subset. The subset renormalization cancels the full-vocab partition function (as the method's own docstring notes), so the identical loss is computed by gathering the K columns of the raw logits and applyinglog_softmaxwithin the subset:Memory: the dominant intermediate drops from
[T, V]≈ 2.32 GiB/sample (T=4096, V=151936, fp32, autograd-retained) to[T, K]≈ 1.0 MiB (K=64) — ~2400×. At TP > 1 this also removes the all-gather of the full vocab axis to every rank.Changes
vocab_parallel_gather_columnsinmodel_utils.py(beside its siblingvocab_parallel_full_log_softmax, mirroring its DTensor-unwrap and uniform mcore vocab-shard assumptions): differentiable TP-aware gather of a shared 1-D[K]column set, reusing the existinggather_logits_at_global_indices(whose mask +all_reduce(SUM)construction keeps gradients on the owning shard)._direct_topk_klgathers K columns and softmaxes within the subset; docstring updated.logits.float() / Tordering).Numerical evidence
Beyond the fp32 spot checks below, the identity was verified exhaustively:
Symbolic (sympy, exact arithmetic): old-vs-new difference simplifies to 0 elementwise.
float64: forward max diff 4.4e-16; complete Jacobian max diff 5.6e-17; both formulations pass
torch.autograd.gradcheck.Randomized stress (200 cases across logit scales 1–1000, K from 1 to V, T ∈ {0.5,1,2,10}, fp32/bf16/fp16): constant ~1.5e-7 relative forward error (fp32 epsilon — pure rounding), all cases pass
torch.testing.assert_close; logits at ±1e4 remain finite and bit-identical.TP path: the sharded gather was run through the production code with an emulated 2-rank group — summed shard outputs equal the full-logits column slice exactly, and each shard's backward receives exactly its own columns' gradients (covered by the new
test_vocab_parallel_gather_columns_tp_sharded).Measured speed (CPU wall-clock, same scale, fwd+bwd, best of 3): old 430.5 ms vs new 54.6 ms (~7.9x) — the eliminated
[T, V]log_softmax is compute as well as memory.Measured memory (CPU RSS, separate processes,
B=1, T=2048, V=151936, K=64, bf16 logits + backward): old path peak 4360 MB vs new path 1392 MB — −2.97 GiB, matching the[T,V]-fp32-intermediates estimate.Forward loss: bit-identical (abs diff 0.0e+00 forward KL; 6e-08 reverse KL)
Gradients w.r.t.
student_logits: max abs diff 1.9e-09 vs magnitudes ~1.8e-02 (~1e-7 relative)Issues
Closes #3272.
Before your PR is "Ready for review"
tests/unit/algorithms/test_loss_functions.pyrather thantests/unit/distributed/test_model_utils.pyeven though the new helper is inmodel_utils.py: these cases are CPU-only, matching the CPU-synthetic section of the loss tests, whereastests/unit/distributed/test_model_utils.pyis Ray/NCCL-gated (13 of its 14 tests require GPUs). Happy to move them if you'd rather group by module.test_vocab_parallel_gather_columns_no_tp(column slice + fp32 upcast) andtest_subset_softmax_matches_full_vocab_reference(parametrized over temperature; asserts forward values and gradients match the previous formulation) intests/unit/algorithms/test_loss_functions.py.ruff check/formatclean.cc @terrykong @avenkateshha @yfw