Repository navigation
feat(automodel): support rollout routing replay (R3) on the Automodel policy - #4458
Conversation
156c674 to
caf1070
Compare
caf1070 to
7b7aabc
Compare
7b7aabc to
0e7a6e5
Compare
771db6a to
60df9dc
Compare
|
/ok to test 60df9dc |
|
@HuiyingLi could you help review? |
|
R3 nightly on head 60df9dc: all 3 gates PASS
This closes the "GPU smoke run on this head" item in the PR's self-review section. Generated by Claude Code |
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main and resolve conflicts.
Thanks for adding Rollout Routing Replay to the Automodel policy, which removes the 1e6-3e9 token_mult_prob_error spikes on the Nemotron-3.5 Lightning recipe!
Great to see the 20-step 4n8g runs with and without R3 posted in the description: the effect on the spikes and on gen_kl_error can be read straight off the table. Thanks also for the extensive self-review.
Scope: nemo_rl/models/automodel/router_replay.py and its wiring in setup, train and the policy worker; the SingleController config guard; per-microbatch padding of jagged routed_experts; docs; the -r3 recipe and nightly test.
Checked:
- Replay hook — the per-instance
applyoverride is reached from everyreplay_selectioncall site in Automodel 72daceff, so the sharedRouterReplayclass is untouched and routing weights still come from the live router. - Backward inside the replay context —
automodel_forward_backwardrunsloss.backward()within thereplay_contextblock, so activation-checkpoint recompute sees the same routes; reference logprobs passrequire_router_replay=False, matching the Megatron override. - Route handling — both payload layouts (per MoE layer, per decoder layer) map to gates, MTP gates are excluded, padding past
input_lengthskeeps the live selection, and partial, out-of-range or repeated rows raise with layer and token details. - Jagged
routed_expertspadding in the microbatch iterator mirrorsmegatron/data.py. - Nightly budget — the +128 GPU hours match 4 nodes x 8 GPUs x 240 min, and the cap moves from 4830 to 4947 accordingly.
… policy policy.router_replay.enabled previously only took effect on the Megatron backend; the Automodel worker ignored the rollout routed_experts. Small numerical differences between vLLM and the training forward flip near-tied MoE top-k decisions, and the flips compound across layers and positions. On Nemotron-3.5-Lightning (dapo-nanov3.5-30BA3B-4n8g-automodel) this produced single tokens whose train/generation logprobs differ by ~30 nats (token_mult_prob_error spikes up to 2.5e9). With replay, all 20 steps stay at ~1.010 and gen_kl_error halves. - Build Automodel MoE gates with RouterReplay handles (moe_overrides.enable_routing_replay) and collect them once after model build (MTP gates excluded). Before loading, reject models that would load through HF (force_hf or no Automodel implementation) with a clear error, since their gates have no replay hooks. - Replay each microbatch's routed_experts in the get_logprobs forward and the train forward+backward. get_logprobs takes require_router_replay (default True, mirroring the Megatron worker); reference-policy logprobs pass False. - Never replay batch padding (positions past input_lengths keep the live router). Only all-sentinel rows mark a missing route; partially negative, out-of-range or repeated-expert rows raise with layer/token details. - Map vLLM's per-decoder-layer payload (52 slots on NemotronH) to gates by decoder-layer index; a per-MoE-layer payload is used in gate order. - Install replay per gate instance instead of patching RouterReplay globally; keep only the MoE-layer slots in the payload's small dtype. - Fail at setup without vLLM generation, with sequence packing, CP > 1 or sequence parallel; reject token_capture.defer_routed_experts_to_policy on a non-Megatron policy during single-controller config validation. - Unit tests include replay through a real Automodel Gate (replayed experts used, live router weights and gradients kept). - Document the automodel backend in docs/guides/router-replay.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jonas Yang <[email protected]>
Nightly coverage for automodel router replay: the same Nemotron-3.5 Lightning DAPO run with policy.router_replay.enabled and vLLM prefix caching off (R3 needs routes for every prompt token). Gate on validation accuracy at step 20 > 0.4, median token_mult_prob_error < 1.02 and mean gen_kl_error < 0.0006. In a 20-step run with R3, token_mult_prob_error stayed at 1.009-1.011 on every step and mean gen_kl_error was 0.00037; without R3 it is 0.00086 and the mean spikes to 1e6-3e9 on ~20% of steps. The new 4n8g test adds 128 nightly GPU hours (4721 -> 4849); raise the budget check from 4735 to 4863. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jonas Yang <[email protected]>
Since #4530 the data plane leaves routed_experts jagged when a replica group has more than one rank (automodel TP > 1 on the single-controller path), and only the Megatron data path pads it per microbatch. Mirror that in the automodel data path: - make_processed_microbatch_iterator pads MICROBATCH_PADDED_FIELDS to the microbatch's input_ids width. Pad rows get -1, the missing-route sentinel, which keeps the live router selection. - check_sequence_dim skips nested tensors. Routes that already arrive padded (the driver path) are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jonas Yang <[email protected]>
Findings from a /review-pr-team self-review, after a devil's-advocate
pass:
- Fail loudly when a gate owns a RouterReplay handle but never consults
it. Automodel's KimiK3Gate does this, so R3 would otherwise route live
with no error. replay_routes now raises RuntimeError naming the gate.
- Range-check gates that name their expert count num_experts (Gemma4Gate).
Previously an out-of-range route reached gather and hit a device assert
instead of the descriptive ValueError.
- Make the "no RouterReplay gates" and "no routed_experts" errors name
causes that can actually reach them.
- Add nemo_rl/models/automodel/router_replay.py to pyrefly and fix its
Optional typing; narrow automodel_cfg; type microbatch arguments.
- Docs: recommend prefix caching off for both backends, rather than
presenting it as an Automodel-only requirement. Disclose that the R3
example recipe also turns it off.
- Docstrings: Raises sections; driver vs data-plane padding values.
- Tests:
- activation-checkpoint recompute (full and selective) replays only
when backward runs inside replay_routes;
- automodel_forward_backward runs backward inside the replay context;
- reference logprobs pass require_router_replay=False;
- the never-consulted gate and num_experts cases.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jonas Yang <[email protected]>
60df9dc to
6a15cdb
Compare
Signed-off-by: Yuki Huang <[email protected]>
|
/ok to test d3af9d9 |
…failures-and-redispatch main gained #4481, #4771, #4458, #4770, #4640, #4765, #4525 and #4670 since the previous merge. #4640 (rubric-mean and fixed-baseline GenRM scoring) rewrote the metric assertions in tests/unit/experience/test_rollouts.py that this branch also edits for nemo_gym_infra_redispatches: the resolution keeps main's per-key assertions and adds the redispatch count beside them, and the expected rollout_metrics dict carries both sides' new keys. test_rollouts.py, test_rollout_manager.py and test_nemo_gym.py pass locally on the merged tree. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: alexandery <[email protected]>
…andery/gym-health-check-during-collection Carries the stack root's merge of main (8338530: #4481, #4771, #4458, #4770, #4640, #4765, #4525 and #4670) forward so this head stays current with main. No conflicts; test_rollouts.py, test_rollout_manager.py and test_nemo_gym.py pass locally on the merged tree. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: alexandery <[email protected]>
…xandery/gym-rollout-metrics-hook Carries the stack's merge of main (8338530: #4481, #4771, #4458, #4770, #4640, #4765, #4525 and #4670) forward. #4640 (rubric-mean and fixed-baseline GenRM scoring) reports the shared GenRM fields once per group through _nemo_gym_group_metrics and skips them in both per-agent loops, which this branch had replaced with per_agent_result_metrics: the resolution keeps the helper on both paths and adds the same _SHARED_GENRM_METRICS skip inside it, so the manager no longer imports the constant. test_rollouts.py, test_rollout_manager.py and test_nemo_gym.py pass locally on the merged tree. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: alexandery <[email protected]>
What does this PR do?
Wires Rollout Routing Replay (
policy.router_replay.enabled, R3) into the Automodel policy. Until now only the Megatron policy replayed vLLM's rollout MoE routing; the Automodel worker ignored the rolloutrouted_experts.Why
On
dapo-nanov3.5-30BA3B-4n8g-automodel(Nemotron-3.5-Lightning 30B-A3B), small numerical differences between vLLM and the training forward flip near-tied MoE top-k decisions, and the flips compound across layers and positions. The result is 0-2 tokens per step whose rollout and training logprobs differ by 10-31 nats, sotrain/token_mult_prob_error(a per-token mean) spikes to 1e6-3e9 on about 20% of steps. Raising the gate to FP32 does not help, because the hidden states entering the router already differ.Results from 20-step runs on 4n8g:
token_mult_prob_errorper stepgen_kl_errorChanges
RouterReplayhandles (moe_overrides.enable_routing_replay) and collect them once after the model is built; MTP gates are excluded because vLLM never routes them.force_hf, or no Automodel implementation) are rejected with a clear error, because their gates have no replay hooks.routed_expertsis replayed in theget_logprobsforward and in the training forward and backward, so activation-checkpoint recomputation sees the same routes.get_logprobstakesrequire_router_replay, default True, as in the Megatron worker. Reference-policy logprobs pass False.-1rows are missing routes and keep the live router. Partially negative, out-of-range, or repeated-expert rows raise with layer and token details.token_capture.defer_routed_experts_to_policyon a non-Megatron policy is rejected during single-controller config validation.docs/guides/router-replay.md.dapo-nanov3.5-30BA3B-4n8g-automodel-r3runs the same recipe with R3 on and vLLM prefix caching off, since R3 needs routes for every prompt token.token_mult_prob_error< 1.02, and meangen_kl_error< 0.0006.Testing
tests/unit/models/automodel/test_router_replay.pycovers config validation, gate discovery, both payload layouts, padding, corrupt-route rejection, rejection of HF models, and replay through a real AutomodelGate. In the real-Gatetest the replayed experts are used, and the router weights and gradients still come from the live router.tests/unit/models/automodel/passes: 261 tests.tests/unit/single_controller/test_setup.py,tests/unit/algorithms/test_grpo_router_replay_async.py, andtests/unit/test_recipes_and_test_suites.pypass: 166 tests.Related
The companion PR #4459 adds the
token_mult_prob_error_p999and spike-count metrics and makes the non-R3 nightly test robust to the spikes. It is independent of this PR and the two can merge in either order. After both merge, the-r3test can also gate on the new metrics.Update (2026-10-14): rebased onto main
86783d1AutomodelPolicyWorker(cp:refactor(automodel): rename the DTensor v2 workers to Automodel 4282#4584), and the config block isautomodel_cfg(cp:refactor: rename the dtensor_cfg config block to automodel_cfg (4283)#4571). The R3 validation now readsautomodel_cfg.context_parallel_sizeandsequence_parallel. The tests, docs and wording follow the new names.fix(automodel): pad jagged routed_experts per microbatch for R3:routed_expertsjagged when the replica group has more than one rank: Automodel TP > 1 on the single-controller path. Only the Megatron data path padded it.MICROBATCH_PADDED_FIELDSto each microbatch'sinput_idswidth, andcheck_sequence_dimskips nested tensors. This mirrorsmegatron/data.py.rl.73529719.sqsh.test_router_replay.py,test_automodel_data.py(2 new tests) andtest_automodel_train.py: 121 passed.test_setup.py,test_recipes_and_test_suites.py,test_vllm_utils.pyandtest_route_assembly.py: 218 passed, 1 skipped.Self-review (
/review-pr-team, 2026-10-14)Head 60df9dc, rebased on main 7a6eabf.
Process.
72daceff.Gates and activation checkpointing.Fixed in
fix(automodel): harden R3 per self-review:KimiK3Gatebuilds a handle but never callsreplay_selection, so R3 used to route live silently.replay_routesnow raisesRuntimeErrornaming the gate.num_experts, notn_experts, so an out-of-range route used to reachgatherand hit a device assert.router_replay.pyis added to pyrefly, its Optional typing is fixed, andautomodel_cfgand the microbatch arguments are typed.automodel_forward_backwardruns backward inside the replay context;require_router_replay=False;Rejected, with reasons:
get_is_hf_modelinstead of the registry check. The check mirrors the existing_maybe_set_force_hf, and every mismatch fails loudly at load.num_hidden_layers. No failing model exists, and it needs config plumbing.max(token_mult_prob_error) < 1.1to the nightly.mean(gen_kl_error) < 0.0006already fails a non-R3 run, and the gate is stricter than every Megatron R3 nightly. A spike-count gate comes with the tail metrics in fix(nightly): check nano35 logprob-error tails at every step #4593.get_logprobs. Out of scope; the same text is in the Megatron worker.router_replay_enabledout of the Megatron module. Existing coupling; a bad hoist would fail loudly in the Automodel test shard.Follow-ups, not in this PR:
KimiK3Gateignores itsRouterReplayhandle.RouterReplayhas no per-token keep-live fallback, which is why this PR overridesapply. DeepSeek-V4's hash-gate swap leaves an orphaned handle.Evidence still to post:
-r3nightly on this head. Multi-noderay.subjobs could not be submitted from the self-review environment.🤖 Generated with Claude Code