Skip to content

Pipeline parallel on the CPU backend: weight the MoE router aux loss as TRL's SFTTrainer does - #17072

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
debojyoti-dev:fix/pp-cpu-router-aux-weighting-17054
Nov 11, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
debojyoti-dev:fix/pp-cpu-router-aux-weighting-17054

Conversation

@debojyoti-dev

@debojyoti-dev debojyoti-dev commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #17054

Problem

On the CPU backend (UNSLOTH_FORCE_CPU=1), pipeline parallel with an MoE model and the router aux loss on trains a different loss than one process once gradient accumulation is above 1. A coefficient set only through SFTConfig(router_aux_loss_coef = ...) is also dropped at every GA.

Reproduced on this PR's base (Qwen3-MoE tiny LoRA, router_aux_loss_coef = 0.5, PP=2 gpipe, bs 2, 3 steps, tests/test_parallel_cp_compose_gloo.py):

case one process PP=2 before PP=2 after
GA 1, aux on 12.9565, 12.9720, 12.9410 12.9565, 12.9720, 12.9411 12.9565, 12.9720, 12.9411
GA 2, aux on 12.9536, 12.9448, 12.9181 13.9711, 13.9492, 13.9275 (+7.9%) 12.9536, 12.9448, 12.9181
GA 4, aux on 12.9460, 12.9322, 12.9387 15.9886, 15.9495, 15.9565 (+23.5%) 12.9460, 12.9322, 12.9387
GA 1, coef only in SFTConfig 12.9565, 12.9720, 12.9410 11.9363, 11.9538, 11.9409 (aux dropped) 12.9565, 12.9720, 12.9411
GA 2, coef only in SFTConfig 12.9536, 12.9448, 12.9181 11.9401, 11.9360, 11.9262 12.9536, 12.9448, 12.9181

Root cause

With UNSLOTH_FORCE_CPU=1 the trainer is stock TRL's SFTTrainer, with zoo's CPU compute_loss wrapped around it. Unless zoo's chunked CE is armed, that wrapper falls through to TRL's own fused head loss. TRL 1.15 then adds the router term itself:

weighted_aux_loss = self.router_aux_loss_coef * outputs.aux_loss
steps = self.current_gradient_accumulation_steps if num_items_in_batch is not None else 1
loss = loss + weighted_aux_loss / steps

The pipeline schedule never calls compute_loss. The last stage adds the term the way the model forward would (pp_native.py):

term = moe.owner.router_aux_loss_coef * aux
loss = loss + _forward_aux_weighting(moe.owner, term, kwargs, ctx.num_items_in_batch)

On this path the forward has no unsloth_ga_scale_aux_loss, so _forward_aux_weighting returns the term unchanged. That gives two separate errors:

  1. Weighting. The full aux term is added on every accumulation step instead of / GA, so a window carries GA − 1 extra aux terms. The measured gap matches that: GA 2 is +1.0 (one extra 0.5 × aux, aux ≈ 2.0), and GA 4 is about +3.
  2. Coefficient. The stage reads moe.owner.router_aux_loss_coef, which the CausalLM cached at init. TRL ≥ 1.7 writes the SFTConfig value only to config.router_aux_loss_coef, and the cached-copy sync in rl.py lives in the Unsloth trainer patch, which the CPU trainer never goes through. So the stage adds the architecture default (0.001 on this tiny model), which is why the aux term vanishes.

On the GPU route the Unsloth trainer runs the model forward, which does call unsloth_ga_scale_aux_loss, so the existing token-share weighting there is right and stays as it is.

Fix

  • pp_env._trainer_router_aux(trainer, stage, n, chunked, train) works out how this trainer's own compute_loss would weight the aux term in one process. It returns (coefficient, divisor) only when all of these hold:

    • the stage carries an MoE aux plan (stage.ctx.moe)
    • type(trainer).compute_loss is zoo's CPU wrapper (_unsloth_cpu)
    • zoo's chunked CE is not armed for the step. When it is armed, zoo calls Trainer.compute_loss, so the forward adds the term and the old path is right. Eval always falls through to TRL under no_grad, so the chunked CE doesn't count there.
    • TRL's aux_loss_enabled is on and router_aux_loss_coef is set
    • TRL's own compute_loss reads router_aux_loss_coef and current_gradient_accumulation_steps (followed through the functools.wraps chain). TRL 1.14.x already sets trainer.router_aux_loss_coef but leaves the term to the model forward, so there the old path stays. Measured with TRL 1.14.2 (loss_type = "nll", GA 2): base PP 13.9724, 13.9471, 13.9359 equals one process; keying on the attribute alone gave 12.9542, 12.9450, 12.9152 (-7.3%); with the code check PP equals one process again.

    The divisor is current_gradient_accumulation_steps (so a short final window divides by its own length), or 1 when there is no window token count, or 1 for eval, where TRL's prediction step passes no num_items_in_batch.

  • _pp_training_step / _pp_prediction_step put that onto stage.ctx.trainer_aux for the step and clear it in a finally.

  • In pp_native, the last stage adds coef * aux / divisor when ctx.trainer_aux is set, and otherwise keeps _forward_aux_weighting. The logged last_aux_loss (unscaled sum) is unchanged.

Every other route (the GPU Unsloth trainer, chunked CE, dense models, aux off) keeps exactly the previous behaviour.

Tests

New tests/test_pp_env_cpu_router_aux.py (10 tests). It drives the real _pp_training_step / _pp_prediction_step with a stage stub that records what the last stage would see:

  • TRL coefficient over the accumulation steps (0.5, 4.0), and cleared after the step
  • a short last window divides by current_gradient_accumulation_steps (3), not the configured GA
  • no window token count gives divisor 1
  • cleared when the stage raises
  • the model forward keeps the term for the GPU trainer, aux off, no coefficient, dense models and an armed chunked CE
  • eval adds TRL's term once, even with chunked CE

4 of the 10 fail on the base commit (the behaviour checks), and all 10 pass with the fix.

End-to-end (real gloo, PP=2, real TRL 1.15 + unsloth_zoo 2026.11.3 CPU backend)

Windows 11, CPU torch 2.11.0 (GLOO_DEVICE_TRANSPORT=UV; torch 2.10's Windows gloo has no usable device here), transformers 5.5.0, TRL 1.15.0, peft 0.21.2, UNSLOTH_FORCE_CPU=1. Each suite ran in its own process, on the fix and on a git archive of the base commit:

suite base fix
test_parallel_cp_compose_gloo.py -k "pp_moe_router_aux or moe_with_router_aux" (24 tests) 7 failed, 17 passed 5 failed, 19 passed
test_pp_moe_aux_gloo.py 13 passed 13 passed
test_pp_env_cpu_chunked_ce.py 4 passed 4 passed
test_pp_env_gloo.py 4 failed, 10 passed, 1 skipped same 4 failed, 10 passed, 1 skipped
test_pp_native_gloo.py 1 failed, 23 passed same 1 failed, 23 passed
test_pp_schedules_gloo.py 19 passed, 5 skipped 19 passed, 5 skipped
test_pp_env_cpu_router_aux.py (new) 4 failed, 6 passed 10 passed

4-aux_on-forward_install and 4-aux_on-zoo_compiled now pass, with losses identical to one process to about 1e-6.

The 5 that still fail in the parity group are tolerance misses also seen on this machine without the fix. None of them is a loss mismatch:

  • 1-aux_on-forward_install: the state_atol = 1e-5 check (fails on the base commit too)
  • 4-aux_off-*: the GA-4 drift the test comment and the issue already mention
  • 2-aux_on-*: losses match (12.9536, 12.9448, 12.9181 on both sides), and the last-step grad norm is off by 5.3e-4 / 5.5e-4 relative against a 5e-4 tolerance. On the base commit these cases are 7.9% off in loss.

The test_pp_env_gloo / test_pp_native_gloo failures are the same on both copies.

Testing notes:

  • Under UNSLOTH_FORCE_CPU=1, the one-process reference of this test needs an attention_mask: TRL 1.15's SFTTrainer.compute_loss raises Expected 'attention_mask' or 'position_ids' in inputs for its token metric, and the test's collator gives only input_ids / labels. For these runs, a scratch-only import hook (not in this PR) added an all-ones mask before TRL's compute_loss (same as no mask for unpadded rows) on both the base and the fix runs. The test file is unchanged.
  • No GPU / Mac runs: this PC has an RTX 3050 4 GB, but the bug and the fix are on the CPU route only. The GPU route keeps _forward_aux_weighting.
  • ruff check passes on the changed files.

…as TRL's SFTTrainer does

On the CPU backend a stock TRL SFTTrainer forms the one-process loss with its
own fused head and adds trainer.router_aux_loss_coef * aux /
current_gradient_accumulation_steps. The last pipeline stage instead added the
model's cached router_aux_loss_coef * aux at full weight on every accumulation
step (the forward has no unsloth_ga_scale_aux_loss there), so PP trained
GA - 1 extra aux terms per window, and a coefficient set only through
SFTConfig never reached the stage (the CausalLM's cached copy stays stale).

The pipeline step now asks the trainer how it weights the term: when zoo's
CPU compute_loss would fall through to TRL's (no chunked CE armed, or under
no_grad for eval) and TRL's aux loss is on, the last stage adds TRL's
coefficient / accumulation steps (/ 1 without a window token count, and once
per eval batch). Every other path keeps the forward weighting.

Fixes unslothai#17054

@0xalkinun 0xalkinun 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.

Reviewed d06f662 against merge-base 0148e62. I found no blocking regression introduced by this change.

Independent Linux CPU runs with torch 2.11.0, transformers 5.5.0, TRL 1.15.0, PEFT 0.21.2 and unsloth_zoo 2026.11.3 confirm the training fix:

  • GA 2: baseline loss is up to 7.86% too high; head matches the one-process reference within 9.54e-7 absolute.
  • GA 4: baseline loss is up to 23.50% too high; head matches within 9.54e-7 absolute.
  • Coefficient supplied only through SFTConfig: the missing auxiliary term is restored.
  • GA 1, auxiliary-loss-off control, and the Zoo-generated forward at GA 2 also pass the existing loss, gradient and final-adapter tolerances. Both pipeline ranks train on the same rows as the reference.

14 focused CPU wrapper tests and all 13 native MoE pipeline tests pass. Running the 10 new tests against the merge-base gives the expected 4 failures / 6 passes.

The private integration harness supplies an all-ones attention_mask through the collator on both arms and both revisions; otherwise TRL 1.15 stops the reference on missing metric inputs. Product sources and numerical tolerances are unchanged. These runs do not revalidate Windows/macOS or GPU execution.

One separate pre-existing evaluation issue remains: _eval_items uses the unshifted label count on this CPU TRL route. With auxiliary loss off, both base and head report eval_loss=11.3089609 versus 11.9288521 in one process. A diagnostic using the shifted count restores exact agreement, including with the auxiliary term enabled. The helper is unchanged by this PR, so I would track that separately rather than block this training fix.

@danielhanchen danielhanchen self-assigned this Nov 10, 2026
Imagineer99 added a commit that referenced this pull request Nov 10, 2026
CPU pipeline evaluation with TRL 1.15 divides the loss over shifted
labels by the count of unshifted labels. This understates `eval_loss`
whenever the first token is not masked, affecting logged evaluation
curves and loss-based decisions.

Use the shifted target count for Zoo's CPU SFTTrainer on TRL >= 1.15,
matching its fused-head evaluation. Earlier TRL releases and other
trainers retain their existing normalization. Training is unchanged.

The new regression calls real `SFTTrainer.evaluate()` on identical
weights and data in one process and on two gloo pipeline ranks. On main
`10c52ed463`, the three cases fail numerically:

| Model | One process | PP=2 before |
| --- | ---: | ---: |
| Llama (CPU chunked CE installed) | 10.374058 | 9.712187 |
| Qwen3-MoE, aux off | 11.932101 | 11.170848 |
| Qwen3-MoE, aux on | 12.948834 | 12.187581 |

All three pass with the fix at `rtol=1e-5`, with identical evaluation
rows and both pipeline stages engaged. The tests set `loss_type="nll"`
explicitly so they also exercise the preserved TRL 1.14 path.

Validation on Linux CPU (torch 2.11.0, transformers 5.5.0, PEFT 0.21.2,
unsloth_zoo 2026.11.3):
- TRL 1.15: **14 passed** — six token-count/compatibility tests, four
existing CPU chunked-CE tests, three real evaluation cases, and the
existing plain-Trainer PP=2 training/evaluation test.
- TRL 1.14: **3 passed** — the same real evaluation cases with NLL.
- Repository formatter, Ruff, import-hoist and duplicate-definition
checks pass.

```bash
UNSLOTH_FORCE_CPU=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 python -m pytest -q \
  tests/test_pp_env_eval.py \
  tests/test_pp_env_cpu_chunked_ce.py \
  tests/test_parallel_cp_compose_gloo.py::test_cpu_pipeline_eval_matches_one_process \
  'tests/test_pp_env_gloo.py::test_pp_env_trainer_matches_one_process[pp2]'
```

This is separate from the router auxiliary-loss weighting in #17072 and
the context-parallel reduction in #17049. No GPU, Windows, or macOS run.

Co-authored-by: Lee Jackson <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 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-11T10:15:37.234830Z 60891a0 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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 5b6fa8f00a

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 60891a061d

ℹ️ 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".

@danielhanchen
danielhanchen merged commit e64acaa into unslothai:main Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pipeline parallel on the CPU backend: MoE router aux loss diverges from one process at gradient accumulation > 1

3 participants