Skip to content

SFT: keep the MoE router aux loss on TRL >= 1.18 - #18230

Merged
danielhanchen merged 2 commits into
mainfrom
sft-moe-router-aux-trl118
Nov 18, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
sft-moe-router-aux-trl118

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

On TRL 1.18 and newer, Unsloth SFT on a Mixture-of-Experts model silently drops the router load-balancing auxiliary loss. Stock TRL keeps training with it. For gpt-oss (router_aux_loss_coef = 0.9) the logged step-1 loss is 12.21 under Unsloth and 14.11 under TRL on the same batch; the gap is 0.9 * aux_loss.

This PR requests the router logits per forward, as TRL does, so the term is back on TRL >= 1.18. Nothing changes on TRL <= 1.17 or for dense models.

Unsloth pins trl<=1.15.0 today, so this does not affect current installs. It needs to land before the pin moves to 1.18.

Root cause

  • TRL 1.7 to 1.17: SFTTrainer.__init__ wrote text_config.output_router_logits = self.aux_loss_enabled (and the coefficient) into the model config. The model forward then added router_aux_loss_coef * aux_loss to its own loss, so any trainer that calls the model with labels got the term.
  • TRL 1.18: Keep the router config of the loaded model in models saved by SFTTrainer huggingface/trl#8103 removed that config write, so a saved model keeps its original router config. TRL now only sets inputs["output_router_logits"] = True inside its own SFTTrainer.compute_loss, then adds router_aux_loss_coef * outputs.aux_loss.
  • Unsloth: the default nll path of the Unsloth SFT compute_loss (sft_trainer_compute_loss in unsloth/models/rl_replacements.py) calls Trainer.compute_loss and never runs TRL's. On TRL 1.18 nothing asks for the router logits, so the model returns no aux_loss and adds nothing.
    • The dft path already adds the term, but it reads outputs.aux_loss, which is also None on TRL 1.18 for the same reason.

Fix

When TRL enables the aux loss (self.aux_loss_enabled), the Unsloth SFT compute_loss passes output_router_logits=True on the forward, the same kwarg TRL 1.15 through 1.18 pass. A shallow copy of the batch is used, so the caller's dict is not mutated.

  • nll: the model forward adds router_aux_loss_coef * aux_loss itself, exactly as it already does on TRL <= 1.17.
  • dft: gets outputs.aux_loss back, and its existing router_aux_loss_coef * aux_loss / steps applies again.
  • Coefficient: the trainer coefficient (including an explicit SFTConfig.router_aux_loss_coef) already reaches the MoE modules through the existing post-init sync in unsloth/models/rl.py.
  • TRL <= 1.17: the config flag is already on, so the kwarg changes nothing and the term is not counted twice.
  • Dense models, router_aux_loss_coef = 0, TRL 0.22: aux_loss_enabled is false or absent, so the batch passes through unchanged.
  • Config: untouched, matching TRL 1.18 (the router config saved with the model stays as loaded).

Tests

tests/test_sft_moe_router_aux_loss.py runs on CPU in a few seconds and needs no downloads. It uses a tiny random Qwen3-MoE and a tiny random gpt-oss, both with router_aux_loss_coef = 0.9, under a real SFTTrainer. For each model it compares three things on one batch, for both the loss and the gradient of every parameter:

  • the Unsloth compute_loss, loaded from source the same way the generated trainer compiles it
  • stock TRL SFTTrainer.compute_loss
  • an fp64 oracle: shifted-label CE / N plus coef * E * sum(f_e * P_e) over every layer's router logits

A second test checks that the kwarg is sent only when TRL enables the aux loss.

transformers / TRL before (main) after
5.23.0 / 1.18.0 3 failed: Unsloth loss 4.152 vs oracle 5.955 (Qwen3-MoE), 4.173 vs 5.975 (gpt-oss) 3 passed
5.22.1 / 1.17.1 parity tests pass (the model adds the term from the config); kwarg test fails 3 passed, no double count
5.17.0 / 1.15.0 parity tests pass; kwarg test fails 3 passed, no double count
4.57.6 / 0.22.2 parity tests skipped (no aux loss in this TRL); kwarg test fails 1 passed, 2 skipped

On TRL 1.15 the stock TRL comparison is skipped on CPU, because that release launches its Triton fused-head kernel on CPU tensors. The Unsloth vs fp64 oracle comparison still runs there.

End to end on GPU (tiny LoRA SFT, bf16, batch 2, gradient accumulation 2, transformers 5.23 / TRL 1.18), logged step-1 loss:

model stock TRL Unsloth before Unsloth after oracle CE + coef * aux
tiny gpt-oss (coef 0.9 from config) 14.1145 12.2090 14.1145 14.1148
tiny Qwen3-MoE (router_aux_loss_coef = 0.9 in SFTConfig) 13.9706 11.9295 13.9709 13.9705
tiny gpt-oss, loss_type = "dft" 1.9056 0.0001 1.9056 DFT term about 0.0001 + 0.9 * 2.1175

Gradient accumulation 2 over identical rows, so the per-micro-batch term weighting is the same in every arm. The stock TRL gpt-oss arm loads the tiny checkpoint with Mxfp4Config(dequantize=True). Grad norms are not compared end to end, because the LoRA A initialisations differ between Unsloth and PEFT; the CPU test compares gradients exactly.

TRL 1.18 (trl#8103) stopped writing output_router_logits into the model
config and only requests the router logits per forward inside its own
SFTTrainer.compute_loss. The Unsloth nll path calls Trainer.compute_loss,
so on TRL >= 1.18 the model never returned aux_loss and the
router_aux_loss_coef * aux_loss term TRL trains with was dropped (dft too).

Request output_router_logits per forward when TRL enables the aux loss,
as TRL does. The model forward then adds the term itself, as it already
does on TRL <= 1.17 where the config flag is on, so there is no double
count and the config is left untouched.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T23:27:19.903834Z af4de5e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: af4de5e7c1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

[skip ci]
@danielhanchen
danielhanchen merged commit a8bdb8f into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the sft-moe-router-aux-trl118 branch November 18, 2026 00:16
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 18, 2026
…thai#18254)

## Summary

Follow-up to unslothai#18230 for pipeline parallel. On TRL 1.18 and newer, SFT of
a mixture-of-experts model under `UNSLOTH_PP_SIZE` silently drops the
router load-balancing auxiliary loss, while a single-GPU run and stock
TRL keep it.

TRL 1.18 (trl#8103) no longer writes `config.output_router_logits`.
`SFTTrainer` now passes `output_router_logits=True` to each forward from
`compute_loss` when `aux_loss_enabled`, and unslothai#18230 made Unsloth's SFT
`compute_loss` do the same. The pipeline Trainer step never calls
`compute_loss`: it hands the batch to the stage schedule, and the stages
decide whether to carry and add the aux term from
`config.output_router_logits` only (`_PPStageModule._router_statistics`
in `unsloth/models/pp_native.py`). On TRL 1.18 that flag stays at the
checkpoint's `False`, so every stage skips the router statistics and the
last stage returns the cross entropy alone. The micro-batch split
refusal and the reentrant checkpointing refusal read the same flag, so
they stopped firing too.

## Changes

- `pp_env._pp_training_step` / `_pp_prediction_step` pass the trainer's
per-forward request to the stages for the step (`True` when
`aux_loss_enabled`, else `None`), the same signal unslothai#18230 uses, and clear
it afterwards (also when the step raises).
- `pp_native` reads `output_router_logits` the way the model forward
does: the step's request, else the config's (`_router_aux_requested`).
Used by the stage statistics, the split refusal, the reentrant
checkpointing refusal and the uncarried MoE refusal.
- The aux term itself is carried and weighted exactly as before when the
config flag is on (same coefficient source, same gradient accumulation
weighting, same zoo CPU path).

Nothing changes for dense models, for a plain `Trainer` (no
`aux_loss_enabled`: the config decides as before), or for TRL 1.15 to
1.17, which already set `config.output_router_logits =
aux_loss_enabled`. The switch is a boolean, so having both the config
flag and the request on adds the term once.

## Verification

New `tests/test_pp_moe_router_aux_trl118_gloo.py`: gloo PP=2 through the
pp_env Trainer step vs one process, tiny random Qwen3-MoE, fp32, with
`config.output_router_logits` as each TRL version leaves it.

| Cell | Before | After |
| --- | --- | --- |
| TRL 1.18 state, aux on | FAIL: PP loss 4.8622 vs 5.9023 (cross entropy
only) | PASS |
| TRL 1.18 state, aux on, CPU backend | FAIL: 4.8622 vs 5.9023 | PASS |
| TRL 1.15 to 1.17 state (config and request on) | PASS | PASS (added
once) |
| `router_aux_loss_coef = 0.0` | PASS | PASS |
| Plain `Trainer`, config on | PASS | PASS |
| TRL 1.18 state, 2 micro-batches (split refusal) | FAIL: trains without
the term | PASS: refused |

Run on transformers 5.23 / TRL 1.18 / torch 2.14 and transformers 5.22 /
TRL 1.17 / torch 2.14 (same results), and transformers 5.17 / TRL 1.15 /
torch 2.10, where GPipe cannot run one micro-batch over two stages, so
only the split refusal cell runs (fails before, passes after) and the
parity cells skip.

The one-process reference matches stock TRL `SFTTrainer.compute_loss` on
the same batch: loss 5.902254 on TRL 1.18 and 1.17, max gradient
difference 9.7e-08.

The same Trainer step on one B200 (two pipeline ranks on one card, gloo,
tiny Qwen3-MoE in float32 and float16), TRL 1.18 state: PP loss 4.8622
before (cross entropy only, gradients off by up to 0.16 against a
largest gradient of 0.28) and 5.9023 after, equal to the one-process
forward, with identical gradients. TRL 1.17 state and
`router_aux_loss_coef = 0.0` are unchanged.

Existing PP MoE suites (`test_pp_moe_aux_gloo.py`,
`test_pp_moe_aux_off_gloo.py`, `test_pp_mm_moe_aux_gloo.py`,
`test_pp_env_cpu_router_aux.py`, `test_pp_env_cpu_chunked_ce.py`,
`test_pp_env_eval.py`, `test_parallel_env.py`) give the same results
before and after. `test_pp2_moe_refusals_for_unproven_cases` fails on
both sides (the DeepSeek-V3 checkpoint is now refused for multi-head
latent attention before the MoE check) and is unrelated to this change.
meefs pushed a commit to meefs/unsloth that referenced this pull request Nov 22, 2026
`pyproject.toml` capped TRL at `<=1.15.0`. That cap was never tied to a
known break: unslothai#13203 set it to the newest release the version matrix had
run, which was 1.15.0 at the time (TRL 1.15 shipped Oct 8). Since then
TRL shipped 1.16.0, 1.17.0, 1.17.1, 1.18.0, 1.18.1 and 1.18.2. AsyncGRPO
needs 1.17+, and tree packing for recurrent layers needs it too. Most of
the 1.16 to 1.18 support work already landed on main (unslothai#16220, unslothai#17714,
unslothai#18070, unslothai#18175, unslothai#18230, unslothai#18254, unslothai#18271, unslothai#18466, unslothai#18614 and others), and
the `HF=latest + TRL=latest` CI lane already runs TRL 1.18.2. Users
still could not install any of it because of the cap.

This PR raises the window to `trl>=0.18.2,!=0.19.0,<=1.18.2` and fixes
the four breaks I found going through 1.16 to 1.18.2 at transformers
5.18.0. Two of them are silent on 1.18: the patch anchor stops matching,
so the trainer still builds but does something different.

### Fixes

1. **AsyncGRPO on TRL 1.16.0 crashed on the first step** with `KeyError:
'tree_segment_parents'`. TRL 1.16 already packs AsyncGRPO rows as a
prefix trie, but it only sends `tree_kv_index` / `tree_cu_seqlens_q` /
`tree_cu_seqlens_k`. `tree_segment_parents` arrived in 1.17, and unslothai#18070
handled only the 1.17+ layout. The parents can be recovered from the K/V
paths: each segment's path is its parent's path plus its own tokens.
`_async_grpo_tree_segment_parents` does that, and on TRL >= 1.17 it
gives exactly the parents TRL sends (there is a test for this). The tree
tests now build TRL 1.16's forward kwargs when `unpad_tree` is missing,
instead of skipping.
2. **SFT with padding-free stopped truncating pre-tokenized datasets on
TRL 1.18.** The padding-free `max_length` block was only generated when
TRL's SFTTrainer had the "`max_length` is not enforced" refusal. TRL
1.18 removed that refusal because its own `_prepare_dataset` truncates.
Zoo's prep replaces that step, though, and leaves rows that already have
`input_ids` alone. So on 1.18 a pre-tokenized dataset trained at full
length: in the version-compat test, 1202-token rows went through against
a 128-token cap. The block is now generated on TRL >= 1.18 too. The 31
tests in `test_trl_padding_free_max_length.py` that skipped on 1.18 now
run there and pass.
3. **SFT `assistant_only_loss` lost its train_on_responses_only fallback
on TRL 1.18.** TRL 1.18 calls
`get_training_chat_template(processing_class,
require_prefix_preservation=False)`, and the anchor only matched the old
one-argument call. A chat template TRL cannot train, such as plain
ChatML without `{% generation %}` markers, went back to raising TRL's
`ValueError`. The anchor now accepts trailing arguments and keeps them.
4. **`UNSLOTH_ENABLE_FLEX_ATTENTION=1` stopped padding to the flex block
size on TRL >= 1.16.** TRL 1.16 changed the `pad_to_multiple_of` default
from `None` to `"auto"`, so `"auto"` now counts as unset too.

Two other changes looked like they might break things and are fine. TRL
1.18's `GKDTrainer` now generates inside `get_batch_samples`, which is
upstream's version of the fix the GKD patch applies to the older
`training_step`, so the patch has nothing to do there. TRL 1.18's new
`qwen3_6_v2` template renders like `qwen3_6` and shares its training
template. The tool-template test now accepts both instead of expecting a
single family.

### Cap sites moved together

- `pyproject.toml` (both trl lines),
`studio/backend/requirements/no-torch-runtime.txt`
- `notebooks-ci.yml` lane, and the `version-compat-ci.yml` ceiling lane
now pins `trl==1.18.2` with `transformers==5.18.0`
- `tests/test_trl_cap_sites.py`: `TESTED_CEILING = 1.18.2`,
`NEWLY_ADMITTED` adds 1.16.0 through 1.18.2, and
`ZOO_FLOOR_ADMITTING_TESTED_TRL_CEILING = None`

unsloth_zoo caps TRL at `<=1.15.0` too, and pip takes the lower of the
two caps. The matching zoo change is a one-line pyproject lift. Until a
zoo release ships with it, pip keeps users on 1.15.0, so the zoo floor
gate stays deferred.
`test_the_zoo_trl_deferral_expires_when_the_zoo_release_ships` fails as
soon as a published zoo admits 1.18.2, and that is the point to raise
the `unsloth_zoo` floor here.

### Testing

Everything below runs at transformers 5.18.0 (the pyproject ceiling).
The CPU suites use torch 2.10 CPU. The GPU jobs run on Colab, with main
and this PR on the same VM and the same deps, and only the unsloth tree
swapped.

**CPU, 307 TRL-touching test files:**

| tree | TRL | passed | failed | skipped |
|---|---|---|---|---|
| main | 1.15.0 | 5960 | 182 | 951 |
| main | 1.16.0 | 5969 | 178 | 946 |
| main | 1.17.1 | 5976 | 173 | 944 |
| main | 1.18.2 | 5941 | 180 | 972 |
| this PR | 1.15.0 | 5957 | 185 | 953 |
| this PR | 1.18.2 | 5982 | 167 | 946 |

163 test IDs fail in every one of these runs: CUDA-only kernels and gloo
cases on a CPU box, plus no torchao. Comparing by test ID, the only
tests that move with the TRL version are the four breaks above. The rest
of the delta is a few dozen gloo / timing / packing tests that flip
between xdist runs, and every one of those passes on both trees and both
TRL versions when rerun alone. The unsloth_zoo side (126 TRL-touching
test files) shows no failure specific to TRL 1.16.0 or 1.18.2.

**Flip tests** (this PR's tests run against main's code):

| test | TRL | main | this PR |
|---|---|---|---|
| AsyncGRPO trio (`test_async_grpo_trl_tree.py`, `_patch.py`,
`_fast_inference.py`) | 1.16.0 | 7 tree tests fail, 4 with `KeyError:
'tree_segment_parents'` | 68 passed |
| same | 1.15.0 / 1.17.1 / 1.18.2 | pass | 61 / 68 / 70 passed |
| `test_trl_padding_free_max_length.py` | 1.18.2 | 34 failed
(pre-tokenized rows not truncated, cap not consumed) | 155 passed |
| same | 1.15.0 / 1.17.1 | pass | 155 passed |
| `version_compat/test_sft_assistant_mask_fallback_trainer.py` (real
UnslothSFTTrainer, ChatML without markers, `assistant_only_loss=True`) |
1.18.2 | `ValueError: The chat template is not training-compatible` |
pass |
| same | 1.15.0 / 1.17.1 | pass | pass |
| `test_sft_assistant_mask_fallback.py::test_applies_to_installed_trl`
(real TRL source) | 1.18.2 | fail | pass |
|
`test_flex_pad_to_multiple_of_auto.py::test_trl_default_pads_to_the_flex_block`
| 1.17.1, 1.18.2 | fail (stays `None`) | pass (128) |
| same | 1.15.0 | pass | pass |
| `test_trl_cap_sites.py` + flex test | 1.15.0 / 1.17.1 / 1.18.2 | | 37
passed, 4 skipped (deferred zoo gate) |
| CI TRL discovery shim (taken from `consolidated-tests-ci.yml`) |
1.15.0 / 1.16.0 / 1.17.1 / 1.18.2 | | pass |

**GPU jobs** (`jobs/*.py --backend unsloth`, verdicts from
`jobs/compare.py`):

Final head, L4, one VM, TRL 1.15.0 / 1.16.0 / 1.18.2 x main / this PR:

| job | model | main vs PR at each TRL | PR, TRL 1.15.0 vs 1.16.0 /
1.18.2 |
|---|---|---|---|
| sft | Qwen3-0.6B | NO_REGRESSION x3 | NO_REGRESSION, same loss on
every step in all 6 runs |
| dpo | Qwen3-0.6B | NO_REGRESSION x3 | NO_REGRESSION, same loss on
every step in all 6 runs |
| vision_sft `--tiny` | tiny Qwen2.5-VL | NO_REGRESSION x3 |
NO_REGRESSION, same loss on every step in all 6 runs |
| grpo (notebook preset) | Qwen3-0.6B-Base | NO_REGRESSION x3 |
NO_REGRESSION (sampled rollouts, within the main-vs-main spread) |

Earlier runs used the first commit. The later commits change AsyncGRPO
tree rows and SFTTrainer init, and the table above covers SFTTrainer
init:

| job | where | main vs PR | PR, TRL 1.15.0 vs 1.18.2 |
|---|---|---|---|
| grpo `--fast-inference` (vLLM 0.32.0), Qwen3-0.6B-Base | G4 |
NO_REGRESSION at 1.15.0 and 1.18.2 | NO_REGRESSION |
| sft / grpo / dpo `--tiny` | A100 | NO_REGRESSION at 1.15.0 and 1.18.2
| same loss on every step |

**AsyncGRPO, `fast_inference=True`** (vLLM 0.32.0, Qwen3-0.6B, LoRA
r=16, 6 steps, RTX PRO 6000):

| TRL | main | this PR |
|---|---|---|
| 1.16.0 | crashes: `KeyError: 'tree_segment_parents'` | trains 6 steps,
mean reward 0.93 |
| 1.17.1 | trains 6 steps, mean reward 0.91 | trains 6 steps, mean
reward 0.91 |
| 1.18.2 | trains 6 steps, mean reward 0.92 | trains 6 steps, mean
reward 0.82 (one sampled 6-step run) |

### Not covered

- No published unsloth_zoo admits TRL > 1.15.0 yet, so users only get
1.16+ after the zoo lift ships and the floor here moves.
- `unslothai/notebooks` pins TRL on its own side (`PIN_TRL`), and so
does Studio's single-env install (`trl==0.23.1`). This PR does not touch
either.
- TRL 1.18 with transformers 5.23+ is covered only by the existing
`HF=latest` lane. pyproject still caps transformers at 5.18.0.
- No multi-GPU (FSDP2 / DDP) GRPO or AsyncGRPO run on 1.16 to 1.18. The
CPU gloo tests cover what they can.
- TRL 1.17.0, 1.18.0 and 1.18.1 were not run on their own. 1.17.1 and
1.18.2 are patch releases on top of them.
- Windows, macOS / MLX and AMD were not run.

Companion: unslothai/unsloth-zoo#2656 raises the zoo ceiling the same
way; merge it first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant