Skip to content

feat(automodel): support rollout routing replay (R3) on the Automodel policy - #4458

Merged
yuki-97 merged 5 commits into
mainfrom
joyang/automodel-router-replay
Oct 17, 2026
Merged

yuki-97 merged 5 commits into
mainfrom
joyang/automodel-router-replay

Conversation

@joyang-nv

@joyang-nv joyang-nv commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

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 rollout routed_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, so train/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:

Without R3 (2 runs) With R3
token_mult_prob_error per step median 1.016; spikes up to 2e7 on 4/20 steps 1.009-1.011 on every step
Mean gen_kl_error 0.00086-0.00087 0.00037
Tokens per step off by > 10 nats 0-2 0 (largest error 5.7 nats)
Validation accuracy at step 20 0.445-0.453 0.438

Changes

  • Gate setup
    • Build Automodel MoE gates with RouterReplay handles (moe_overrides.enable_routing_replay) and collect them once after the model is built; MTP gates are excluded because vLLM never routes them.
    • Before loading, models that would load through HF (force_hf, or no Automodel implementation) are rejected with a clear error, because their gates have no replay hooks.
  • Where routes are replayed
    • Each microbatch's routed_experts is replayed in the get_logprobs forward and in the training forward and backward, so activation-checkpoint recomputation sees the same routes.
    • get_logprobs takes require_router_replay, default True, as in the Megatron worker. Reference-policy logprobs pass False.
    • Only the expert selection is replayed; routing weights come from the live router, so it keeps training.
  • Route handling
    • Batch padding is never replayed.
    • All--1 rows are missing routes and keep the live router. Partially negative, out-of-range, or repeated-expert rows raise with layer and token details.
    • vLLM's per-decoder-layer payload (52 slots on NemotronH) is mapped to gates by decoder-layer index; a per-MoE-layer payload is used in gate order.
  • Setup checks
    • Setup fails without vLLM generation, or with sequence packing, CP > 1, or sequence parallel.
    • token_capture.defer_routed_experts_to_policy on a non-Megatron policy is rejected during single-controller config validation.
  • Docs: the automodel backend is documented in docs/guides/router-replay.md.
  • Nightly: the new test dapo-nanov3.5-30BA3B-4n8g-automodel-r3 runs the same recipe with R3 on and vLLM prefix caching off, since R3 needs routes for every prompt token.
    • It gates on step-20 validation accuracy > 0.4, median token_mult_prob_error < 1.02, and mean gen_kl_error < 0.0006.
    • It adds 128 nightly GPU hours, so the budget check rises from 4830 to 4947 (main's DRYRUN total is 4819; this branch's is 4947).

Testing

  • Unit tests:
    • tests/unit/models/automodel/test_router_replay.py covers config validation, gate discovery, both payload layouts, padding, corrupt-route rejection, rejection of HF models, and replay through a real Automodel Gate. In the real-Gate test 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, and tests/unit/test_recipes_and_test_suites.py pass: 166 tests.
  • End to end: the 20-step runs in the table above, plus a 3-step smoke run of the new nightly test on this branch's final code.

Related

The companion PR #4459 adds the token_mult_prob_error_p999 and 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 -r3 test can also gate on the new metrics.

Update (2026-10-14): rebased onto main 86783d1

  • Renames on main: the worker is now AutomodelPolicyWorker (cp: refactor(automodel): rename the DTensor v2 workers to Automodel 4282 #4584), and the config block is automodel_cfg (cp: refactor: rename the dtensor_cfg config block to automodel_cfg (4283) #4571). The R3 validation now reads automodel_cfg.context_parallel_size and sequence_parallel. The tests, docs and wording follow the new names.
  • fix(sc): Fix router replay with token capture for multi-turn rollouts #4610 compatibility: route pad rows are now filled with the missing-route sentinel (-1). This PR already treats all-sentinel rows as "keep the live router selection", so no change was needed.
  • New commit, fix(automodel): pad jagged routed_experts per microbatch for R3:
    • Since perf(data-plane): broadcast unpadded rows and pad on each rank #4530, the data plane leaves routed_experts jagged when the replica group has more than one rank: Automodel TP > 1 on the single-controller path. Only the Megatron data path padded it.
    • The Automodel microbatch iterator now pads MICROBATCH_PADDED_FIELDS to each microbatch's input_ids width, and check_sequence_dim skips nested tensors. This mirrors megatron/data.py.
    • Routes that already arrive padded (the driver path) are unchanged.
  • Nightly budget: main raised its cap to 4830 (fix(ci): raise nightly GPU-hour cap to 4830 #4705), and this PR's test adds 128, so the cap is now 4947.
  • Tests: run in container rl.73529719.sqsh.
    • Automodel venv: test_router_replay.py, test_automodel_data.py (2 new tests) and test_automodel_train.py: 121 passed.
    • Main venv: test_setup.py, test_recipes_and_test_suites.py, test_vllm_utils.py and test_route_assembly.py: 218 passed, 1 skipped.
  • No GPU rerun yet. The 20-step nightly evidence in the description is from before the rebase. The nightly recipe uses the driver path with TP=1, which the rebase does not change.

Self-review (/review-pr-team, 2026-10-14)

Head 60df9dc, rebased on main 7a6eabf.

Process.

  • Five independent reviewers: RL expert, Automodel expert, test, bug-finder and design.
  • A devil's-advocate pass challenged every finding against the code and the pinned Automodel 72daceff.
  • The Automodel expert and the bug-finder ran GPU probes on a tiny NemotronH model, real Automodel Gates and activation checkpointing.
  • No correctness bug was found in the replay logic. Token/route alignment, weight re-gathering, AC recompute, exception-safe state clearing, the reference path, MTP exclusion and the jagged-padding commit were all verified.

Fixed in fix(automodel): harden R3 per self-review:

  • Gates that never consult their replay handle now fail loudly. Automodel's KimiK3Gate builds a handle but never calls replay_selection, so R3 used to route live silently. replay_routes now raises RuntimeError naming the gate.
  • Gemma4 gates are range-checked. They store num_experts, not n_experts, so an out-of-range route used to reach gather and hit a device assert.
  • Accurate error messages for "no RouterReplay gates" and "no routed_experts".
  • pyrefly: router_replay.py is added to pyrefly, its Optional typing is fixed, and automodel_cfg and the microbatch arguments are typed.
  • Docs:
    • prefix caching off is now a recommendation for both backends, not an Automodel-only requirement;
    • the R3 example recipe's prefix-caching difference is disclosed.
  • Docstrings: added Raises sections.
  • New tests:
    • activation-checkpoint recompute (full and selective) replays only when backward runs inside the context;
    • automodel_forward_backward runs backward inside the replay context;
    • reference logprobs pass require_router_replay=False;
    • the never-consulted-gate and Gemma4-style cases.

Rejected, with reasons:

  • Use Automodel's get_is_hf_model instead of the registry check. The check mirrors the existing _maybe_set_force_hf, and every mismatch fails loudly at load.
  • Tighter payload-layout check against num_hidden_layers. No failing model exists, and it needs config plumbing.
  • Add max(token_mult_prob_error) < 1.1 to the nightly. mean(gen_kl_error) < 0.0006 already 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.
  • Relabel to CI:L1. The maintainer set CI:Lfast, and this PR changes no dependencies.
  • Pre-existing "left-padded" docstring in get_logprobs. Out of scope; the same text is in the Megatron worker.
  • Move router_replay_enabled out of the Megatron module. Existing coupling; a bad hoist would fail loudly in the Automodel test shard.

Follow-ups, not in this PR:

  • Automodel upstream: KimiK3Gate ignores its RouterReplay handle. RouterReplay has no per-token keep-live fallback, which is why this PR overrides apply. DeepSeek-V4's hash-gate swap leaves an orphaned handle.
  • NeMo-RL: the base nanov3.5 recipe has a stale Automodel-pin comment, and it runs an MTP head whose output is never used.

Evidence still to post:

  • A short GPU smoke run of the -r3 nightly on this head. Multi-node ray.sub jobs could not be submitted from the self-review environment.
  • A step-time comparison of R3 vs non-R3.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 3, 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.

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 3, 2026
@joyang-nv joyang-nv added the CI:L1 Run doctests, unit tests, and functional tests label Oct 3, 2026
@joyang-nv
joyang-nv force-pushed the joyang/automodel-router-replay branch from 156c674 to caf1070 Compare October 3, 2026 10:01
@joyang-nv
joyang-nv force-pushed the joyang/automodel-router-replay branch from caf1070 to 7b7aabc Compare October 7, 2026 17:13
@RayenTian RayenTian added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L1 Run doctests, unit tests, and functional tests labels Oct 14, 2026
@joyang-nv
joyang-nv force-pushed the joyang/automodel-router-replay branch from 7b7aabc to 0e7a6e5 Compare October 14, 2026 07:17
@joyang-nv joyang-nv changed the title feat(automodel): support rollout routing replay (R3) on the DTensor policy feat(automodel): support rollout routing replay (R3) on the Automodel policy Oct 14, 2026
@joyang-nv
joyang-nv force-pushed the joyang/automodel-router-replay branch 2 times, most recently from 771db6a to 60df9dc Compare October 14, 2026 10:43
@joyang-nv

Copy link
Copy Markdown
Member Author

/ok to test 60df9dc

@joyang-nv
joyang-nv requested a review from yuki-97 October 14, 2026 14:44
@yuki-97

yuki-97 commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

@HuiyingLi could you help review?

@joyang-nv

Copy link
Copy Markdown
Member Author

R3 nightly on head 60df9dc: all 3 gates PASS

dapo-nanov3.5-30BA3B-4n8g-automodel-r3: 4n8g H100 (cw_dfw), container rl.73529719.sqsh, 20 steps, Slurm job 20192519, COMPLETED.

Gate Value Result
validation/accuracy[20] > 0.4 0.4492 PASS
median(token_mult_prob_error) < 1.02 1.0100 PASS
mean(gen_kl_error) < 0.0006 0.00037 PASS
  • token_mult_prob_error: stayed between 1.0086 and 1.0110 on every step, with no spikes. This matches the pre-rebase R3 run (1.009–1.011). Without R3, the error spikes to 1e6–3e9 on about 20% of steps.
  • gen_kl_error: mean 0.00037 (max 0.00040), the same as before the rebase (0.00037). Without R3 it is 0.00086.
  • Validation accuracy: 0.356 → 0.375 → 0.449 at steps 0, 10 and 20.
  • Step time: median 376 s, of which generation is 331 s (the base recipe still runs vLLM eager). The 20 steps total 142 min.
  • New checks: the "never consulted" check did not fire. No missing or incomplete routed_experts errors.

This closes the "GPU smoke run on this head" item in the PR's self-review section.

Generated by Claude Code

yuki-97
yuki-97 previously approved these changes Oct 15, 2026

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

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 apply override is reached from every replay_selection call site in Automodel 72daceff, so the shared RouterReplay class is untouched and routing weights still come from the live router.
  • Backward inside the replay context — automodel_forward_backward runs loss.backward() within the replay_context block, so activation-checkpoint recompute sees the same routes; reference logprobs pass require_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_lengths keeps the live selection, and partial, out-of-range or repeated rows raise with layer and token details.
  • Jagged routed_experts padding in the microbatch iterator mirrors megatron/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.

joyang-nv and others added 4 commits October 16, 2026 22:30
… 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]>
@yuki-97
yuki-97 force-pushed the joyang/automodel-router-replay branch from 60df9dc to 6a15cdb Compare October 17, 2026 05:41
@yuki-97

yuki-97 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

/ok to test d3af9d9

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

LGTM.

Moving R3 code out of the Megatron package (for example router_replay_enabled, which the Automodel path currently imports from nemo_rl.models.megatron.router_replay) is out of scope here and tracked in #4767.

@yuki-97
yuki-97 enabled auto-merge (squash) October 17, 2026 06:07
@yuki-97
yuki-97 merged commit c7aca81 into main Oct 17, 2026
93 checks passed
@yuki-97
yuki-97 deleted the joyang/automodel-router-replay branch October 17, 2026 11:32
alexandery-nvidia added a commit that referenced this pull request Oct 17, 2026
…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]>
alexandery-nvidia added a commit that referenced this pull request Oct 17, 2026
…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]>
alexandery-nvidia added a commit that referenced this pull request Oct 17, 2026
…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]>
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) Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants