Repository navigation
fix(model-utils): reuse the logits storage for the chunked logprob grad - #4973
Conversation
ChunkedDistributedLogprob.backward allocated a zeros_like grad the size of the vocab-parallel logits. With an fp32 LM head that is a second full [B, S, V/TP] fp32 tensor (about 12 GiB for a 98k-token CP shard), and the SWE PPO recipe OOMed at step 2. Add an opt-in reuse_logits_storage flag: the grad is written into the fp32 logits' own storage, since each chunk is read before it is overwritten. It is only safe when the op is the logits' sole consumer, so it is enabled only on the fused packed loss path; other callers (non-fused packing, OPD_FULL with a reference KL) keep the zeros_like grad. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
After backward the logits tensor holds the grad, so reading it as logits gives wrong values. Say so in the reuse_logits_storage docstring. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
The unfiltered KL logprob call reads the same packed logits again; it is safe only because that call runs with chunking off. Pass use_chunking instead of True so the condition is in the code rather than implied. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
test_sequence_packing_fusion_vs_baseline never passed chunk_size, so no test ran the logits-storage reuse under real TP/CP all-reduces. Parametrize it over chunk_size None and 3. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
…b shim ChunkedDistributedLogprob now takes reuse_logits_storage after inference_only. _FullVocabLogprob unpacked inference_only as the last argument, so with zero_train_gen_mismatch, sequence packing and logprob_chunk_size it read reuse_logits_storage as inference_only and inference_only as the TP group, and failed with "'bool' object has no attribute 'size'". Split the arguments at inference_only's fixed position and replay the trailing ones in the backward. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
…-reuse-logits Signed-off-by: bg51717 <[email protected]>
bg51717
left a comment
There was a problem hiding this comment.
Claude self-review. No correctness bugs found: the read-before-overwrite order, the backward return arity, the shim argument split, and the single opt-in call site (loss_input.py:541) all check out. Inline comments cover the bf16 scope, a comment nit, the shim index, and two test nits. Not run locally (no GPU); ruff check/format pass.
Description notes:
- The llama run also needs
policy.megatron_cfg.defer_fp32_logits=true: its basegrpo_math_1B.yaml:282sets it toFalse, andsetup.py:2086asserts it whenlogprob_chunk_sizeis set. Consider listing it with the other overrides. - AI-3 on #4776 (r4385915311) asked for the SWE run; one line on why nanov3 was used instead (same
S_local × V/TPbuffer) would close that thread.
Generated by Claude Code
Each chunk is upcast to fp32 (a copy) before its slice is overwritten, and the grad is rounded to the logits' dtype exactly as the old zeros_like buffer was, so bf16 logits can take their grad in place as well. The unit test now runs fp32 and bf16 and uses the single_rank_collectives fixture. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Snapshot the packed logits before backward and assert they were overwritten iff chunk_size is set, so a flag that stops reaching the backward fails the test instead of silently falling back to zeros_like. Also run the comparison with bf16 logits. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Split _FullVocabLogprob into one subclass per replaced function whose apply mirrors that function's forward, so inference_only, the group and chunk_size bind by name instead of positional indices that shift when a parameter is added. A CPU test asserts each apply lists the same parameters as the replaced forward. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
The shim now binds arguments by name, so the replaced function receives reuse_logits_storage=False explicitly when the caller omits it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
|
Updated the description: the llama run now lists |
|
/ok to test 075d9b0 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
Reviewed all seven changed files and their directly affected paths across three focused reviews. No correctness blockers found.
The current source addresses the earlier bf16, argument-binding, fixture-reuse, and storage-overwrite-test feedback. One low-severity maintenance suggestion remains: (C1) shorten the added in-function comment while preserving its ownership warning.
Static inspection only; tests, linters, benchmarks, and convergence runs were not executed.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
|
/ok to test 9b7575f |
…-reuse-logits Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Score centering takes the policy log-probs at the sampler's top-k ids from the same packed logits as the chunked logprob. Writing the chunked grad into those logits then breaks the second consumer's backward, so turn the reuse off whenever score centering is on. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main and resolve conflicts.
Thanks for isolating the chunked-logprob storage optimization and preserving the default behavior of other kernel callers.
The fp32/bf16 memory comparisons and 50-step numerical curves in the description make the effect clear. Thanks also for the extensive self-review.
Scope: Logits-storage reuse, affected callers, compatibility shims and tests, at 9b7575f
Checked:
- Gradient computation — fp32/bf16 chunks finish reading logits before overwriting their storage; default-off callers preserve shared and narrow-view logits.
- Shim compatibility — explicit signatures preserve argument forwarding, and backward recomputation uses a leaf tensor that cannot trigger reuse.
- Unit coverage — existing CI logs confirm 32 relevant cases passed, including separate TP2 and CP2 fusion cases in fp32/bf16; larger configurations skipped on two-GPU runners.
- Convergence — reviewed the posted 50-step reward, loss, gradient-norm and logprob-agreement comparisons; an automated e2e convergence regression is still requested below. No local training or tests were run.
Remaining comments are on:
- An explicit Megatron reuse flag, disabled by default in the config definition and all applicable base YAMLs and reference configs.
- Setup checks requiring positive
policy.logprob_chunk_sizeand disabledloss_fn.score_centeringwhen reuse is enabled, with a config note to extend these checks for future logits consumers. - An e2e test that enables the reuse path and includes an automated reward/convergence assertion in its checks.
nit
- Clarify read-before-overwrite wording in the code comment and PR description, without attributing safety to an fp32 cast or copy.
Generated by Codex
…re-overwrite Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Gate the chunked logprob's in-place grad behind policy.megatron_cfg.reuse_logits_storage (default false in every exemplar). Setup rejects the flag unless the fused, chunked sequence-packing path that reads it is configured, and SingleController rejects it with score centering, which reads the packed logits again. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Base it on the GB200 1B Megatron GRPO nightly so it differs from that recipe only in the flags that put the loss on the reuse path. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
The GB200 runs took ~12.1 s per step with the reuse on and off; keep the base recipe's 13.4 s gate. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
|
/ok to test 6ac3d28 |
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
|
/ok to test 0289ee8 |
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main; the PR is 19 commits behind and the "Check if PR branch is up to date" job allows at most 10.
Thanks for addressing the opt-in, ownership and convergence-regression requests from the previous round.
Scope: fix commits 57da4c7 through 0289ee8, checked against the previous threads, plus a scan of the changed files for new issues.
Checked:
- Explicit opt-in — the config flag reaches the packed backward, and setup rejects missing positive chunking and the score-centering combination; the future-consumer warning is retained beside the field.
- Convergence regression — the registered GB200 recipe enables reuse and includes an automated reward gate at step 500;
reuse-logits.sh:38–41. - Unit behavior — head CI logs confirm flag propagation, storage/gradient checks, setup rejection and shim-contract cases passed; no local tests or training were run.
Remaining comments are on:
- Rejecting explicit reuse with training top-k/top-p instead of silently disabling it.
nit
- Add the default-off flag to the standalone research template.
- Remove the repeated runtime score-centering/reuse check and its dedicated unit test; keep setup validation.
Generated by Codex
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: bg51717 <[email protected]>
|
/ok to test 825d665 |
Conflicts: - grpo.py: keep _validate_val_sampling and accept trtllm as main (NVIDIA-NeMo#4123) does. The TRT-LLM server picks the train or validation profile by temperature/top_p like the vLLM one, so the val_top_k rule applies to both; main's "val_top_k is not supported" check is dropped. - loss_input.py: keep the replay/non-replay split; pass main's (NVIDIA-NeMo#4973) reuse_logits_storage on the non-replay logprob call. - vllm/config.py: keep resolve_vllm_logprobs_mode and main's resolve_vllm_kv_cache_dtype (NVIDIA-NeMo#5028). - test_model_utils.py: keep both sides' new tests. - interfaces.py comment and test_setup_accepts_val_sampling_on_gym_path updated to the val_top_k rule. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Hayate Iso <[email protected]>
Main's #4973 makes LossPostProcessor read megatron_cfg.reuse_logits_storage on the fused packing path, so the fused case of test_non_csd_packing_wrapper_reads_boundaries_from_the_note failed with KeyError: 'megatron_cfg' after the rebase onto main. Give its config stub an empty megatron_cfg, as every Megatron config has one. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adithya Hanasoge <[email protected]>
From #4776 (comment)
What
ChunkedDistributedLogprob.backwardallocates azeros_likegrad the size of the vocab-parallel logits. This adds an opt-inreuse_logits_storageflag that writes the grad into the logits' own storage (each chunk is read before its slice is overwritten). It is set bypolicy.megatron_cfg.reuse_logits_storage(defaultfalsein every exemplar) and takes effect only on the fused packed loss path with chunking: the unfiltered KL call reads the logits again, but only when chunking is off. Setup rejects the flag unless that path is configured, and rejects it together withloss_fn.score_centering, which reads the packed logits a second time.When it applies
Any algorithm, when all of these hold:
policy.megatron_cfg.reuse_logits_storage=truesequence_packing.enabled=trueandfuse_loss=truelogprob_chunk_sizeset, no top-k / top-pLossInputType.LOGPROBloss (GRPO, DAPO, PPO actor; not the PPO value model)loss_fn.score_centering=falseNo shipped recipe turns it on except the new GB200 nightly below.
Memory saving
Saving per GPU = the grad buffer no longer allocated:
S_local = train_mb_tokens / CPis one CP rank's tokens in a packed micro-batch,V / TPis one TP rank's vocab shard.Measured with
grpo-dapomath17k-nanov3-30BA3B-8n4g-megatron-trtllm.yamlon GB200, keeping its TP2 × CP4 × EP8 layout and sequence length (so the buffer matches the full recipe), withfuse_loss=true,fp32_lm_head=true, and a smaller run: 2 nodes, vLLM, 512 samples/step, 5 steps.Expected:
S_local = 49152 / 4 = 12288,V / TP = 131072 / 2 = 65536→ 3.00 GiB.Peak
max_memory_allocatedper GPU per train step (GiB, two ranks):Steps 2–4 average ~2.9 GiB; the spread comes from different rollouts.
With
fp32_lm_head=false(bf16 logits, as the shipped recipes run), same setup, expected12288 × 65536 × 2 B= 1.50 GiB:Steps 2–4 average ~1.4 GiB.
The SWE recipe from #4776 (
grpo-nanov3-30ba3b-3n8g-megatron-dynamo-swe1.yaml) needs too many resources for an on/off comparison. It uses the same model, and the saving depends only onS_local,V / TPand the logits dtype, not on the environment, so the nanov3 math run stands in for it. With its TP4 × CP2 and 196608-token micro-batch:S_local = 98304,V / TP = 32768→ 12 GiB with fp32 logits, 6 GiB with bf16.Numerical behavior
The
grpo-dapomath17k-nanov3experiment loss and grad norm are noise. So training metrics are compared ongrpo-llama3.2-1b-instruct-1n4g-megatron.yaml(nightly) withfp32_lm_head=true,defer_fp32_logits=true(required withlogprob_chunk_size),logprob_chunk_size=256,fuse_loss=true, 50 steps. Its memory is not used above: at this model size the refit staging buffer (30% of free memory) sets the peak, not the training step.Rollouts come from vLLM and drift apart after the first steps, so on and off should match as curves:
train/reward: mean reward per step; on and off should learn at the same rate.train/loss,train/grad_norm: the quantities the flag could change.train/token_mult_prob_error: training vs. generation logprob agreement; unchanged means the forward is unchanged.Tests
test_sequence_packing_fusion.py:test_sequence_packing_fusion_vs_baselineruns no-chunk + reuse, chunked, and chunked + reuse with fp32 / bf16 logits, so the reuse branch runs under real TP/CP all-reduces (cp1/cp2 × tp1/tp2 on GB200); it also asserts the packed logits are overwritten iff reuse is on andchunk_sizeis set.test_model_utils.py: reuse on/off for fp32 and bf16, leaf logits, shared and narrowed logits;prepare_packed_loss_inputreuses only with the flag and chunking, and raises with score centering.test_megatron_setup.py: the flag is rejected without sequence packing,fuse_lossor a positivelogprob_chunk_size.single_controller/test_setup.py: score centering is rejected with the flag on.test_zero_train_gen_mismatch.py: the logprob shim'sapplysignatures match the replaced functions, and the shim passesreuse_logits_storagethrough to the backward.grpo-llama3.2-1b-instruct-1n4g-megatron-reuse-logits: the 1n4g Megatron GRPO nightly plusfuse_loss,logprob_chunk_size=128,defer_fp32_logitsand the flag. It keeps the base recipe's gates (train/rewardat step 500 > 0.1,token_mult_prob_error< 1.1, step time < 13.4 s). 500-step runs with the reuse on and off: