Repository navigation
[rl] RL model defaults in every run: fp32 lm_head, frozen MoE expert bias and router gate - #5271
Conversation
| if self.fp32_lm_head: | ||
| model = LMHeadFP32OutputConverter.Config().build().convert(model) | ||
| for _fqn, moe_config, _parent, _attr in model.traverse(MoE.Config): | ||
| if self.freeze_expert_bias: | ||
| moe_config.freeze_expert_bias = True | ||
| if self.freeze_router_gate: | ||
| moe_config.router.freeze_gate = True | ||
| if self.disable_router_aux_loss: | ||
| moe_config.router.aux_loss = None | ||
| return model |
There was a problem hiding this comment.
This can be covered by a single RLModelConfigTransform at config time, which won't be so bad?
- After all it's going to be agents looking at examples in titan before constructing their own.
- Serious users already manage their own configs (not using our setup, not using our transform, just use the runtime after building their own config). Example: [Config][CP] Implement ModelTransform internface and use CP as the first example #4322 (comment)
- We also have
overridemechanism which mixed together could be quite confusing.
There was a problem hiding this comment.
reply from claude: Agreed. The controller doesn't touch the model anymore. build_rl_model_configs applies the RL defaults at config time to both role configs, so --print-config shows them and override still applies on top. The MoE part is now a ModelConfigTransform (FreezeMoERoutingTransform; details in the model_configs.py thread). The fp32 head stays the existing LMHeadFP32OutputConverter, appended to converters, until the lm_head-transform PR turns it into a transform.
| model_config = _build_qwen3_rl_model_config( | ||
| "0.6B", seq_len=seq_len, attn_backend="varlen" | ||
| ) | ||
| model_config = build_model_config("0.6B", seq_len=seq_len, attn_backend="varlen") |
There was a problem hiding this comment.
I'm in a refactor to let trainer and generator have their own config. See #5280 (comment)
"isn't this (allowing) breaking unified model assumption" -- yes, but there are other pragmatic concerns like some transform can be applied for trainer not generator; it also makes sharding annotation easier.
There was a problem hiding this comment.
reply from claude: Rebased on it. Both configs get the defaults: the lm_head has to match on both sides, and the freezes are no-ops on the generator.
| freeze_expert_bias: bool = True | ||
| """Keep every MoE layer's expert bias at its loaded value. A moving bias flips more expert | ||
| choices between the trainer and generator each step, so their logprob gap keeps growing. | ||
| No-op on dense models and on MoE layers without an expert bias.""" | ||
|
|
||
| # TODO: consider training the router at a lower lr instead of freezing it: set this | ||
| # False and add an optimizer group matching `router\.gate\.` before the catch-all. | ||
| freeze_router_gate: bool = True | ||
| """Keep every MoE router's gate (weight and bias) at its loaded value, so expert choices move | ||
| only with the hidden states and the expert bias. The Qwen3.5 shared-expert gate still trains. | ||
| Side effects: | ||
| - an optimizer group that matches only gates fails with "matched no parameters"; | ||
| - LoRA adapters on a gate are frozen too; | ||
| - a checkpoint saved with this on cannot resume with it off: "Missing key ... gate.weight.step". |
There was a problem hiding this comment.
maybe score centering solves them all?
There was a problem hiding this comment.
reply from claude: I don't think so; they act on different things. Score centering corrects the gradient for a trainer/vLLM gap, but it doesn't shrink the gap. The bias drift has no gradient: at lr=0 the gap grew 0.053 -> 0.157 in 30 steps from the balancing hook alone (Qwen3 with a bias; today only Kimi K3's bias moves), so no loss term can stop it. Freezing the gate covers the case you raised: with the bias frozen and no aux loss, nothing would balance a trainable gate. Score centering stacks on top, and it fits the ~3% of tokens per layer that still route differently with everything frozen. I'm running the ablation now (gate frozen vs trainable, aux loss on vs off) and will post the numbers here; happy to drop either piece if it shows no effect.
180e8dc to
0e7ba99
Compare
0e7ba99 to
16b427d
Compare
…rt bias and router gate build_rl_model_configs applies them to the trainer and generator model configs: fp32_lm_head (lm_head -> HiMidLoLinear) and freeze_moe_routing (every MoE layer keeps its expert bias and router gate, no router aux loss). Muse Glimmer opts out of the fp32 head. A moving expert bias made the trainer-vs-vLLM logprob gap grow every step on MoE models.
16b427d to
e2a14cc
Compare
| # TODO: consider enabling router training, but with a lower lr | ||
| if freeze_moe_routing: | ||
| for model_config in model_configs: | ||
| for _fqn, moe_config, _parent, _attr in model_config.traverse(MoE.Config): | ||
| moe_config.freeze_expert_bias = True | ||
| moe_config.router.freeze_gate = True | ||
| moe_config.router.aux_loss = None |
There was a problem hiding this comment.
This itself should be a ModelConfigTransform -- you can either let agent do it, or leave it to @jinsooihm
There was a problem hiding this comment.
reply from claude: Done: FreezeMoERoutingTransform in torchtitan/config/transform/freeze_moe_routing.py. For every MoE.Config it sets freeze_expert_bias=True, router.freeze_gate=True and router.aux_loss=None. build_rl_model_configs applies it to both role configs when freeze_moe_routing=True (the default), through transform_model_config_. It needs no options and no relations: it only sets fields, so its order relative to LoRA, CP or the dispatcher transforms doesn't matter. Tests: tests/unit_tests/cpu/config/test_freeze_moe_routing.py, one AdamW step per MoE family, frozen vs not.
| if not moe.freeze_expert_bias: | ||
| moe.expert_bias_E.add_(expert_bias_delta_E) |
There was a problem hiding this comment.
If only changing here, the above all-reduce collectives are all "wasted".
I think we should
- update
_should_register_moe_balancing_hookto look atfreeze_expert_biasfield and return False - similar to what it's doing in the function -- just raise exception if not all layers have the same decision
There was a problem hiding this comment.
reply from claude: Done. _should_register_moe_balancing_hook is now module-level and takes the MoE layers. It returns False when they are frozen, and raises if only some are. So neither hook registers for a frozen model, there's no all-reduce, and the per-layer guards are gone. I kept the load_balance_coeff check in the sign hook: Kimi K3's quantile layers have load_balance_coeff=None, so sharing it would stop the quantile hook from ever registering.
| quantile_balancer.required_bias_histogram_EB.zero_() | ||
| router.tokens_per_expert_E.zero_() | ||
|
|
||
| optimizers.register_step_pre_hook(lambda *args, **kwargs: _update_expert_bias()) |
There was a problem hiding this comment.
I think we should let this load balancing update share _should_register_moe_balancing_hook
There was a problem hiding this comment.
reply from claude: Done. The quantile hook calls _should_register_moe_balancing_hook too, in place of its if not moe_layers: return.
| moe.expert_bias_E.add_(expert_bias_delta_E) | ||
| if not moe.freeze_expert_bias: | ||
| moe.expert_bias_E.add_(expert_bias_delta_E) | ||
| moe.router.tokens_per_expert_E.zero_() |
There was a problem hiding this comment.
A side effect is that this would never be zero'ed from iteration to iteration, but for now it seems OK as it's not used in logging anyways. Can revisit later.
There was a problem hiding this comment.
reply from claude: Agreed. Main already behaves this way for every model with load_balance_coeff=None (all Qwen3 MoE recipes today): the router keeps adding to the counts and nothing resets them. When frozen, Kimi K3's histogram behaves the same way. I left a TODO in _should_register_moe_balancing_hook: add a zero-only hook once something else reads them.
…skip a frozen bias - New FreezeMoERoutingTransform (torchtitan/config/transform): for every MoE.Config it sets freeze_expert_bias=True, router.freeze_gate=True and router.aux_loss=None. - build_rl_model_configs takes shared_transforms, default (FreezeMoERoutingTransform(),), applied to both role configs. It replaces the freeze_moe_routing flag; shared_transforms=() trains the router. - _should_register_moe_balancing_hook is module-level and decides on freeze_expert_bias. The sign and quantile hooks both use it, so a frozen model registers no hook and skips the counts all-reduce. Mixed frozen and unfrozen layers raise. - The transform tests move to tests/unit_tests/cpu/config/test_freeze_moe_routing.py.
…nsforms tuple Flags read better and flip one default at a time. The flag adds FreezeMoERoutingTransform to one transforms list, applied to both role configs with transform_model_config_ (keeping the returned root).
TLDR:
build_rl_model_configsis called by every RL recipe. It now gives the trainer and generator model configs two defaults: fp32 lm_head logits, and frozen MoE routing (newFreezeMoERoutingTransform). A moving expert bias makes the trainer-vs-vLLM logprob gap grow: 0.053 -> 0.157 in 30 steps at lr=0 (Qwen3-30B-A3B with a bias, earlier main). With the bias frozen, the gap stays flat (0.054 -> 0.053). Today only the 3 Kimi K3 debug recipes move a bias, but an RL run on any model that ships one (DeepSeek-V3, Kimi K2.7) would. No recipe's lm_head changes; new recipes can no longer forget the fp32 head.Problem
expert_bias_E. This happens in RL too.LMHeadFP32OutputConverter.Solution
build_rl_model_configsapplies both defaults to both configs, each behind a flag:fp32_lm_head=Trueandfreeze_moe_routing=True. Pass False to skip one.fp32_lm_headappendsLMHeadFP32OutputConverter, as the recipes did.FreezeMoERoutingTransformsets three fields on everyMoE.Config:freeze_expert_bias=True(new field): the balancing hooks are not registered, so they skip their all-reduce;router.freeze_gate=True(new field): the gate gets no gradient and no optimizer state;router.aux_loss=None.LMHeadFP32OutputConverterchanges in two ways:Results
You may ask:
load_balance_coeff=Nonein the recipes? It deletes a checkpoint's bias (DeepSeek-V3, Kimi K2.7). Kimi K3's quantile balancing keeps its bias anyway.transform_model_config_(model, [FreezeMoERoutingTransform()]).NOTE:
freeze_moe_routing=False, because the gates have no optimizer state. The other direction works.Test plan
test_freeze_moe_routing.pyruns one AdamW step on each MoE family's debug flavor, frozen vs not. With the freeze:test_model_defaults.pybuilds every RL recipe and checks both model configs:CI's Verifiers pass runs it too, because the first pass can't import the two Verifiers recipe modules. A second test checks that
freeze_moe_routing=Falseleaves DeepSeek-V3's routing untouched.