Skip to content

Context parallel: eval loss is the sequence's token mean, not cp_size times it - #17049

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
lonexreb:fix/cp-eval-loss-weights-each-shard
Nov 11, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
lonexreb:fix/cp-eval-loss-weights-each-shard

Conversation

@lonexreb

@lonexreb lonexreb commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Under context parallelism, trainer.evaluate() reports eval_loss multiplied by the cp size.

patched_prediction_step (#16558) puts the sequence's target count in inputs["num_items_in_batch"], calls self.compute_loss(model, inputs) on each rank's shard, and sums the results over the cp group. TRL's SFTTrainer.compute_loss only reads its num_items_in_batch argument (here None); the fused forward accepts the inputs key and does nothing with it. So each rank returns its own shard's token mean, and the all_reduce adds cp_size of them.

Real SFTTrainer on the CPU backend (tiny Llama, same data and weights; the agent-written repro is the audit's e2e.py):

eval_loss
one process 10.336449
cp = 2, main 20.673664 on both ranks
dp2 x cp2, main 20.673664 on all 4
cp = 2, this PR 10.336451 on both ranks

Training is unaffected (training_step passes the count as an argument). What breaks is eval_loss and everything that reads it: early stopping, load_best_model_at_end, and logged curves. The existing unit test missed it because its stand-in compute_loss read inputs["num_items_in_batch"].

Fix: weight each shard's mean by its share of the sequence's targets (local / count) before the sum, and stop relying on how compute_loss normalises. An empty shard still contributes 0.

Tests: the stand-in compute_loss now takes num_items_in_batch as an argument the way TRL does. New test_eval_loss_is_not_multiplied_by_the_cp_size: two ranks with 2 of 4 targets each should sum to 1. It gets 2.0 on main and passes here. 104 passed in tests/test_context_parallel.py, including the existing empty-shard test.

🤖 Generated with Claude Code

… times it

patched_prediction_step put the target count in inputs["num_items_in_batch"]
and summed each rank's compute_loss over the cp group. TRL's
SFTTrainer.compute_loss reads only its num_items_in_batch argument, so every
rank returned its own shard's token mean and the all_reduce added cp_size of
them: with a real SFTTrainer on the CPU backend, eval_loss was 20.67 at
cp = 2 against 10.34 in one process (dp2 x cp2: 20.67 too). Training is
unaffected; eval_loss, early stopping and best-model selection were off.

Weight each shard's mean by its share of the sequence's targets before the
sum, so the result no longer depends on how compute_loss normalises. The
test's stand-in compute_loss now reads the argument like TRL does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 danielhanchen self-assigned this Nov 11, 2026
…older TRL

TRL < 1 leaves the averaging to the model, which returns 0 / 0 for a shard
holding only prompt tokens, so eval_loss became NaN under completion-only
loss. Weight the shard's mean only where it has targets, and test both
compute_loss conventions.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 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:37:39.901684Z fd39cae 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: fd39cae517

ℹ️ 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 76f3834 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.

2 participants