Repository navigation
[rl] Train the MoE router gate; RL turns off only load balancing - #5730
Conversation
build_rl_model_configs froze the router gate, froze the expert bias and dropped the router aux loss (FreezeMoERoutingTransform). The logprob drift came from the expert-bias update; a trainable gate leaves the trainer-vs-generator gap flat. So the RL default now only disables load balancing (frozen expert bias, no aux loss) and the gate trains: - build_rl_model_configs: freeze_moe_routing -> disable_moe_load_balancing, applied inline to both roles. - Remove FreezeMoERoutingTransform, its test, and TokenChoiceTopKRouter.Config.freeze_gate, which only it set.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 36s —— View job Approve -- please fill in the human-written summary before merging (review); a maintainer still needs to review the core changes. |
There was a problem hiding this comment.
Verdict: Approve -- please fill in the human-written summary before merging. The PR removes a gate freeze that was never measured and keeps the load-balancing shutoff that was measured. It also deletes a transform and a config field that had only one caller each (net -162 LoC). A maintainer still needs to review, because this touches models/common/moe and config/transform.
What this PR does. For RL, build_rl_model_configs now does two things on every MoE.Config of the trainer and the generator. It sets freeze_expert_bias=True and router.aux_loss=None, and it no longer freezes the router gate. FreezeMoERoutingTransform and TokenChoiceTopKRouter.Config.freeze_gate are deleted; nothing else used them.
Example.
RL recipe, any MoE flavor (e.g. DeepSeek-V3 debugmodel):
main this PR
router.gate.weight requires_grad=False trains, has AdamW state, synced to the generator
expert_bias_E frozen (no hook) frozen (no hook)
router.aux_loss None None
Dense RL recipes unchanged unchanged
Must fix
- PR description -- "Summary (human-written)" is empty. The author has to write it (see
CONTRIBUTING.md, "AI-assisted contributions").
Should consider
torchtitan_recipes/rl/model_configs.py:26-- no recipe setsdisable_moe_load_balancing=False. You could drop the flag and its opt-out test (see the inline comment).
Details
- Callsites:
freeze_gate,FreezeMoERoutingTransform, andfreeze_moe_routingappear nowhere else in the repo at HEAD, including docs, recipes, graph_trainer, and RL. - Coverage after deleting
test_freeze_moe_routing.py: the expert-bias freeze is still tested for both hooks, intests/unit_tests/cpu/components/optim/test_optimizer_param_groups.py:266(load balancing) and:303(quantile balancing). The aux-loss removal and the bias freeze on every RL recipe are still checked intest_model_defaults.py. Gate freezing has no field left to test, so dropping that part of the test is right. - RL path: nothing under
torchtitan/rl/depended on the gate being frozen. The generator wrapper setsrequires_grad_(False)on its own modules (model_wrapper.py:597), and weight sync already pushed the full state dict. - Checkpoint resume: the gate now has optimizer state, so an MoE RL checkpoint saved since the gate freeze landed won't load its optimizer state. The description documents this and gives a workaround. torchtitan makes no backward-compatibility promise for native checkpoints, so this doesn't block the PR.
- Numerics: dense RL recipes are unchanged. MoE RL recipes change by design, and the ablation in the description explains why.
Not verified: the GPU logprob-gap ablation. It can't run here, so the review relies on the numbers in the description.
| fp32_lm_head: bool = True, | ||
| # TODO: consider enabling router training, but with a lower lr | ||
| freeze_moe_routing: bool = True, | ||
| disable_moe_load_balancing: bool = True, |
There was a problem hiding this comment.
Should consider: no recipe passes disable_moe_load_balancing=False. The only caller that does is test_build_rl_model_configs_keeps_moe_load_balancing_when_asked. fp32_lm_head is different, because search_r1.py and verifiers_terminal_bench.py set it to False. Since you're renaming this anyway, you could drop the flag, always apply the two flips, and delete the opt-out test (about -15 lines). If someone later needs load balancing in RL, they can add the flag back along with that recipe. This one is a judgment call, because the old freeze_moe_routing flag didn't have a consumer either.
There was a problem hiding this comment.
Reply from claude: Keeping the flag. The author asked for a switch for the bias, and it matches the docstring's "RL defaults, applied to both (pass False to skip one)" table next to fp32_lm_head. It's also what a load-balancing-on RL ablation would flip.
| freeze_gate: bool = False | ||
| """Keep ``gate.weight`` (and ``gate.bias``, if any) at their loaded values: no gradient, | ||
| no optimizer state. The gate's input still gets gradients.""" |
There was a problem hiding this comment.
we could keep the flag. I think its fine. It just shouldnt be the default
There was a problem hiding this comment.
Reply from claude: Done in a514a7b. freeze_gate stays on the router config, off by default; RL leaves it off.
… it off Review on this PR: keep the flag, just not as the RL default. The field and its two lines in TokenChoiceTopKRouter.__init__ are back as on main. The RL default test now checks that RL recipes don't freeze the gate.
…alancingTransform build_rl_model_configs applies the RL MoE default as a ModelConfigTransform in its transforms list, as on main. The transform is renamed for what it does: on every MoE.Config it sets freeze_expert_bias=True and router.aux_loss=None. It leaves router.freeze_gate alone, so the gate trains. - freeze_moe_routing.py -> disable_moe_load_balancing.py, same for its test. - The test checks every MoE family: the expert bias is frozen, every parameter (gate included) trains, and the aux loss is removed.
|
Reply from claude: New head a514a7b since your last review (11-02):
@claude please review the full diff again. |
|
Claude finished @felipemello1's task in 1m 16s —— View job Approve -- please fix the stale |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. At HEAD, a514a7be6 deletes one line from the transform: the gate freeze, which was never measured. It keeps the expert-bias freeze and the aux-loss removal, which were measured. A maintainer still needs to review, because this touches torchtitan/config/transform.
What this PR does. FreezeMoERoutingTransform is renamed DisableMoELoadBalancingTransform. On every MoE.Config it sets freeze_expert_bias=True and router.aux_loss=None. It no longer sets router.freeze_gate. build_rl_model_configs(disable_moe_load_balancing=True) replaces freeze_moe_routing=True. TokenChoiceTopKRouter.Config.freeze_gate is unchanged from main (off by default, moe.py:186), so pretraining and SFT behave as on main.
Example.
RL recipe, any MoE flavor (e.g. DeepSeek-V3 debugmodel), both roles:
main this PR
router.gate.weight requires_grad=False trains, has AdamW state, synced to the generator
expert_bias_E frozen (no hook) frozen (no hook)
router.aux_loss None None
Dense RL recipes unchanged unchanged
Since the last review (11-02): the human-written summary is now filled in, so that must-fix is resolved. The disable_moe_load_balancing flag stays. The author answered that comment, and I'm dropping it.
Must fix
- PR description, "Why one learning rate for the gate?" --
torchtitan_recipes/models/muse_spark.py:82is stale. The\.router\.gate\.AdamW pattern with_ROUTER_LR_MULTIPLIERis attorchtitan_recipes/models/muse_spark.py:368.
Questions
torchtitan_recipes/rl/dapo_math.py:322(not in the diff) -- with this PR, the Muse Spark 816B RL recipe trains the gate at the fulllr=1e-6. That is 8x its pretraining ratio, and it sits next to the only frozen nonzero expert bias in any RL recipe. The description lists this combination as unmeasured. Should this recipe get the\.router\.gate\.pattern atlr * _ROUTER_LR_MULTIPLIER, or setrouter.freeze_gate=Trueuntil it is measured? Muse Spark RL owners should decide; it's a recipe-level choice, not a blocker for the shared default.
Details
- Callsites: at HEAD,
FreezeMoERoutingTransformandfreeze_moe_routingappear nowhere in the repo.freeze_gateremains only inmoe.py:186-194(the field andrequires_grad_(False)) and in thenot any(...)assert intest_model_defaults.py:76. - Transform: the change is the one line
moe_config.router.freeze_gate = Trueplus the rename. The docstring matches the code. - Tests:
test_expert_bias_and_params_after_one_stepstill checks the bias freeze for both hooks (load_balance_coeff=1e-3and kimi_k3 quantile balancing) and that every parameter trains, gate included. The non-gate check is the same as before; only the gate exemption is gone.test_model_defaults.py:76checks the property this PR is about across all RL recipes, using an existing loop, so it costs nothing. freeze_gatecoverage: its behavior test went away with the old transform test. A regression would show up as a loud resume error (missing optimizer keys), not silently, so no new test is needed.- Numerics: dense RL recipes are unchanged. MoE RL recipes change by design, and the description explains why.
Not verified: the GPU logprob-gap ablation in the description.
There was a problem hiding this comment.
In a previous PR we froze the router. We shouldn't.
I didn't get the argument.
gate frozen (main) gate trains (this PR)
Qwen3.5-35B-A3B-Base, 60 steps 0.0315 -> 0.0290 -8% 0.0317 -> 0.0312 -1%
same frozen arm, run again 0.0319 -> 0.0271 -15%
Qwen3-30B-A3B, 20 steps 0.0199 -> 0.0187 -6% 0.0185 -> 0.0190 +3%
why gap shrinking is a bad thing?
trained gate at the end, vs frozen Qwen3.5: +8% and +15% Qwen3: +2%
noise: the two identical frozen runs end 7% apart (one pair), so part or all of the +2% to +15% may be noise
what is the object that's being compared? reward?
What's the common practice of other RL libs? I thought we "copied" this setup from others. The testing in the PR summary is also limited.
… only the adapters LoRA RL trains a few adapters on a frozen base, but every weight sync sent the whole model (Qwen3.5-27B in bf16: ~54 GB per sync for ~0.3% trainable parameters). Generators can already load the HF checkpoint themselves (`Generator.Config.checkpointer`, `ModelStateDictLoader`'s initial load), but the RL loop forbade it, so every weight sync carried the whole model. Now: - Every weight sync (the initial one, which also covers resume, included) carries the trainable parameters and the buffers: `Trainer.push_model_state_dict` leaves out the parameters with `requires_grad=False`. For LoRA that leaves `lora_a` and `lora_b`. Since #5730 RL recipes freeze nothing else, so every other recipe still sends the whole model. No flag, no new config field. - Generators load the frozen parameters from `generator.checkpointer`, which the controller no longer rejects, and loads leave them out: `_restore_sharded_params` refills their shards from the unsharded storage, which CUDA graphs read, before the group's unshard. Groups of only frozen parameters (e.g. tok_embeddings, the vision tower under LoRA) are skipped. This lives in the engine-agnostic `ModelStateDictLoader` (rl/generator/model.py). - `build_inference_model` reads `requires_grad` right after the build, before it freezes every parameter, and returns the frozen keys for `ModelStateDictLoader`. The model cannot tell them afterwards: a module does not record whether its config froze it (`LoRATransform.trainable_modules`, #6003, keeps any module trainable). With frozen parameters and no generator checkpointer the loader raises at setup (no sync would fill them), as it does for a quantized frozen parameter (its unsharded weight cannot refill its shard). A load that misses any other parameter still raises. The cpu_prefetch path's pinned receive buffers cover only what the trainer pushes (for Muse Spark 816B, the frozen base's buffers would pin ~102 GB of host memory per GPU that no load writes). The generator's HF load defaults to the model's HF assets, like the trainer's, for vLLM and SGLang. - `rl_grpo_qwen3_5_0_8b_geometry3k_lora`: rank-32 LoRA on the language model's attention, GatedDeltaNet and MLP projections, generators loading the HF checkpoint.
… only the adapters (#5844) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> **Stack** (image RL; review bottom up, each PR is one commit on the one below): 0. #5873 [multimodal] VisionProcessor: one per-model image and video processor (merged) 1. #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions (merged) 2. #5824 [rl] Image prompts through rollouts and the vLLM generator (merged) 3. #5825 [rl] Train on image prompts, with a Geometry3K recipe (merged) 4. **→** #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters 5. #6025 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for Muse Spark 816B 6. #5845 [rl] CUDA graphs for the generator's vision encoder ## Why A LoRA run trains a few adapters on a frozen base, but every weight sync sent the whole model (Qwen3.5-27B in bf16: ~54 GB per sync, for ~0.3% trainable parameters at rank 32). Generators can already load the HF checkpoint (`Generator.Config.checkpointer`, `ModelStateDictLoader`'s initial load), but the RL loop forbade it, so every sync, the initial one included, carried the whole model. **Example.** Geometry3K, Qwen3.5-0.8B, rank-32 LoRA (measured below): ``` before: every weight sync = the whole model 2.2 GB (Qwen3.5-27B in bf16: ~54 GB) after: generators load the base from the HF checkpoint once, every weight sync = lora_a + lora_b + buffers 38 MB ``` ## What changed - Every weight sync (the initial one, which also covers resume, included) carries the trainable parameters and the buffers: `Trainer.push_model_state_dict` leaves out the parameters with `requires_grad=False`. For LoRA that leaves `lora_a` and `lora_b`. Since #5730 RL recipes freeze nothing else (the router gate trains), so every other recipe still sends the whole model. No flag, no new config field. - Generators load the frozen parameters from `generator.checkpointer`, which the controller no longer rejects. Loads leave them out, and they keep their weight: the load reallocates each FSDP group's sharded storage, and `_restore_sharded_params` refills the frozen parameters' shards from the unsharded storage (which CUDA graphs read) before the group's unshard. Groups of only frozen parameters (e.g. `tok_embeddings`, the vision tower) are skipped. This lives in the engine-agnostic `ModelStateDictLoader` (`rl/generator/model.py`, #5811). - The generator freezes every parameter, so `build_inference_model` reads `requires_grad` right after the build, before freezing, and passes the frozen keys to `ModelStateDictLoader`. They are passed because the model cannot tell afterwards: a module does not record whether its config froze it. Inferring them from the module structure (every parameter but the LoRA adapters) breaks with `LoRATransform.trainable_modules` (#6003), which keeps any module trainable. - With frozen parameters but no generator checkpointer, the loader raises at setup, since no sync would fill them; so does a quantized frozen parameter (its unsharded weight cannot refill its shard). A load that misses any other parameter still raises. The `cpu_prefetch` path's pinned receive buffers cover only what the trainer pushes. The generator's HF load defaults to the model's HF assets, like the trainer's, for vLLM and SGLang (SGLang passes its `model_path`). - `rl_grpo_qwen3_5_0_8b_geometry3k_lora`: rank-32 LoRA on the language model's attention, GatedDeltaNet and MLP projections (vision tower frozen), lr 10x the full fine-tuning one, generators loading the HF checkpoint. At step 0 the generator's adapters are its own random `lora_a` with `lora_b = 0`, so its policy equals the trainer's; the first sync after an optimizer step sends both. ## Numerics / performance Geometry3K, Qwen3.5-0.8B on 4 GB300 (trainer FSDP=2 + 2 generators at TP=1), 30 steps: `rl_grpo_qwen3_5_0_8b_geometry3k_lora` vs the full fine-tuning recipe (TensorBoard logger; FA4 with `num_splits=1` for head_dim 256, a separate fix). Sync numbers are TorchStore's own timings, rank 0; later syncs are the median over syncs 2-31. | | full fine-tuning | LoRA, generators load the base | |---|---|---| | initial weight sync | 2.21 GB | 38 MB | | later weight syncs: bytes | 2,215 MB | 38 MB | | later weight syncs: generator pull / trainer put | 1.02 s / 0.089 s | 0.30 s / 0.026 s | | generator blocked on the pull, mean per step | 0.85 s | 0.16 s | | step time, steps 2-30, mean | 10.4 s | 8.6 s | | validation reward (601 test problems), start -> end | 0.263 -> 0.384 | 0.291 -> 0.371 | | trainer-generator logprob difference, mean per token | -0.0009 | -0.0006 | The generators' own HF load gives the trainer's frozen weights: the logprob agreement matches a run whose base came through the weight sync (-0.0007). At 38 MB a pull is bound by per-tensor overhead (~0.13 GB/s); with larger models the bytes dominate (a full Qwen3.5-27B sync in bf16 is ~54 GB). Step-0 validation differs by 0.02 between runs with the same weights, so the reward rows are within run-to-run noise. ## Testing Unit tests: a push carries the trainable parameters and the buffers (a LoRA base or a `freeze_gate` gate is left out); a load leaves out only frozen parameters, which keep their weight (one rank, and two ranks with uneven shards), and a missing trainable parameter raises; frozen parameters without a generator checkpointer raise at setup. ## Known issues / follow-ups - TODO in `ModelStateDictLoader`: every generator replica reads the checkpoint from storage at once (80 reads with 10 nodes x 8 GPUs at DP=1). A follow-up sends the frozen parameters once through the initial weight sync instead (drafted on top of this PR). - Not in this PR: adapters-only checkpoints and HF export. (The trainer already stores the frozen base in `precision.param_dtype`, #5894.)
Summary (human-written)
In a previous PR we froze the router. We shouldn't. In this PR i rename the class and remove the router from it.
Agent details
TLDR: RL recipes train the MoE router gate.
build_rl_model_configsturns off only load balancing: the expert-bias update and the router aux loss. The moving expert bias is what grew the trainer-vs-generator logprob gap. With the gate trainable, the gap stayed flat over 60 steps on a 4-layer Qwen3.5-35B-A3B (-1%; the frozen-gate runs fell 8% and 15%).Problem
topk(score(gate(x)) + expert_bias_E).gateis a linear layer.expert_bias_Eis a buffer that a load-balancing hook moves once per optimizer step, just before the step.Solution
FreezeMoERoutingTransformbecomesDisableMoELoadBalancingTransform(disable_moe_load_balancing.py). On everyMoE.Configit setsfreeze_expert_bias=Trueandrouter.aux_loss=None. It no longer setsrouter.freeze_gate.build_rl_model_configs(disable_moe_load_balancing=True)replacesfreeze_moe_routing=True. It appends the transform to the same transforms list, for both roles.TokenChoiceTopKRouter.Config.freeze_gatestays, off by default. The expert bias still routes, at its loaded value. Dense recipes, pretraining and SFT are untouched.Results
You may ask:
torchtitan_recipes/models/muse_spark.py:82, applied at:368-369), and its RL recipe uses one lr, so its RL gate runs at 8x its pretraining ratio. A recipe can add an AdamW pattern\.router\.gate\.before.*(first match wins; it must match a parameter in every model part).freeze_gate? To resume a checkpoint saved on main with its optimizer state (NOTE), and for a frozen-gate run like the one in the table.NOTE: two different biases.
router.gate.bias(gpt-oss) is a learned weight of the gate,gate(x) = W x + b: it trains withgate.weight, as in pretraining.expert_bias_Eis the load-balancing buffer, kept frozen. gpt-oss has none (load_balance_coeff=None).NOTE: an MoE RL checkpoint saved on main since 2026-10-12 has no optimizer state for the gate, so it fails to resume:
Missing key in checkpoint state_dict: optimizer.state.layers.0.feed_forward.router.gate.weight.step. Either setrouter.freeze_gate=Trueon the trainer's MoE configs (the optimizer state loads as saved), orexclude_from_loading=["optimizer", "lr_scheduler"](fresh Adam state, restarted LR schedule; the checkpointer requires both). Checked on CPU withdcp.save/dcp.load: the error and thefreeze_gateload. The second way was not run.NOTE: not measured: gpt-oss, and a trainable gate next to a frozen nonzero expert bias (Muse Spark 816B, the only MoE RL recipe that loads one; the DeepSeek-V3 and Kimi K3 debug recipes start it at zero).
NOTE: not run: a reward A/B of frozen vs trained gate, and a batch-invariant check that the trained gate reaches the generator bitwise. The trainer pushes its full state dict (no
requires_gradfilter). GPU CI runs the MoE RL recipes with zero gradients (random init, zero reward), so it never moves the gate. Only the ablation above moved it on GPU (TP1).Test plan
pytest tests/rl/unit_tests/cpu: 504 passed, 9 skipped (verifiers, dist_moe, CUDA, one TODO).pytest tests/unit_tests/cpu/models/common/test_moe.py tests/unit_tests/cpu/config tests/unit_tests/cpu/components/optim tests/unit_tests/cpu/models/common/test_aux_loss.py: 337 passed.test_disable_moe_load_balancing.py: every MoE family, one AdamW step with the balancing hooks. Expert bias frozen, every parameter trains (gate included), aux loss removed.test_model_defaults.pybuilds everyrl_*recipe intorchtitan_recipes/rlandtorchtitan_recipes/tests/rlthat needs no argument or missing package (44 here, 18 MoE). Both roles: expert bias frozen, no aux loss, gate not frozen. Not swept: the Muse Spark 816B config (takes arguments) and the verifiers, MXFP8 and dist-MoE recipes.freeze_gatehas no behavior test.