Repository navigation
Make Phi-4-reasoning-vision load and preprocess images on transformers 5 - #11469
Conversation
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.
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. |
|
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. |
…s' into siglip-image-processing-reexports
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.
|
@codex security review |
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.
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.
|
Codex Review: Didn't find any major issues. 👍 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". |
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.
|
pre-commit.ci run |
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.
|
Codex Review: Didn't find any major issues. Nice work! 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". |
# Conflicts: # tests/test_import_fixes_drift.py # unsloth/_gpu_init.py
|
Codex Review: Didn't find any major issues. 🎉 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". |
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.
|
Codex Review: Didn't find any major issues. Nice work! 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". |
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.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
|
pre-commit.ci run |
|
pre-commit.ci run |
…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>
Problem
microsoft/Phi-4-reasoning-vision-15Bfails to load withIts 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
Siglip2ImageProcessoronto a torchvision backend, so preprocessing an image dies too.Fix
Two halves, both in
import_fixes.pystyle, both applied only while a checkpoint's own code isbeing 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. Theforwarder 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 isuntouched.
2. The numpy contract on the class. transformers 5 put a torchvision backend in every image
processor's MRO (
Siglip2ImageProcessor->TorchvisionBackend->BaseImageProcessor), whilethis checkpoint's
preprocessbuilds channel-last numpy and callsself.rescalethenself.normalizeon it:transformers 5 still ships
transformers.image_transforms.rescaleand.normalizewith the 4.xnumpy signatures, and in 4.x the
BaseImageProcessormethods of those names were four-lineforwards to exactly those functions. So numpy inputs are forwarded to transformers' own
functions, by keyword, and set on the remote subclass only — transformers' own
Siglip2ImageProcessoris 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 unslothdoes not pull in any imageprocessing 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.
AutoProcessor.from_pretrained(..., trust_remote_code=True)AttributeError: module 'transformers.models.siglip2.image_processing_siglip2' has no attribute 'filter_out_non_signature_kwargs'Phi4VisionRProcessorwith aSiglip2ImageProcessorNoUpscaleTypeError: Functional F.normalize ... but got numpy.ndarraypixel_values (1, 3600, 768) float32,pixel_attention_mask (1, 3600)with 256 valid patches,spatial_shapessumming 32logits (1, 790, 100352)bfloat16, all finite, mean -0.65611 std 1.74083The 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
uint8array:rescaleandnormalizeagreeunder
np.array_equal, same dtype, same shape. Unpatched transformers 5.17 does not:rescalereturns float64,
normalizeraises.Two things measurement changed about the fix
rescaleis in scope although it never raises.TorchvisionBackend.rescaleisimage * scale,which numpy accepts and returns as float64, where 4.x returned float32. Patching only the method
that raises leaves
pixel_valuesin float64: twice the host memory per batch and a dtype thevision tower was not built for, with nothing raised. Same image, same seed:
pixel_valuesdtypenormalizeonlynormalize+rescaleSo 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_cropandpadare deliberately out. They also reject numpy, but withAttributeError: 'dict' object has no attribute ...— they reject the 4.x dictsize, not thearray — and in 4.x they were not thin passthroughs, so there is no verified implementation to
forward to, only a reimplementation.
convert_to_rgbis already bit-identical on numpy, checkedon uint8, float32 and float64. Remote code reaches
resizeoff the module anyway, where there-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.
get_class_in_module. On this checkpointexactly two classes do,
Phi4VisionRProcessorandPhi4VisionR; the image processor is definedbeside 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.picklerebuilds a processor by importing the remote module directly, so a spawn-startedDataLoader worker never goes near
get_class_in_moduleand would get an unpatched class. Asys.meta_pathfinder covers that, matching the existing_TorchaoIntmmPatchFinder. Its ownnegative 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,
Siglip2ImageProcessorhas nonormalizein its__dict__, still resolves toTorchvisionBackend.normalize, and producestorch.equaloutput on every tensor. Same forSiglipImageProcessor(pixel_valuessum -532.447021 before and after).Full default test selection, merge base vs this branch, 31k tests:
Failure sets are identical — 24 shared, 0 new, 0 fixed. They are pre-existing on
mainand arenot 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 intests/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'sper-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__.pycall sites fails exactly three tests and passes the other 18;reverting the method-shim call out of the
get_class_in_modulewrapper 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
rescalestill returnsfloat64 and
normalizestill raises on numpy — so if transformers restores either contract theshim 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 unslothgets as far as it can and thetransformers 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.pyandtests/test_import_fixes_drift.py.ubuntu-latest(x64 Linux)windows-latest(x64 Windows)ubuntu-24.04-arm(ARM64 Linux)macos-15(Apple Silicon)macos-15-intel(Intel macOS)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_*hitImportError: cannot import name 'get_quant_type' from 'unsloth_zoo.utils', a version skew, andthe extra four on Intel macOS hit
NameError: name 'nn' is not definedandPreTrainedModel requires the PyTorch library but it was not found, because torch is unusable onthat 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_backendsimports finewithout a usable torchvision but only binds
tvFbehindis_torchvision_available(), so thebackend 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
a LoRA run on image batches is not.
venv's vLLM 0.30.0 requires transformers >= 5, so
import unslothfails identically at base andhead. The 4.57.6 floor is covered by the
Core (HF=4.57.6 + TRL<1)job and by the isolated4.57.6 venv used for the bit-identity check.
save_pretrained/from_pretrainedround trip of this checkpoint's processor, which isbroken for reasons that predate this PR: the processor has no
chat_template, and itspreprocessor_config.jsoncarries noauto_mapfor the image processor, so a standalonereload cannot find the class. The half this PR is responsible for is proven — the saved config
is clean, with no
_unslothkey among its 11 entries.macos-26,windows-11-armand WSL did not run.normalizeitself and callssuper().normalize(numpy_array)isstill broken. Patching an ancestor to fix it would mean touching a transformers base class,
which this deliberately never does. The failure is loud.