Skip to content

GRPO packing: turn packing off for models whose packed documents see each other - #18335

Merged
danielhanchen merged 2 commits into
mainfrom
grpo-packing-leak-probe
Nov 18, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
grpo-packing-leak-probe

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_ids that packing passes in, so its positions are right. But its mask builder reads neither position_ids nor packed_seq_lengths: _update_causal_mask on transformers 4.57 and create_causal_mask(...) called without position_ids on 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-OPTForCausalLM the packed log-probs move by only 0.0035 nats, the verify marks packing as trusted, and the gradients come out wrong:

batch verify max abs diff last-layer v_proj grad rel err worst parameter grad rel err
1 0.0035 (passes) 23.9% 220%
2 trusted 55.5% 195%
3 trusted 15.2% 173%

That is CPU fp32, through the real generated GRPOTrainer.compute_loss, 4 completions of 1 to 6 tokens per prompt, packed vs UNSLOTH_GRPO_SEQ_PACKING=0. transformers 4.57.6 + TRL 0.24.0 and transformers 5.23.0 + TRL 1.18.0 give identical numbers. On facebook/opt-125m the leak is larger (up to 6.5 nats), so the verify already falls back there.

Fix

_unsloth_grpo_packing_leaks runs once per model, next to the existing packing_boundary_blocker check 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:

  • runs in eval mode, so LoRA dropout cannot fake a leak, then restores train mode;
  • uses the trainer's latched autocast if there is one;
  • is skipped for sharded layouts with collective forwards, which never pack;
  • returns None and keeps the old behaviour if the model cannot run it.

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):

  • On main, 6 tests fail: 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_packing and test_the_generated_trainer_carries_the_probe.
  • With this change, all 9 pass on transformers 4.57.6 and on 5.23.0.
  • test_opt_packed_documents_see_each_other shows the leak itself and passes on both, as expected.

tests/test_grpo_packing_boundary_blind.py now 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_leak and test_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 with UNSLOTH_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

  • SFT packing / padding-free with OPT goes through a different path and was not checked here.
  • Only OPT has been found leaking. Other architectures that build their own mask without position_ids would be caught by the same probe but were not enumerated.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 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-18T14:00:52.083992Z 92c2dae 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. Already looking forward to the next diff.

Reviewed commit: 92c2dae738

ℹ️ 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 5b28215 into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the grpo-packing-leak-probe branch November 18, 2026 16:26
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.
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