Skip to content

Stop dividing the GRPO eval loss by the accumulation steps - #11337

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
vineethsaivs:fix-grpo-eval-accumulation-20260919
Sep 22, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
vineethsaivs:fix-grpo-eval-accumulation-20260919

Conversation

@vineethsaivs

Copy link
Copy Markdown
Contributor

eval_loss from a GRPO run is smaller than the train loss by exactly gradient_accumulation_steps, and moves when that setting changes.

The patched compute_loss reads self.current_gradient_accumulation_steps unconditionally. TRL uses it in train mode and 1.0 in eval, since an eval pass accumulates nothing, and Trainer never clears the attribute after the training loop sets it. The existing fallback only covers a standalone evaluate(), where the attribute is missing altogether. Resolve the divisor through a helper that returns 1 when the model is not training, reading model.training the way TRL does, and ship it to the generated trainer.

Test: python -m pytest tests/test_grpo_eval_accumulation.py -q. Eight CPU tests cover both modes, the missing attribute and a trainer with no model, plus a structural check that compute_loss no longer reads the attribute directly. They fail before and pass after; 42 tests pass across the three GRPO source-lift files. Ruff 0.15.18 and the pinned kwarg-spacing formatter pass. Executed on Apple M2 Pro CPU; no GPU or distributed run. The helper is lifted with ast, so the test does not import unsloth.

Resolve the divisor through a helper that returns 1 when the model is not training, reading `model.training` the way TRL does, and ship it to the generated trainer.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits rl_replacements.py:2790, where the divisor is still read unconditionally and flows into the loss at lines 2909 and 3030, so an in-training evaluation reports eval_loss scaled by the training accumulation window. Will get this reviewed.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@danielhanchen danielhanchen self-assigned this Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Verified on a B200. issue: REAL | PR as submitted: CORRECT, no changes needed | merge: YES

The fix reproduces and resolves cleanly against an independent oracle, and the training path is bitwise unchanged.

Setup

Qwen3-0.6B + LoRA, loss_type="grpo", beta=0.1, num_generations=2, max_steps=4, eval_strategy="steps", eval_steps=2, seed 3407, single GPU, trl 0.25.1 / transformers 5.17.0. Base is the merge base 768d644, head is fafcec8. Both arms generate their own UnslothGRPOTrainer.py into separate cache dirs.

Because the policy-gradient term is zero in eval here (ratio is 1, group advantages sum to zero), the true eval objective is exactly beta * eval_kl, and eval_kl is logged as a metric that never passes through the divisor. That gives a divisor-independent oracle rather than a base-versus-head comparison alone.

Before / after

arm GA eval_loss (two eval points) oracle beta * eval_kl verdict
base 1 0.00296269, 0.00674352 matches correct already
base 4 0.00083432, 0.00287031 0.00333719, 0.01148128 exactly 1/4 of the truth
head 1 0.00296269, 0.00674352 matches unchanged, as expected
head 4 0.00333726, 0.01148125 0.00333719, 0.01148128 matches the oracle

head/base eval ratio is 4.000000 at GA=4 and 1.000000 at GA=1, at both eval points.

loss_type="dapo" (which normalises by num_items_in_batch, not the window) reports 0.00333726, 0.01148125 on base and head alike, so the PR is a no-op there and the bug really is confined to the loss types that divide by the window.

No training regression

At both GA=1 and GA=4, base and head produce bitwise identical train losses and grad-norms:

GA=4  train losses  [-2.98e-08, -7.0035e-07, 0.0022902191, 0.0116797760]   base == head
GA=4  grad norms    [1.0782871, 1.0817116, 1.0797282, 1.1270765]           base == head

The generated UnslothGRPOTrainer.py differs between the two arms by exactly the two expected hunks: the helper added at module level, and the one line inside compute_loss. Nothing else moved.

The invariant the fix rests on

I instrumented every compute_loss call because self.model.training is not obviously trustworthy here: rl_replacements.py:1292-1293 injects an unconditional self.model.for_training(...) inside the generated _generate_and_score_completions, which runs on eval batches too, and the only thing that undoes it is _wrap_grpo_generate_and_score in rl.py:625-648, whose restore is conditional and swallows exceptions.

It holds. Across 32 calls in the GA=4 head run:

(trainer.model.training, current_gradient_accumulation_steps, grad_enabled) -> count
(True,  4, True)  -> 16     every training micro-batch
(False, 4, False) -> 16     every eval batch

current_gradient_accumulation_steps is 4 during eval, which is the stale training window the report describes. trainer.model is model for the compute_loss argument in this single-GPU PEFT setup, so reading trainer.model rather than the argument makes no difference here, and it matches what TRL main does (mode = "train" if self.model.training else "eval").

Where this leaves the divergence

TRL main guards the same division at grpo_trainer.py:3206 and friends with normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0. The source-lifted copy in rl_replacements.py dropped that guard; #6523 restored only the standalone-evaluate() half of it. This PR closes the rest.

Not covered

Multi-GPU, DDP, DeepSpeed and FSDP, where self.model_wrapped can hold a training flag out of sync with self.model because Unsloth's for_training / for_inference set the flag attribute-wise down .model chains instead of going through nn.Module.train(). Also not covered: vLLM fast_inference=True, non-Linux, and vision GRPO.

One suggestion, not a blocker: the new tests are a truth table for the helper plus a structural assertion, and the thing that can actually break in future is the mode invariant above, not the helper. A fake-trainer test asserting self.model.training is False at compute_loss time during an in-training eval would pin down the part that is load-bearing. tests/version_compat/test_trl_grpo_fake_run.py already drives the generated source and would be a natural home.

Separately and out of scope for this PR: unsloth_zoo/rl_replacements.py:1472 reads trainer._step % trainer.current_gradient_accumulation_steps in the autotune branch, and trainer._step only advances on the train branch of _prepare_inputs. Worth its own look.

All CI green. Merging.

@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Thanks for the oracle run, the beta * eval_kl comparison is a better check than anything I had.

On the mode-invariant test: I will add it as a follow-up rather than push to this head. It is a forward guard on for_training and the conditional restore in rl.py, not a fail-before case for this PR (your own instrumentation shows the flag was already False pre-fix), so it does not belong in the same diff. test_trl_fake_train_cpu.py looks like the better home than the fake-run file, which compiles and inspects rather than trains.

Taking the unsloth_zoo _step % current_gradient_accumulation_steps one separately.

The helper decides between 1 and the accumulation window by reading model.training,
so its correctness rests on an assumption the truth-table tests cannot see: that an
eval pass still reports model.training == False by the time compute_loss runs.

That is not free in unsloth. grpo_trainer__generate_and_score_completions injects an
unconditional self.model.for_training(...) into the generated
_generate_and_score_completions, which fires on eval batches too, and the only thing
that puts the flag back is the finally in _wrap_grpo_generate_and_score, which restores
inference mode solely when it entered in it and swallows exceptions from the restore.

If that restore regresses, the helper quietly starts dividing eval_loss again while
every existing test stays green. This file asserts the property directly: eval mode
survives generation and the divisor comes back 1, training mode survives and the window
is kept, the restore still happens when generation raises, and the wrapper does not
stack. Verified by removing the for_inference() call in rl.py, which turns three of the
six red.

Both the helper and the wrapper are lifted with ast from the shipped source, matching
_grpo_dispatch_source and _rl_source, so the test stays CPU-only and does not import
unsloth.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed bf7ffd7 to this branch: the behavioural test I suggested above. The fix itself needed no changes.

tests/test_grpo_eval_accumulation.py pins the helper's truth table, which is right, but it cannot see the assumption underneath it. The helper reads model.training, and that flag does not survive a GRPO step untouched: grpo_trainer__generate_and_score_completions injects an unconditional self.model.for_training(...) into the generated _generate_and_score_completions, so an eval batch gets flipped into training mode partway through, and the only thing that puts it back is the finally in _wrap_grpo_generate_and_score (rl.py:625-648), which restores inference mode solely when it entered in it and swallows exceptions from the restore.

So if that restore ever regresses, the helper quietly resumes dividing eval_loss by the training window and every test in the PR stays green. The new file asserts the property directly: eval mode survives generation and the divisor comes back 1, training mode survives and the window is kept, the restore still fires when generation raises, and the wrapper does not stack.

I checked it actually bites rather than just passing. Removing the self.model.for_inference() call in rl.py turns three of the six red, and reverting makes them green again. On the merge base three fail because the helper does not exist yet.

Same ast lift as _grpo_dispatch_source / _rl_source, so it stays CPU-only and does not import unsloth. 85 tests pass across the GRPO source-lift files with it added. Ruff clean and the pinned kwarg-spacing formatter is idempotent on it.

@vineethsaivs

vineethsaivs commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for writing that test, it pins the right thing: the helper is only correct while model.training survives generation, and the truth table cannot see that. I will take the rl_replacements.py:1472 autotune modulo separately.

@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #11337, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#53.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1 — reviewed mirror f0dd215fde (this PR's bf7ffd74f)

chatgpt-codex-connector[bot] (on the mirror)

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

Reviewed commit: f0dd215fde

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror f0dd215fde (this PR's bf7ffd74f).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@unslothai unslothai deleted a comment from shimmyshimmer Sep 22, 2026
@danielhanchen
danielhanchen merged commit 06c1bb4 into unslothai:main Sep 22, 2026
30 of 31 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…#11337)

* Stop dividing the GRPO eval loss by the accumulation steps

Resolve the divisor through a helper that returns 1 when the model is not training, reading `model.training` the way TRL does, and ship it to the generated trainer.

* Pin the eval-mode invariant the GRPO divisor helper depends on

The helper decides between 1 and the accumulation window by reading model.training,
so its correctness rests on an assumption the truth-table tests cannot see: that an
eval pass still reports model.training == False by the time compute_loss runs.

That is not free in unsloth. grpo_trainer__generate_and_score_completions injects an
unconditional self.model.for_training(...) into the generated
_generate_and_score_completions, which fires on eval batches too, and the only thing
that puts the flag back is the finally in _wrap_grpo_generate_and_score, which restores
inference mode solely when it entered in it and swallows exceptions from the restore.

If that restore regresses, the helper quietly starts dividing eval_loss again while
every existing test stays green. This file asserts the property directly: eval mode
survives generation and the divisor comes back 1, training mode survives and the window
is kept, the restore still happens when generation raises, and the wrapper does not
stack. Verified by removing the for_inference() call in rl.py, which turns three of the
six red.

Both the helper and the wrapper are lifted with ast from the shipped source, matching
_grpo_dispatch_source and _rl_source, so the test stays CPU-only and does not import
unsloth.

---------

Co-authored-by: Daniel Han <[email protected]>
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
…_evaluate (unslothai#14112)

GRPO `compute_loss` picked the metrics bucket from
`control.should_evaluate`, which is still False for `eval_on_start=True`
and a standalone `trainer.evaluate()`. Those eval passes logged `kl`,
`completion_length` and `clip_ratio/*` into the train bucket, so
`eval_*` got none and step-1 `train/completion_length` averaged in the
eval batch.

TRL uses `"train" if self.model.training else "eval"`; this does the
same. unslothai#11337 already moved the eval loss divisor to `model.training`.

Test: new `tests/test_grpo_metrics_bucket.py` lifts the shipped
`compute_loss`, stubs the zoo loss, and checks the bucket for train,
eval_on_start and a scheduled eval. On main 2 of 4 fail (`[] == [4.0]`,
train length `6.0` instead of `8.0`); with the fix all 4 pass. CPU only,
no GRPO run on a GPU.

---------

Co-authored-by: Daniel Han <[email protected]>
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.

4 participants