Repository navigation
GRPO: forward every vision kwarg, and accept an image column holding a list - #11031
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| 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 = {} |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
f313da4 to
162ef7f
Compare
|
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. |
… 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.
162ef7f to
f986bf0
Compare
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.
|
@codex security review |
…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.
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.
# 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.
…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.
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…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]>
Summary
Two GRPO vision bugs.
#6960: both GRPO logprob paths dropped multimodal inputs.spatial_shapes(LFM2-VL),image_position_ids(Gemma 4) and thenum_tilescounts 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_thwthepixel_valueswere replaced byNone, so the reference and old logprobs were computed from the text alone. Both pathsnow read one key tuple that unsloth-zoo owns and chunk through one shared slicer.
#3605: a singularimagecolumn holding a list of images crashed withValueError: 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 pluralimagespath.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_chunksfromunsloth_zoo.rl_replacements. The runtime code degrades gracefully against an olderunsloth-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 dictcompute_lossreceives. 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 itselsebranch appended
Noneforpixel_values. Every VLM withoutimage_grid_thw, whichincludes 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:
max_left_padanchored on the first two lines of TRL'snum_imagesoutput block. Since TRL 1.7.0 that block also holds a nestedif num_tiles is not None: output["num_tiles"] = num_tiles, so the nested line endedup inside the
try/except NameErrorthat the rewrite appends andnum_tilesneverreached the inputs dict. TRL's own
split_pixel_values_by_gridthen raisedKeyError: 'num_tiles'on LFM2-VL.model.forwardwith a bare(*args, **kwargs)function. transformers validatesgenerate's kwargs againstinspect.signature(self.forward), so every kwarg a VLM takes only on forward lookedunused 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'].compute_lossnamed seven keys, not ten, so thedegraded 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 iskwargs = {"images": [[img] for img in images]}, on TRL 1.x it isimages = [[example.get("image")] ... ]. Either way a cell holding two images becomes[[[img, img]]], whichtransformers.image_utils.make_nested_list_of_imagesand theprocessor both reject with the reporter's message. Nothing in Unsloth normalised it.
Changes
unsloth/models/rl_replacements.py_get_per_token_logps_and_entropiesandcompute_lossread the multimodal inputsthrough
grpo_get_vision_inputsand chunk throughgrpo_vision_chunks, both fromunsloth-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
UnslothGRPOTrainerwithout this module's imports.num_imagesoutput anchor now has a long form that includes TRL 1.7.0's nestednum_tilesline, tried first, with a warn once if neither form is found.against
GRPO_VISION_KEYS._unsloth_grpo_image_cellnormalises a singularimagecell, and the_generate_and_score_completionsrewrite applies it to both TRL spellings. TRL 0.22.x'sprepare_multimodal_messages(prompt, num_images=1)becomes the cell's own length, so atwo image cell gets two placeholders.
_unsloth_reject_grpo_image_listraises a named error, injected at the top of_generate_and_score_completionsonly when no known spelling matched, so an unknown TRLsays which column to rename instead of failing inside the processor.
unsloth/models/rl.pyfunctools.wrapson the GRPO hidden state forward wrapper, soinspect.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_DIRand oneUNSLOTH_COMPILE_LOCATIONand overwrote each other mid-run. Giving every invocationa 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:
tests/test_grpo_vision_kwargs_forwarded.py(new)tests/test_grpo_image_column_normalisation.py(new)tests/test_multi_image_grpo_chunking.pytests/test_grpo_vision_kwargs.pytests/version_compat/The
tests/version_compat/row fails identically with and without this change, becauseour CPU compatibility runs set
UNSLOTH_COMPILE_DISABLE=1and the trainers are thennever generated, so
test_trl_fake_train_cpu.pyreports "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_zooinstalled fromthe paired branch. Counts are read out of each job's pytest summary:
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 Windowsrunner 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, bothpasses use the shared chunker,
compute_losssplats the whole set into bothgrpo_accumulated_losscall sites, both paths reach the same helper object, an oldunsloth-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 realsignature, and
num_tilessurvives the output dict rewrite.tests/test_grpo_image_column_normalisation.py, 7 tests. The cell helper, thereporter'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.pyhad four source grep assertions that named thechunk lists this change removes. They are replaced with behavioural tests that call
grpo_vision_chunksdirectly, which is stricter than what they replaced. Two exec basedharnesses,
tests/test_grpo_padded_raw_logits.pyandtests/test_grpo_hidden_states_signal.py, pass the per chunk kwargs as a dict now insteadof a fixed six element tail.
Re run on the newest corner with both repos together, 1817 passed, 182 skipped:
An earlier, wider run over every GRPO, DPO, ORPO, CPO and RL config suite in the repo plus
tests/test_collection_hygiene.pyandtests/test_import_fixes_drift.pypassed 309 of309 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:One real GRPO step on the same checkpoint, through the generated
UnslothGRPOTrainerwithnum_iterations = 2so the no grad old logprob pass runs, completes: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 withKeyError: 'num_tiles'inside TRL'ssplit_pixel_values_by_grid.For
#3605, the reporter's shape against the function in their traceback:The three scripts behind the output above are
repro_6960_lfm2vl_parity.py,repro_6960_lfm2vl_grpo_step.pyandrepro_3605_image_column.py.Known limitations
imagecolumn. It lives inthe notebooks repo and is not touched here; a two image cell now works either way.
image_position_idsand InternVLnum_tilespaths follow TRL's own arithmetic andare 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.
num_imagesin the inputs dict, so a model whosepixel_valuesis image indexed rather than sample indexed is still sliced on the sampleaxis. 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 keyimage_position_idsin 1.1.0. The shared tuple named only the newer one, so on TRL 1.0.x the veryclass 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 internallyas
pixel_position_ids;pixel_position_idsis the TRL 1.0.0 spelling alone, and a forward that ishanded it absorbs it through
**kwargs: Unpack[TransformersKwargs]rather than raising. Stock TRL1.0.0 puts it straight into
model_inputs, so matching it is matching upstream. Fixed in theunsloth-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 helperit collected nothing, so a run carrying only
token_type_idslost them although the code it replacedsliced them itself. Both paths go through one
_unsloth_grpo_vision_inputsnow. Only the imageindexed 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 stringnum_images. Now that the functiondelegates 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_chunksby import first and keeps the source grep only for an older zoo.
The forward wrapper carries a signature. Setting
wrapped_forward.__signature__is what makesLFM2-VL work, since
generate()validates againstinspect.signature(self.forward)and a bare(*args, **kwargs)wrapper hides every real parameter.__signature__rather thanfunctools.wraps:wrapssets__wrapped__, and accelerate unwraps past this wrapper and losesit, while
inspect.unwrap()stops at__signature__.logits_to_keepis not affected either way. A forward-kwarg probe finds it present in 4 of 4logprob 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_keepagain 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
UnslothGRPOTrainerbuilt and parsed on TRL 0.22.2, 0.27.2, 1.0.0 and 1.13.0, base andhead, 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.
pixel_position_idspresent in the generated trainerThe 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_valuesarriving at the logprob forward as an explicit
Nonein 4 of 4 calls, so the reference and oldlogprobs are computed from text alone while the run reports normal losses. On this branch the same
probe finds
pixel_valuesof shape(2, 17, 3, 512, 512)andpixel_attention_maskof 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
imagecolumn holdingNonestill fails exactly as it does on main. Not in TRL's ownall(img_list == [] for img_list in images)guard, which an earlier revision of this descriptionnamed:
None == []isFalse, so that guard is a no-op for aNoneentry and the failure landslater, at
len(None)on TRL <= 1.12 and inside the processor on 1.13.0 and 0.22.x. Either way thebehaviour 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 itmatters for users rather than for CI.
CI is unaffected either way, because no CPU CI job installs
unsloth_zoofrom PyPI (an earlierrevision of this description said Backend CI does).
consolidated-tests-ci.ymlresolvesrefs/heads/mainwithgit ls-remoteandcore-cpu-setupclones that sha editable;studio-backend-ci.yml,version-compat-ci.yml,mlx-ci.ymlandnotebooks-ci.ymlall installunsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo;wheel-smoke.ymluses--no-deps.Read out of a raw job log rather than out of the YAML:
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
mainthat carries the helpers.What the release gates is the user path. The newest release on PyPI is
unsloth_zoo 2026.9.4and it carries none of the three helpers, while
pyproject.tomlhere floors at>=2026.9.4. Onthat combination every vision GRPO batch raises before any forward, including the
image_grid_thwgrid path that worked before and is unrelated to this bug, because the gate is
_grpo_vision_chunks is None and pixel_values is not Noneand the inline chunk loop main usedinstead 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.tomlmove to it and the skip intests/test_grpo_vision_zoo_floor.pycomes off, in thisPR.
Measured locally against both zoo states, running the same selection each time:
unsloth_zooon the pathmainEight of those skips are the chunker-gated tests, five in
test_grpo_vision_kwargs_forwarded.pyandthree in
test_multi_image_grpo_chunking.py; the ninth is the deferred zoo floor. They are skipsrather than failures because of the
pytest.importorskipguards. An earlier revision of thisdescription 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_runsandtest_an_old_zoo_still_forwards_the_sample_indexed_keysboth hold, so a user who upgradesunslothalone 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. Whennum_imageshappens to sum tothat 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_samplesplit thepadded one by image. Driving it with a
(2, 2, 3, 4, 4)tensor whose every value encodes its own rowindex:
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_sizeasserts on row provenancerather than on shapes, and fails on the previous commit. The existing
test_a_padded_row_per_sample_is_left_alonepassed only because[2, 2]over two rows does not sumto 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_valuesis[n_images, max_patches, C, H, W], one rowper 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
imagecolumn normalisation has two anchors. Thelegacy cell spelling,
kwargs = {"images": [[img] for img in images]}, matches on TRL 0.20.0 through0.23.1, but the rewrite that sizes
prepare_multimodal_messagesto the cell matches only on 0.22.0through 0.23.1: 0.20.0 and 0.21.0 predate that helper entirely and inline one
{"type": "image"}peruser message with no count. Measured against the shipped sources:
prepare_multimodal_messagesexistsSo 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_oncefires on none of them. A single imagecell is unaffected everywhere.
test_a_trl_that_cannot_size_its_placeholders_refuses_the_multi_image_rowand its controltest_a_trl_that_can_size_its_placeholders_is_not_refused, both canary checked against the previouscommit.
Full suite, against main at the same base
CPU, CI's own env and selection, 8 workers:
8c54628mainat the merge point26 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
VideoReaderwhich torchvision 0.28 removed. The one on each side that is not shared(
test_import_fixes_drifton this branch, avllm_compatimport on main) passes in isolation onboth trees, so both are xdist ordering flakes rather than outcomes. No regressions.
The merge order constraint is now satisfied
unsloth_zoo 2026.9.5is on PyPI and carries the shared helpers,pyproject.tomlfloors at it atall three sites, and the deferred floor assertion in
tests/test_grpo_vision_zoo_floor.pyisre-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_valuesis[n_images, max_patches, C, H, W], and the chunker's rank test read thatimage 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 checksrenders a cancelled run as "fail"; read from the API, all of them arecancelled, notfailed, and none is a test failure.
The real answer came from replicating the head onto a staging repo, off that queue:
All 16 reproduce identically on
main, and none touches GRPO -- each was re-run locally in bothtrees 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_zootest_per_layer_device.pywhich pass on current zoomain.test_formatter_fixed_point.pynamesthree files this PR does not touch.
The green is not vacuous.
Repo tests (CPU, rest)returned6 failed, 7843 passed, 344 skipped, itsraw log shows
test_grpo_vision_kwargs_forwarded.pyexecuting, and it resolved the zoo at54e9376b, a descendant of unslothai/unsloth-zoo#1233, so the chunker-gated tests ran rather thanskipping.
The refusal reads every row. It inspected
inputs[0]alone, so a batch whose first row holds abare 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:
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
imagecolumn, rows that are not dicts, anempty batch, and
Nonein 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:
NonecellNoneZero 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 isIndexError: list index out of rangerather 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 aNoneentry, sothe
Nonecolumn 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 thecomparison is
main's own Backend CI run from the same hour (run 35252245488, head1d5210d7a),which fails on the same jobs with the same tests and the same counts:
maintest_accelerator_skip_guards+test_docker_hub_readme, 2 failed, 5215 passedtest_st_save_merged_signature, 5 failed, 7853 passedtest_installer_av_shapes(bitdefender), 2 failed, 11216 passedThe only difference anywhere is the +66 passing tests in
rest, which are this PR's own. The otherthree reds are the same shape:
GGUF inference smokefails 3 checks intests/studio/test_path_probe_access_denied.ps1, a file main added today in #10533 that this PR doesnot touch;
workflow-trigger lintfails on the same twobitdefenderassertions; andpip scan-packages :: hf-stackreports findings inside third party packages while this PR adds nodependency.
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 thetest_rope_carry_*drift pair (identical on mainunder transformers 4.57.6) and two unsloth_zoo
test_per_layer_device.pycases that pass on currentzoo main.
The green is not vacuous:
Repo tests (CPU, rest)showstest_grpo_vision_kwargs_forwarded.pyexecuting in its raw log, and resolved the zoo at
e12fb791, a descendant ofunslothai/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
imagecellsrather 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, andtrl/extras/vllm_client.pydoesimages = [pil_to_base64(img) for img in images] if images else Nonewithpil_to_base64callingimage.save(buffer, format="PNG"). A cell holding two images is one top level entry, so it arrives atlist.save(...). This is exposure created by this branch: before it, that row died earlier inside theprocessor 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_vllmis set andvllm_modeisserver. 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 onkwargs, so emptyingkwargsalone still submitted[[], ...]as animage payload and server mode called
.save()on an empty list.has_images = Falseis 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_maskis patch-row indexed would be left flat whilepixel_valuesis regrouped. No processor emits both keys, so that batch cannot be built. Scanning every model
package's declared
model_input_names:image_grid_thwpixel_attention_maskThe 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. Thepatch-axis mask handling is the LFM2-VL and Idefics shape, reached through the
num_tilesand paddedbranches, which are covered.
Final CI state, against
main's own runsb591e84: 68 success, 10 failure, 7 skipped. None of the 10 is this PR's.main's own runs fromthe same evening (35252245488 and 35252245556) fail on the same jobs with the same tests and the same
counts:
maintest_accelerator_skip_guards+test_docker_hub_readme, 2 failed, 5215 passedtest_st_save_merged_signature, 5 failed, 7853 passedtest_installer_av_shapes, 2 failed, 11216 passedtest_rope_carry_*, 2 failed, 38 passedtest_per_layer_device, 5834 / 5807 / 5852 passedtests/studio/test_path_probe_access_denied.ps1test_installer_av_shapesThe only difference anywhere is the +66 passing tests in
rest, which are this PR's own. TheCore zoocells run the unsloth_zoo suite against zoomain, which this PR does not touch.(Python 3.13, l-r)failed once on two studio backend timing tests; both files pass locally on bothtrees (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.