Skip to content

GRPO: score old / ref logps under no_grad, not inference_mode - #18642

Merged
danielhanchen merged 1 commit into
mainfrom
nwb-oldlogp-parity
Nov 20, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
nwb-oldlogp-parity

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

With num_iterations > 1, GRPO scores the old-policy logprobs once in _generate_and_score_completions and then trains on the same batch for several iterations. On the first iteration the weights and tokens are the same ones the old logprobs were scored with, so the PPO ratio should be exactly 1.

On main it was not. Every iteration-1 token carried a log ratio of about 0.01 nats on average, up to 0.2-0.6 nats, and 0% of tokens matched. Measured on Qwen3-0.6B LoRA with fast_inference = True on an L4, and it happens with PrefixGrouper off too.

The cause is the grad mode of the scoring forward. Unsloth scored old / ref logprobs under torch.inference_mode() (via _get_inference_mode_context_manager), while the loss scores the policy under grad mode. With the default compiled packed forward, those two are not bit-equal. TRL scores old logprobs under torch.no_grad().

This PR runs the four scoring forwards in _get_per_token_logps_and_entropies under torch.no_grad() instead: PrefixGrouper, packed, packed verify, and the padded loop. With that change the two passes agree bitwise.

Evidence (Colab L4, torch 2.13, transformers 5.17, TRL 1.15, vLLM 0.29)

Setup: GRPO on unsloth/Qwen3-0.6B, LoRA r16, bf16, G = 8, bs = 8, GA = 2, num_iterations = 2, 96 completion tokens, a shared ~1.2k token system prompt. The loss's grpo_compute_loss is wrapped to record masked |new - old| on iteration-1 calls, 3072 tokens per run.

Iteration-1 |new - old|, mean over all iteration-1 tokens (4 loss calls = 2 generations per 4-step run, 30 calls per 30-step run):

config main this PR
UNSLOTH_GRPO_PREFIX_GROUPER=0, vLLM, compiled 0.0105-0.0124 nats, 0% bitwise (5 runs) 0 nats, 100% bitwise (2 runs)
UNSLOTH_GRPO_PREFIX_GROUPER_VLLM=0, vLLM, 4 steps 0.0113, 0% bitwise (30-step row below) 0.0042-0.0043, 50% bitwise (2 runs)
UNSLOTH_GRPO_PREFIX_GROUPER=0, no vLLM not run 0.0042, 50% bitwise
UNSLOTH_GRPO_PREFIX_GROUPER=0, UNSLOTH_COMPILE_DISABLE=1 0.0047-0.0049, 50% bitwise (2 runs) 0.0049, 50% bitwise
vLLM, UNSLOTH_GRPO_PREFIX_GROUPER_VLLM=0, 30 steps 0.0113, 0% bitwise 0 and 0.00016, 100% and 98.7% bitwise (2 runs)
stock TRL GRPOTrainer, same setup 0, 100% bitwise n/a

The 30-step runs scored completions on whether they contain the right answer. In them, iteration-1 optimizer steps had a clip fraction of 0.00078 on main and exactly 0 with this PR. Step time did not change: generation steps took 3.00 s vs 3.00-3.05 s, and train steps 1.48 s on both.

Not covered by this PR:

  • With PrefixGrouper on, both passes run the shared-prefix FlexAttention forward, but over a different set of rows (the whole generation batch vs one shuffled loss slice). Those forwards are not bit-equal, and the gap stays at about 0.012 nats on main and with this PR alike. Turning PrefixGrouper off under vLLM closes it, but makes the train step about 2x slower (0.75 s to 1.48 s), so it stays on.
  • The no-grad pass packs the whole generation batch (16 rows) while the loss packs one 8-row slice. The GEMM shapes differ, so some generations still come out about 0.004 nats apart (the 50% rows above: the first generation matches bitwise and the second does not).

Bisection that led here (main, PrefixGrouper off):

arm iteration-1 tokens bitwise equal
main 0%
UNSLOTH_GRPO_SEQ_PACKING=0 100%
scoring forward under torch.no_grad() instead of inference_mode 100%
same 16 rows in both passes (GA 1, bs 16) 0%
stock TRL GRPOTrainer, same model and data 100%

So on the compiled path, the gap does not come from batch composition or from the scorer: it comes from the inference-mode forward. A side effect: the no-grad packed-vs-per-row self-verify now reads max|d| = 0.0000, where main read 0.27-0.59.

Tests

  • tests/test_grpo_old_logps_no_inference_mode.py (CPU, about 2 s):
    • It runs the real packed + verify block and checks that no model forward runs under inference mode and that all of them run with grad off.
    • An AST check confirms that none of the four scoring sites enters inference_mode, and that each one sits under torch.no_grad().
    • On main 3 tests fail; with this PR 3 pass.
  • The existing tests/test_grpo*.py suite gives the same result with and without this PR. 6 tests in test_grpo_rollout_scope.py fail on main too in a TRL 0.24 environment, so those failures are not from this change.

With num_iterations > 1 the first PPO ratio should be exactly 1: the old logps are
scored with the same weights and tokens the loss scores. Under inference_mode the
compiled packed forward was not bit-equal to the loss's grad-mode forward, so every
iteration-1 token carried a ~0.01 nats log ratio (max 0.2-0.6) on Qwen3-0.6B.
TRL scores old logps under torch.no_grad(); doing the same makes both passes agree
bitwise.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T14:35:21.356177Z 271ac12 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. What shall we delve into next?

Reviewed commit: 271ac12de7

ℹ️ 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 a579dc9 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the nwb-oldlogp-parity branch November 20, 2026 16:19
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 21, 2026
… a separate forward (unslothai#18675)

## Summary

With `num_iterations > 1`, GRPO scores pi_old in a separate no-grad
forward over the whole generation batch, then the loss scores the same
weights again on the first pass over each micro-batch. Those two
forwards are not bit-equal: the no-grad pass runs PrefixGrouper /
sequence packing over the full generation batch and the loss runs it
over an 8-row slice, so the iteration-1 ratio is not 1. unslothai#18642 removed
the inference-mode part of the gap; the PrefixGrouper and
batch-composition part (about 0.012 nats per token on Qwen3-0.6B, the
vLLM default) remained, and iteration-1 steps still clip a few tokens
they should not.

When each generation starts on an optimizer step and its first pass over
every micro-batch stays inside that step, the first loss pass scores
exactly the rollout weights, so its detached logps are pi_old. This PR:

- skips TRL's old-policy forward in that case and marks the batch
(`unsloth_old_logps_store`);
- on the first pass over a marked micro-batch, asks the zoo loss for
`old = new.detach()` and writes it back into the buffered inputs as
`old_per_token_logps`;
- reuses it unchanged on every later iteration.

The iteration-1 ratio is then exactly 1 by construction, and one full
forward per generation batch is gone.

## When it applies

Same reasoning TRL uses for its own `per_token_logps.detach()` shortcut,
extended to the later iterations:

- `num_iterations > 1`
- `steps_per_generation * num_iterations` is a multiple of
`gradient_accumulation_steps` (generation starts on an optimizer step)
- `steps_per_generation <= gradient_accumulation_steps` (the first pass
over every micro-batch ends before the next optimizer step)
- `gradient_accumulation_steps % (steps_per_generation * num_iterations)
!= 0` (otherwise the existing single-step path already covers it)

The defaults (`steps_per_generation = gradient_accumulation_steps`,
`num_iterations = 2`) qualify. The gate is checked against a brute-force
walk of TRL's schedule for every (GA, steps_per_generation,
num_iterations) in {1,2,3,4,8} x {1,2,3,4,8} x {1,2,3,4}.

It stays off (today's separate forward) for a stochastic policy
(dropout, LoHa / LoKr dropout, router jitter), an unsloth_zoo without
`grpo_old_logps_store`, rollout logprobs as pi_old, and
`UNSLOTH_GRPO_OLD_LOGPS_FROM_POLICY=0`.

## Safety

- If the buffered batch is ever handed to `compute_loss` as a copy, the
later pass would find no kept pi_old. The marker tensor is cleared in
place on the first pass, so that case raises instead of silently
training with ratio 1.
- If the zoo does not hand the logps back, it also raises.
- Unchanged: beta > 0 (reference logps are still scored as before), all
loss types (grpo / bnpo / dr_grpo / dapo / GSPO sequence level),
PrefixGrouper on / off, packing on / off, the vLLM IS correction (the IS
ratio uses the same pi_old on every iteration, as in TRL).

## Needs

Companion PR unslothai/unsloth-zoo#2638 (`grpo_old_logps_store`,
`store_old_logps`). Either side alone keeps today's behaviour.

## Tests

- `tests/test_grpo_old_logps_store.py` (new, CPU, about 16 s): the gate
against the brute-force schedule, the generation patch on a fake TRL and
on the installed TRL, and `compute_loss` over three iterations of one
buffered batch (first pass keeps pi_old, later passes reuse the same
tensor, the copy and old-zoo cases raise). Fails on main (213 of 214),
passes here.
- Two existing tests updated for the extra line in the patched
generation.
- `tests/test_grpo*.py`: all pass with the companion zoo.

## Results

Qwen3-0.6B LoRA r16, `fast_inference=True` (vLLM), `num_iterations=2`,
per-device batch 8, GA 2, PrefixGrouper and packing on (the defaults),
beta 0, answer-correctness reward. torch 2.13.0, transformers 5.17.0,
TRL 1.15.0, vLLM 0.29.0. Three runs per arm, interleaved, 30 steps, on
one exclusive Colab A100-40GB.

| | main | this PR |
| --- | --- | --- |
| iteration-1 mean abs(new - old) per token | 0.0089 / 0.0095 / 0.0102 |
0 / 0 / 0 (every call, 30 per run) |
| clip fraction, iteration-1 steps | 0.00052 / 0.00052 / 0.00065 | 0 / 0
/ 0 |
| clip fraction, iteration-2 steps | 0.00104 / 0.00117 / 0.00143 |
0.00091 / 0.00100 / 0.00130 |
| no-grad scoring forwards | 15 per run | 0 |
| generation step, median s | 1.386 / 1.397 / 1.407 | 1.265 / 1.271 /
1.283 |
| iteration-2 step, median s | 0.694 / 0.698 / 0.701 | 0.685 / 0.689 /
0.699 |
| steps 2-30 total, s | 30.49 / 30.56 / 30.96 | 28.36 / 28.89 / 29.79 |
| mean reward | 0.553 / 0.577 / 0.646 | 0.546 / 0.588 / 0.633 |

Generation steps are 9% faster (1.397 s to 1.271 s median; the main runs
spread 0.021 s). The 29-step total is 5.5% faster. Reward, loss and the
iteration-2 clip fraction are within the run-to-run spread.

Each of these was one 8-step run of this PR, all with iteration-1
abs(new - old) exactly 0 and clip 0 on iteration-1 steps:

- grpo, bnpo, dr_grpo, GSPO (`importance_sampling_level="sequence"`),
and dapo (the TRL default)
- GA 1 / batch 16 (steps_per_generation 1)
- beta 0.04: the reference forward still runs, KL 0.00129 vs 0.00126 on
main
- PrefixGrouper off
- PrefixGrouper and packing both off (2 runs each arm on an L4; the
generation step is 2.47 s vs 2.89-2.94 s on main)

With `UNSLOTH_GRPO_OLD_LOGPS_FROM_POLICY=0` the old forward comes back
and the iteration-1 gap is main's.

## A100 crash found while testing this

On Colab A100-40 this PR pair crashed 3/3 (main 0/3) with an illegal
memory access in vLLM decode. The cause is a latent main bug, not this
change: Inductor CUDA graph trees free the cuBLAS workspace vLLM's CUDA
graphs were captured with. Removing the no-grad forward only changes the
memory layout enough to unmap it. unslothai/unsloth-zoo#2639 fixes that;
with it these heads ran 0/4 on A100-40 (unfixed 4/4 in the same batch).
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