Skip to content

[rl] RL model defaults in every run: fp32 lm_head, frozen MoE expert bias and router gate - #5271

Merged
felipemello1 merged 5 commits into
pytorch:mainfrom
felipemello1:rl-model-defaults
Oct 13, 2026
Merged

felipemello1 merged 5 commits into
pytorch:mainfrom
felipemello1:rl-model-defaults

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: build_rl_model_configs is called by every RL recipe. It now gives the trainer and generator model configs two defaults: fp32 lm_head logits, and frozen MoE routing (new FreezeMoERoutingTransform). 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

  1. The trainer moves the expert bias. Before each optimizer step, a balancing hook updates every MoE layer's expert_bias_E. This happens in RL too.
  2. The bias changes which experts win. It pushes experts close to the top-k cutoff. There, tiny trainer-vs-vLLM numeric differences pick different experts: 3.2% -> 9.0% of tokens per layer after 30 steps at lr=0, with bitwise-correct weight sync. The logprob gap triples.
  3. Who has a moving bias today: Kimi K3 (quantile balancing), and any checkpoint that ships a bias (DeepSeek-V3, Kimi K2.7). Qwen3 MoE had one until the batch-wise aux loss replaced it.
  4. Balancing is not the RL objective. 13 of the 16 MoE recipes add a batch-wise aux loss. Its gradient pushes the hidden states toward uniform expert load.
  5. fp32 logits are opt-in. Each recipe has to remember LMHeadFP32OutputConverter.

Solution

  1. build_rl_model_configs applies both defaults to both configs, each behind a flag: fp32_lm_head=True and freeze_moe_routing=True. Pass False to skip one.
  2. fp32_lm_head appends LMHeadFP32OutputConverter, as the recipes did.
    • The recipes drop 14 converter lines, and 3 wrappers drop their append.
    • Muse Glimmer opts out: its soft-capped head can't be converted yet.
  3. FreezeMoERoutingTransform sets three fields on every MoE.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.
  4. LMHeadFP32OutputConverter changes in two ways:
    • it skips a head that is already converted;
    • it raises on a Linear subclass (e.g. a soft-capped head) instead of dropping its forward.
  5. Unchanged: pretraining and SFT, which don't call this function. The new MoE fields default to False.

Results

What changes per RL recipe vs main: 43 of 45 recipes build on CPU (MXFP8 and dist_moe need packages),
trainer and generator configs
16 MoE recipes       freeze_expert_bias, router.freeze_gate: False -> True
13 of them           router.aux_loss: BatchWiseLoadBalanceLoss -> None
3 Kimi K3 recipes    quantile-balanced expert bias: moves -> frozen
all recipes          lm_head unchanged (already fp32; Muse Glimmer stays bf16)
Qwen3-30B-A3B, first 8 layers, real weights, H100, earlier main (Qwen3 MoE still had an expert bias).
Real trainer + vLLM actors and weight sync, no RL loop: 30 x (generate -> score -> optimizer_step(lr=0) -> push/pull).

trainer-vs-vLLM logprob abs mean, step 0 -> 29
bias moves     0.053 -> 0.157
bias frozen    0.054 -> 0.053

You may ask:

  • Why not load_balance_coeff=None in the recipes? It deletes a checkpoint's bias (DeepSeek-V3, Kimi K2.7). Kimi K3's quantile balancing keeps its bias anyway.
  • Why freeze the gate rather than train it at a lower lr? With the bias frozen and the aux loss off, nothing balances a trainable gate. A lower gate lr is the alternative, left as a TODO in the code. There is no ablation yet.
  • Why a transform, not code inside the RL helper? Any recipe can apply it, e.g. for MoE SFT: transform_model_config_(model, [FreezeMoERoutingTransform()]).

NOTE:

  • GPU: a 3-step RL smoke on 2 H100s (Kimi K3 and Qwen3.5 MoE debug models, random init, forced non-zero advantages). The router gates and expert biases stay bitwise unchanged while the other weights move, and no balancing hook is registered. Not run: the GPU unit tests, a real-checkpoint run, and FSDP+TP+EP.
  • The "bias frozen" run used an earlier version of this PR, which still ran the hook but skipped the update. The bias stays at its loaded value either way.
  • A checkpoint saved with frozen routing can't resume with freeze_moe_routing=False, because the gates have no optimizer state. The other direction works.
  • With the bias frozen, nothing resets the router's usage counts. Only the balancing hooks read them (TODO in the code).

Test plan

pytest tests/unit_tests/cpu/config/test_freeze_moe_routing.py tests/rl/unit_tests/cpu/test_model_defaults.py \
  tests/unit_tests/cpu/components/optim/test_optimizer_param_groups.py \
  tests/unit_tests/cpu/models/common/test_hi_mid_lo_linear.py \
  torchtitan/experiments/torchft/tests/test_torchft_optimizer.py
  • test_freeze_moe_routing.py runs one AdamW step on each MoE family's debug flavor, frozen vs not. With the freeze:

    • the gate (and gpt-oss's gate bias) stays unchanged and has no optimizer state;
    • the expert bias stays unchanged;
    • every other parameter still moves.
  • test_model_defaults.py builds every RL recipe and checks both model configs:

    • fp32 head, except Muse Glimmer;
    • every MoE layer frozen;
    • no aux loss.

    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=False leaves DeepSeek-V3's routing untouched.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
Comment thread torchtitan/rl/controller.py Outdated
Comment on lines +197 to +206
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

@tianyu-l tianyu-l Oct 11, 2026 •

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.

This can be covered by a single RLModelConfigTransform at config time, which won't be so bad?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan_recipes/rl/alphabet_sort.py Outdated
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")

@tianyu-l tianyu-l Oct 11, 2026 •

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/rl/controller.py Outdated
Comment on lines +166 to +179
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".

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.

maybe score centering solves them all?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@felipemello1
felipemello1 force-pushed the rl-model-defaults branch 2 times, most recently from 180e8dc to 0e7ba99 Compare October 12, 2026 04:37
@felipemello1
felipemello1 marked this pull request as ready for review October 12, 2026 04:51
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 12, 2026
…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.
Comment thread torchtitan_recipes/rl/model_configs.py Outdated
Comment on lines +51 to +57
# 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

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.

This itself should be a ModelConfigTransform -- you can either let agent do it, or leave it to @jinsooihm

@felipemello1 felipemello1 Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +1044 to +1045
if not moe.freeze_expert_bias:
moe.expert_bias_E.add_(expert_bias_delta_E)

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.

If only changing here, the above all-reduce collectives are all "wasted".

I think we should

  • update _should_register_moe_balancing_hook to look at freeze_expert_bias field and return False
  • similar to what it's doing in the function -- just raise exception if not all layers have the same decision

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())

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 think we should let this load balancing update share _should_register_moe_balancing_hook

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_()

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Felipe Mello added 2 commits October 12, 2026 17:53
…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).
@felipemello1
felipemello1 merged commit 4a4176e into pytorch:main Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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