Skip to content

fix(sc): reduce and finalize gradients once per step, not per chunk - #3660

Merged
terrykong merged 2 commits into
NVIDIA-NeMo:mainfrom
saumishr:fix/sc-finalize-grads-once-per-step
Aug 18, 2026
Merged

terrykong merged 2 commits into
NVIDIA-NeMo:mainfrom
saumishr:fix/sc-finalize-grads-once-per-step

Conversation

@saumishr

Copy link
Copy Markdown
Contributor

The SingleController streaming train path feeds N chunks into a single optimizer step, but two paths still behaved as though each chunk were a step of its own.

mcore calls config.finalize_model_grads_func at the end of every forward_backward_func invocation, so under streaming it fired once per chunk. Nothing already overridden gated it: it reaches finish_grad_sync directly, and model.no_sync() only clears is_last_microbatch, which finish_grad_sync ignores. With a distributed optimizer the reduce-scatter also writes into the buffer it reads, leaving this rank's shard DP-summed and the remainder local for the next chunk to accumulate on top of. Null the hook for the step's duration and invoke the saved callable once from _finish_train_step_body with num_tokens=None, since this path applies its own 1/N. Relocating rather than dropping it matters because it also owns the non-tensor-parallel/layernorm all-reduce across TP, the tied word- and position-embedding all-reduces across PP, the MoE router expert-bias update, and reset_model_temporary_tensors.

prepare_for_lp_inference offloaded the grad buffers on every logprob detour. mcore's offload_to_cpu(move_grads=True) does not copy the gradients anywhere, it resizes their storage to 0, and the matching reload zeroes it; param.main_grad stays a valid view throughout, so nothing raises and every chunk but the last is silently discarded against a 1/N normalizer that still counts them all. Add keep_train_buffers, which the controller passes as step_open.

Record the chunk count per step alongside grad_norm and sample the CUDA allocator at the phase boundaries under debug, so the accumulation is greppable from a run rather than inferred from timer ratios.

Cover both bugs in tests: the finalize hook is saved, nulled, invoked exactly once with num_tokens=None whether the step arrived as one chunk or five, and restored on finish and abort; the grad buffers survive a logprob detour mid-step; and the controller passes keep_train_buffers=step_open across a multi-chunk step.

What does this PR do ?

Add a one line overview of what this PR aims to accomplish.

Issues

List issues that this PR closes (syntax):

Usage

  • You can potentially add a usage example below
# Add a code snippet demonstrating how to use this

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

  • ...

@saumishr
saumishr requested review from a team as code owners August 16, 2026 04:20
@copy-pr-bot

copy-pr-bot Bot commented Aug 16, 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.

@cursor

cursor Bot commented Aug 16, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@saumishr saumishr added the CI:L1 Run doctests, unit tests, and functional tests label Aug 16, 2026
@saumishr
saumishr force-pushed the fix/sc-finalize-grads-once-per-step branch from 10e7576 to f27a8ea Compare August 16, 2026 04:29
@NVIDIA-NeMo NVIDIA-NeMo deleted a comment from copy-pr-bot Bot Aug 16, 2026
@saumishr

Copy link
Copy Markdown
Contributor Author

/ok to test f27a8ea

@saumishr
saumishr requested review from mehraakash and yuki-97 August 16, 2026 04:34

@saumishr saumishr left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review summary

Both bugs are real and were verified independently against the pinned Megatron-Core: finalize_model_grads_func is invoked at the end of every forward_backward_func call and reaches finish_grad_sync directly, and offload_to_cpu(move_grads=True) resizes grad storage to 0 rather than copying it. Seven of the eight upstream claims in the new comments check out line by line. The eighth is wrong and is the pg_collection comment flagged inline.

Two findings that could not be anchored to a diff line:

[PERF-EVIDENCE] The PR ships no numbers, and this is not a small perturbation

Pre-fix, the per-chunk finish_grad_sync all-reduced a growing buffer at every chunk boundary and the finish path reduced it again, and the logprob detour freed all but the last chunk's contribution against an N-chunk normalizer. Gradient magnitude on the streaming path therefore moves substantially, which moves clip_grad behavior and the effective learning rate with it — meaning any hyperparameters tuned on that path were tuned against a broken normalizer.

Could we see before/after on grpo-llama3.1-8b-instruct-2n8g-async-1off-single-controller-streaming2.yaml, same seed? It is the only nightly recipe with min_groups_for_streaming_train below num_prompts_per_step (16 vs 64), so the only one that produces multiple chunks:

  1. grad_norm vs step
  2. loss and task reward over >= 100 steps
  3. peak HBM at the lp_prep_exit / train_prep_exit boundaries — that is what keep_train_buffers gives up, and what the new instrumentation was added to measure
  4. a one-chunk control showing the change is inert when chunks == 1

[TEST] Nothing that can run drives more than one chunk per optimizer step

Both bugs are chunk-count-dependent, but the GPU parity A/B in tests/unit/models/policy/test_megatron_split_parity.py — which test_megatron_split_state.py's own docstring defers to for numerical equivalence — issues exactly one train_microbatch fan-out per step, and tests/unit/single_controller/test_train_pump.py:317, the only end-to-end pump test against real mcore, pins min_groups_for_streaming_train=num_prompts. Every new assertion in this PR sits on mocks where megatron_forward_backward, scale_gradients, finish_grad_sync and move_model are all fakes, so none of them can observe a wrong gradient.

The pump test is the cheaper and better-targeted place to add a chunked variant — single GPU, and mcore's grad-buffer offload/reload is not DP-dependent, so a numeric assertion there exercises the logprob-detour bug for real. A parity variant at chunks=2, tp=1 (DP=2) is what would cover the reduce. Both files are outside this diff, so a follow-up is fine.

One thing worth watching when CI lands: since the hook was non-None before this PR (Bridge binds it), the single-chunk split path may have been reducing twice, in which case the existing parity baseline shifts. I could not settle that without running it.


Also noted, below the bar for individual comments: a .v2 bump for the streaming2 recipe and its GB200 twin — tests/test_suites/README.md lists "convergence bug fix" as an explicit .vN trigger, though there are no stored numeric baselines to invalidate here, only loose threshold gates, so leaving this to a maintainer; a docstring sentence recording that the fix depends on mcore gating reload_from_cpu on grad_data_size > 0, since prepare_for_training runs on every chunk with move_grads=True; tests for the two restore-on-exception paths; a TestLogGpuMem pinning the "do not reset peak counters when DEBUG is off" contract.

Checked and dropped: keyword-only * on keep_train_buffers; raise NotImplementedError in the interface (every abstract sibling uses pass); the dtensor docstring reword (they already say what would have been asked); a _MCORE_STEP_OVERRIDES table; and a suspected OOM from keep_train_buffers overriding offload_optimizer_for_logprob — that knob is false throughout the streaming recipe's config chain, prepare_for_training re-onloads on the next call, and the grad buffer that must stay resident is larger than the DP-sharded optimizer state anyway.


Reviewed by 5 specialist agents plus 2 adversarial passes: 13 findings confirmed, 9 disputed, 12 downgraded. Two self-overturns, both in the PR's favor — the pg_collection finding was nearly escalated to "crashes MoE recipes" before use_mpu_process_groups(required_pgs=None) proved it populates tp_dp_cp, and a calculate_per_token_loss compounding theory died on the loss wrapper's return arity. Repo linters: NOT RUN (no uv/pre-commit on the review host). No GPU, so no runtime verification of the new tests.

Comment thread nemo_rl/algorithms/single_controller.py Resolved
@saumishr

Copy link
Copy Markdown
Contributor Author

Pushed ab35ed0 with fixes for all six inline comments; replies on each thread. The two findings in the review body that were not anchored to a diff line:

[TEST] the multi-chunk case — not in this commit. Every new assertion still sits on mocks, and the two places that could drive a real multi-chunk step are both outside this diff and both need hardware I do not have in front of me: a chunks=2, tp=1 variant of the parity A/B (needs DP=2, so 2 GPUs) and a chunked variant of test_train_pump.py against real mcore (1 GPU). The pump one is the better target — mcore's grad-buffer offload/reload is not DP-dependent, so a numeric assertion there exercises the logprob-detour bug for real on a single GPU. Happy to take it as a follow-up PR, or to fold it in here if you would rather not merge without it.

[PERF-EVIDENCE] — still owed. grpo-llama3.1-8b-instruct-2n8g-async-1off-single-controller-streaming2.yaml is the only nightly recipe that produces multiple chunks, and I have not run the before/after on it yet. Worth flagging that the [step] line now actually prints, so grad_norm vs chunk count is greppable straight out of the driver log, which is what that comparison needs.

One caveat on this commit: I could not execute the unit tests locally. The host has no uv, and its venv is missing transformer_engine (so test_megatron_split_state.py skips at the megatron.bridge import) and enough of the CPU-only chain that the dtensor files will not collect either. Everything here is py_compile-clean and reviewed by hand, but CI is the first real run — flag anything it turns up and I will fix it.

@saumishr
saumishr requested a review from terrykong August 18, 2026 03:02
@saumishr
saumishr force-pushed the fix/sc-finalize-grads-once-per-step branch 2 times, most recently from 7441354 to 7c80e7c Compare August 18, 2026 03:11
@saumishr
saumishr requested a review from a team as a code owner August 18, 2026 03:11
The SingleController streaming train path feeds N chunks into a single
optimizer step, but two paths still behaved as though each chunk were a
step of its own.

mcore calls config.finalize_model_grads_func at the end of every
forward_backward_func invocation, so under streaming it fired once per
chunk. Nothing already overridden gated it: it reaches finish_grad_sync
directly, and model.no_sync() only clears is_last_microbatch, which
finish_grad_sync ignores. With a distributed optimizer the reduce-scatter
also writes into the buffer it reads, leaving this rank's shard DP-summed
and the remainder local for the next chunk to accumulate on top of. Null
the hook for the step's duration and invoke the saved callable once from
_finish_train_step_body with num_tokens=None, since this path applies its
own 1/N. Relocating rather than dropping it matters because it also owns
the non-tensor-parallel/layernorm all-reduce across TP, the tied word- and
position-embedding all-reduces across PP, the MoE router expert-bias
update, and reset_model_temporary_tensors.

The saved callable is Megatron-Bridge's partial(finalize_model_grads,
pg_collection=...), so the per-step call passes no pg_collection keyword and
lets that binding through. That is group-equivalent to what the schedule
passed per chunk: megatron_forward_backward calls forward_backward_func
without a collection, so the schedule built _build_default_pg_collection() and
overrode the binding with it, and both carry the same groups and both populate
tp_dp_cp, the field the MoE expert-bias update asserts on.

prepare_for_lp_inference offloaded the grad buffers on every logprob
detour. mcore's offload_to_cpu(move_grads=True) does not copy the
gradients anywhere, it resizes their storage to 0, and the matching reload
zeroes it; param.main_grad stays a valid view throughout, so nothing
raises and every chunk but the last is silently discarded against a 1/N
normalizer that still counts them all. Add keep_train_buffers, which the
controller passes as step_open.

Record the chunk count per step alongside grad_norm, and sample the CUDA
allocator at the phase boundaries under debug, so the accumulation is
greppable from a run rather than inferred from timer ratios. The worker's
summary is emitted from rank 0 only, since its fields are already DP- or
MP-reduced, and the per-chunk record is guarded by isEnabledFor because its
arguments are evaluated at the call site whether or not the record is emitted
and four of them are .item() host-device syncs.

None of that could reach a run's output as first written. __init__.py's bare
basicConfig() installs a root handler and leaves the root logger at WARNING,
and every later basicConfig returns early because handlers already exist, so
virtual_cluster.py's level=INFO is a no-op and nothing raises the level on the
`nemo_rl` logger. Every log.info and log.debug in the package was dropped: a
68-node run on this branch produced zero matches for the new records. Set the
level there from NRL_LOG_LEVEL, defaulting to INFO, on the `nemo_rl` logger
rather than on root so that raising it does not also enable debug output for
torch, ray and every other third-party logger. DEBUG additionally turns on the
per-chunk and allocator records, which are per chunk per rank.

Cover both bugs in tests: the finalize hook is saved, nulled, invoked
exactly once with num_tokens=None whether the step arrived as one chunk
or five, and restored on finish and abort; the grad buffers survive a
logprob detour mid-step; the controller passes keep_train_buffers=step_open
across a multi-chunk step; the same flag gates the optimizer offload on both
dtensor workers; the step summary is logged at INFO from rank 0 and nowhere
else; and the chunk record stays silent at INFO but appears under DEBUG.

Signed-off-by: Saurabh Mishra <[email protected]>
@saumishr
saumishr force-pushed the fix/sc-finalize-grads-once-per-step branch from 7c80e7c to e07e788 Compare August 18, 2026 03:19
@saumishr

Copy link
Copy Markdown
Contributor Author

/ok to test e07e788

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

thanks @saumishr , fix LGTM, left some minor comments.

Comment thread nemo_rl/__init__.py Resolved
Review follow-up on the split-step gradient fix.

The split-step orientation header still named start_grad_sync +
finish_grad_sync as the step's reduce site and listed one nulled hook.
Both are now the relocated finalize_model_grads_func call and three hooks,
pointing at begin_train_step rather than restating what it documents.

Drop the finish_grad_sync fallback for a missing finalize hook.
Megatron-Bridge's _update_model_config_funcs binds the hook whenever an
optimizer exists and an open train step implies one, so the branch was
unreachable -- and reaching it would have reduced across DP while silently
skipping the TP layernorm all-reduce, the tied word- and position-embedding
all-reduces across PP, the MoE router expert-bias update and
reset_model_temporary_tensors, i.e. wrong gradients with no error. Assert
instead, before anything is dispatched. The two tests that pinned the
fallback now pin the failure and that nothing reduces or steps.

Name the mcore invariant keep_train_buffers rests on: prepare_for_training
reloads with move_grads=True before every chunk, and reload_from_cpu
resizes and zero_()s the grad buffer only if grad_data_size > 0, a counter
set only by a matching offload_to_cpu. Suppressing the offload keeps it at
0, so the reload is a no-op; an mcore change dropping that guard would
silently reinstate the bug.

Document NRL_LOG_LEVEL in docs/debugging.md. Defaulting it to INFO changes
what every entrypoint emits, and DEBUG is what turns on the new per-chunk
and CUDA-allocator records.

Trim the two densest comment blocks to their invariants, dropping the
derivations that established correctness rather than constraining a future
reader: the force_all_reduce equivalence, the BucketGroup.finish_grad_sync
internals, and the schedules.py source quote.

Signed-off-by: Saurabh Mishra <[email protected]>
@saumishr
saumishr requested a review from a team as a code owner August 18, 2026 16:23
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Aug 18, 2026
@saumishr

Copy link
Copy Markdown
Contributor Author

Thanks @yuki-97 — all four addressed in 4447ddf, with a reply on each thread.

  • Stale orientation header. Item 1 now names the relocated finalize_model_grads_func call as the step's reduce site, start_grad_sync only as the overlap_grad_reduce precondition. Item 2 lists all three nulled hooks and defers to begin_train_step for the detail instead of restating it, so the two cannot drift apart again.
  • The grad_data_size > 0 reload invariant. Named in the keep_train_buffers docstring, along with the consequence: an mcore change dropping the guard, or zeroing unconditionally, silently reinstates the bug. You were right that the reload is the load-bearing half — suppressing the offload only matters because the matching reload is a no-op when nothing was offloaded.
  • NRL_LOG_LEVEL. Documented in docs/debugging.md under a new "Control Log Verbosity" section, first on the page. Added that the level applies to the nemo_rl logger rather than root, and that setting it in the driver environment covers Ray workers.
  • The unreachable else. Replaced with an assert, hoisted above the start_grad_sync block so nothing is dispatched before the check. A bare finish_grad_sync fallback was the worst of the three options — it reduces across DP and silently skips the TP layernorm all-reduce, the tied-embedding all-reduces across PP, the MoE expert-bias update and reset_model_temporary_tensors. Bridge binds the hook under if optimizer is not None and an open step implies an optimizer, so the branch really was dead; the assert message points at _update_model_config_funcs so a failure blames setup rather than the step that noticed. The two tests that pinned the fallback now pin the failure.

Also took the trimming pass you offered: the block you flagged is down from 47 comment lines to ~25. I dropped the reasoning that established correctness (the force_all_reduce equivalence, the BucketGroup.finish_grad_sync internals, the schedules.py source quote) and kept the two by-omission arguments, since those are what a future edit would break by helpfully passing something.

Still owed from the review body, unchanged: a real multi-chunk test (needs 1–2 GPUs; test_train_pump.py is the better target) and the before/after on ...single-controller-streaming2.yaml. Happy to take either as a follow-up or fold in here.

Same caveat on this commit as the last: I could not run the mcore-marked tests locally — megatron is not importable on this host and the repo pins Python 3.13.14 against a 3.13.13 interpreter, so uv cannot build the env. ruff format and ruff check are clean and both changed files are py_compile-clean; CI is the first real run of the two rewritten tests.

@saumishr

Copy link
Copy Markdown
Contributor Author

/ok to test 4447ddf

@mehraakash mehraakash 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.

LGTM, Tested!

@terrykong
terrykong enabled auto-merge (squash) August 18, 2026 23:47
@terrykong
terrykong merged commit f8ed295 into NVIDIA-NeMo:main Aug 18, 2026
99 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L1 Run doctests, unit tests, and functional tests Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants