Skip to content

Make Phi-4-reasoning-vision load and preprocess images on transformers 5 - #11469

Merged
danielhanchen merged 27 commits into
mainfrom
siglip-image-processing-reexports
Sep 23, 2026
Merged

danielhanchen merged 27 commits into
mainfrom
siglip-image-processing-reexports

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Problem

microsoft/Phi-4-reasoning-vision-15B fails to load with

ValueError: Could not load any image processor class

Its remote code imports image processing helpers from where transformers 4.x kept them.
transformers 5 moved those symbols into per-model modules and dropped the old re-exports, so
the import fails inside the checkpoint's own code, long before Unsloth sees a model. The
checkpoint cannot be fixed from here, and pinning transformers back is not an option.

Getting past that exposes a second break in the same checkpoint: transformers 5 also rebased
Siglip2ImageProcessor onto a torchvision backend, so preprocessing an image dies too.

Fix

Two halves, both in import_fixes.py style, both applied only while a checkpoint's own code is
being loaded.

1. The missing re-exports. Reinstate the names on the modules that used to carry them, with
a module-level __getattr__ that forwards to each symbol's new home and caches the result. The
forwarder only answers for names that are genuinely missing, only for public names, and chains
to any pre-existing __getattr__, so a transformers version that still has the re-exports is
untouched.

2. The numpy contract on the class. transformers 5 put a torchvision backend in every image
processor's MRO (Siglip2ImageProcessor -> TorchvisionBackend -> BaseImageProcessor), while
this checkpoint's preprocess builds channel-last numpy and calls self.rescale then
self.normalize on it:

TypeError: Functional F.normalize supports inputs of type
dict_keys([tv_tensors.Image, torch.Tensor, tv_tensors.Video]), but got numpy.ndarray

transformers 5 still ships transformers.image_transforms.rescale and .normalize with the 4.x
numpy signatures, and in 4.x the BaseImageProcessor methods of those names were four-line
forwards to exactly those functions. So numpy inputs are forwarded to transformers' own
functions, by keyword, and set on the remote subclass only — transformers' own
Siglip2ImageProcessor is not merely left unpatched, it is unreachable from the shim.

Both halves are lazy: they hang off a wrap of transformers.dynamic_module_utils.get_class_in_module,
so they cost nothing until remote code actually runs. import unsloth does not pull in any image
processing module as a result, asserted by a subprocess test rather than assumed.

What works now, measured

transformers 5.17.0, torch 2.13.0+cu130, one B200, real checkpoint, real image.

before after
AutoProcessor.from_pretrained(..., trust_remote_code=True) AttributeError: module 'transformers.models.siglip2.image_processing_siglip2' has no attribute 'filter_out_non_signature_kwargs' Phi4VisionRProcessor with a Siglip2ImageProcessorNoUpscale
preprocessing one image TypeError: Functional F.normalize ... but got numpy.ndarray pixel_values (1, 3600, 768) float32, pixel_attention_mask (1, 3600) with 256 valid patches, spatial_shapes summing 32
a real forward pass never reached model loads (15.12B params, 15.0 s), logits (1, 790, 100352) bfloat16, all finite, mean -0.65611 std 1.74083
transformers 4.57.6 works unchanged; the fix is a no-op there, by probe and not by version

The forward pass is the part worth stating plainly: 7 text tokens in, 790 positions out, so the
3600 image patches were consumed by the model rather than merely shaped correctly.

Bit-identical to transformers 4.57.6. Both shimmed methods were run against a real 4.57.6
install in an isolated venv on the same seeded uint8 array: rescale and normalize agree
under np.array_equal, same dtype, same shape. Unpatched transformers 5.17 does not: rescale
returns float64, normalize raises.

Two things measurement changed about the fix

rescale is in scope although it never raises. TorchvisionBackend.rescale is image * scale,
which numpy accepts and returns as float64, where 4.x returned float32. Patching only the method
that raises leaves pixel_values in float64: twice the host memory per batch and a dtype the
vision tower was not built for, with nothing raised. Same image, same seed:

dispatched pixel_values dtype sum
normalize only float64 -593.91369629
normalize + rescale float32 -593.90917969

So the install gate is equivalence with the 4.x implementation, called on a real array. Never a
version comparison — on 4.57.6 the live method is the passthrough, so the installer returns
[] there, proven against a real 4.57.6 venv with the version gate bypassed.

resize, center_crop and pad are deliberately out. They also reject numpy, but with
AttributeError: 'dict' object has no attribute ... — they reject the 4.x dict size, not the
array — and in 4.x they were not thin passthroughs, so there is no verified implementation to
forward to, only a reimplementation. convert_to_rgb is already bit-identical on numpy, checked
on uint8, float32 and float64. Remote code reaches resize off the module anyway, where the
re-export forwarder hands back the genuine 4.x function.

Two things the obvious implementation gets wrong

Both found by running it, not by reading it.

  • The image processor class never comes through get_class_in_module. On this checkpoint
    exactly two classes do, Phi4VisionRProcessor and Phi4VisionR; the image processor is defined
    beside the model and read off the module as an attribute. So the hook patches the loaded class's
    module and every transformers_modules.* module, not just the returned class.
  • pickle rebuilds a processor by importing the remote module directly, so a spawn-started
    DataLoader worker never goes near get_class_in_module and would get an unpatched class. A
    sys.meta_path finder covers that, matching the existing _TorchaoIntmmPatchFinder. Its own
    negative control asserts a child that never imports unsloth still fails, so the finder is
    demonstrably what fixes the first case.

Blast radius

transformers' own processors are unchanged, asserted rather than argued: with the shim installed,
Siglip2ImageProcessor has no normalize in its __dict__, still resolves to
TorchvisionBackend.normalize, and produces torch.equal output on every tensor. Same for
SiglipImageProcessor (pixel_values sum -532.447021 before and after).

Full default test selection, merge base vs this branch, 31k tests:

failed passed skipped
merge base 24 30688 728
this branch 24 30728 729

Failure sets are identical — 24 shared, 0 new, 0 fixed. They are pre-existing on main and are
not touched here. The +40 passed and +1 skipped are this PR's own tests.

Tests

tests/test_image_processing_reexports.py (39) and three drift detectors in
tests/test_import_fixes_drift.py. They cover the forwarding, the laziness, the numpy contract,
the torch contract, idempotency and the live-descriptor guard, a subclass of a patched class,
full removal, __wrapped__ preservation, deepcopy, pickle, the spawn worker, the finder's
per-thread re-entrancy guard, and that no shim state reaches a saved config.

Negative controls, all of which fail when the thing they guard is removed: reverting the two
_gpu_init.py / __init__.py call sites fails exactly three tests and passes the other 18;
reverting the method-shim call out of the get_class_in_module wrapper fails the wiring test;
reverting the meta-path finder fails the spawn test. Plus controls that must stay green: an
unknown name still raises AttributeError, the classifier rejects configs, models, processors,
tokenizers and transformers-owned classes, a method the remote code owns itself is never
replaced, and a class whose methods already honour numpy is left alone.

The drift detectors assert the upstream pathology is still real — that rescale still returns
float64 and normalize still raises on numpy — so if transformers restores either contract the
shim is flagged rather than left wrapping a method with itself.

Platform coverage

Five runners, each installing torch, torchvision, transformers==5.5.0, numpy, accelerate, peft,
trl, datasets and unsloth_zoo first, so import unsloth gets as far as it can and the
transformers 5 path is the one under test rather than the 4.x no-op. Counts are the executed
totals from the run logs, not the colour of the badge, and cover both
tests/test_image_processing_reexports.py and tests/test_import_fixes_drift.py.

runner result failures
ubuntu-latest (x64 Linux) 70 passed, 21 skipped 2, neither this PR's
windows-latest (x64 Windows) 70 passed, 21 skipped 2, neither this PR's
ubuntu-24.04-arm (ARM64 Linux) 70 passed, 21 skipped 2, neither this PR's
macos-15 (Apple Silicon) 68 passed, 23 skipped 2, neither this PR's
macos-15-intel (Intel macOS) 53 passed, 34 skipped 6, none this PR's

No test added by this PR fails on any of the five. The failures are pre-existing drift
detectors that cannot run on those runners: test_patch_loss_functions_* hit
ImportError: cannot import name 'get_quant_type' from 'unsloth_zoo.utils', a version skew, and
the extra four on Intel macOS hit NameError: name 'nn' is not defined and
PreTrainedModel requires the PyTorch library but it was not found, because torch is unusable on
that runner. All six pass locally at both the merge base and this branch, and this PR makes zero
deletions to that file — it only appends. They surface in staging CI now solely because adding
drift detectors made the generator include the file.

Intel macOS also earned its place. Three tests added here first failed there on
NameError: name 'tvF' is not defined: transformers.image_processing_backends imports fine
without a usable torchvision but only binds tvF behind is_torchvision_available(), so the
backend raises from inside transformers. They now ask transformers' own probe and skip, which is
why the skip count on that runner is higher than the rest.

What this does not prove

  • That the checkpoint trains on images. Loading, preprocessing and a forward pass are measured;
    a LoRA run on image batches is not.
  • The transformers 4.51.3 floor as a live run. The corner is VOID here, not passing: the shared
    venv's vLLM 0.30.0 requires transformers >= 5, so import unsloth fails identically at base and
    head. The 4.57.6 floor is covered by the Core (HF=4.57.6 + TRL<1) job and by the isolated
    4.57.6 venv used for the bit-identity check.
  • A save_pretrained / from_pretrained round trip of this checkpoint's processor, which is
    broken for reasons that predate this PR: the processor has no chat_template, and its
    preprocessor_config.json carries no auto_map for the image processor, so a standalone
    reload cannot find the class. The half this PR is responsible for is proven — the saved config
    is clean, with no _unsloth key among its 11 entries.
  • macos-26, windows-11-arm and WSL did not run.
  • A checkpoint that overrides normalize itself and calls super().normalize(numpy_array) is
    still broken. Patching an ancestor to fix it would mean touching a transformers base class,
    which this deliberately never does. The failure is loud.

transformers 5 stopped re-exporting the generic image helpers from each
model's image_processing_* module. Checkpoints whose own modeling file was
written against the 4.x layout do

    import transformers.models.siglip2.image_processing_siglip2 as siglip2_ips
    ...
    @siglip2_ips.filter_out_non_signature_kwargs()

and now raise AttributeError while the class body executes, so the model
cannot be loaded at all. On transformers 5.17.0, ten of the sixteen names
microsoft/Phi-4-reasoning-vision-15B reads off that module are gone, and
AutoProcessor.from_pretrained fails with

    module 'transformers.models.siglip2.image_processing_siglip2' has no
    attribute 'filter_out_non_signature_kwargs'

The helpers were not removed, only the re-exports, so forward attribute
reads on those modules to wherever transformers keeps them now. A module
level __getattr__ rather than a fixed list of names, because the set that
was dropped differs per release. Names transformers does not define
anywhere still raise AttributeError, so a typo in remote code does not turn
into a confusing failure later.

Applied when remote code is about to run, by wrapping get_class_in_module,
rather than at import: plain import transformers does not pull in the
siglip2 image processing module, and importing it eagerly costs every user
about three seconds of PIL and torchvision setup for a checkpoint they may
never load. No-op on transformers 4.x, where the names are still there.

Verified on 8xB200, torch 2.13.0+cu130, transformers 5.17.0: without this,
AutoProcessor.from_pretrained on Phi-4-reasoning-vision-15B raises; with
it, the processor and tokenizer load and a 10 step LoRA run completes.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 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-22T17:19:27.014642Z f10d56f 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[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the failure path: remote code reads helpers off transformers.models.siglip2.image_processing_siglip2, which transformers 5 no longer re-exports, and the forwarder here is probe-gated and only installed when remote code actually runs. Will get this reviewed.

All ten existing tests still passed with the
fix_transformers5_image_processing_reexports() call reverted out of
_gpu_init.py: they drive _install_legacy_image_reexports directly, so
they prove the helper works and never that it runs.

The two added here fail with that hunk reverted and pass with it. The
second drives a stand-in remote-code image processor through
dynamic_module_utils.get_class_in_module, which is the entry point
transformers really uses and the only place the lazy patch installs.
Forwarding only reaches names that no longer resolve. convert_image_to_patches
and pad_along_first_dim are still defined on the siglip2 module, so the
module __getattr__ never fires for them, yet transformers 5 changed both
from numpy channel-last to torch channel-first. Phi-4-reasoning-vision-15B
builds numpy arrays and hands them to exactly those two, so the class
loaded and preprocessing then failed with "cannot reshape array of size
150528 into shape (224,14,16,0,16)".

They are now dispatched on the argument type: a numpy array takes the
transformers 4.x implementation, anything else goes to whatever the module
already had, so transformers' own Siglip2ImageProcessor is untouched.
Verified bit-identical to real transformers 4.57.6 output for the numpy
path and bit-identical to the current module for the torch path.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
transformers 4.x specified convert_image_to_patches and pad_along_first_dim
for numpy only, so the baseline the test captures raises there with or
without this patch. Asserting a contract into existence made the floor
corner red for a reason unrelated to the fix.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
Both helpers have a valid keyword form, and args is empty there, so the
wrapper handed a numpy array to the torch implementation. transformers
also renamed pad_along_first_dim's first parameter from array to tensor
when it moved to torch, so a 4.x caller using the keyword names something
the current implementation does not accept at all.

The first argument is now looked for under either era's spelling and
normalised onto the one the legacy function names. Parametrised over
positional, current-keyword and legacy-keyword; the whole set is skipped
on a transformers that never dropped the re-exports, where the shim is
correctly a no-op.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 40cc6d8585

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

The test asserts that importing unsloth does not pull in the siglip2 image
module, by importing unsloth in a subprocess. On a CPU-only runner that
subprocess never gets far enough to measure: import unsloth raises
NotImplementedError: Unsloth cannot find any torch accelerator, so the test
failed on the exit code and reported a wall of unrelated warnings as the
reason. Skip that case instead. There is no import to measure the laziness of
without an accelerator, and asserting there tests the runner rather than the
fix. Any other non-zero exit still fails, with stderr attached.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 22, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 22, 2026
@danielhanchen danielhanchen changed the title Restore transformers 4.x image processing re-exports for remote code Make Phi-4-reasoning-vision load and preprocess images on transformers 5 Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The meta path loader patched only AFTER delegating to the real exec_module,
but exec_module is what runs the module body, and a checkpoint written against
the 4.x layout reads the dropped re-exports while its CLASS BODY executes:
Phi-4's own file carries @siglip2_ips.filter_out_non_signature_kwargs() on the
preprocess method. So on the unpickle path the delegation raised

  AttributeError: module 'transformers.models.siglip2.image_processing_siglip2'
  has no attribute 'filter_out_non_signature_kwargs'

before the method shim was ever reached, and a spawn-started worker was still
broken. Reproduced with a probe module of exactly that shape: child exits 1 at
the decorator line.

Python's import reference is explicit that exec_module runs the module's code
in the module namespace, and that a class statement is executed like any other
top level statement, so anything a class body reads must exist beforehand. The
re-exports are now installed before the delegation; the class level numpy shim
stays after, since the classes do not exist until the body has run.

The spawn probe missed it because its module never touched a removed
re-export, which is a test that passed while the code was broken. It now
carries the decorator, and the documented-limit control accepts either failure
mode, since an unpatched child now dies earlier at the class body rather than
later at normalize.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 068c7d24f3

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

# Conflicts:
#	tests/test_import_fixes_drift.py
#	unsloth/_gpu_init.py
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: e2f056c41f

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

pre-commit-ci Bot and others added 4 commits September 22, 2026 15:26
Post-convergence pass, comments and docstrings only, AST verified.

tests/test_image_processing_reexports.py 28.0% -> 19.6% comment lines
(226/807 -> 144/734). Deleted the docstrings that only restated the test
name, and collapsed the multi-line rationales to one line each. Measured
numbers and per-runner narration were removed: those belong in the PR
description, which carries them.

Survivors are the ones that name a mistake the next reader would otherwise
make: why the install gate cannot be "did it raise", why the class-body
decorator in the spawn probe is load-bearing, why the probe is not a version
compare, and why removal is delattr rather than a restoring setattr.

One edit was reverted after the gate caught it: the comment it targeted lives
inside the _SPAWN_CHILD string literal, so shortening it is a code change, not
a comment change.
… all

transformers 5 imports torchvision at the top of image_processing_siglip2, so
on a host without torchvision the fixture raised ModuleNotFoundError and 25
tests errored without saying anything about this fix. Production already
treats that import failure as nothing to patch, so the tests now agree.
On the CPU runners the child dies in import unsloth for want of an
accelerator, and the dynamic-module cache the pickled class lives in is not
on a fresh interpreter's path; neither says anything about the finder. The
skip condition also had its accelerator clause inverted.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1ed510d780

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

The two spawn tests failed on CI with ModuleNotFoundError: No module named
'transformers_modules'. init_hf_modules() only puts HF_MODULES_CACHE on the
PARENT's sys.path, and parent and child need not resolve it to the same place,
so the child could not import the module pickle names. Pass the root in argv
instead, and mark the preamble with a printed sentinel so a runner where
import unsloth cannot finish is told apart from a real failure.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The guard was one shared attribute, so two threads importing remote modules at
once (a threaded DataLoader is the realistic case) read each other's flag and
the loser was told "not mine": its module imported UNPATCHED, with nothing
raised. The new test raises the guard by hand on one thread and asserts
another still gets the wrapping loader, and fails on the shared attribute.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 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. Another round soon, please!

Reviewed commit: f10d56f81d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 310fb74 into main Sep 23, 2026
55 of 107 checks passed
@danielhanchen
danielhanchen deleted the siglip-image-processing-reexports branch September 23, 2026 06:47
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…s 5 (unslothai#11469)

* Restore transformers 4.x image processing re-exports for remote code

transformers 5 stopped re-exporting the generic image helpers from each
model's image_processing_* module. Checkpoints whose own modeling file was
written against the 4.x layout do

    import transformers.models.siglip2.image_processing_siglip2 as siglip2_ips
    ...
    @siglip2_ips.filter_out_non_signature_kwargs()

and now raise AttributeError while the class body executes, so the model
cannot be loaded at all. On transformers 5.17.0, ten of the sixteen names
microsoft/Phi-4-reasoning-vision-15B reads off that module are gone, and
AutoProcessor.from_pretrained fails with

    module 'transformers.models.siglip2.image_processing_siglip2' has no
    attribute 'filter_out_non_signature_kwargs'

The helpers were not removed, only the re-exports, so forward attribute
reads on those modules to wherever transformers keeps them now. A module
level __getattr__ rather than a fixed list of names, because the set that
was dropped differs per release. Names transformers does not define
anywhere still raise AttributeError, so a typo in remote code does not turn
into a confusing failure later.

Applied when remote code is about to run, by wrapping get_class_in_module,
rather than at import: plain import transformers does not pull in the
siglip2 image processing module, and importing it eagerly costs every user
about three seconds of PIL and torchvision setup for a checkpoint they may
never load. No-op on transformers 4.x, where the names are still there.

Verified on 8xB200, torch 2.13.0+cu130, transformers 5.17.0: without this,
AutoProcessor.from_pretrained on Phi-4-reasoning-vision-15B raises; with
it, the processor and tokenizer load and a 10 step LoRA run completes.

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

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

* Test that the re-export fix is wired up, not just that it works

All ten existing tests still passed with the
fix_transformers5_image_processing_reexports() call reverted out of
_gpu_init.py: they drive _install_legacy_image_reexports directly, so
they prove the helper works and never that it runs.

The two added here fail with that hunk reverted and pass with it. The
second drives a stand-in remote-code image processor through
dynamic_module_utils.get_class_in_module, which is the entry point
transformers really uses and the only place the lazy patch installs.

* Also restore the helpers transformers kept but re-specified

Forwarding only reaches names that no longer resolve. convert_image_to_patches
and pad_along_first_dim are still defined on the siglip2 module, so the
module __getattr__ never fires for them, yet transformers 5 changed both
from numpy channel-last to torch channel-first. Phi-4-reasoning-vision-15B
builds numpy arrays and hands them to exactly those two, so the class
loaded and preprocessing then failed with "cannot reshape array of size
150528 into shape (224,14,16,0,16)".

They are now dispatched on the argument type: a numpy array takes the
transformers 4.x implementation, anything else goes to whatever the module
already had, so transformers' own Siglip2ImageProcessor is untouched.
Verified bit-identical to real transformers 4.57.6 output for the numpy
path and bit-identical to the current module for the torch path.

* Skip the torch-contract test where there is no torch contract

transformers 4.x specified convert_image_to_patches and pad_along_first_dim
for numpy only, so the baseline the test captures raises there with or
without this patch. Asserting a contract into existence made the floor
corner red for a reason unrelated to the fix.

* Dispatch the numpy helpers on keyword calls too

Both helpers have a valid keyword form, and args is empty there, so the
wrapper handed a numpy array to the torch implementation. transformers
also renamed pad_along_first_dim's first parameter from array to tensor
when it moved to torch, so a 4.x caller using the keyword names something
the current implementation does not accept at all.

The first argument is now looked for under either era's spelling and
normalised onto the one the legacy function names. Parametrised over
positional, current-keyword and legacy-keyword; the whole set is skipped
on a transformers that never dropped the re-exports, where the shim is
correctly a no-op.

* Skip the laziness test where import unsloth cannot finish

The test asserts that importing unsloth does not pull in the siglip2 image
module, by importing unsloth in a subprocess. On a CPU-only runner that
subprocess never gets far enough to measure: import unsloth raises
NotImplementedError: Unsloth cannot find any torch accelerator, so the test
failed on the exit code and reported a wall of unrelated warnings as the
reason. Skip that case instead. There is no import to measure the laziness of
without an accelerator, and asserting there tests the runner rather than the
fix. Any other non-zero exit still fails, with stderr attached.

* Install the image re-export fix on the MLX import path too

* Key the accelerator skip on the raising function, not its wording

* Gate the get_class_in_module wrap on the live function, not a module flag

* Reinstall the retained-helper shims a module reload wiped

* Skip the import-wired tests on a host that cannot import unsloth

test_the_fix_is_actually_installed_on_import,
test_remote_code_reading_siglip_helpers_loads and
test_the_wrapper_is_reinstalled_after_a_module_reload assert on state that
import unsloth installs, but none of them owns that import: the module-level
import of unsloth.import_fixes is what triggers it. On a host with no
supported accelerator that import ends at the device check in _gpu_init.py,
before the line that installs the fix, so all three reported the fix missing
for a reason unrelated to the re-exports.

Measured on GitHub macos-15 (Apple Silicon, mlx installed but
is_mlx_available() false, so neither import path completes): 3 failed,
17 passed, 1 skipped, against 20 passed and 1 skipped on ubuntu-latest,
ubuntu-24.04-arm, windows-latest and macos-15-intel at the same commit.

The guard is the one test_import_unsloth_does_not_pull_in_the_image_stack
already used, keyed on the raising function rather than unsloth_zoo's wording.
Anything other than that NotImplementedError still fails, so a host that can
import unsloth and still lacks the wrap stays a red test, and
test_every_import_path_installs_the_fix keeps the wiring covered from a host
that skips here.

* Widen the skip to any reason import unsloth cannot finish

The first version of this guard matched only the accelerator
NotImplementedError. The next cross-platform pass then failed
ubuntu-24.04-arm and windows-latest on a different exception entirely,
ImportError: cannot import name 'get_quant_type' from 'unsloth_zoo.utils',
with the same three tests red for the same underlying reason: import unsloth
never completed, so nothing installed the wrap they assert on.

Any exception now skips, with the type and message in the skip reason so -rs
still reports which hosts opted out and why. The subprocess guard in
test_import_unsloth_does_not_pull_in_the_image_stack is aligned the same way
and keeps the stderr tail.

This does not make the tests unfailable. Reverting the two call sites out of
_gpu_init.py and __init__.py on a healthy host still fails exactly these three
and passes the other 18, which is the control: a host that can import unsloth
and still has no wrap does not skip.

* Restore the transformers 4.x numpy contract on remote image processor methods

Loading microsoft/Phi-4-reasoning-vision-15B works after the re-export fix, but
preprocessing an image still did not: transformers 5 put a torchvision backend
in every image processor's MRO (Siglip2ImageProcessor -> TorchvisionBackend ->
BaseImageProcessor), and the checkpoint's own preprocess builds channel-last
numpy and calls self.rescale then self.normalize on it.

  TypeError: Functional F.normalize supports inputs of type
  dict_keys([tv_tensors.Image, torch.Tensor, tv_tensors.Video]),
  but got numpy.ndarray

transformers 5 still ships transformers.image_transforms.rescale and .normalize
with the 4.x numpy signatures, and in 4.x the BaseImageProcessor methods of the
same names were four-line forwards to exactly those. So this restores the 4.x
contract by forwarding numpy inputs to transformers' own functions, and sets it
on the REMOTE SUBCLASS only: transformers' own Siglip2ImageProcessor is not
merely left unpatched, it is unreachable from here.

rescale is in scope although it does not raise. TorchvisionBackend.rescale is
image * scale, which numpy accepts and returns as float64 where 4.x returned
float32. Patching only the method that raises leaves pixel_values float64, with
nothing to notice. Measured, same image and seed: normalize alone gives float64
and sum -593.91369629, both methods give float32 and -593.90917969.

resize, center_crop and pad are deliberately out. They also reject numpy, but
with AttributeError: 'dict' object has no attribute ... -- they reject the 4.x
dict size, not the array -- and in 4.x they were not thin passthroughs, so there
is no verified implementation to forward to, only a reimplementation.
convert_to_rgb is already bit-identical on numpy.

The install gate is equivalence with the 4.x implementation, called on a real
array, never a version comparison: on transformers 4.57.6 the live method IS
the passthrough, so the installer returns [] there. Proven against a real
4.57.6 venv with the version gate bypassed.

Two things the obvious implementation gets wrong, both found by measuring:

- The image processor class never comes through get_class_in_module. On this
  checkpoint only Phi4VisionRProcessor and Phi4VisionR do; the image processor
  is defined beside the model and read off the module, so the hook patches the
  loaded class's module and every transformers_modules.* module instead.
- pickle rebuilds a processor by importing the remote module directly, so a
  spawn-started DataLoader worker never goes near get_class_in_module. A
  sys.meta_path finder covers that, matching _TorchaoIntmmPatchFinder.

Measured on transformers 5.17.0, real checkpoint, real image: pixel_values
(1, 3600, 768) float32 with 256 valid patches, and both methods bit-identical
to real transformers 4.57.6 output. transformers' own Siglip2ImageProcessor and
SiglipImageProcessor are unchanged, asserted with torch.equal on every output
tensor.

* Skip the backend tests where torchvision is present but unusable

transformers 5's image_processing_backends imports cleanly even when
torchvision cannot be used, but it binds tvF (torchvision.transforms.v2.functional)
only behind is_torchvision_available(). Its methods then raise
NameError: name 'tvF' is not defined from inside transformers.

Live on GitHub's macos-15-intel, where pip install torch torchvision resolves
but the wheels are unusable: three tests went red on that NameError, which says
nothing about the shim. Several pre-existing drift tests on the same runner
failed the same way, with name 'nn' is not defined and PreTrainedModel requires
the PyTorch library.

The guard asks transformers' own probe rather than import torchvision, which
succeeds there, and also checks the tvF binding directly so a build that flips
the probe without binding the alias still skips instead of failing.

* Install the re-exports before the remote module executes

The meta path loader patched only AFTER delegating to the real exec_module,
but exec_module is what runs the module body, and a checkpoint written against
the 4.x layout reads the dropped re-exports while its CLASS BODY executes:
Phi-4's own file carries @siglip2_ips.filter_out_non_signature_kwargs() on the
preprocess method. So on the unpickle path the delegation raised

  AttributeError: module 'transformers.models.siglip2.image_processing_siglip2'
  has no attribute 'filter_out_non_signature_kwargs'

before the method shim was ever reached, and a spawn-started worker was still
broken. Reproduced with a probe module of exactly that shape: child exits 1 at
the decorator line.

Python's import reference is explicit that exec_module runs the module's code
in the module namespace, and that a class statement is executed like any other
top level statement, so anything a class body reads must exist beforehand. The
re-exports are now installed before the delegation; the class level numpy shim
stays after, since the classes do not exist until the body has run.

The spawn probe missed it because its module never touched a removed
re-export, which is a test that passed while the code was broken. It now
carries the decorator, and the documented-limit control accepts either failure
mode, since an unpatched child now dies earlier at the class body rather than
later at normalize.

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

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

* Reduce comments on this PR's files

Post-convergence pass, comments and docstrings only, AST verified.

tests/test_image_processing_reexports.py 28.0% -> 19.6% comment lines
(226/807 -> 144/734). Deleted the docstrings that only restated the test
name, and collapsed the multi-line rationales to one line each. Measured
numbers and per-runner narration were removed: those belong in the PR
description, which carries them.

Survivors are the ones that name a mistake the next reader would otherwise
make: why the install gate cannot be "did it raise", why the class-body
decorator in the spawn probe is load-bearing, why the probe is not a version
compare, and why removal is delattr rather than a restoring setattr.

One edit was reverted after the gate caught it: the comment it targeted lives
inside the _SPAWN_CHILD string literal, so shortening it is a code change, not
a comment change.

* Skip the re-export tests when the target module cannot be imported at all

transformers 5 imports torchvision at the top of image_processing_siglip2, so
on a host without torchvision the fixture raised ModuleNotFoundError and 25
tests errored without saying anything about this fix. Production already
treats that import failure as nothing to patch, so the tests now agree.

* Skip the spawn worker tests when the child cannot run at all

On the CPU runners the child dies in import unsloth for want of an
accelerator, and the dynamic-module cache the pickled class lives in is not
on a fresh interpreter's path; neither says anything about the finder. The
skip condition also had its accelerator clause inverted.

* Hand the remote-code root to the spawn probe child explicitly

The two spawn tests failed on CI with ModuleNotFoundError: No module named
'transformers_modules'. init_hf_modules() only puts HF_MODULES_CACHE on the
PARENT's sys.path, and parent and child need not resolve it to the same place,
so the child could not import the module pickle names. Pass the root in argv
instead, and mark the preamble with a printed sentinel so a runner where
import unsloth cannot finish is told apart from a real failure.

* Make the remote-module finder's re-entrancy guard thread-local

The guard was one shared attribute, so two threads importing remote modules at
once (a threaded DataLoader is the realistic case) read each other's flag and
the loser was told "not mine": its module imported UNPATCHED, with nothing
raised. The new test raises the guard by hand on one thread and asserts
another still gets the wrapping loader, and fails on the shared attribute.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant