Repository navigation
GRPO num_iterations > 1: take old logps from the first loss pass, not a separate forward - #18675
Merged
Merged
Conversation
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.
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. Bravo. 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". |
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.
[skip ci]
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.
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 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:
unsloth_old_logps_store);old = new.detach()and writes it back into the buffered inputs asold_per_token_logps;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 > 1steps_per_generation * num_iterationsis a multiple ofgradient_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, andUNSLOTH_GRPO_OLD_LOGPS_FROM_POLICY=0.Safety
compute_lossas 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.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, andcompute_lossover 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.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.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:
importance_sampling_level="sequence"), and dapo (the TRL default)With
UNSLOTH_GRPO_OLD_LOGPS_FROM_POLICY=0the 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).