Repository navigation
fix(sc): reduce and finalize gradients once per step, not per chunk - #3660
Conversation
|
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. |
10e7576 to
f27a8ea
Compare
|
/ok to test f27a8ea |
saumishr
left a comment
There was a problem hiding this comment.
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:
grad_normvs step- loss and task reward over >= 100 steps
- peak HBM at the
lp_prep_exit/train_prep_exitboundaries — that is whatkeep_train_buffersgives up, and what the new instrumentation was added to measure - 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.
|
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 [PERF-EVIDENCE] — still owed. One caveat on this commit: I could not execute the unit tests locally. The host has no |
7441354 to
7c80e7c
Compare
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]>
7c80e7c to
e07e788
Compare
|
/ok to test e07e788 |
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]>
|
Thanks @yuki-97 — all four addressed in 4447ddf, with a reply on each thread.
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 Still owed from the review body, unchanged: a real multi-chunk test (needs 1–2 GPUs; Same caveat on this commit as the last: I could not run the mcore-marked tests locally — |
|
/ok to test 4447ddf |
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
# Add a code snippet demonstrating how to use thisBefore your PR is "Ready for review"
Pre checks:
Additional Information