Repository navigation
GRPO: score old / ref logps under no_grad, not inference_mode - #18642
Merged
Merged
Conversation
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.
Member
Author
|
@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: Didn't find any major issues. What shall we delve into next? 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". |
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
With
num_iterations > 1, GRPO scores the old-policy logprobs once in_generate_and_score_completionsand 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 = Trueon 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 undertorch.no_grad().This PR runs the four scoring forwards in
_get_per_token_logps_and_entropiesundertorch.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'sgrpo_compute_lossis 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):UNSLOTH_GRPO_PREFIX_GROUPER=0, vLLM, compiledUNSLOTH_GRPO_PREFIX_GROUPER_VLLM=0, vLLM, 4 stepsUNSLOTH_GRPO_PREFIX_GROUPER=0, no vLLMUNSLOTH_GRPO_PREFIX_GROUPER=0,UNSLOTH_COMPILE_DISABLE=1UNSLOTH_GRPO_PREFIX_GROUPER_VLLM=0, 30 stepsThe 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:
Bisection that led here (main, PrefixGrouper off):
UNSLOTH_GRPO_SEQ_PACKING=0torch.no_grad()instead ofinference_modeSo 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):inference_mode, and that each one sits undertorch.no_grad().tests/test_grpo*.pysuite gives the same result with and without this PR. 6 tests intest_grpo_rollout_scope.pyfail on main too in a TRL 0.24 environment, so those failures are not from this change.