Repository navigation
GRPO packing: turn packing off for models whose packed documents see each other - #18335
Merged
Merged
Conversation
…ther OPT builds a plain causal mask over the whole packed row on transformers 4.57 and 5.x (its mask builder reads neither position_ids nor packed_seq_lengths), so each packed document attends to the ones before it. Its learned positions are fine: they take the per-document position_ids. On a tiny OPT the packed log-probs move by 0.0035 nats, which passes the 0.7 nat per-row self-verify, while the GRPO v_proj gradient is 15-55% off the padded one. A once-per-model probe packs two rows that differ only in the first document and refuses packing when the second document's outputs change. UNSLOTH_GRPO_PACKING_LEAK_PROBE=0 skips it.
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. Already looking forward to the next diff. 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". |
This was referenced Nov 18, 2026
danielhanchen
added a commit
that referenced
this pull request
Nov 18, 2026
…ckward harnesses (#18368) ## Summary Sixteen tests in the CPU "rest" shard fail on main since #18285, in two groups: ``` tests/test_for_inference_resets_inference_runs.py (6) KeyError: "'__name__' not in globals" tests/test_return_logits_survives_for_training.py (8) KeyError: "'__name__' not in globals" tests/test_fp8_down_proj_bf16_backward.py (2) RuntimeError: 0 active drivers ([]). There should only be one. ``` Seen on the staging run for #17742, which does not touch these files. ## Cause #18285 keeps dequantized NF4 LoRA base weights in a cache. Both new call paths are correct; the CPU harnesses could not follow them. 1. `FastBaseModel.for_inference` (`unsloth/models/vision.py`) now clears that cache with an inline `from ..kernels.dequant_cache import clear_dequant_cache`. `_fast_base_model()` in `test_return_logits_survives_for_training.py` lifts `for_inference` / `for_training` out of the source and execs them in a namespace with no package. A relative import there raises `KeyError: '__name__' not in globals`. The harness already stubbed whole helpers for this reason, but this import sits in the lifted method itself. 2. The LoRA backward now dequantizes through `dequant_cache.dequantize`. That function reads `fast_dequantize` from `kernels.utils` when called. The fp8 fixture only patched `fast_lora.fast_dequantize`, so the real Triton path ran on a CPU runner. For an fp8 quant state, `dequantize` falls straight through to `fast_dequantize`, so production behaviour is unchanged. ## Fix Test-only: - `_fast_base_model()` rewrites each relative `from ..x import a` in the lifted bodies to `a = _relative_import("x", "a")`, resolved from an explicit stub table. The table starts with `clear_dequant_cache` as a no-op. Guarded imports the fakes never reach still need no stub. One that a fake does reach without a stub fails with `stub the relative import ('kernels.dequant_cache', 'clear_dequant_cache') lifted from unsloth/models`, so the next inline import says what to add instead of surfacing as a `KeyError`. - The fp8 fixture patches `fast_dequantize` in `kernels.utils` as well as in `fast_lora`. ## Verification | Tree | Result (the three files) | |---|---| | main | 16 failed, 5 passed | | this branch | 21 passed | | this branch, stub table emptied (sabotage) | 14 failed, each naming the missing stub | | this branch, `kernels.utils` patch removed (sabotage) | 2 failed, `0 active drivers` | ruff is clean. The 17th failure in that shard, `test_grpo_autocast_disabled.py::test_reading_it_tolerates_an_older_trainer`, has a different cause (#18335) and is handled separately.
danielhanchen
added a commit
that referenced
this pull request
Nov 18, 2026
…ast (#18369) ## Summary `tests/test_grpo_autocast_disabled.py::test_reading_it_tolerates_an_older_trainer` fails on main since #18335: ``` AssertionError: getattr(self, "_autocast_enabled", False) ``` Seen in the CPU "rest" shard on the staging run for #17742. ## Cause The test requires every `getattr(self, "_autocast_enabled", ...)` in `rl_replacements.py` to default to `True`. On a trainer built before the autocast latch existed, that keeps the scoring forwards autocasting as they always did. #18335 added `_unsloth_grpo_packing_leaks`, a one-off probe that checks whether packed documents can see each other. It reads `getattr(self, "_autocast_enabled", False)`, and `False` is the right default there. The probe runs from `_unsloth_grpo_refuse_boundary_blind_packing` on the loss path as well, where the latch may not have run yet (for example under vLLM). Unlatched, `True` would autocast in the `bfloat16` fallback dtype. As `_unsloth_grpo_autocast` itself notes, reading the precision as bfloat16 raises on a T4 or V100. Running the probe in the model's own dtype is the safe choice, and once the latch exists the probe follows it. So the code is correct and the test rule was broader than its intent. ## Fix Test-only: - `test_reading_it_tolerates_an_older_trainer` scans `rl_replacements.py` with the probe's function body removed. It now also asserts that it found scoring call sites, so it cannot pass on an empty match. - A new `test_an_unlatched_probe_runs_without_autocast` pins the probe's `False` default, so neither side of the rule can drift silently. ## Verification | Change to `rl_replacements.py` | Result | |---|---| | none (main) | 18 passed (before: 1 failed) | | a scoring site switched to `False` | `test_reading_it_tolerates_an_older_trainer` fails | | the probe switched to `True` | `test_an_unlatched_probe_runs_without_autocast` fails | ruff is clean.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Nov 19, 2026
…nslothai#18438) ## Summary The GRPO sequence packing leak probe from unslothai#18335 now restores each submodule's own train / eval mode. Before, it could leave a deliberately eval-mode submodule in training mode for the rest of the run, turning its dropout back on. ## Root cause `_unsloth_grpo_packing_leaks` (`unsloth/models/rl_replacements.py`) recorded only `unwrapped.training`, called the recursive `unwrapped.eval()` for its two no-grad forwards, and afterwards called the recursive `unwrapped.train()`. With a training model whose block was kept in eval mode on purpose (for example a frozen block whose dropout must stay off), that block came back in training mode: before `(parent=True, block=False)`, after `(True, True)`. The probe runs once per model when GRPO packing is considered, so the change persists through training. ## Fix Record `(module, module.training)` for every submodule before `eval()` and restore exactly those flags in the `finally` block. There is no change to the probe's forwards, threshold or result. ## Tests `tests/test_grpo_packing_leak_probe.py::test_probe_restores_every_submodule_mode[opt, llama]` keeps the first decoder block of a training tiny OPT / Llama in eval mode and checks that every submodule's mode is the same after the probe. | Arm | Result (`test_grpo_packing_leak_probe.py` + `test_grpo_packing_boundary_blind.py`) | |---|---| | main (`8ef13a7a83`) with the new test | 2 failed (both new cases), 15 passed | | this branch | 17 passed | CPU, torch 2.14.1, transformers 4.57.6; the test loads each arm's own `rl_replacements.py`. ## Not proven here An end-to-end GRPO run with a deliberately eval-mode submodule.
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
GRPO sequence packing gives wrong gradients on OPT while its self-verify passes. The cause is the attention mask, not OPT's learned position embeddings. OPT takes the per-document
position_idsthat packing passes in, so its positions are right. But its mask builder reads neitherposition_idsnorpacked_seq_lengths:_update_causal_maskon transformers 4.57 andcreate_causal_mask(...)called withoutposition_idson 5.x. So each packed document attends to every document before it in the row.The per-row self-verify compares packed and per-row log-probs against a 0.7 nat threshold, which is set to absorb bf16 kernel noise. A small leak passes it. On
trl-internal-testing/tiny-OPTForCausalLMthe packed log-probs move by only 0.0035 nats, the verify marks packing as trusted, and the gradients come out wrong:That is CPU fp32, through the real generated
GRPOTrainer.compute_loss, 4 completions of 1 to 6 tokens per prompt, packed vsUNSLOTH_GRPO_SEQ_PACKING=0. transformers 4.57.6 + TRL 0.24.0 and transformers 5.23.0 + TRL 1.18.0 give identical numbers. Onfacebook/opt-125mthe leak is larger (up to 6.5 nats), so the verify already falls back there.Fix
_unsloth_grpo_packing_leaksruns once per model, next to the existingpacking_boundary_blockercheck in_unsloth_grpo_refuse_boundary_blind_packing. It packs two rows that differ only in the first document and compares the second document's outputs. A mask that isolates documents gives identical values, so no noise floor is needed (tolerance 1e-3 of the output scale). On a leak, the no-grad and grad packed forwards and the no-grad PrefixGrouper are turned off for that model, the same flags the boundary-blind check sets, and the padded path runs. The probe:To turn it off:
UNSLOTH_GRPO_PACKING_LEAK_PROBE=0.The check is behavioural rather than a model-type list, so it covers any architecture whose mask ignores packing. GPT-2 (learned absolute positions as well) isolates packed documents correctly on transformers 4.57, and the probe leaves it packed.
Tests
tests/test_grpo_packing_leak_probe.py(CPU, tiny random OPT / Llama / GPT-2 built from configs, no download):test_leaking_model_has_packing_refused,test_isolating_models_keep_packing[llama],test_isolating_models_keep_packing[gpt2],test_probe_runs_once_per_model,test_a_model_the_probe_cannot_run_keeps_packingandtest_the_generated_trainer_carries_the_probe.test_opt_packed_documents_see_each_othershows the leak itself and passes on both, as expected.tests/test_grpo_packing_boundary_blind.pynow also loads the probe next to the helper it executes. The other GRPO packing tests pass:test_async_grpo_packed_rows,test_grpo_packed_nograd_oom_recovery,test_grpo_packed_raw_logits_nograd,test_grpo_packing_verify_outlier,test_padding_free_boundary_leakandtest_grpo_metrics_bucket(33 passed, 2 skipped).End to end, with this change all three batches above have 0.0000% gradient error on tiny OPT and opt-125m, because packing is refused. On tiny Llama and tiny GPT-2, packing stays on and matches padded (worst parameter 0.0001%).
GPU correctness on B200: under Unsloth
FastLanguageModel+ LoRA in train mode with dropout 0.1, in bf16 and fp16 autocast, with logits and withUNSLOTH_RETURN_HIDDEN_STATES=1, the probe reads exactly 0 for tiny Llama and tiny Qwen3, so they keep packing. It flags tiny OPT in every cell.Not covered
position_idswould be caught by the same probe but were not enumerated.