Repository navigation
Pipeline parallel on the CPU backend: weight the MoE router aux loss as TRL's SFTTrainer does - #17072
Conversation
…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
left a comment
There was a problem hiding this comment.
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.
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]>
…compute_loss adds the term (TRL 1.14 leaves it to the forward)
[skip ci]
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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 throughSFTConfig(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):SFTConfigSFTConfigRoot cause
With
UNSLOTH_FORCE_CPU=1the trainer is stock TRL'sSFTTrainer, with zoo's CPUcompute_losswrapped 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:The pipeline schedule never calls
compute_loss. The last stage adds the term the way the model forward would (pp_native.py):On this path the forward has no
unsloth_ga_scale_aux_loss, so_forward_aux_weightingreturns the term unchanged. That gives two separate errors:/ GA, so a window carries GA − 1 extra aux terms. The measured gap matches that: GA 2 is +1.0 (one extra0.5 × aux, aux ≈ 2.0), and GA 4 is about +3.moe.owner.router_aux_loss_coef, which the CausalLM cached at init. TRL ≥ 1.7 writes the SFTConfig value only toconfig.router_aux_loss_coef, and the cached-copy sync inrl.pylives 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 owncompute_losswould weight the aux term in one process. It returns(coefficient, divisor)only when all of these hold:stage.ctx.moe)type(trainer).compute_lossis zoo's CPU wrapper (_unsloth_cpu)Trainer.compute_loss, so the forward adds the term and the old path is right. Eval always falls through to TRL underno_grad, so the chunked CE doesn't count there.aux_loss_enabledis on androuter_aux_loss_coefis setcompute_lossreadsrouter_aux_loss_coefandcurrent_gradient_accumulation_steps(followed through thefunctools.wrapschain). TRL 1.14.x already setstrainer.router_aux_loss_coefbut 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 nonum_items_in_batch._pp_training_step/_pp_prediction_stepput that ontostage.ctx.trainer_auxfor the step and clear it in afinally.In
pp_native, the last stage addscoef * aux / divisorwhenctx.trainer_auxis set, and otherwise keeps_forward_aux_weighting. The loggedlast_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_stepwith a stage stub that records what the last stage would see:(0.5, 4.0), and cleared after the stepcurrent_gradient_accumulation_steps(3), not the configured GA4 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 agit archiveof the base commit:test_parallel_cp_compose_gloo.py -k "pp_moe_router_aux or moe_with_router_aux"(24 tests)test_pp_moe_aux_gloo.pytest_pp_env_cpu_chunked_ce.pytest_pp_env_gloo.pytest_pp_native_gloo.pytest_pp_schedules_gloo.pytest_pp_env_cpu_router_aux.py(new)4-aux_on-forward_installand4-aux_on-zoo_compilednow 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: thestate_atol = 1e-5check (fails on the base commit too)4-aux_off-*: the GA-4 drift the test comment and the issue already mention2-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_gloofailures are the same on both copies.Testing notes:
UNSLOTH_FORCE_CPU=1, the one-process reference of this test needs anattention_mask: TRL 1.15'sSFTTrainer.compute_lossraisesExpected 'attention_mask' or 'position_ids' in inputsfor its token metric, and the test's collator gives onlyinput_ids/labels. For these runs, a scratch-only import hook (not in this PR) added an all-ones mask before TRL'scompute_loss(same as no mask for unpadded rows) on both the base and the fix runs. The test file is unchanged._forward_aux_weighting.ruff checkpasses on the changed files.