Skip to content

Make the GRPO canary run through Unsloth's own batch sampler - #11126

Merged
danielhanchen merged 5 commits into
mainfrom
pr/grpo-fake-run-takes-a-step
Sep 21, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
pr/grpo-fake-run-takes-a-step

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The GRPO canary in tests/version_compat/test_trl_fake_train_cpu.py proves the trainer runs.
It does not prove Unsloth's own get_batch_samples runs, and that gap let a total GRPO
breakage sit on unsloth-zoo main for a day.

This adds one test, 6 seconds, that takes real GRPO steps through the patched batch sampler.

What happened

unsloth-zoo#1217 rewrote a list-safe membership test into a .get:

-    if "labels" in batch_samples[0]:
+    labels_are_countable = getattr(
+        batch_samples[0].get("labels") if len(batch_samples) > 0 else None, "ndim", None,
+    ) is not None

TRL's GRPO trainer uses an identity collator, so every element of batch_samples is a
list of dicts, never a dict. in on a list is simply False; .get raises. Every GRPO
run died at step 0:

File ".../unsloth_zoo/loss_utils.py", line 402, in _unsloth_get_batch_samples
    batch_samples[0].get("labels") if len(batch_samples) > 0 else None, "ndim", None,
AttributeError: 'list' object has no attribute 'get'

Fixed in unsloth-zoo#1254. It never reached PyPI: the regression landed 2026-09-15 and the
released unsloth_zoo 2026.9.3 is from 2026-09-09, so no user was affected. It was found by
accident, while verifying an unrelated PR, not by a gate.

Why the existing lanes could not catch it

lane what it does catches #1217
test_trl_grpo_fake_run.py source-transform patching; its own header says "no GPU, no training" no
test_trl_fake_train_cpu.py::test_sft_trains_on_cpu real .train(), but an SFT collator hands back dicts no
test_trl_fake_train_cpu.py::test_grpo_trains_on_cpu real GRPO .train() no, see below

The third is the surprising one. It does run a real UnslothGRPOTrainer for two steps, but
_load_plain() loads a plain HF model and never goes through the loader that calls
patch_gradient_accumulation_fix, so Trainer.get_batch_samples stays stock transformers.
Measured by wrapping the zoo function and counting: 0 calls, with
Trainer.get_batch_samples still resolving to Trainer.get_batch_samples.

So the canary was exercising TRL's trainer, not Unsloth's batch sampler.

What this adds

test_grpo_trains_on_cpu_through_the_patched_batch_sampler:

  1. calls patch_gradient_accumulation_fix(Trainer), the way a real run does,
  2. asserts the patch took, so the test cannot silently pass against any zoo at all,
  3. runs two real GRPO steps on CPU under the existing spoof harness,
  4. asserts the sampler was entered at least once, and
  5. asserts at least one batch arrived as a list, which is the shape that broke. Without
    that last assertion the test would still pass on a harness that only ever produced the SFT
    dict shape, which is exactly how this class of regression hides.

Evidence

Both arms, same test file, only unsloth_zoo changed:

unsloth_zoo under test result
e2e81b7 (#1217, the regression) 1 failed, AttributeError: 'list' object has no attribute 'get' at loss_utils.py:402
2dcbe9c (#1254, fixed) 4 passed, 6.32 s

The existing three canaries pass on both, which is the point: they are blind to this.

Cost

6.3 seconds for the whole file, CPU only, no GPU, tiny random-weight model
(hf-internal-testing/tiny-random-LlamaForCausalLM), reusing the fixtures already in the
file. The grpo-fake-run lane in version-compat-ci.yml already clones unsloth-zoo at main
and already runs this file, so it is covered with no workflow change.

@danielhanchen danielhanchen self-assigned this Sep 16, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T19:47:36.078005Z 4f2c5d8 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: abba707ce4

ℹ️ 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".

# has that same problem, since it also needs the names up front.
trainer_attributes_before = dict(Trainer.__dict__)

patch_gradient_accumulation_fix(Trainer)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore Trainer if installing the patch raises

When a latest/main Transformers change makes patch_gradient_accumulation_fix raise after it has already replaced get_batch_samples or another method, this call is still outside the try/finally, so the partially patched base Trainer leaks into the remaining files in the same pytest invocation. In particular, test_trl_loss_normalization_contract.py can then inspect Unsloth's wrapper instead of the upstream implementation, causing misleading follow-on results in the compatibility job; include patch installation and its assertion inside the protected region so every exit restores the snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and it is the one path the snapshot did not cover. Fixed in 4f2c5d8.

patch_gradient_accumulation_fix and its assertion now sit inside the try, so every exit restores, including the one where the patcher itself raises partway through.

I proved it with a negative control rather than by reading the code, and my first attempt at that control was wrong in a way worth stating: I raised after the patch but still inside the try, so the finally ran anyway and the run looked identical to the fixed one. The faithful control is a patcher that replaces the methods and then raises, called from outside the protected region. With it:

outside the try   1 failed, 9 passed, 2 skipped
                  SKIPPED test_trl_loss_normalization_contract.py:209:
                          Trainer.training_step source unavailable
inside the try    1 failed, 10 passed, 1 skipped   (that skip gone)

So the leak is real on that path and the fix closes it. The clean run is unchanged at 14 passed / 1 skipped across both files.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 4f2c5d8e7e

ℹ️ 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

Copy link
Copy Markdown
Member Author

The fast fake GRPO run, and what it is proved to catch

Status of the ask for a fast GRPO validation run: this PR is it, and it is verified two ways rather
than assumed.

The new test takes two real GRPO steps on CPU, through patch_gradient_accumulation_fix(Trainer),
in about 6 seconds. The existing three lanes all miss the class of defect it targets: the source
transform lane never trains, the SFT lane hands the sampler dicts rather than lists, and the
existing test_grpo_trains_on_cpu loads a plain HF model so Trainer.get_batch_samples stays stock
transformers. Measured by wrapping the zoo function and counting: 0 calls.

Two corrections were made to this PR after the first version, both found by trying to make the test
fail on purpose rather than by reading it:

  1. The first mutation control raised from inside the try, so the finally ran anyway and the
    mutant looked identical to the fix. A faithful control is a patcher that replaces methods and
    then raises, called from outside the protected region. Rebuilt that way, the control does turn
    the test red.
  2. State restoration was too narrow. It now snapshots and restores the whole Trainer.__dict__,
    deletes names the patch added, restores names it rebound, and asserts the dict is identical
    afterwards, so the test cannot leak a patched Trainer into whatever runs next in the same
    process. The patch install moved inside the try for the same reason.

What it would have caught: unsloth-zoo#1217 rewrote a list safe membership test into .get, and
TRL's GRPO identity collator makes every element of batch_samples a list, so every GRPO run died
at step 0 with AttributeError: 'list' object has no attribute 'get'. That sat on zoo main for a
day, was never released, and was found by accident during an unrelated review rather than by a gate.
This test is the gate.

@danielhanchen
danielhanchen force-pushed the pr/grpo-fake-run-takes-a-step branch from 4f2c5d8 to 7a1e4f5 Compare September 17, 2026 11:20
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto current main (6ba103b) and re-checked the five red jobs. Notes on what they were, and on the three files that had no business being in the file list.

The three Studio files were a pre-commit.ci autofix, and nothing was lost by dropping them

studio/backend/main.py, studio/backend/tests/test_bootstrap_banner_password_visibility.py and tests/studio/playwright_queue_localization.py came from 3d249d2, [pre-commit.ci] auto fixes from pre-commit.com hooks, pushed by the bot onto this branch. Nobody's feature work: every hunk is ruff-format line joining, e.g.

-def bootstrap_banner_lines(
-    username: str,
-    bootstrap_path,
-    ...
+def bootstrap_banner_lines(
+    username: str, bootstrap_path, password: Optional[str], *, autofill_available: bool

All of it is on main already, verbatim and independently: main carries username: str, bootstrap_path, password: Optional[str], *, autofill_available: bool at studio/backend/main.py:666, the None if _suppress_bootstrap else ... one-liner at :829, and both quote changes in the Playwright driver at :125 and :171. test_bootstrap_banner_password_visibility.py is byte-identical to main. So the rebase dropped a duplicate, not a change, and the diff is back to the one file this PR is about.

The five jobs

Four were red on main itself at this branch's old base. The base was b802399, which predates #11139, Repair the six CI checks that are red on main itself, and #11179. Every failing test maps one-to-one onto a file #11139 touched:

job failing test cause
workflow-trigger lint test_cache_budget_discipline.py, test_playwright_suites_run_in_ci.py fixed by #11139
Repo tests (CPU, studio) test_woa_wheelhouse_guard_behaviour.py, test_cache_budget_discipline.py, test_playwright_suites_run_in_ci.py, test_pwsh_calls_use_the_shared_runner.py fixed by #11139
Repo tests (CPU, rest) test_windows_amd_gpu_scan_fallback.py (x2) fixed by #11139
Selftests, lint and the single-file build test_studiobench_queued_idle_live.py fixed by #11139

All six files now pass at this head: 390 passed, 24 skipped. Selftests, lint and the single-file build also no longer runs at all, correctly: studiobench CI is filtered to tests/studio/studiobench/** and the frontend, and this PR touches neither now that the autofix commit is gone.

The fifth is different and is not fixed by the rebase. Repo tests (CPU, python) failed on test_windows_studio_update_launcher.py::test_non_windows_preserves_call_order_without_launcher_operations, on gw3, with typer.Exit: 1 out of a BlockingIOError in _studio_runtime_gate.py:224. That is a shared-state collision between xdist workers, not a defect in anything this PR or #11139 changed:

STUDIO_HOME (module-level, resolved at import): ~/.unsloth/studio
lock file: ~/.unsloth/studio/.studio-runtime.lock
while parent holds it -> CHILD REFUSED

unsloth_cli/commands/studio.py resolves STUDIO_HOME once at import to the real home, _studio_runtime_launch_guard takes a non-blocking flock on the single file under it, and the test drives studio.update(...) without redirecting either. Under pytest -n any two tests in that shard that reach update() land on one lock and the loser exits 1. It is a flake that will keep landing on unrelated PRs; the fix is to point studio.STUDIO_HOME at tmp_path in that file, which belongs in its own change rather than here.

Not adding the transformers/TRL pin test here

transformers >= 5.3.0 returns a tuple from _is_package_available even for return_version=False; TRL <= 0.28.0 stores it as a bool, so every optional dep reports present and from trl import GRPOTrainer dies on vllm_ascend / mergekit / weave. Measured: trl 0.24.0 fails on transformers 5.3.0 with No module named 'mergekit', 0.28.0 with No module named 'weave', and 0.29.0 vendors its own bool-returning _is_package_available, which is the fix. pyproject.toml's trl<=0.24.0 with transformers<=5.5.0 does overlap that region.

That is #11137's subject, which lifts the ceiling to 1.13.0 with a seven-version evidence table, so it is not being duplicated here. One residual worth naming there: lifting a ceiling does not forbid a resolver from picking transformers 5.4 with trl 0.24, so the declared window still admits the broken pair.

danielhanchen and others added 5 commits September 17, 2026 15:47
The existing GRPO canary runs a real UnslothGRPOTrainer for two steps, but _load_plain
never goes through the loader that calls patch_gradient_accumulation_fix, so
Trainer.get_batch_samples stays stock transformers and the zoo function is never entered.
Measured: 0 calls.

That is how unsloth-zoo#1217 killed every GRPO run at step 0 for a day without any lane
noticing. TRL's GRPO collator is the identity, so a batch is a list of dicts, and the
rewrite from a membership test to .get raised AttributeError.

This installs the patch the way a real run does, asserts it took, takes real steps, and
asserts at least one batch arrived as a list, since a canary that only sees the SFT dict
shape cannot catch a regression that assumes one. Fails against zoo e2e81b7, passes
against 2dcbe9c, 6.3 seconds for the file.
patch_gradient_accumulation_fix mutates the Trainer class, and in the
grpo-fake-run workflow this file shares a pytest process with
test_trl_loss_normalization_contract.py, which reads Trainer.get_batch_samples
and Trainer.training_step to check what upstream transformers returns. The
finally block restored get_batch_samples to the already-patched Zoo function and
left training_step, __init__ and compute_loss wrapped, so that later file was
inspecting Unsloth's methods and calling them transformers.

Measured, not argued: at the previous head
test_transformers_training_step_still_keys_off_model_accepts_loss_kwargs
SKIPPED with 'Trainer.training_step source unavailable', because the generated
wrapper has no retrievable source. With this change it runs and passes, so the
four-file CI set goes from 137 passed / 33 skipped to 138 passed / 32 skipped.

Snapshot the whole class dict rather than naming attributes: a hand-written list
falls behind the next attribute the patcher touches, and monkeypatch needs the
names up front too. The restore is then asserted by identity, so the canary
proves its own cleanup instead of assuming it.
patch_gradient_accumulation_fix and its assertion sat outside the try, so a
transformers change that made the patcher raise AFTER replacing one method would
skip the finally entirely and leak a partially patched Trainer into every later
file in the same pytest invocation. That is the leak the snapshot exists to
prevent, reachable through the one path the snapshot did not cover.

Negative control, with a patcher that replaces the methods and then raises:
called outside the try, test_trl_loss_normalization_contract.py reports 9 passed
/ 2 skipped with 'Trainer.training_step source unavailable'; called inside, 10
passed / 1 skipped and that skip is gone. Clean run is unchanged at 14 passed /
1 skipped across both files.
The post-cleanup check compared the two Trainer class dicts with ==, which
reads as an identity check but is not one: dict equality compares values with
==, so a wrapper that merely compares equal to the method it replaced passes.
It also prints several hundred entries and no verdict when it does fail.

Compare with is, per attribute, and name the ones that leaked or were not put
back.
@danielhanchen
danielhanchen force-pushed the pr/grpo-fake-run-takes-a-step branch from 1ad8e5a to c83bf08 Compare September 17, 2026 15:48
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto current main (e43b2ba), and the full run is in. The job that actually covers this PR is green:

job result
GRPO fake-run (latest + main TRL, CPU spoof) pass, 2m44s
pinned-symbol matrix pass
unsloth_zoo modules import under CUDA spoof pass
Source lint pass
security suites pass
pre-commit.ci pass
Shell installer tests, llama.cpp build, CodeQL, Analyze x4, (Python 3.11 floor / 3.13 a-k / 3.13 rest) pass

Raw log of the GRPO lane, against unsloth_zoo cloned at main (2026.9.5, editable) and TRL 1.13.0, no || true anywhere in the job:

tests/version_compat/test_trl_fake_train_cpu.py::test_sft_trains_on_cpu PASSED
tests/version_compat/test_trl_fake_train_cpu.py::test_grpo_trains_on_cpu PASSED
tests/version_compat/test_trl_fake_train_cpu.py::test_grpo_trains_on_cpu_through_the_patched_batch_sampler PASSED
tests/version_compat/test_trl_fake_train_cpu.py::test_dpo_trains_on_cpu PASSED
================= 171 passed, 114 warnings in 87.98s =================

Both arms re-measured after the rebase, same file, only unsloth_zoo swapped:

unsloth_zoo result
the #1217 spelling 1 failed, AttributeError: 'list' object has no attribute 'get' at loss_utils.py:402, other three canaries pass
#1254, fixed 4 passed

The rest of the red is main's, and it is filed

Five jobs are still red. Every one of them reproduces on a clean checkout of main with no PR content at all:

8 failed, 286 passed, 1 skipped
  5x tests/test_st_save_merged_signature.py       KeyError: "'__name__' not in globals"   -> #11067
  2x tests/studio/test_installer_av_shapes.py     install.ps1 names a vendor              -> #10533
  1x tests/python/test_accelerator_skip_guards.py two guards read a spoofed probe         -> #11038

which accounts for Repo tests (CPU, python), Repo tests (CPU, rest), Repo tests (CPU, studio) and workflow-trigger lint. All four are fixed in #11216. The formatting drift that failed pre-commit.ci here was #11207, now merged, which is why that check is green again.

The fifth, (Python 3.13, l-r), is studio/backend/tests/test_openai_auto_switch.py::test_companion_root_scan_does_not_block_the_event_loop, a wall-clock assertion on a loaded shared runner. 1 failed against 18700 passed, and nothing in it is reachable from a file under tests/version_compat.

None of the five run this PR's change: the three Repo tests (CPU, *) shards --ignore=tests/version_compat explicitly, and workflow-trigger lint runs a named list that does not include it.

The P2 fix is real, and checked rather than taken on trust

Verified by making patch_gradient_accumulation_fix raise after it has replaced get_batch_samples, training_step and added an attribute, then reading the Trainer class dict back:

revision result
abba707, the patch call outside the try leaked: ['_unsloth_brand_new_attr'] changed: ['training_step', 'get_batch_samples']
head, the patch call inside it leaked: [] changed: [], and the RuntimeError still propagates

Also tightened the post-cleanup check itself. It compared the two class dicts with ==, which reads as identity but is not: dict.__eq__ compares values with ==, so a wrapper that merely compares equal to what it replaced passes. It now compares with is, per attribute, and names the ones that leaked or were not put back instead of printing several hundred entries and no verdict.

@danielhanchen
danielhanchen merged commit 74aefad into main Sep 21, 2026
33 of 47 checks passed
@danielhanchen
danielhanchen deleted the pr/grpo-fake-run-takes-a-step branch September 21, 2026 08:27
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…ai#11126)

* Make the GRPO canary run through Unsloth's own batch sampler

The existing GRPO canary runs a real UnslothGRPOTrainer for two steps, but _load_plain
never goes through the loader that calls patch_gradient_accumulation_fix, so
Trainer.get_batch_samples stays stock transformers and the zoo function is never entered.
Measured: 0 calls.

That is how unsloth-zoo#1217 killed every GRPO run at step 0 for a day without any lane
noticing. TRL's GRPO collator is the identity, so a batch is a list of dicts, and the
rewrite from a membership test to .get raised AttributeError.

This installs the patch the way a real run does, asserts it took, takes real steps, and
asserts at least one batch arrived as a list, since a canary that only sees the SFT dict
shape cannot catch a regression that assumes one. Fails against zoo e2e81b7, passes
against 2dcbe9c, 6.3 seconds for the file.

* Restore every Trainer attribute the GRPO canary patches, not just one

patch_gradient_accumulation_fix mutates the Trainer class, and in the
grpo-fake-run workflow this file shares a pytest process with
test_trl_loss_normalization_contract.py, which reads Trainer.get_batch_samples
and Trainer.training_step to check what upstream transformers returns. The
finally block restored get_batch_samples to the already-patched Zoo function and
left training_step, __init__ and compute_loss wrapped, so that later file was
inspecting Unsloth's methods and calling them transformers.

Measured, not argued: at the previous head
test_transformers_training_step_still_keys_off_model_accepts_loss_kwargs
SKIPPED with 'Trainer.training_step source unavailable', because the generated
wrapper has no retrievable source. With this change it runs and passes, so the
four-file CI set goes from 137 passed / 33 skipped to 138 passed / 32 skipped.

Snapshot the whole class dict rather than naming attributes: a hand-written list
falls behind the next attribute the patcher touches, and monkeypatch needs the
names up front too. The restore is then asserted by identity, so the canary
proves its own cleanup instead of assuming it.

* Install the GRPO patch inside the protected region, not before it

patch_gradient_accumulation_fix and its assertion sat outside the try, so a
transformers change that made the patcher raise AFTER replacing one method would
skip the finally entirely and leak a partially patched Trainer into every later
file in the same pytest invocation. That is the leak the snapshot exists to
prevent, reachable through the one path the snapshot did not cover.

Negative control, with a patcher that replaces the methods and then raises:
called outside the try, test_trl_loss_normalization_contract.py reports 9 passed
/ 2 skipped with 'Trainer.training_step source unavailable'; called inside, 10
passed / 1 skipped and that skip is gone. Clean run is unchanged at 14 passed /
1 skipped across both files.

* Drop the unused inspect import from the GRPO canary

* Name the attribute the GRPO canary failed to restore

The post-cleanup check compared the two Trainer class dicts with ==, which
reads as an identity check but is not one: dict equality compares values with
==, so a wrapper that merely compares equal to the method it replaced passes.
It also prints several hundred entries and no verdict when it does fail.

Compare with is, per attribute, and name the ones that leaked or were not put
back.

---------

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants