Skip to content

[rl] MoE router replay: train on the experts the generator chose - #5255

Draft
felipemello1 wants to merge 1 commit into
pytorch:mainfrom
felipemello1:rl/router-replay-upstream
Draft

felipemello1 wants to merge 1 commit into
pytorch:mainfrom
felipemello1:rl/router-replay-upstream

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: The trainer can now route each token to the experts the vLLM generator chose (router replay). On Qwen3-30B-A3B the trainer-generator k3 KL drops ~6x. One flag, off by default.

Problem

  1. The generator (vLLM) and the trainer run the same MoE weights.
  2. bf16 noise near the top-k boundary still sends some tokens to different experts: 12.8% of (token, layer) top-8 sets on Qwen3-30B-A3B, from 0.1% at layer 0 to 19% at layer 36.
  3. A token routed differently gets a different logprob, so p_trainer / q_generator moves for reasons unrelated to the policy update.
  4. Cost: k3 KL 2.8e-4 per token; the worst token per step is off by 2 nats on average.

Solution

  1. VLLMGenerator.Config.return_routed_experts = True.
  2. The generator returns each token's experts; the trainer routes the same tokens to them.
  3. Gate weights still come from the trainer's scores, so the router keeps its gradient.
  4. Without the flag nothing changes.
generator (vLLM)             rollout                                trainer
router --hook--> capture     Completion.routed_expert_ids           model_kwargs["routed_expert_ids"]  [T, L, K]
                             [P+N-1, L, K] uint8                      Decoder: layer i gets [:, i]
                             -> RolloutTurn: a delta, like the prompt router:  ids    = replayed ids
                             -> TrainingSample: [len(tokens)-1, L, K]          weights = scores.gather(ids)

Results

Qwen3-30B-A3B (48 layers), DAPO math, on-policy, 8xH100; steps 1-3, same seed and prompts
                 replay off            replay on
k3 KL            2.4e-4 - 3.2e-4  ->   4e-5 - 5e-5        ~6x
mean |Δlogp|     0.0071 - 0.0085  ->   0.0030 - 0.0038    2.3x
max |Δlogp|      1.04 - 1.35      ->   0.21 - 0.93

Same model cut to 2 layers, DAPO math, 4 steps, this branch
native rollouter     k3 7.6e-4 - 1.2e-3  ->  9e-5 - 1.0e-4     max |Δlogp| 0.76 - 1.46  ->  0.07 - 0.085
Verifiers rollouter  k3                      9e-5 - 1.0e-4     max |Δlogp|                  0.06 - 0.074
  • Correctness: replaying a model's own routing is bitwise identical (logits and grads), with FullAC, SelectiveAC and RegionAC, in all 7 MoE families.
  • Cost: every trainer rank receives the whole microbatch grid, and the ids grow it 38 -> 422 B/token: +270 ms/step (~1.5%) on the 30B grid. TODO in controller.py.

You may ask:

  • Why a forward argument and not router state? Activation-checkpoint recompute and CP sharding both see forward arguments; state would be read again later.
  • Why not replay the gate weights? The router would get no gradient.
  • Where is the routing-mismatch % above from? Router counters plus a measure-only mode, left for a follow-up PR to keep this one small.

NOTE:

  • The 30B replay arm ran 3 steps; the matched 100-step pair is not run yet.
  • Verifiers gives a continued turn's last token the row of the token before it (TODO in the rollouter).

Test plan

pytest tests/unit_tests/cpu/models/common/test_moe.py tests/rl/unit_tests/cpu
pytest tests/unit_tests/gpu/test_router_replay.py   # 1 GPU

Follow up

  • Routing-mismatch metrics and a measure-only mode.
  • Send each trainer rank only its microbatch column.
  • Ask vLLM only for a continued turn's new rows (routed_experts_prompt_start).
  • vLLM Model Runner V2.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 10, 2026

@acisseJZhong acisseJZhong 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 for making this PR!!

Comment thread torchtitan/models/kimi_k3/moe.py Outdated
routed_x_TD,
routed_padding_mask_T,
) = self._maybe_shard_routed_branch_inputs_across_tp(x_TD, padding_mask_T)
if routed_expert_ids_TK is not None:

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.

nit: combine with previous sharding?

Comment thread torchtitan/rl/components/batcher.py Outdated
input_ids = [10, 11, 20, 21, 0, 0, 0, 0]
labels = [11, 12, 21, 22, 0, 0, 0, 0]
positions = [ 0, 1, 0, 1, 0, 1, 2, 3]
# Routed expert ids follow input_ids; padding rows are 0, where the routers

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.

update the doc string example above?

for start, end in _trainable_token_spans(mask):
absolute_start = branch_offset + start
absolute_end = branch_offset + end
# TODO: router replay. Return Completion.routed_expert_ids through the

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.

oh I assume the in agent RL we will only use the Verifier Rollouter not the native rollouter? so this is also very important to add?

Comment thread torchtitan/rl/model/vllm_wrapper.py Outdated
vLLM binds ``capture_fn`` on every module that has ``layer_id`` and ``capture_fn``
attributes (``RoutedExpertsCaptureSource``) after its profile run, stores the ids
by KV slot, and returns them as ``CompletionOutput.routed_experts``. A prefix-cache
hit therefore returns the ids computed with that cached KV.

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.

I guess less related to titan, but do you know if the expert ids are literally stored together with kv cache?

Comment thread torchtitan/rl/controller.py Outdated
step_timer.record("timing/step/forward_backward"),
):
# TODO: every trainer rank receives the whole [num_microbatches][dp_degree]
# grid and keeps its own column. Routed expert ids make that 418 B/token

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.

did you measure the comm time increase?

@felipemello1

felipemello1 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

update by claude: addressed the review, then rebased on main and trimmed the PR to replay only (1290 -> 734 lines; the routing-mismatch metrics move to a follow-up).

  • combine sharding: done, one helper shards the ids with the padding mask.
  • docstring example: done.
  • Verifiers: done. The generation server returns routed_experts the way Verifiers/prime-rl expect; the rollouter slices each turn's rows. 2-layer smoke: same k3 drop as the native rollouter. Caveat (Verifiers' own attribution): on multi-turn, the previous turn's last token keeps its neighbor's row (TODO).
  • KV cache: not inside the KV tensors; vLLM keeps a CPU array indexed by the same KV slots, so prefix-cache hits return the cached rows.
  • comm time: +~270 ms/step (~1.5%) on the 30B grid (4 ranks x 8 microbatches), because every rank gets the whole grid. Sending each rank its column: ~75 ms. TODO for a follow-up.

@felipemello1
felipemello1 force-pushed the rl/router-replay-upstream branch 2 times, most recently from a6a36c6 to 31ee9fe Compare October 11, 2026 20:42
The generator (vLLM) and the trainer run the same MoE, but bf16 noise near
the top-k boundary sends some tokens to different experts, which moves the
importance ratio for reasons unrelated to the policy update.

- VLLMGenerator.Config.return_routed_experts: a forward hook on every router
  feeds vLLM's routed-experts capture; Completion.routed_expert_ids is
  [prompt + completion - 1, num_layers, top_k].
- The rows ride like the prompt: RolloutTurn keeps a delta, TrainingSample
  one row per trainer input, the batcher packs model_kwargs["routed_expert_ids"].
- Decoder.forward(routed_expert_ids=...) gives layer i its [:, i] slice; the
  router routes real tokens there; gate weights still come from its scores.
- The Verifiers rollouter speaks Verifiers' routed_experts protocol.
- DAPOLoss logs bit_wise/{kl_k3,logprob_diff_abs,ratio_beyond_2x}/mean.
- Off by default; without ids every forward is unchanged.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants