Skip to content

feat(megatron): split-API train-step state machine on MegatronPolicyWorker - #2683

Merged
yuki-97 merged 20 commits into
NVIDIA-NeMo:mainfrom
mehraakash:asyncrl/split_train_mcore
Jul 8, 2026
Merged

yuki-97 merged 20 commits into
NVIDIA-NeMo:mainfrom
mehraakash:asyncrl/split_train_mcore

Conversation

@mehraakash

@mehraakash mehraakash commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

📚 Stacked PR — 3-PR async-GRPO split-API series (top → bottom):

Stack-aware base retargeting is unavailable for fork PRs (gh-stack limitation); manual header. Locally rebased so each layer's branch contains its parents' commits — but GitHub's "Files changed" shows cumulative diff. Per-layer scope: read commits authored on this branch.


Adds begin_train_step / train_microbatch / finish_train_step / abort_train_step on MegatronPolicyWorkerImpl, mirroring the DTensor v1/v2 implementations but adapted for mcore's contiguous grad bucket + pipeline-schedule reduce path.

Mechanism:

  • begin_train_step: zero_grad_buffer + optimizer.zero_grad, store loss_fn / gbs / mbs / local_valid_seqs/toks accumulators on _train_step_state, and null model.config.grad_sync_func (saved for restore) so the PP scheduler's direct reduce dispatch cannot bypass no_sync.
  • train_microbatch(data): wrap one megatron_forward_backward invocation in with self.model.no_sync(): so mcore DDP hooks accumulate param.main_grad locally without dispatching the cross-DP reduce. Pass global_valid_seqs/toks=tensor(1.0) so the loss returns un-normalized sums; backward deposits raw d(sum)/dθ. Accumulate local mask sums + per-mb metrics + the total pipeline-microbatch count (for finish-time MoE aux-loss scaling).
  • finish_train_step: all_reduce mask sums to get true N (toks for TOKEN_LEVEL loss, seqs for SEQUENCE_LEVEL), call self.model.scale_gradients(1/N), then the one true cross-DP reduce via start_grad_sync + finish_grad_sync, optimizer.step (clips internally), restore grad_sync_func, scheduler.step(increment=gbs). Rescale per-mb metrics by 1/N (linear-in-1/N math), aggregate, surface global counts.
  • abort_train_step: restore grad_sync_func, zero_grad_buffer + zero_grad, drop state. trainer_version unchanged.

Sync train() is left untouched.

Includes CPU unit tests at tests/unit/models/policy/test_megatron_split_state.py covering the lifecycle and call-order invariants (no_sync wrap, grad_sync_func save/restore, mask-sum accumulation, N selection by loss_type, abort idempotence, MoE scaling). Marked pytest.mark.mcore so they run only in mcore-enabled CI containers.

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

  • ...

@mehraakash
mehraakash requested review from a team as code owners June 4, 2026 06:09
@copy-pr-bot

copy-pr-bot Bot commented Jun 4, 2026

Copy link
Copy Markdown

Auto-sync is disabled for ready for review pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test

@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test 3d24224

@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test cb65400

@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test 108ec17

mehraakash added a commit to mehraakash/RL that referenced this pull request Jun 8, 2026
Drives the begin/train_microbatch/finish split API in NVIDIA-NeMo#2683 and
group, per-group prepare_logprobs (when configured) -> advantage_pump
-> train_microbatch_from_meta (queued), one finish_train_step + one
clear_samples at end-of-step. Buffer capacity released per group, not
per step.

- StalenessSampler.select_one_group: picks one eligible prompt group;
  same predicate as select_indices, sort by (lag, indices[0]).
- SingleControllerConfig.target_prompt_groups_per_step: explicit per-
  step admission count; validated against min_prompt_groups_per_batch.
- _reap_in_flight_nonblocking: ray.wait(timeout=0) drain helper.
- DryRunTrainer: split-API stub with begin/microbatch/finish/abort
  invariants for dry-run tests.
- 7 streaming dry-run tests: arrival order, finish-time trainer_version
  tick, strict on-policy filter, long-tail overlap, abort idempotence,
  empty-step no-op, single clear_samples per step.

Signed-off-by: Akash Mehra <[email protected]>
@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test 5753eb4

mehraakash added a commit to mehraakash/RL that referenced this pull request Jul 7, 2026
…n path

train_microbatch returned {local_valid_seqs_mb, local_valid_toks_mb,
num_pipeline_microbatches} but no caller consumes it — the SC driver
discards the result and everything finish_train_step needs already
accumulates in the open-step state (yuki-97, PR NVIDIA-NeMo#2683 review). Return
None through the whole chain (worker body, presharded wrapper,
TQPolicy.train_microbatches_from_meta) so the per-call fan-out carries
no payload back to the driver.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test a73d1df

mehraakash and others added 20 commits July 7, 2026 17:06
…orker

Adds begin_train_step / train_microbatch / finish_train_step / abort_train_step
on MegatronPolicyWorkerImpl, mirroring the DTensor v1/v2 implementations but
adapted for mcore's contiguous grad bucket + pipeline-schedule reduce path.

Mechanism:
- begin_train_step: zero_grad_buffer + optimizer.zero_grad, store loss_fn /
  gbs / mbs / local_valid_seqs/toks accumulators on _train_step_state, and
  null model.config.grad_sync_func (saved for restore) so the PP scheduler's
  direct reduce dispatch cannot bypass no_sync.
- train_microbatch(data): wrap one ``megatron_forward_backward`` invocation
  in ``with self.model.no_sync():`` so mcore DDP hooks accumulate
  ``param.main_grad`` locally without dispatching the cross-DP reduce.
  Pass ``global_valid_seqs/toks=tensor(1.0)`` so the loss returns
  un-normalized sums; backward deposits raw d(sum)/dθ. Accumulate local
  mask sums + per-mb metrics + the total pipeline-microbatch count
  (for finish-time MoE aux-loss scaling).
- finish_train_step: all_reduce mask sums to get true N (toks for
  TOKEN_LEVEL loss, seqs for SEQUENCE_LEVEL), call
  self.model.scale_gradients(1/N), then the one true cross-DP reduce via
  start_grad_sync + finish_grad_sync, optimizer.step (clips internally),
  restore grad_sync_func, scheduler.step(increment=gbs). Rescale per-mb
  metrics by 1/N (linear-in-1/N math), aggregate, surface global counts.
- abort_train_step: restore grad_sync_func, zero_grad_buffer + zero_grad,
  drop state. ``trainer_version`` unchanged.

Sync ``train()`` is left untouched.

Includes CPU unit tests at tests/unit/models/policy/test_megatron_split_state.py
covering the lifecycle and call-order invariants (no_sync wrap,
grad_sync_func save/restore, mask-sum accumulation, N selection by
loss_type, abort idempotence, MoE scaling). Marked pytest.mark.mcore so
they run only in mcore-enabled CI containers.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
Pre-existing zero-error file from NVIDIA-NeMo#2078 (Eagle3) that was never added
to the project-includes whitelist. Carrying the fix forward in this
PR to unblock the lint job.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
The file is introduced by NVIDIA-NeMo#2692 (DTensor PR), not by this branch.
Whitelisting it here causes pyrefly to fail with 'No Python files
matched pattern' since the file does not exist on mcore.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
cloudpickle traverses globals/closures of each method when serializing
the Ray actor class. With torch 2.11, 'config' in __code__.co_names
matches torch.distributed.config (a non-pickleable ConfigModuleInstance),
breaking actor creation with:
  TypeError: cannot pickle 'ConfigModuleInstance' object
  Could not serialize the actor class ...MegatronPolicyWorker

Same workaround as the existing sync train(): read 'config' via
getattr-by-string in begin/finish/abort_train_step.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
test_megatron_split_state.py eagerly imports megatron_policy_worker
which transitively imports megatron.bridge. In non-mcore shards (Models,
Vllm, Sglang, Automodel_Policy), megatron.bridge isn't installed so
collection of this file fails, killing every other test in the shard.

pytest.importorskip stops collection cleanly when megatron.bridge is
not available. The pytest.mark.mcore filter still ensures these tests
only run in mcore shards.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
`finish_train_step` was calling both `model.start_grad_sync()` and
`model.finish_grad_sync()` unconditionally. In megatron-core's BucketGroup,
when `overlap_grad_reduce=False` (the production default), `finish_grad_sync`
internally invokes `start_grad_sync(force_all_reduce=True)`, so calling
`start_grad_sync` ourselves first dispatches the synchronous collective
once, and `finish_grad_sync` dispatches it again — scaling the reduced
gradient by ~world_size. The optimizer then steps with grads that are
DP-world-size too large.

Parity tests pass because they assert call order / state shape, not
numerical equivalence at world_size > 1. The bug surfaces only at runtime.

Fix: only call `start_grad_sync` explicitly when `overlap_grad_reduce=True`
(the async path that needs an explicit dispatch since `model.no_sync()`
gates off the per-microbatch hooks). For `overlap_grad_reduce=False`,
`finish_grad_sync` handles everything.

Tests:

- Parametrize `test_start_then_finish_grad_sync_called_after_rescale` on
  `overlap_grad_reduce` and assert the correct call order in each case.
- Add `distributed_data_parallel_config` to the test cfg fixture so the
  worker's branch can read the flag.

Reported by terrykong in PR NVIDIA-NeMo#2683 review.

Signed-off-by: Akash Mehra <[email protected]>
Two bugs around the split-API state machine fixed in one pass:

1. **no_sync_func leak (latent assertion on step 2 with PP=1).**
   `forward_backward_no_pipelining` (the PP=1 path, which is the common
   one) wraps inner microbatches in `model.config.no_sync_func` but runs
   the *last* microbatch OUTSIDE of it. Our outer `with self.model.no_sync():`
   in `train_microbatch` was therefore bypassed for the trailing MB.
   `register_grad_ready` leaked per-param counts past the explicit DP
   sync at `finish_train_step`, and the next `begin_train_step` then
   asserted on the stale counts (typically step 2).

   Fix: in `begin_train_step` also save and null `no_sync_func` (set to
   `contextlib.nullcontext`). Restore both hooks at finish/abort via the
   new `_restore_saved_grad_sync_func` helper.

   Spotted in yuki-97's PR NVIDIA-NeMo#2819 (`begin_train_step` also nulls
   `config.no_sync_func`); same fix landed here.

2. **No exception safety around the open step (terrykong, NVIDIA-NeMo#2683:640).**
   If `train_microbatch` or `finish_train_step` raised mid-body, both
   `grad_sync_func` and (now also) `no_sync_func` would stay nulled and
   future steps would run with the PP scheduler bypass disabled silently.

   Fix: extract `_train_microbatch_body` and `_finish_train_step_body`,
   wrap each entry method in try/except that calls
   `_restore_saved_grad_sync_func` before re-raising. Caller is still
   expected to invoke `abort_train_step` (idempotent on the saved
   values) to drop `_train_step_state`.

3. **Cleanup (terrykong, NVIDIA-NeMo#2683:582).** Drop dead `no_sync_active` field
   from `_split_step_state_init` — never read or written; `no_sync` is
   applied via the `with self.model.no_sync():` context manager.

Also: add module-level `log = logging.getLogger(__name__)` so the
try/except handlers can `log.exception(...)` if the restore itself fails.

Signed-off-by: Akash Mehra <[email protected]>
The split-API runs each microbatch with global_valid_*=1 (raw sums) and
applies the 1/N rescale once at finish, but the previous code used a
single inv_n for every non-min/max metric. ClippedPGLossFn normalizes
different metrics by different denominators — and some not at all — so
the single-scalar rescale was wrong for:

- Always-toks-normalized metrics under a SEQUENCE_LEVEL loss
  (token_mult_prob_error, gen_kl_error, policy_kl_error,
  js_divergence_error, approx_entropy, probs_ratio, probs_ratio_clamped).
  These came out off by ~average-sequence-length.
- Raw count metrics (num_valid_samples, num_unmasked_tokens) — these are
  ABSOLUTE counts the loss never normalized; the previous code divided
  them by N (e.g. 8.0 came out as 0.0039). Sync path passes them through
  via num_global_batches=1 → identity, then grpo.py's downstream reducer
  sums across microbatches for the global count.

Gradients are unaffected — they derive only from `loss`, whose
normalizer matches inv_n (loss-type-aware).

Fix: add module-level `_METRIC_NORMALIZATION_KIND` mapping each known
metric name to one of {toks, seqs, loss_type, none, skip}. In
`finish_train_step`, look up each metric's kind and apply the right
scale. Unknown metric names default to "loss_type" — preserves prior
behavior for any metric not in the table.

The catalog follows terrykong's review on NVIDIA-NeMo#2683 (`:789`/`:845`).
sampling_importance_ratio and is_oob_ratio have a flag-dependent
denominator (sequence_level_importance_ratios / sequence_level_loss_mask
toggles); for now they default to "loss_type" with a TODO noting the
seq-mask-tis + token-level mismatch.

Signed-off-by: Akash Mehra <[email protected]>
Two small follow-ups to terrykong's NVIDIA-NeMo#2683 review:

- :832 — capture curr_lr / curr_wd BEFORE scheduler.step so the per-mb
  metrics carry the value of THIS step, not the next. Drops the
  duplicate capture from inside the rescale loop.
- :538 — drop the misleading "Mirrors the v1/v2 implementations" line
  from the split-API block docstring; v1/v2 don't define these methods.
  Replaced with a brief surface description (begin / train_microbatch /
  finish / abort) before the mcore-specific details.

No behavior change.

Signed-off-by: Akash Mehra <[email protected]>
…tion

run_all_workers_single_data returns one dict per GPU. With TP>1 (or
CP>1, or PP>1 without last-stage gating), each DP shard has multiple
GPUs returning IDENTICAL copies of that shard's per-pp-mb metric list.
_aggregate_train_results then extends naively across all dicts and
the resulting metric list is TP*CP*(PP-last-stage-count) too long.

Every per-token metric — gen_kl_error, policy_kl_error,
js_divergence_error, probs_ratio, sampling_importance_ratio,
token_mult_prob_error, num_valid_samples — gets summed with too many
entries and ends up inflated by that same multiplicative factor.

train_from_meta avoids the issue because its sharded dispatch declares
output_is_replicated on TP/CP/PP and get_all_worker_results dedupes
before returning. finish_train_step has no data to shard so it uses
single_data dispatch; we now tag each worker result with
is_replica_leader and filter in TQPolicy.finish_train_step.

Gradient flow is unaffected (TP twins write the same main_grad and
the DP reduce ignores TP), so this is reporting-only — but the wandb
panels showing a fictitious training divergence are corrected.

Verified on grpo-llama3.1-8b-instruct-2n8g-async-1off (TP=2, PP=1,
CP=1, DP=8). Before fix: probs_ratio=2.0, gen_kl_error=5.1e-4. After
fix: probs_ratio=1.0, gen_kl_error=2.5e-4 — matches legacy GRPO.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
…PI rescale

Replace the worker-side _METRIC_NORMALIZATION_KIND table with a
metric_normalizations attribute on the loss (MetricNormalizer enum in the
loss interfaces): each loss builds the mapping in __init__ from the same
flags that pick the denominators inside __call__, so the mapping lives
next to the metric definitions and finish_train_step just applies it
(review ask on e3c872c).

This also closes the F-SEQ gap: sampling_importance_ratio now keys on
sequence_level_importance_ratios and is_oob_ratio on the TIS type
(seq-mask-tis → sequences, tis/icepop → tokens) instead of the loss_type
guess, and positive_nll_loss (a per-microbatch mean over the local
correct-token count) is no longer divided by N a second time.

Sync-path behavior is unchanged: __call__ is untouched and only the
split-path finish_train_step reads the new attribute; losses that do not
advertise fall back to the gradient normalization as before.

Tests: flag-combination advertisement tests + a sync-vs-split metric
parity test on the real ClippedPGLossFn (CPU), and worker-side tests for
advertised TOKENS/SEQUENCES/NONE scaling, raw-count pass-through, and the
flag-keyed F-SEQ case via a real loss instance.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
Runs the same GRPO batch through sync train() and the
begin/train_microbatch/finish split path on freshly-initialized identical
models for two optimizer steps, asserting the loss curve, grad norm, and
every per-microbatch metric agree (review F-TESTGAP). The split side
drives the presharded worker fan-out with replica-leader dedup and the
shared _aggregate_train_results, so TP=2 also covers the twin-dedup fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
Only one train step can be open at a time — begin raises on a second
begin, and every other call operates on the open step — so threading a
step identifier through begin/train_microbatch/finish/abort adds callee
burden without disambiguating anything (terrykong, PR NVIDIA-NeMo#2683 review).
Removed from the worker state machine, the presharded mixin wrappers,
and the TQPolicy driver; abort remains idempotent when no step is open.

Also renames TQPolicy.train_microbatch_from_meta to
train_microbatches_from_meta: one call fans out to every DP rank and the
backend iterates its own internal pipeline/packed microbatches, so the
plural reflects what actually runs (same review thread).

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
run_all_workers_single_data returns plain ObjectRefs (one per GPU), not
a MultiWorkerFuture, so passing them to get_all_worker_results raises
AttributeError. TQPolicy's begin/finish/abort_train_step fan-outs had
this latent since they were mocked in every prior test — the new GPU
parity test executed the path for real and caught it. Consume with
ray.get, matching every other single-data fan-out in lm_policy.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
…args

main renamed use_linear_ce_fusion_loss to use_fused_linear_logprobs and
added router-replay arguments to megatron_forward_backward; the split
path's call predated the rename, so the first real execution (the new
GPU parity test) raised TypeError. Mirror the sync train() call exactly:
renamed kwarg + config key, and the _should_use_router_replay gate with
the r3 trace stage.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
…n path

train_microbatch returned {local_valid_seqs_mb, local_valid_toks_mb,
num_pipeline_microbatches} but no caller consumes it — the SC driver
discards the result and everything finish_train_step needs already
accumulates in the open-step state (yuki-97, PR NVIDIA-NeMo#2683 review). Return
None through the whole chain (worker body, presharded wrapper,
TQPolicy.train_microbatches_from_meta) so the per-call fan-out carries
no payload back to the driver.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
codecov/patch flagged the presharded wrappers and the TQPolicy split
fan-out as uncovered — they run only under the GPU-gated parity test.
Pin the contracts on CPU: begin/finish/abort pass-through, the
fetch → attach → backend chain (returning None), the is_replica_leader
tag, ray.get consumption of single-data futures, and the replica-twin
dedup in finish aggregation.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Akash Mehra <[email protected]>
@mehraakash
mehraakash force-pushed the asyncrl/split_train_mcore branch from a73d1df to a7c52b7 Compare July 8, 2026 00:11
@mehraakash

Copy link
Copy Markdown
Contributor Author

/ok to test a7c52b7

@yuki-97 yuki-97 added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L0 Run doctests and unit tests labels Jul 8, 2026
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)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants