Skip to content

GRPO num_iterations > 1: take old logps from the first loss pass, not a separate forward - #18675

Merged
danielhanchen merged 3 commits into
mainfrom
nwg-oldlogp-from-loss
Nov 21, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
nwg-oldlogp-from-loss

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

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. #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).

With num_iterations > 1 and each generation starting on an optimizer step
(steps_per_generation * num_iterations a multiple of gradient_accumulation_steps,
steps_per_generation <= gradient_accumulation_steps), the first loss pass over
every micro-batch scores the rollout weights, so its detached logps are pi_old.
Skip the separate no-grad old-policy forward over the generation batch and keep
the first pass's logps in the buffered inputs for the later iterations. The
iteration-1 ratio is then exactly 1 (also with PrefixGrouper and packing, where
the two forwards were not bit-equal), and one forward per generation is saved.

Needs an unsloth_zoo exporting grpo_old_logps_store; otherwise, with a
stochastic policy, or UNSLOTH_GRPO_OLD_LOGPS_FROM_POLICY=0, behaviour is unchanged.
@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-20T20:16:29.621844Z fae3f87 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. Bravo.

Reviewed commit: fae3f87b73

ℹ️ 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 added a commit that referenced this pull request Nov 20, 2026
…aseline (#18677)

## Summary

`Source lint (Python + shell + YAML + JSON + safety nets)` is red on
`main` (seen on #18675, reproduced on current `main`). Its blocking step
is `No new risky loader call sites`:

```
1 risky loader call site(s) not in the baseline:
  unsloth/import_fixes.py:1135  [dynamic-import] import_module
```

## Cause

#18662 (keep tokenizers loading when the Hub rate limits the Mistral tag
lookup) adds `fix_transformers_mistral_regex_hub_error`. It calls
`importlib.import_module(module_name)` over a fixed literal tuple:

- `transformers.tokenization_utils_base`
- `transformers.tokenization_utils_tokenizers`

The call has the same shape as the four already-reviewed
`import_module(module_name)` sites in `import_fixes.py`, so it lands in
their baseline group (digest `59e72c01edb14c86`) as a fifth instance.
The gate reports one site over the recorded count; the line it names
(1135) is simply the last one it counts. The new call is safe: the
module names are written out in the source. The baseline just was not
updated.

## Change

`scripts/risky_loaders_baseline.json`, regenerated with `python
scripts/lint_risky_loaders.py --update`:

- the group's count goes from 4 to 5;
- its reason now also names the two literal tokenizer owners of
`_patch_mistral_regex`.

No other entry changes.

## Testing

- `python scripts/lint_risky_loaders.py`: exits 1 on `main` with the
message above; with this change, `ok: 122 risky loader call site(s), all
recorded`.
- `python scripts/lint_risky_loaders.py --self-test`: ok.
- `tests/security/test_lint_risky_loaders.py`: 46 passed.
@danielhanchen
danielhanchen merged commit 1d83925 into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the nwg-oldlogp-from-loss branch November 21, 2026 03:24
Penguinjanator pushed a commit to Penguinjanator/unsloth-zoo that referenced this pull request Nov 21, 2026
…nslothai#2639)

## Problem

GRPO with `fast_inference=True` can crash on A100 with `CUDA error: an
illegal memory access was encountered` in vLLM's async output copy
during the second generation. After that, the merged-rollout restore
fails and the state is poisoned. When it does not crash, the same race
can silently overwrite memory the trainer owns.

Root cause:
- vLLM's `graph_capture()` captures every CUDA graph on a fresh capture
stream. cuBLAS keeps one workspace per (handle, stream), so the graphs
bake in the capture stream's workspace address. Split-K decode GEMMs
write their partial sums there on every replay.
- Inductor CUDA graph trees (Unsloth's block CUDA graphs in training)
call `torch._C._cuda_clearCublasWorkspaces()` around every warm-up and
recording. That frees the capture stream's workspace back to the caching
allocator while vLLM's graphs still point at it.
- Each later decode replay then writes into memory the trainer was
handed (silent corruption), or that `empty_cache` unmapped (illegal
address).
- It shows on A100 because cuBLAS uses split-K with a workspace for
small-M decode shapes there (Qwen3-0.6B `o_proj` / `down_proj`: M=16,
N=1024, K=2048/3072). On L4 the same GEMMs use no workspace.

Evidence (Colab A100-40, Qwen3-0.6B LoRA GRPO, vLLM 0.29.0, torch 2.13):
- CUDA coredumps of 3 crashes all fault in
`ampere_s16816gemm_bf16_64x64_ldg8_stages_64x6_tn<<<(16,1,7)>>>` on the
store of split-K partials.
- Crashes need both sides: `enforce_eager=True` gives 0/3 and
`UNSLOTH_BLOCK_CUDAGRAPHS=0` gives 0/2. Exact vs copy restore, async
scheduling, model runner V1/V2, pinned memory and expandable segments
make no difference (2/3 to 3/3 each).
- A torch-only reproducer (capture a bf16 linear on a new stream, clear
the cuBLAS workspaces, `empty_cache`, replay) gives the illegal address
4/4 on A100, and 0/4 with this change.

## Fix

`unsloth_zoo/vllm_utils.py`, around vLLM's `capture_model`:
- Before the first graph on each capture stream, the stream's workspaces
are allocated from a private `torch.cuda.MemPool`.
- After the capture, they are taken out of cuBLAS's cache and held by
tensors for the life of the process. A later clear cannot free them, the
trainer is never handed that memory, and `empty_cache` cannot unmap it.
Later eager GEMMs get a fresh workspace.
- Model Runner V2's `capture_model` (the CUDA default in vLLM 0.29) is
now wrapped too, with only this hold.
- It runs once per capture at engine load and adds nothing per step.
About 40-64 MiB stays held per engine.
- It is idempotent. It is a no-op on ROCm and on torch without
`MemPool`.

## Results (Colab A100-40, same VMs, block CUDA graphs on)

| arm | crashed |
| --- | --- |
| unslothai/unsloth#18675 + unslothai#2638 heads, without this change | 4/4 |
| #18675 + unslothai#2638 heads, with this change | 0/4 (30/30 steps each) |
| main, with this change | 0/4 |

- With `UNSLOTH_BLOCK_CUDAGRAPHS=1` forced, both arms with this change
were 0/3.
- Colab L4: both arms with this change complete 30/30 steps.
- Generation step time is unchanged: paired deltas of -0.064, -0.066 and
+0.042 s, inside the 0.254 s spread between repeated unfixed runs.

## Tests

- `tests/test_vllm_cublas_workspace_pin.py`: 5 CPU tests that fail on
main and pass here, plus one CUDA test that replays a captured split-K
GEMM after a workspace clear.
- Existing merged-rollout and graph-capture tests: 179 passed, 19
skipped.

## Not covered

- A100-80, H100, B200 and T4 were not run.
- ROCm and torch without `MemPool` take the no-op path.
- With block CUDA graphs forced on, unfixed main did not crash in 0/6
runs. Whether the freed pages get unmapped depends on memory layout.
Those runs most likely overwrote memory silently instead, but no memory
history was captured to show it.
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