Skip to content

perf(loss): avoid full-vocab student log-softmax in same-vocab top-k KD - #3314

Merged
yuki-97 merged 4 commits into
NVIDIA-NeMo:mainfrom
tianyi-zhang-02:perf/topk-kd-subset-softmax
Aug 3, 2026
Merged

yuki-97 merged 4 commits into
NVIDIA-NeMo:mainfrom
tianyi-zhang-02:perf/topk-kd-subset-softmax

Conversation

@tianyi-zhang-02

@tianyi-zhang-02 tianyi-zhang-02 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

_direct_topk_kl (same-vocab top-k KD in CrossTokenizerDistillationLossFn) materialized the all-gathered full-vocab [B, T, V] fp32 student log-probs via vocab_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 applying log_softmax within the subset:

log_softmax_V(x/T)[idx] − lse_K(log_softmax_V(x/T)[idx]) = log_softmax_K(x/T[idx])

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

  • New vocab_parallel_gather_columns in model_utils.py (beside its sibling vocab_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 existing gather_logits_at_global_indices (whose mask + all_reduce(SUM) construction keeps gradients on the owning shard).
  • _direct_topk_kl gathers K columns and softmaxes within the subset; docstring updated.
  • CP behavior unchanged: the student stays CP-local, per-position; the masked reduction is untouched.
  • fp32/temperature semantics preserved exactly (logits.float() / T ordering).

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 live in tests/unit/algorithms/test_loss_functions.py rather than tests/unit/distributed/test_model_utils.py even though the new helper is in model_utils.py: these cases are CPU-only, matching the CPU-synthetic section of the loss tests, whereas tests/unit/distributed/test_model_utils.py is Ray/NCCL-gated (13 of its 14 tests require GPUs). Happy to move them if you'd rather group by module.
  • Tests: test_vocab_parallel_gather_columns_no_tp (column slice + fp32 upcast) and test_subset_softmax_matches_full_vocab_reference (parametrized over temperature; asserts forward values and gradients match the previous formulation) in tests/unit/algorithms/test_loss_functions.py.
  • Validation: equivalence verified locally (forward + grads, T=1.0/2.0); ruff check / format clean.
  • Docs: N/A (behavior-identical optimization; method docstring updated in place).

cc @terrykong @avenkateshha @yfw

tianyi-zhang-02 and others added 2 commits July 17, 2026 14:16
_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]>
@tianyi-zhang-02
tianyi-zhang-02 requested review from a team as code owners July 22, 2026 19:07
@copy-pr-bot

copy-pr-bot Bot commented Jul 22, 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.

…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]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Jul 24, 2026
@tianyi-zhang-02

Copy link
Copy Markdown
Contributor Author

CUDA measurements + a real 2-rank TP run

Follow-up to the CPU numbers above, on an NVIDIA GeForce RTX 4090, torch 2.13.0+cu130 / CUDA 13.0, V=151,936, K=64, T=2.0, bf16 logits. Peak is torch.cuda.max_memory_allocated() over forward+backward, reset per run, median of 3 timed iterations — note this is the whole working set, so it includes the [B, T, V] bf16 student logits that both paths hold, and is therefore not the same quantity as the 2.32 GiB [T, V] fp32 intermediate cited above.

seq_len peak, main peak, this PR fwd+bwd, main fwd+bwd, this PR
2048 4.06 GiB 1.16 GiB 23.3 ms 1.2 ms
4096 8.12 GiB 2.32 GiB 47.4 ms 1.7 ms
8192 16.23 GiB 4.64 GiB 95.0 ms 3.2 ms
12288 24.35 GiB ⚠️ 6.96 GiB 606.7 ms 5.1 ms

Peak memory is a flat 3.50× at every length. ⚠️ = exceeded the card's 23.99 GiB of physical VRAM; that row did not OOM only because the driver spilled to host RAM, so its 606.7 ms is spill-dominated and not a like-for-like compute number. The defensible statement is the capacity one: on a 24 GB card the current formulation stops fitting somewhere between 8192 and 12288 tokens, where this PR is still at 6.96 GiB.

The cost is also flat in vocab_topk, which is really the motivation: at seq_len 4096, main is 8.12 GiB / ~47 ms for every K in {8, 16, 32, 64, 128, 256} — you pay for all 151,936 columns whether you asked for 8 of them or 256 — against 2.32 GiB / 1.5–2.0 ms for this PR across the same range.

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 ProcessGroup and genuinely vocab-sharded student logits (V=32,768, V_local=16,384, K=64), with the pre-PR full-vocab formulation computed single-process on the unsharded logits as ground truth:

rank top-K columns owned Δ loss vs reference grad rel. L2 grad outside owned columns
0 35 0.0e+00 5.0e-07 0.0e+00
1 29 0.0e+00 5.0e-07 0.0e+00

The 64 columns split 35/29 across the ranks, so the all_reduce(SUM) does real cross-rank work rather than a degenerate one-sided gather. Loss matches the unsharded reference exactly on both ranks, gradients match to fp32 round-off, and each shard receives gradients only on its own columns.

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Jul 27, 2026

@yuki-97 yuki-97 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.

@tianyi-zhang-02 thanks for the contribution! @RayenTian @avenkateshha could you help review?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Jul 30, 2026
@RayenTian RayenTian added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Aug 2, 2026
@RayenTian

RayenTian commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Overall LGTM. Would please update the branch then we can trigger CI? @tianyi-zhang-02
Additionally, do you happen to have any test results, such as wandb curve, to show the convergence of change? If yes, would you please attach them in PR doc?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-customer Waiting on the original author to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Aug 2, 2026
@tianyi-zhang-02

tianyi-zhang-02 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

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):

PR #3314: loss trajectories, loss gap, and parameter divergence over 2000 steps across 3 seeds

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: get_distillation_topk_logprobs_from_logits in the same file already gathers the K columns and log_softmaxes within the subset, so this mostly brings _direct_topk_kl in line with the path right next to it.

tianyi-zhang-02 added a commit to tianyi-zhang-02/RL that referenced this pull request Aug 3, 2026
@RayenTian

RayenTian commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Thanks a lot for experiences results!Triggered CI.

@RayenTian

Copy link
Copy Markdown
Contributor

/ok to test 4fa15ea

@copy-pr-bot

copy-pr-bot Bot commented Aug 3, 2026

Copy link
Copy Markdown

/ok to test 4fa15ea

@RayenTian, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@RayenTian

Copy link
Copy Markdown
Contributor

/ok to test 4fa15ea

@copy-pr-bot

copy-pr-bot Bot commented Aug 3, 2026

Copy link
Copy Markdown

/ok to test 4fa15ea

@RayenTian, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@RayenTian

Copy link
Copy Markdown
Contributor

/ok to test 63e0485

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-customer Waiting on the original author to respond label Aug 3, 2026
@yuki-97
yuki-97 enabled auto-merge (squash) August 3, 2026 05:34
@yuki-97
yuki-97 merged commit 5f5d82b into NVIDIA-NeMo:main Aug 3, 2026
80 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) community-request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MOPD top-k same-vocab KL materializes a full-vocab student log-softmax that cancels out of the loss

4 participants