Skip to content

GRPO: forward every vision kwarg, and accept an image column holding a list - #11031

Merged
danielhanchen merged 27 commits into
mainfrom
pr/grpo-vision-kwargs
Sep 17, 2026
Merged

danielhanchen merged 27 commits into
mainfrom
pr/grpo-vision-kwargs

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Two GRPO vision bugs.

#6960: both GRPO logprob paths dropped multimodal inputs. spatial_shapes (LFM2-VL),
image_position_ids (Gemma 4) and the num_tiles counts that say where one sample's tiles end
(LFM2-VL, InternVL) were never carried through,
and for any model that does not emit image_grid_thw the pixel_values were replaced by
None, so the reference and old logprobs were computed from the text alone. Both paths
now read one key tuple that unsloth-zoo owns and chunk through one shared slicer.

#3605: a singular image column holding a list of images crashed with
ValueError: Invalid input type. Must be a single image, a list of images, or a list of batches of images.. A list cell is now normalised into TRL's plural images path.

Pairs with unslothai/unsloth-zoo#1233, which adds the shared tuple and slicer.
Merge the unsloth-zoo PR first: the tests added here import grpo_vision_chunks from
unsloth_zoo.rl_replacements. The runtime code degrades gracefully against an older
unsloth-zoo, with a named error on the vision path only.

Root cause

#6960, the dropped keys

TRL's GRPO trainer passes everything the processor produced into its own
_get_per_token_logps_and_entropies, and saves the same set into the dict compute_loss
receives. Unsloth replaces both functions wholesale, and each replacement read a hand
written list of four keys, so the three newer keys reached neither. Worse, the chunk loop
was gated on image_grid_thw is not None and pixel_values is not None, and its else
branch appended None for pixel_values. Every VLM without image_grid_thw, which
includes Gemma 3, SmolVLM, InternVL and LFM2-VL, had its images removed from the forward.
Stock TRL in the same situation does pixel_values[start:end].

Three supporting defects surfaced while validating this on a real tiled VLM, and all three
had to be fixed for the keys to actually arrive:

  1. The rewrite that saves max_left_pad anchored on the first two lines of TRL's
    num_images output block. Since TRL 1.7.0 that block also holds a nested
    if num_tiles is not None: output["num_tiles"] = num_tiles, so the nested line ended
    up inside the try/except NameError that the rewrite appends and num_tiles never
    reached the inputs dict. TRL's own split_pixel_values_by_grid then raised
    KeyError: 'num_tiles' on LFM2-VL.
  2. The GRPO hidden state forward wrapper replaced model.forward with a bare
    (*args, **kwargs) function. transformers validates generate's kwargs against
    inspect.signature(self.forward), so every kwarg a VLM takes only on forward looked
    unused and LFM2-VL GRPO died in generation with The following model_kwargs are not used by the model: ['pixel_values', 'pixel_attention_mask', 'spatial_shapes'].
  3. The old unsloth-zoo fallback list in compute_loss named seven keys, not ten, so the
    degraded path would have dropped the three new keys again.

#3605, the singular image column

TRL wraps whatever example["image"] holds in a list of its own. On TRL 0.22.x that is
kwargs = {"images": [[img] for img in images]}, on TRL 1.x it is
images = [[example.get("image")] ... ]. Either way a cell holding two images becomes
[[[img, img]]], which transformers.image_utils.make_nested_list_of_images and the
processor both reject with the reporter's message. Nothing in Unsloth normalised it.

Changes

unsloth/models/rl_replacements.py

  • _get_per_token_logps_and_entropies and compute_loss read the multimodal inputs
    through grpo_get_vision_inputs and chunk through grpo_vision_chunks, both from
    unsloth-zoo, and splat the per chunk kwargs into the forward. The per key chunk lists
    are gone, so a key cannot be added to one path and forgotten on the other. The imports
    are body local because these function bodies are copied into the generated
    UnslothGRPOTrainer without this module's imports.
  • The num_images output anchor now has a long form that includes TRL 1.7.0's nested
    num_tiles line, tried first, with a warn once if neither form is found.
  • The old unsloth-zoo fallback key list names all ten keys, with a test that gates it
    against GRPO_VISION_KEYS.
  • _unsloth_grpo_image_cell normalises a singular image cell, and the
    _generate_and_score_completions rewrite applies it to both TRL spellings. TRL 0.22.x's
    prepare_multimodal_messages(prompt, num_images=1) becomes the cell's own length, so a
    two image cell gets two placeholders.
  • _unsloth_reject_grpo_image_list raises a named error, injected at the top of
    _generate_and_score_completions only when no known spelling matched, so an unknown TRL
    says which column to rename instead of failing inside the processor.

unsloth/models/rl.py

  • functools.wraps on the GRPO hidden state forward wrapper, so
    inspect.signature(model.forward) still reports the model's real parameters.

Compatibility

What changes for an input that already succeeded

Nothing changes. A text-only GRPO run that already worked keeps the same peak
memory, 16565.4 MiB on both sides on every run here, the same step time inside
noise, 0.230 s base against 0.235 s head over a 0.213 to 0.248 s band, and the same
loss trajectory to every printed digit.

That last point is measured rather than assumed, because an earlier revision of this
description claimed the opposite. Six base and six head runs, sequential on one GPU,
alternating arms, seed 3407, Qwen2.5-0.5B-Instruct, 8 steps, on TRL 0.22.2 with
torch 2.9 and transformers 4.57.6 and again on TRL 1.13.0 with torch 2.14 and
transformers 5.17.0: all twelve curves are identical. The comparison is exact
equality rather than an epsilon, chosen after measuring the noise floor and finding
these runs deterministic run to run, so any nonzero difference would have been
causal. A third arm with only the signature hunk reverted also matched base exactly,
which isolates the multimodal rewrite as numerically inert for a text run.

The earlier claim of a divergence from step 3 came from a harness fault, not from
the code: concurrent same-arm runs shared one RUN_DIR and one
UNSLOTH_COMPILE_LOCATION and overwrote each other mid-run. Giving every invocation
a unique tag removed the divergence, and it did not reappear across twelve runs.

Run across three version corners, CPU only, with both repos checked out together:

step mA (torch 2.6.0, transformers 4.57.6, trl 0.22.2, py3.10) mC (torch 2.11.0, transformers 5.5.0, trl 1.0.0) mD (torch 2.14.0, transformers 5.17.0, trl 1.13.0)
tests/test_grpo_vision_kwargs_forwarded.py (new) pass pass pass
tests/test_grpo_image_column_normalisation.py (new) pass pass pass
tests/test_multi_image_grpo_chunking.py pass pass pass
GRPO logprob loop suites pass pass pass
unsloth-zoo tests/test_grpo_vision_kwargs.py pass pass pass
tests/version_compat/ fail fail fail
LFM2-VL GPU parity not run not run skip, torchvision not installed

The tests/version_compat/ row fails identically with and without this change, because
our CPU compatibility runs set UNSLOTH_COMPILE_DISABLE=1 and the trainers are then
never generated, so test_trl_fake_train_cpu.py reports "SFT patch did not apply".
Measured directly: setting only that variable turns a clean run into exactly those 30
failures. With compilation on, the same directory passes 1681 of 1681 on mA, 1713 of 1713
on mC and 1719 of 1719 on mD, before and after this change. The GRPO patch therefore still
applies across the whole TRL range this repo supports, and this change does not alter that
suite's result on any of the three.

The GPU check is not resolvable in those three environments: the LFM2-VL fast image processor
requires torchvision, which those venvs do not carry, so it is recorded as skipped with that reason. The GPU evidence below was taken on the newest of the three pins plus torchvision.

Cross-platform CI was also run on owned staging runners, with unsloth_zoo installed from
the paired branch. Counts are read out of each job's pytest summary:

runner result
ubuntu-latest 69 passed
ubuntu-24.04-arm 69 passed
macos-15, Apple Silicon 69 passed
windows-latest not exercised
windows-11-arm not exercised

Every test file this PR adds or changes is inside the 69 that passed on each of the three.
The same 28 setup errors appear on all three, all of them in one unrelated Studio backend
file (ModuleNotFoundError: No module named 'utils.native_path_leases'). Neither Windows
runner could import unsloth in that environment at all: x64 needs a triton wheel that does
not exist for Windows under a plain pip install, and ARM64 cannot install sqlite-vec.
This PR is pure Python with no platform specific paths, but Windows coverage for it is
absent and should be read that way.

Tests

New, both fail on main:

  • tests/test_grpo_vision_kwargs_forwarded.py, 9 tests. The key tuple has one home, both
    passes use the shared chunker, compute_loss splats the whole set into both
    grpo_accumulated_loss call sites, both paths reach the same helper object, an old
    unsloth-zoo fails loudly on the vision path, LFM2-VL shaped inputs reach the forward
    kwargs, the fallback list matches GRPO_VISION_KEYS, the forward wrapper keeps the real
    signature, and num_tiles survives the output dict rewrite.
  • tests/test_grpo_image_column_normalisation.py, 7 tests. The cell helper, the
    reporter's exact nesting, single image cells unchanged, the rewrite landing on the
    installed TRL, the TRL 0.22.x placeholder count following the cell (executed, not just
    asserted on the source), the named error, and the guard being injected when no anchor
    matches.

tests/test_multi_image_grpo_chunking.py had four source grep assertions that named the
chunk lists this change removes. They are replaced with behavioural tests that call
grpo_vision_chunks directly, which is stricter than what they replaced. Two exec based
harnesses, tests/test_grpo_padded_raw_logits.py and
tests/test_grpo_hidden_states_signal.py, pass the per chunk kwargs as a dict now instead
of a fixed six element tail.

Re run on the newest corner with both repos together, 1817 passed, 182 skipped:

tests/test_grpo_vision_kwargs_forwarded.py
tests/test_grpo_image_column_normalisation.py
tests/test_multi_image_grpo_chunking.py
tests/test_grpo_padded_raw_logits.py
tests/test_grpo_hidden_states_signal.py
tests/test_grpo_hidden_states_logits_cost.py
tests/test_grpo_hidden_states_per_call_degradation.py
tests/test_grpo_hidden_states_wrap_target.py
tests/version_compat/

An earlier, wider run over every GRPO, DPO, ORPO, CPO and RL config suite in the repo plus
tests/test_collection_hygiene.py and tests/test_import_fixes_drift.py passed 309 of
309 with 6 skipped.

Evidence

Logprob parity on LFM2-VL-450M, one B200, fp32, two rows whose images split into 11 and 10
tiles so the tile axis differs per row. Reference is one forward over the whole batch,
under test is the same batch chunked one row at a time through the shared slicer, and the
pre fix column is the behaviour of dropping every key that is not image_grid_thw:

num_images=[1, 1] num_tiles=[11, 10]
pixel_values (21, 1024, 768) spatial_shapes (21, 2)
max abs logprob error, fixed  path vs reference: 0.000e+00
max abs logprob error, pre fix path vs reference: 6.659e+00

One real GRPO step on the same checkpoint, through the generated UnslothGRPOTrainer with
num_iterations = 2 so the no grad old logprob pass runs, completes:

{'loss': '0', 'grad_norm': '67', 'num_tokens': '5658', 'completion_length': '8', 'kl': '0', ...}
VERDICT: PASSED

On main the same step never reaches the logprob code: it dies in generation with
The following model_kwargs are not used by the model: ['pixel_values', 'pixel_attention_mask', 'spatial_shapes'], and with that fixed it then dies with
KeyError: 'num_tiles' inside TRL's split_pixel_values_by_grid.

For #3605, the reporter's shape against the function in their traceback:

a singular `image` cell holding 2 images
unpatched:
  TRL >= 1.0.0 extraction: [[[Image x2] x1] x1]
    make_nested_list_of_images raised: Invalid input type. Must be a single image, a list of images, or a list of batches of images.
  TRL 0.22.x processor kwargs: [[[Image x2] x1] x1]
    make_nested_list_of_images raised: Invalid input type. Must be a single image, a list of images, or a list of batches of images.
patched:
  normalised cell: [[Image x2] x1]
    make_nested_list_of_images accepted it
rewrite landed on the installed TRL: True

The three scripts behind the output above are repro_6960_lfm2vl_parity.py,
repro_6960_lfm2vl_grpo_step.py and repro_3605_image_column.py.

Known limitations

  • The Gemma 3 Vision GRPO notebook still documents the singular image column. It lives in
    the notebooks repo and is not touched here; a two image cell now works either way.
  • The image_position_ids and InternVL num_tiles paths follow TRL's own arithmetic and
    are covered by unit tests, but were not exercised on a real Gemma 4 or InternVL
    checkpoint on this host. Only LFM2-VL was run end to end.
  • On TRL 0.22.x there is no num_images in the inputs dict, so a model whose
    pixel_values is image indexed rather than sample indexed is still sliced on the sample
    axis. That matches stock TRL 0.22.x and is unchanged here.

Follow-up review pass

Four further findings, all fixed on this branch.

pixel_position_ids. TRL 1.0.x carries the Gemma 4 position ids under that name and renamed the key
image_position_ids in 1.1.0. The shared tuple named only the newer one, so on TRL 1.0.x the very
class of key this change exists to forward was still dropped. Both spellings are read now, and each
is forwarded under the name it arrived with. Transformers itself only ever named the outer parameter
image_position_ids, from Gemma 4's first release in 5.5.4 through 5.17.0, and forwards it internally
as pixel_position_ids; pixel_position_ids is the TRL 1.0.0 spelling alone, and a forward that is
handed it absorbs it through **kwargs: Unpack[TransformersKwargs] rather than raising. Stock TRL
1.0.0 puts it straight into model_inputs, so matching it is matching upstream. Fixed in the
unsloth-zoo half as well.

One collector, not two lists. The old unsloth_zoo fallback was a second copy of the key names written
inline in compute_loss, and the no-grad logprob pass had no fallback at all: without the zoo helper
it collected nothing, so a run carrying only token_type_ids lost them although the code it replaced
sliced them itself. Both paths go through one _unsloth_grpo_vision_inputs now. Only the image
indexed slicing still needs the zoo, and that case refuses to run rather than degrading.

The multi image gate. It decided whether the installed unsloth_zoo could serve the run by grepping
inspect.getsource(grpo_accumulated_loss) for the string num_images. Now that the function
delegates its slicing to the shared chunker, the name survives there only as a local nobody reads, so
removing it, which is what a linter asks for, turned a working multi image run into a false "Please
upgrade unsloth_zoo". Observed while cleaning that local up. The gate probes for grpo_vision_chunks
by import first and keeps the source grep only for an older zoo.

The forward wrapper carries a signature. Setting wrapped_forward.__signature__ is what makes
LFM2-VL work, since generate() validates against inspect.signature(self.forward) and a bare
(*args, **kwargs) wrapper hides every real parameter. __signature__ rather than
functools.wraps: wraps sets __wrapped__, and accelerate unwraps past this wrapper and loses
it, while inspect.unwrap() stops at __signature__.

logits_to_keep is not affected either way. A forward-kwarg probe finds it present in 4 of 4
logprob calls for SmolVLM on base and on head alike, and absent on both for a text model, so this
change neither restores nor removes it. An earlier revision of this description said the signature
hunk let TRL pass logits_to_keep again for text models as well; that is not what the probe shows,
and the corrected text-only measurement above is the same finding from the other direction.

Compatibility, this pass

Generated UnslothGRPOTrainer built and parsed on TRL 0.22.2, 0.27.2, 1.0.0 and 1.13.0, base and
head, and the anchors were read out of TRL 0.23.0, 0.24.0, 1.1.0, 1.3.0, 1.5.0, 1.7.0, 1.9.0 and
1.11.0 as well.

Corner Result
TRL 0.22.2, transformers 4.57.6 GRPO suites 81 passed, 5 skipped. The two image cell fails on main and passes here. SmolVLM single image passes on main on this TRL: its defect there is the silent kind, below
TRL 0.27.2, transformers 5.0.0 81 passed, 5 skipped
TRL 1.0.0, transformers 5.5.0 81 passed, 5 skipped. pixel_position_ids present in the generated trainer
TRL 1.13.0, transformers 5.17.0 86 passed. LFM2-VL, Qwen2.5-VL, SmolVLM and a two image cell all fail on main, all pass here
text only, TRL 1.13.0 and 1.0.0 pass on both, and bit-identical to base across 12 runs, see above

The silent half of #6960 is worth stating on its own, because it is the case that does not raise.
On a SmolVLM run that trains to completion on main, a forward-kwarg probe finds pixel_values
arriving at the logprob forward as an explicit None in 4 of 4 calls, so the reference and old
logprobs are computed from text alone while the run reports normal losses. On this branch the same
probe finds pixel_values of shape (2, 17, 3, 512, 512) and pixel_attention_mask of shape
(2, 17, 512, 512) in 4 of 4 calls. That is the arm with no error message anywhere.
| TRL 0.22.2 on torch 2.6 | not run, that torch has no kernel for this card; TRL 0.22.2 is covered on torch 2.9 instead |

A singular image column holding None still fails exactly as it does on main. Not in TRL's own
all(img_list == [] for img_list in images) guard, which an earlier revision of this description
named: None == [] is False, so that guard is a no-op for a None entry and the failure lands
later, at len(None) on TRL <= 1.12 and inside the processor on 1.13.0 and 0.22.x. Either way the
behaviour is identical to main, and changing it means diverging from TRL's extraction, so it is left
alone and recorded here.

Fixes #6960
Fixes #3605


Merge order, and what Backend CI shows until then

unslothai/unsloth-zoo#1233 has to merge AND ship a release before this PR can merge. #1233 is
merged as 878103bd, so the first half is done. The release is the half that still matters, and it
matters for users rather than for CI.

CI is unaffected either way, because no CPU CI job installs unsloth_zoo from PyPI (an earlier
revision of this description said Backend CI does). consolidated-tests-ci.yml resolves
refs/heads/main with git ls-remote and core-cpu-setup clones that sha editable;
studio-backend-ci.yml, version-compat-ci.yml, mlx-ci.yml and notebooks-ci.yml all install
unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo; wheel-smoke.yml uses --no-deps.
Read out of a raw job log rather than out of the YAML:

Resolved https://github.com/unslothai/unsloth-zoo to commit b38fd40aa2e0bb2026f41685efe63c4188649723

That run predates #1233 by four hours, which is why the shared-chunker tests were inert on it. Any
run created after #1233 merged resolves a main that carries the helpers.

What the release gates is the user path. The newest release on PyPI is unsloth_zoo 2026.9.4
and it carries none of the three helpers, while pyproject.toml here floors at >=2026.9.4. On
that combination every vision GRPO batch raises before any forward, including the image_grid_thw
grid path that worked before and is unrelated to this bug, because the gate is
_grpo_vision_chunks is None and pixel_values is not None and the inline chunk loop main used
instead is what this change deletes. Raising beats silently training on the text, but it means the
floor and the release have to move together: the release ships, then the three floors in
pyproject.toml move to it and the skip in tests/test_grpo_vision_zoo_floor.py comes off, in this
PR.

Measured locally against both zoo states, running the same selection each time:

unsloth_zoo on the path result
released PyPI build 2026.9.4 (no shared helpers) 95 passed, 9 skipped, 0 failed
unslothai/unsloth-zoo#1233 on main 103 passed, 1 skipped

Eight of those skips are the chunker-gated tests, five in test_grpo_vision_kwargs_forwarded.py and
three in test_multi_image_grpo_chunking.py; the ninth is the deferred zoo floor. They are skips
rather than failures because of the pytest.importorskip guards. An earlier revision of this
description reported five failures, which was true of commit 2c873acc, before those guards.

The old-zoo path itself is covered and passes on the released build: test_old_zoo_without_the_helper_fails_loudly_for_vision_runs and test_an_old_zoo_still_forwards_the_sample_indexed_keys both hold, so a user who upgrades unsloth alone gets a clear refusal on a vision run and keeps the sample-indexed keys on a text-only one.


Second review pass, and one more fix

A padded per sample image axis whose counts sum to the batch size. Idefics and SmolVLM pad to the
widest sample, so pixel_values.shape[0] stays the batch size. When num_images happens to sum to
that same number, which any mixed text plus vision dataset reaches, a padded batch and a flat image
indexed one are numerically indistinguishable, and _unsloth_grpo_split_vision_by_sample split the
padded one by image. Driving it with a (2, 2, 3, 4, 4) tensor whose every value encodes its own row
index:

num_images=[2, 0]:    SPLIT into [2, 0] rows, owners=[[0.0, 1.0], []]           MISATTRIBUTED
num_images=[0, 2]:    SPLIT into [0, 2] rows, owners=[[], [0.0, 1.0]]           MISATTRIBUTED
num_images=[1, 2, 0]: SPLIT into [1, 2, 0] rows, owners=[[0.0], [1.0, 2.0], []] MISATTRIBUTED
num_images=[1, 1]:    SPLIT into [1, 1] rows, owners=[[0.0], [1.0]]             OK

The second sample's images train against the first sample's prompt and the second gets an empty
tensor, with nothing raised. The list branch of the same function already guarded this collision and
named num_images = [2, 0] in its comment; the tensor branch did not.

Inside that ambiguous region the batch now keeps TRL's layout rather than guessing, which is what
every TRL version does today and what main did. Rank does not separate the two either, since a flat
image indexed tensor for one family has the same rank as a padded one for a family with one fewer
axis. All ones is excluded because both readings agree there, so the common case is unchanged. The
cost, stated rather than hidden: a genuinely flat batch in the same region is left unsplit and the
shuffle scrambles it, which is the pre-existing hazard rather than a new misattribution.

test_a_padded_row_per_sample_survives_counts_that_sum_to_the_batch_size asserts on row provenance
rather than on shapes, and fails on the previous commit. The existing
test_a_padded_row_per_sample_is_left_alone passed only because [2, 2] over two rows does not sum
to two.

Pairs with unslothai/unsloth-zoo#1271 as well. The chunker's own rank test, which tells a padded
sample axis from a flat image axis, was applied unconditionally, and LLaVA-NeXT and LLaVA-OneVision
pad on the patch axis: their flattened pixel_values is [n_images, max_patches, C, H, W], one row
per image at rank 5. Two samples holding two images and one gave the first sample one of its images,
gave the second the image belonging to the first, and never forwarded the third. Stock TRL slices
that layout by image and so does the splitter here, so the chunker was the one component disagreeing
with both. #1271 confines the rank test to the region where the two axes are the same length, which
is the only region they are confusable in. It should land before the release this PR waits on.

Full suite against the merge base, CI's own shards and env, on CPU: 26805 passed, 1004 skipped, 9
failed on head against 26744, 1005, 9 on base, with an identical failure set and an empty list of
tests whose outcome differs. The 9 are local environment only and fail the same way on both sides.

A TRL that cannot size its placeholders. The image column normalisation has two anchors. The
legacy cell spelling, kwargs = {"images": [[img] for img in images]}, matches on TRL 0.20.0 through
0.23.1, but the rewrite that sizes prepare_multimodal_messages to the cell matches only on 0.22.0
through 0.23.1: 0.20.0 and 0.21.0 predate that helper entirely and inline one {"type": "image"} per
user message with no count. Measured against the shipped sources:

TRL image cell anchor placeholder anchor prepare_multimodal_messages exists
0.20.0 1 0 no
0.21.0 1 0 no
0.22.0, 0.22.2, 0.23.1 1 1 yes
0.24.0 and up 0, sizes them itself 0 yes

So on those two versions a normalised two image cell reached the processor with one placeholder, and
the prologue counted the same cells, so nothing else in the batch disagreed. The named refusal did
not fire, because its gate only asked whether the cell had been normalised, and there it had. Both
versions are inside the declared pin, trl>=0.18.2,!=0.19.0,<=0.24.0.

The gate now also asks whether the placeholders were sized. Diffed over the 28 TRL releases from
0.18.2 to 1.13.0: only 0.20.0 and 0.21.0 change, gaining the refusal, and the generated source for
every other version is byte for byte what it was. _warn_once fires on none of them. A single image
cell is unaffected everywhere.

test_a_trl_that_cannot_size_its_placeholders_refuses_the_multi_image_row and its control
test_a_trl_that_can_size_its_placeholders_is_not_refused, both canary checked against the previous
commit.

Full suite, against main at the same base

CPU, CI's own env and selection, 8 workers:

tree tests failed skipped
this branch, 8c54628 28451 27 1052
main at the merge point 28391 27 1054

26 of the 27 failures are shared and are all local environment: a GPU only q_galore test, torchcodec
provenance against the local torch build, sandboxed venv probes in the Windows updater tests, QAT,
and VideoReader which torchvision 0.28 removed. The one on each side that is not shared
(test_import_fixes_drift on this branch, a vllm_compat import on main) passes in isolation on
both trees, so both are xdist ordering flakes rather than outcomes. No regressions.

The merge order constraint is now satisfied

unsloth_zoo 2026.9.5 is on PyPI and carries the shared helpers, pyproject.toml floors at it at
all three sites, and the deferred floor assertion in tests/test_grpo_vision_zoo_floor.py is
re-armed. Against that released zoo, which is what a user actually resolves, the seven GRPO test
files this PR touches give 106 passed, 0 skipped, 0 failed. Against 2026.9.4 the same selection
gave 95 passed and 9 skipped.

Worth carrying forward separately: 2026.9.5 still contains the LLaVA-NeXT and LLaVA-OneVision
mis-slice that unslothai/unsloth-zoo#1271 fixes. Those processors pad on the patch axis, so their
flattened pixel_values is [n_images, max_patches, C, H, W], and the chunker's rank test read that
image axis as a sample axis. It predates this PR inside the zoo; this PR only routes through it.

CI

The org queue is running 1h45m to 2h behind today, longer than the interval between pushes here, so
every batch of runs on this branch has been cancelled by the next push before a runner picked it up.
gh pr checks renders a cancelled run as "fail"; read from the API, all of them are cancelled, not
failed, and none is a test failure.

The real answer came from replicating the head onto a staging repo, off that queue:

workflow conclusion
Wheel CI success
Version Compat CI success
Notebooks CI success
Lint CI success
Backend CI 10 failures
Core 4 failures
Workflow trigger lint 2 failures

All 16 reproduce identically on main, and none touches GRPO -- each was re-run locally in both
trees rather than judged by its name: 5 test_st_save_merged_signature.py, test_accelerator_skip_guards.py,
2 test_installer_av_shapes.py (twice, it also fails the trigger lint job), test_base_model_dir_name_fallback.py,
2 test_import_fixes_drift.py::test_rope_carry_* under transformers 4.57.6, and 2 unsloth_zoo
test_per_layer_device.py which pass on current zoo main. test_formatter_fixed_point.py names
three files this PR does not touch.

The green is not vacuous. Repo tests (CPU, rest) returned 6 failed, 7843 passed, 344 skipped, its
raw log shows test_grpo_vision_kwargs_forwarded.py executing, and it resolved the zoo at
54e9376b, a descendant of unslothai/unsloth-zoo#1233, so the chunker-gated tests ran rather than
skipping.

The refusal reads every row. It inspected inputs[0] alone, so a batch whose first row holds a
bare image and whose second holds a list passed it, and the normalisation then gave that later row
several images against one placeholder. A dataset that mixes a bare image with a list is exactly the
shape that puts the list somewhere other than row 0:

row 0 holds the list                -> REFUSED
row 1 holds the list                -> no refusal
row 2 holds the list                -> no refusal
row 0 is None, row 1 holds the list -> no refusal

Every row is read now and the message names the row. The shapes that pass today were checked rather
than assumed: single image cells, single item lists, no image column, rows that are not dicts, an
empty batch, and None in place of the batch.

An empty legacy cell takes no placeholder. On TRL 0.22.x and 0.23.x an empty cell took one
placeholder while the prologue counted it as zero, so a batch mixing an image bearing row with an
empty one reached the processor a placeholder ahead of its pixels. Measured against a real Gemma 3
processor rather than argued:

batch main before after
image + empty cell fail fail ok
all cells empty fail fail ok, text batch
image + None cell fail fail fail, as on main
all cells None fail fail fail, as on main
all single images ok ok ok
2 image cell + 1 image cell fail ok ok

Zero on its own is not enough, and that is why the fallback was 1: an all empty column then reaches
the processor as [[], []] against no placeholders, which is IndexError: list index out of range
rather than a text run. TRL demotes that batch itself from 0.24.0, so the same guard is ported into
the legacy rewrite. It mirrors TRL's all(img_list == []), which never fires for a None entry, so
the None column still behaves exactly as on main.

Only 0.22.0 through 0.23.1 change, verified by diffing the generated source across the 28 TRL
releases from 0.18.2 to 1.13.0.

Final CI state

e980e3d: 64 success, 6 failure, 7 skipped on the org queue. The six are not this PR's, and the
comparison is main's own Backend CI run from the same hour (run 35252245488, head 1d5210d7a),
which fails on the same jobs with the same tests and the same counts:

job this PR main
Repo tests (CPU, python) test_accelerator_skip_guards + test_docker_hub_readme, 2 failed, 5215 passed same two, 2 failed, 5215 passed
Repo tests (CPU, rest) 5 x test_st_save_merged_signature, 5 failed, 7853 passed same five, 5 failed, 7787 passed
Repo tests (CPU, studio) 2 x test_installer_av_shapes (bitdefender), 2 failed, 11216 passed same two, 2 failed, 11218 passed

The only difference anywhere is the +66 passing tests in rest, which are this PR's own. The other
three reds are the same shape: GGUF inference smoke fails 3 checks in
tests/studio/test_path_probe_access_denied.ps1, a file main added today in #10533 that this PR does
not touch; workflow-trigger lint fails on the same two bitdefender assertions; and
pip scan-packages :: hf-stack reports findings inside third party packages while this PR adds no
dependency.

The cross platform answer came from replicating the head onto a staging repo, off the org queue:
17 of 22 runs green, including Windows Unsloth API / UI / Update CI, Windows Application Control
CI, Windows ARM64 CI and the Apple Silicon Mac CI, none of which this PR touches. The red there
is the same set plus Core, whose failures are the test_rope_carry_* drift pair (identical on main
under transformers 4.57.6) and two unsloth_zoo test_per_layer_device.py cases that pass on current
zoo main.

The green is not vacuous: Repo tests (CPU, rest) shows test_grpo_vision_kwargs_forwarded.py
executing in its raw log, and resolved the zoo at e12fb791, a descendant of
unslothai/unsloth-zoo#1233, so the chunker-gated tests ran rather than skipping.

Full suite against the exact main commit this branch merged (317b702), CPU, CI's env and selection:
28588 tests and 42 failures on the branch against 28522 and 42 on main, with identical failure
sets
and no test whose outcome differs in either direction.

Third review pass: the legacy vLLM paths

Both of these are on TRL 0.22.x and 0.23.x, where the vLLM branches read the raw image cells
rather than the processor kwargs, so the processor fix above does not reach them.

A multi image row cannot go through legacy vLLM server mode. The raw cells reach
VLLMClient.generate, and trl/extras/vllm_client.py does
images = [pil_to_base64(img) for img in images] if images else None with pil_to_base64 calling
image.save(buffer, format="PNG"). A cell holding two images is one top level entry, so it arrives at
list.save(...). This is exposure created by this branch: before it, that row died earlier inside the
processor and the vLLM path was never reached. Re-encoding the payload would mean changing a wire
format shared with a separately running vLLM server, so the refusal is injected on these versions too
and handed the trainer, firing only when use_vllm is set and vllm_mode is server. Colocate mode,
a run without vLLM, and a single image row in server mode all keep working, asserted rather than
assumed.

Demoting an all empty column has to clear the flag too. Every vLLM branch on those versions is
gated on has_images, never on kwargs, so emptying kwargs alone still submitted [[], ...] as an
image payload and server mode called .save() on an empty list. has_images = False is set with it,
which also short circuits the legacy vision prologue.

Only 0.22.0 through 0.23.1 change. 0.20.0 and 0.21.0 already refuse unconditionally for the
placeholder reason, and 0.24.0 and up are byte for byte what they were, with no guard injected.

Not taken: patch indexed masks on a grid batch

A grid batch whose pixel_attention_mask is patch-row indexed would be left flat while pixel_values
is regrouped. No processor emits both keys, so that batch cannot be built. Scanning every model
package's declared model_input_names:

transformers declaring image_grid_thw declaring pixel_attention_mask both
4.57.6 2 5 none
5.0.0 7 5 none
5.5.4 7 5 none
5.12.1 9 5 none
5.17.0 15 5 none

The sets are disjoint at every version: the grid families carry no attention mask over their patches,
and the five that do (idefics2, idefics3, lfm2_vl, siglip2, smolvlm) carry no grid. The
patch-axis mask handling is the LFM2-VL and Idefics shape, reached through the num_tiles and padded
branches, which are covered.

Final CI state, against main's own runs

b591e84: 68 success, 10 failure, 7 skipped. None of the 10 is this PR's. main's own runs from
the same evening (35252245488 and 35252245556) fail on the same jobs with the same tests and the same
counts:

job this PR main
Repo tests (CPU, python) test_accelerator_skip_guards + test_docker_hub_readme, 2 failed, 5215 passed same two, 2 failed, 5215 passed
Repo tests (CPU, rest) 5 x test_st_save_merged_signature, 5 failed, 7853 passed same five, 5 failed, 7787 passed
Repo tests (CPU, studio) 2 x test_installer_av_shapes, 2 failed, 11216 passed same two, 2 failed, 11218 passed
Core (HF=4.57.6 + TRL<1) 2 x test_rope_carry_*, 2 failed, 38 passed same two, 2 failed, 38 passed
Core zoo x3 2 x test_per_layer_device, 5834 / 5807 / 5852 passed same two, 5834 / 5807 / 5851 passed
GGUF inference smoke 3 checks in tests/studio/test_path_probe_access_denied.ps1 that file was added to main today by #10282's successor #10533 and is not in this diff
workflow-trigger lint 2 x test_installer_av_shapes same two
pip scan-packages :: hf-stack findings inside third party packages this PR adds no dependency

The only difference anywhere is the +66 passing tests in rest, which are this PR's own. The
Core zoo cells run the unsloth_zoo suite against zoo main, which this PR does not touch.

(Python 3.13, l-r) failed once on two studio backend timing tests; both files pass locally on both
trees (781 passed) and the job went green on a re-run.

Cross platform, from replicating the head onto a staging repo off the org queue: 17 of 22 runs
green
, including Windows Unsloth API / UI / Update CI, Windows Application Control CI, Windows
ARM64 CI and the Apple Silicon Mac CI, none of which this PR touches.

Full suite against the exact main commit this branch merged (317b702), CPU, CI's env and selection:
28591 tests and 43 failures on the branch against 28522 and 42 on main, with no test failing on the
branch that does not also fail on main. The single extra id passes in isolation on both trees and
appeared on the main side of an earlier pass, so it is an xdist ordering flake.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 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-17T19:14:04.703923Z b591e84 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 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: 3386c5aae3

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

Comment thread unsloth/models/rl_replacements.py Outdated
Comment on lines +1542 to +1549
if _grpo_vision_chunks is None:
if kwargs.get("pixel_values", None) is not None:
raise RuntimeError(
"Unsloth: vision GRPO needs an unsloth_zoo build that exports "
"grpo_vision_chunks, the shared multimodal key tuple and chunker "
"used by both GRPO logprob paths. Please upgrade unsloth_zoo."
)
vision_inputs = {}

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 Retain token-type inputs in the old-zoo fallback

When the installed unsloth_zoo predates the new helpers and a text-only GRPO batch carries token_type_ids or mm_token_type_ids without pixel_values, this branch neither raises nor retains those inputs. Previously both fields were sliced and passed to every old/reference forward, while the fallback in compute_loss still forwards them to the gradient pass, so models that use token-type embeddings or masks can compute policy and reference logprobs from different inputs. Populate the fallback mapping with these sample-axis fields even when the vision chunker is unavailable.

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.

Not taking this one: the old-zoo fallback does retain both fields at head.

_unsloth_grpo_vision_inputs collects them either way. Its zoo-less fallback names token_type_ids and mm_token_type_ids explicitly, for exactly the reason given at the docstring, and test_legacy_fallback_list_matches_the_zoo_tuple fails if that list ever drifts from GRPO_VISION_KEYS. The chunk fallback then slices precisely those two keys per sample:

vision_chunks.append({
    _key: vision_inputs[_key][_start:_end]
    for _key in ("token_type_ids", "mm_token_type_ids")
    if vision_inputs.get(_key, None) is not None
})

Ran it on a text-only batch of 8 with both fields present and no pixel_values, against an unsloth_zoo with no grpo_vision_chunks:

collected non-None: ['mm_token_type_ids', 'token_type_ids']
pixel_values: None
chunk 0: keys=['mm_token_type_ids', 'token_type_ids'] token_type_ids=[0, 1, 2, 3]
chunk 1: keys=['mm_token_type_ids', 'token_type_ids'] token_type_ids=[4, 5, 6, 7]

Both fields are present and sample-indexed the same way grpo_vision_chunks and the pre-PR code index them, so the no-grad pass and the gradient pass see the same inputs and there is no policy/reference divergence. The raise above is deliberately scoped to pixel_values, since only the image-indexed slicing needs the zoo; the sample-indexed keys are handled here.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed this on main: the chunk loop in unsloth/models/rl_replacements.py is still gated on image_grid_thw and drops pixel_values to None for Gemma 3 and other VLMs, and the singular image column still hits the nesting reported separately, so the parity numbers here look like the right check. Will get this reviewed once the paired unsloth-zoo change lands.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
shimmyshimmer and others added 3 commits September 16, 2026 01:36
… list

Two GRPO vision bugs.

The logprob paths dropped multimodal inputs. TRL passes everything the processor
produced into its per token logprob helper and stores the same set in the dict
compute_loss receives, but the Unsloth replacements read a hand written list of
four keys. spatial_shapes (LFM2-VL), num_tiles (LFM2-VL, InternVL) and
image_position_ids (Gemma 4) reached neither pass, and a model that does not
emit image_grid_thw had its pixel_values replaced by None, so the reference and
old logprobs were computed from the text alone. Both passes now read one key
tuple that unsloth_zoo owns and chunk through one shared slicer, so a key added
there reaches both. Three supporting defects went with it:

- The rewrite that saves max_left_pad matched only the first two lines of TRL's
  num_images output block, which since TRL 1.7.0 also holds a nested num_tiles
  line. The nested line ended up inside the try/except, so num_tiles never
  reached the inputs dict and the tile indexed slicing had nothing to index
  with. The anchor now covers the whole block.
- The GRPO hidden state forward wrapper replaced the forward with a bare
  (*args, **kwargs) function. transformers validates generate's kwargs against
  inspect.signature(self.forward), so every kwarg a VLM takes only on forward
  looked unused and LFM2-VL GRPO died in generation with "The following
  model_kwargs are not used by the model: ['pixel_values',
  'pixel_attention_mask', 'spatial_shapes']". The wrapper now uses
  functools.wraps.
- The old zoo fallback list in compute_loss now names all ten keys.

A singular image column holding a list of images crashed. TRL wraps whatever
example["image"] holds in a list of its own, so a cell carrying two images
reaches the processor as [[[img, img]]] and both make_nested_list_of_images and
the processor reject it with "Invalid input type. Must be a single image, a list
of images, or a list of batches of images.". The extraction is now rewritten to
treat a list cell as the plural images form, on both the TRL 0.22.x and the TRL
1.x spelling, and TRL 0.22.x's one image placeholder per example is widened to
the cell's length. Where no known spelling matches, a named error says which
column to rename instead of failing inside the processor.

With this, one real GRPO step on LFM2-VL-450M completes end to end, and the
chunked logprobs match a single whole batch forward exactly.

Fixes #6960
Fixes #3605
…zoo by import

Three changes on top of the shared key tuple.

The old unsloth_zoo fallback list was a second copy of the key names written
inline in compute_loss, and the logprob pass had no fallback at all: without the
zoo helper it collected nothing, so a run that only carried token_type_ids lost
them, having sliced them itself before. Both now go through one
_unsloth_grpo_vision_inputs, which prefers the zoo's tuple and names the keys
once for a zoo too old to export it. Only the image indexed slicing belongs to
the zoo, and that is the one case that still refuses to run, loudly.

pixel_position_ids joins the fallback list, matching unsloth_zoo: it is the
TRL 1.0.x name for image_position_ids.

The multi image gate used to decide whether the installed zoo could serve the
run by grepping inspect.getsource(grpo_accumulated_loss) for the string
num_images. That function delegates its slicing to the shared chunker now, so
the name survives there only as a local nobody reads, and removing it, which is
what a linter asks for, turned a working multi image run into a false 'Please
upgrade unsloth_zoo'. The gate probes for grpo_vision_chunks by import first and
keeps the source grep only for a zoo older than that helper.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
danielhanchen and others added 3 commits September 16, 2026 08:18
functools.wraps set __wrapped__, and accelerate's extract_model_from_parallel
with keep_fp32_wrapper False walks that chain and rebinds what it lands on, so
once prepare_model had recorded _original_forward the hidden-state wrapper was
removed on every GRPO step and the vocabulary-wide logits came back. Setting
__signature__ gives generate the same answer with no link to follow.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…size

A padded per sample pixel_values (Idefics, SmolVLM) and a flat image indexed one
have the same first dimension when num_images sums to the sample count, so a mixed
batch such as [2, 0] was split as if it were image indexed: both padded rows went
to the first sample and the second received an empty tensor, with no error raised.
Nothing in the batch distinguishes the two readings, so keep TRL's layout there, as
every version does today. All ones is excluded because both readings agree on it.
The list branch already guards the same collision.
Picks up the formatter fix from #11203, which is what pre-commit.ci was failing
on: it runs --all-files against the PR merged into main, so two files that had
drifted out of format on main failed the hook on every open PR rather than on the
PR that touched them.
shimmyshimmer and others added 2 commits September 17, 2026 13:37
TRL 0.20.0 and 0.21.0 take the legacy image cell spelling the normalisation rewrites,
but predate prepare_multimodal_messages entirely: they inline one {"type": "image"}
per user message with no count. Normalising a two image cell there sent the processor
two images against one placeholder, and the prologue counted the same cells, so nothing
else in the batch disagreed and the mismatch surfaced inside the processor, naming
neither the column nor the fix. That is the outcome the named refusal exists to replace,
and it was not firing, because its gate only asked whether the cell had been normalised.

Both versions are inside the declared pin, trl>=0.18.2,!=0.19.0,<=0.24.0.

The gate now also asks whether the placeholders were sized. Measured over the 28 TRL
releases on this box from 0.18.2 to 1.13.0: only 0.20.0 and 0.21.0 change, gaining the
refusal, and the generated source for every other version is byte for byte what it was.
A single image cell is unaffected on every version.
2026.9.5 is on PyPI and carries grpo_vision_chunks, so the floor that was
deferred for want of a release can be declared. Three pyproject sites move
from 2026.9.4 to 2026.9.5, and the skip comes off the floor assertion in
tests/test_grpo_vision_zoo_floor.py.

The four installer sites that pass --no-deps also move, from 2026.9.3. On
those paths uv ignores package metadata by definition, so the literal on the
command line is the only floor there is and the pyproject pin does not reach
them. The seven sites without --no-deps are left alone: there the resolver
intersects the spec with unsloth's own metadata, so they are already covered.

tests/studio/install/test_installer_zoo_floor_parity.py ties the two together
so they cannot drift a third time.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 3 commits September 17, 2026 14:16
# Conflicts:
#	install.ps1
#	pyproject.toml
The guard inspected inputs[0] alone, so a batch whose first row holds a bare image and
whose second holds a list passed it. The normalisation then gave that later row several
images while a TRL that cannot size its placeholders still emitted one, and the mismatch
surfaced inside the processor naming neither the column nor the fix. A dataset mixing a
bare image with a list is exactly the shape that puts the list somewhere other than row 0.

Every row is read now, and the message says which row. Shapes that pass today still pass,
including a batch with no image column, rows that are not dicts, an empty batch and None.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ty column

On TRL 0.22.x and 0.23.x an empty cell took one placeholder while the prologue counted it
as zero, so a batch mixing an image bearing row with an empty one reached the processor a
placeholder ahead of its pixels. Measured against a real Gemma 3 processor, one image and
one empty cell:

    main                        Invalid input type. Must be a single image, ...
    one placeholder for empty   Prompt contained 1 image tokens but received 0 images.
    no placeholder for empty    ok, pixel_values (1, 3, 896, 896)

Zero placeholders alone is not enough: an all empty column then reaches the processor as
[[], []] against no placeholders, which is an IndexError rather than a text run. TRL demotes
that batch itself from 0.24.0, so the same guard is ported here and the column becomes a
text batch, which is a case that failed on main as well.

The guard mirrors TRL's own all(img_list == []), so it never fires for a None cell and that
column still fails exactly as it does on main, as the description records.

Only 0.22.0 through 0.23.1 change: 0.20.0 and 0.21.0 do not take this rewrite, and 0.24.0
and up size their own placeholders. Verified by diffing the generated source across the
28 TRL releases on this box.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: e980e3dd6b

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 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: e980e3dd6b

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

Comment on lines +1015 to +1018
and _per_image.shape[0] == sum(num_images)
and _per_image.shape[0] != len(num_images)
):
split[_image_key] = list(torch.split(_per_image, num_images, dim = 0))

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 Group patch-indexed masks before sample shuffling

When TRL 0.22–0.23 supplies a grid batch whose pixel_attention_mask is indexed by patch row (a layout the shared chunker explicitly supports), this condition only converts per-image masks into sample-level lists. The patch-indexed mask therefore remains a flat tensor while pixel_values is regrouped by sample; the subsequent shuffle_sequence_dict indexes that tensor with the sample permutation, truncating and reordering mask rows independently of their pixels. Multi-image training can consequently forward an incomplete or mismatched mask. Split patch-indexed masks using the grid-derived per-sample patch counts before the shuffle as well.

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.

Not taking this one: no processor emits both keys, so the batch this describes cannot be built.

The branch is the grid one, so it requires image_grid_thw and a patch-row-indexed pixel_attention_mask in the same batch. Scanning every model package's declared model_input_names across the transformers range this repo supports:

transformers processors declaring image_grid_thw declaring pixel_attention_mask both
4.57.6 2 5 none
5.0.0 7 5 none
5.5.4 7 5 none
5.12.1 9 5 none
5.17.0 15 5 none

At 5.17.0 the two sets are cohere_compass, cosmos3_edge, ernie4_5_vl_moe, glm46v, glm4v, glm5_next, glm_image, glmga, hunyuan_vl, kimi_k25, minimax_m3_vl, muse_glimmer, paddleocr_vl, qwen2_vl, video_llama_3 against idefics2, idefics3, lfm2_vl, siglip2, smolvlm, and they are disjoint at every version. The grid families carry no attention mask over their patches, and the five that do carry a mask are the padded ones with no grid.

The chunker's patch-axis mask handling that the comment points at is the LFM2-VL and Idefics shape, where the mask rides the tile or patch axis without a grid. That case is reached through the num_tiles and padded branches, not this one, and it is covered.

So this is a guard for an input the code cannot receive. If a future processor ever emits both, the shape assertion inside the model fires rather than the run training on a truncated mask, and the branch can be extended then against a real checkpoint instead of a hypothetical layout.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…flag with it

Two gaps on TRL 0.22.x and 0.23.x that the processor fix does not reach, because the vLLM
paths there read the raw cells rather than the processor kwargs.

The server path hands those cells to VLLMClient.generate, which does
[pil_to_base64(img) for img in images] over the top level entries, so a cell holding two
images arrives at list.save(...) and dies with an AttributeError naming neither the column
nor the fix. Before this branch that row died earlier, inside the processor, so the path was
unreachable; making the processor accept it is what exposes it. The refusal is injected on
these versions too and handed the trainer, so it fires only when use_vllm is set and
vllm_mode is server. Colocate mode and a run without vLLM both go through the processor and
keep working, checked explicitly.

Demoting an all empty image column emptied kwargs but left has_images true, and every vLLM
branch is gated on that flag rather than on kwargs, so the batch still submitted [[], ...]
as an image payload and server mode called .save() on an empty list. The flag is cleared
with the kwargs.

Measured over the 28 TRL releases here: only 0.22.0 through 0.23.1 change, which are exactly
the versions that take the legacy cell spelling and size their placeholders. 0.20.0 and
0.21.0 already refuse unconditionally, and 0.24.0 and up are byte for byte what they were.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: b591e84423

ℹ️ 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 448bf6b into main Sep 17, 2026
81 of 95 checks passed
@danielhanchen
danielhanchen deleted the pr/grpo-vision-kwargs branch September 17, 2026 21:53
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…a list (unslothai#11031)

* Forward every GRPO vision kwarg, and accept an image column holding a list

Two GRPO vision bugs.

The logprob paths dropped multimodal inputs. TRL passes everything the processor
produced into its per token logprob helper and stores the same set in the dict
compute_loss receives, but the Unsloth replacements read a hand written list of
four keys. spatial_shapes (LFM2-VL), num_tiles (LFM2-VL, InternVL) and
image_position_ids (Gemma 4) reached neither pass, and a model that does not
emit image_grid_thw had its pixel_values replaced by None, so the reference and
old logprobs were computed from the text alone. Both passes now read one key
tuple that unsloth_zoo owns and chunk through one shared slicer, so a key added
there reaches both. Three supporting defects went with it:

- The rewrite that saves max_left_pad matched only the first two lines of TRL's
  num_images output block, which since TRL 1.7.0 also holds a nested num_tiles
  line. The nested line ended up inside the try/except, so num_tiles never
  reached the inputs dict and the tile indexed slicing had nothing to index
  with. The anchor now covers the whole block.
- The GRPO hidden state forward wrapper replaced the forward with a bare
  (*args, **kwargs) function. transformers validates generate's kwargs against
  inspect.signature(self.forward), so every kwarg a VLM takes only on forward
  looked unused and LFM2-VL GRPO died in generation with "The following
  model_kwargs are not used by the model: ['pixel_values',
  'pixel_attention_mask', 'spatial_shapes']". The wrapper now uses
  functools.wraps.
- The old zoo fallback list in compute_loss now names all ten keys.

A singular image column holding a list of images crashed. TRL wraps whatever
example["image"] holds in a list of its own, so a cell carrying two images
reaches the processor as [[[img, img]]] and both make_nested_list_of_images and
the processor reject it with "Invalid input type. Must be a single image, a list
of images, or a list of batches of images.". The extraction is now rewritten to
treat a list cell as the plural images form, on both the TRL 0.22.x and the TRL
1.x spelling, and TRL 0.22.x's one image placeholder per example is widened to
the cell's length. Where no known spelling matches, a named error says which
column to rename instead of failing inside the processor.

With this, one real GRPO step on LFM2-VL-450M completes end to end, and the
chunked logprobs match a single whole batch forward exactly.

Fixes unslothai#6960
Fixes unslothai#3605

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Collect the GRPO multimodal inputs through one helper, and probe the zoo by import

Three changes on top of the shared key tuple.

The old unsloth_zoo fallback list was a second copy of the key names written
inline in compute_loss, and the logprob pass had no fallback at all: without the
zoo helper it collected nothing, so a run that only carried token_type_ids lost
them, having sliced them itself before. Both now go through one
_unsloth_grpo_vision_inputs, which prefers the zoo's tuple and names the keys
once for a zoo too old to export it. Only the image indexed slicing belongs to
the zoo, and that is the one case that still refuses to run, loudly.

pixel_position_ids joins the fallback list, matching unsloth_zoo: it is the
TRL 1.0.x name for image_position_ids.

The multi image gate used to decide whether the installed zoo could serve the
run by grepping inspect.getsource(grpo_accumulated_loss) for the string
num_images. That function delegates its slicing to the shared chunker now, so
the name survives there only as a local nobody reads, and removing it, which is
what a linter asks for, turned a working multi image run into a false 'Please
upgrade unsloth_zoo'. The gate probes for grpo_vision_chunks by import first and
keeps the source grep only for a zoo older than that helper.

* Expose the GRPO forward signature without a __wrapped__ link

functools.wraps set __wrapped__, and accelerate's extract_model_from_parallel
with keep_fp32_wrapper False walks that chain and rebinds what it lands on, so
once prepare_model had recorded _original_forward the hidden-state wrapper was
removed on every GRPO step and the vocabulary-wide logits came back. Setting
__signature__ gives generate the same answer with no link to follow.

* Add the AGPL-3.0 header to the new GRPO test files

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reduce comment volume in the GRPO vision kwarg paths and their tests

* Gate the gradient path on the zoo chunker too

With beta = 0 and num_iterations = 1 there are no reference or old logprobs to
compute, so the no-grad pass that carries the upgrade check never runs. An older
grpo_accumulated_loss accepts arbitrary kwargs, ignores the keys it does not
know and replaces pixel_values with None for a model with no image_grid_thw, so
a vision run trained on the text alone without saying so. Check for
grpo_vision_chunks before the gradient call whenever pixels are present.

* Skip the zoo driven multi image tests when the installed zoo predates the helpers

* Persist every vision kwarg in the batch, and keep each sample's tiles with it

* Count the images a legacy TRL never counted

* Carry the whole vision batch through a legacy TRL, and require the zoo that slices it

TRL 0.22.x-0.23.x has neither forward_kwargs nor num_images. Three things followed
from that, and a singular `image` column holding a list makes all three reachable.

The no-grad old and reference logprob calls take four hand named processor tensors
and no counts, so the shared chunker slices an image indexed image_grid_thw by
sample index. Build the counts before those calls rather than in the output block,
which only runs once they have returned, and hand the whole mapping to all three
call sites.

The same versions save only those four keys, so spatial_shapes, num_tiles and the
Gemma position ids never leave the processor and the gradient forward runs without
arguments the model requires. Copy the same mapping into the output, which also
carries token_type_ids across, widened over the completion the way TRL 0.24.0
widens it in place before the identical call. A copy that cannot be made to fit,
as after max_prompt_length truncation, is dropped rather than sent.

split_pixel_values_by_grid before TRL 1.1.0 splits pixel_values by GRID ROW, one
element per image, and leaves image_grid_thw flat. shuffle_sequence_dict then takes
its length from prompt_ids, so a row holding two images has that list permuted
wrongly and truncated to the sample count. Regroup it per sample and split the grid
the way 1.1.0 does, and merge the grid back after the slice, which TRL's own unsplit
does not do before 1.1.0. All-ones rather than a length comparison decides when the
axes already coincide: num_images = [0, 2] over two samples makes the counts agree
while the axes still differ.

Finally, both logprob paths raise without unsloth_zoo.grpo_vision_chunks while the
declared floor still admits 2026.9.4, which does not export it, so a dependency
compliant install raised for every vision batch including the single image grid
models that worked before. Move the floor to 2026.9.5, the same release unslothai#11137
names, rather than keeping a fallback: a fallback could only cover the no-grad half,
since the gradient half lives inside the zoo's own grpo_accumulated_loss, and half a
fallback makes the two policies disagree.

Tested across trl 0.22.2, 0.23.0, 0.23.1, 0.24.0, 0.26.2, 0.29.1, 1.0.0, 1.1.0,
1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0: the legacy rewrite fires on the
three 0.2x releases and on nothing else, and no anchor warning is raised anywhere.

* Keep the legacy vision prologue off a text batch, and off a newer TRL entirely

Three corrections to the previous commit.

Gemma 3's processor returns token_type_ids with no images at all
(return_mm_token_type_ids defaults True), and the prologue read the processor
before testing has_images, so a text only GRPO run on TRL 0.22.x-0.23.x started
forwarding an all zeros mask where main forwarded nothing. Both PrefixGrouper and
sequence packing are keyed on that name being absent, on the no-grad side here and
on the gradient side in the zoo, so the run silently lost both fast paths. Gate the
whole prologue the way TRL 0.24.0 gates forward_kwargs, on `images is not None`,
and drop the two spellings when the processor produced no pixels, which is what an
image column with every cell empty looks like.

A width equal to prompt+completion was kept untouched rather than dropped. On these
versions prompt_inputs is prompt only, so that width can only be an untruncated
prompt reached through max_prompt_length, and truncate_with_protected_tokens keeps
the image tokens but moves them, leaving the marks at the wrong offsets. Only the
prompt width is widened now; everything else is dropped.

The prologue is also emitted only for the versions whose call sites consume it.
0.24.0 and up leave prompt_inputs unbound at that anchor so it fell through anyway,
but not emitting it makes their generated source byte for byte what it was: patched
_generate_and_score_completions now compares identical to 772802c for 0.24.0,
0.26.2, 0.29.1, 1.0.0, 1.1.0, 1.5.0, 1.7.0, 1.9.2, 1.11.0, 1.12.0 and 1.13.0, and
differs only on 0.22.2, 0.23.0 and 0.23.1.

* Defer the unsloth_zoo 2026.9.5 floor until the release exists

2026.9.5 is not on PyPI, so declaring it in pyproject.toml makes the package
unresolvable for everyone, which is worse than the raise the floor prevents.
Put the three dependency lines back to 2026.9.4 and skip the gate that asserts
the floor in the same commit, so the pin and its test move together instead of
turning CI red. The upgrade message still names 2026.9.5, and the assertion that
checks it stays live. Dropping the skip re-arms the floor when the release ships.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse a multi image row on a TRL whose reference calls lost the counts

Normalising the singular `image` cell is only half of a multi image row. On TRL
0.22.x-0.23.x the reference logprob call sites also have to carry the image counts,
or the vision batch is sliced by sample index and every image after the first is
dropped, which the model reports as a token/feature mismatch that names neither the
column nor the fix.

Every TRL from 0.22.2 to 0.23.1 takes all three call site rewrites, and 0.24.0 and
up pass forward_kwargs and need none, so nothing in the supported range changes
behaviour here. If those call sites ever drift, the existing warning is now paired
with the guard that already exists for an unmatched cell anchor, so the user gets
the unsloth level error instead of the mismatch. A single image row is unaffected.

* Keep a padded per sample image axis when the counts sum to the batch size

A padded per sample pixel_values (Idefics, SmolVLM) and a flat image indexed one
have the same first dimension when num_images sums to the sample count, so a mixed
batch such as [2, 0] was split as if it were image indexed: both padded rows went
to the first sample and the second received an empty tensor, with no error raised.
Nothing in the batch distinguishes the two readings, so keep TRL's layout there, as
every version does today. All ones is excluded because both readings agree on it.
The list branch already guards the same collision.

* Refuse a multi image cell on a TRL that cannot size its placeholders

TRL 0.20.0 and 0.21.0 take the legacy image cell spelling the normalisation rewrites,
but predate prepare_multimodal_messages entirely: they inline one {"type": "image"}
per user message with no count. Normalising a two image cell there sent the processor
two images against one placeholder, and the prologue counted the same cells, so nothing
else in the batch disagreed and the mismatch surfaced inside the processor, naming
neither the column nor the fix. That is the outcome the named refusal exists to replace,
and it was not firing, because its gate only asked whether the cell had been normalised.

Both versions are inside the declared pin, trl>=0.18.2,!=0.19.0,<=0.24.0.

The gate now also asks whether the placeholders were sized. Measured over the 28 TRL
releases on this box from 0.18.2 to 1.13.0: only 0.20.0 and 0.21.0 change, gaining the
refusal, and the generated source for every other version is byte for byte what it was.
A single image cell is unaffected on every version.

* Declare the unsloth_zoo 2026.9.5 floor now that the release is published

2026.9.5 is on PyPI and carries grpo_vision_chunks, so the floor that was
deferred for want of a release can be declared. Three pyproject sites move
from 2026.9.4 to 2026.9.5, and the skip comes off the floor assertion in
tests/test_grpo_vision_zoo_floor.py.

The four installer sites that pass --no-deps also move, from 2026.9.3. On
those paths uv ignores package metadata by definition, so the literal on the
command line is the only floor there is and the pyproject pin does not reach
them. The seven sites without --no-deps are left alone: there the resolver
intersects the spec with unsloth's own metadata, so they are already covered.

tests/studio/install/test_installer_zoo_floor_parity.py ties the two together
so they cannot drift a third time.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read every row in the singular image column refusal, not only the first

The guard inspected inputs[0] alone, so a batch whose first row holds a bare image and
whose second holds a list passed it. The normalisation then gave that later row several
images while a TRL that cannot size its placeholders still emitted one, and the mismatch
surfaced inside the processor naming neither the column nor the fix. A dataset mixing a
bare image with a list is exactly the shape that puts the list somewhere other than row 0.

Every row is read now, and the message says which row. Shapes that pass today still pass,
including a batch with no image column, rows that are not dicts, an empty batch and None.

* Give an empty legacy image cell no placeholder, and demote an all empty column

On TRL 0.22.x and 0.23.x an empty cell took one placeholder while the prologue counted it
as zero, so a batch mixing an image bearing row with an empty one reached the processor a
placeholder ahead of its pixels. Measured against a real Gemma 3 processor, one image and
one empty cell:

    main                        Invalid input type. Must be a single image, ...
    one placeholder for empty   Prompt contained 1 image tokens but received 0 images.
    no placeholder for empty    ok, pixel_values (1, 3, 896, 896)

Zero placeholders alone is not enough: an all empty column then reaches the processor as
[[], []] against no placeholders, which is an IndexError rather than a text run. TRL demotes
that batch itself from 0.24.0, so the same guard is ported here and the column becomes a
text batch, which is a case that failed on main as well.

The guard mirrors TRL's own all(img_list == []), so it never fires for a None cell and that
column still fails exactly as it does on main, as the description records.

Only 0.22.0 through 0.23.1 change: 0.20.0 and 0.21.0 do not take this rewrite, and 0.24.0
and up size their own placeholders. Verified by diffing the generated source across the
28 TRL releases on this box.

* Refuse a multi image row on a legacy vLLM server run, and demote the flag with it

Two gaps on TRL 0.22.x and 0.23.x that the processor fix does not reach, because the vLLM
paths there read the raw cells rather than the processor kwargs.

The server path hands those cells to VLLMClient.generate, which does
[pil_to_base64(img) for img in images] over the top level entries, so a cell holding two
images arrives at list.save(...) and dies with an AttributeError naming neither the column
nor the fix. Before this branch that row died earlier, inside the processor, so the path was
unreachable; making the processor accept it is what exposes it. The refusal is injected on
these versions too and handed the trainer, so it fires only when use_vllm is set and
vllm_mode is server. Colocate mode and a run without vLLM both go through the processor and
keep working, checked explicitly.

Demoting an all empty image column emptied kwargs but left has_images true, and every vLLM
branch is gated on that flag rather than on kwargs, so the batch still submitted [[], ...]
as an image payload and server mode called .save() on an empty list. The flag is cleared
with the kwargs.

Measured over the 28 TRL releases here: only 0.22.0 through 0.23.1 change, which are exactly
the versions that take the legacy cell spelling and size their placeholders. 0.20.0 and
0.21.0 already refuse unconditionally, and 0.24.0 and up are byte for byte what they were.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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

2 participants