Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han310fb74f88ac
diff --git a/tests/test_image_processing_reexports.py b/tests/test_image_processing_reexports.py
new file mode 100644
index 00000000000..cf79c7e69fe
--- /dev/null
+++ b/tests/test_image_processing_reexports.py
@@ -0,0 +1,995 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Remote code reading image helpers off a model's image_processing module.
+
+Nothing asserts on a literal list of names: the set transformers 5 dropped
+differs per release, so a hardcoded list would pass while the fix did nothing.
+"""
+
+import importlib
+
+import pytest
+
+transformers = pytest.importorskip("transformers")
+
+from unsloth.import_fixes import ( # noqa: E402
+ _IMAGE_PROCESSING_MODULES,
+ _IMAGE_PROCESSING_SYMBOL_HOMES,
+ _IMAGE_REEXPORT_FLAG,
+ _image_processing_reexports_are_missing,
+ _install_legacy_image_reexports,
+ _remove_legacy_image_reexports,
+)
+
+SIGLIP2 = "transformers.models.siglip2.image_processing_siglip2"
+
+
+def _import_or_skip(name):
+ """Import a target module, or skip when this host cannot have it at all.
+
+ transformers 5 made `image_processing_siglip2` import torchvision at module
+ top level, so on a transformers 5 host without torchvision every test that
+ touches it raised `ModuleNotFoundError` out of a fixture: measured on a
+ torchvision-free transformers 5.17.0 venv, 25 of 38 tests ERRORED and not
+ one of those errors said anything about this fix. Production already treats
+ that as "nothing to patch here" -- `_install_legacy_image_reexports`
+ catches the import and returns False -- so the tests must agree with it.
+ """
+ try:
+ return importlib.import_module(name)
+ except ImportError as exception:
+ pytest.skip(f"{name} cannot be imported on this host ({exception})")
+
+
+def _fresh_module(name):
+ """A module with our patch fully removed, so a test sees the upstream state.
+
+ Removing only ``__getattr__`` is not enough: the forwarder caches each hit
+ with ``setattr``, so a later probe would see the names still present and
+ the test would skip itself into passing.
+ """
+ _import_or_skip(name)
+ _remove_legacy_image_reexports(name)
+ return importlib.import_module(name)
+
+
+def siglip2_module():
+ module = _fresh_module(SIGLIP2)
+ yield module
+ _fresh_module(SIGLIP2)
+
+
+def test_homes_are_importable():
+ """Every home the fix resolves from must exist, or it silently finds nothing."""
+ for home in _IMAGE_PROCESSING_SYMBOL_HOMES:
+ importlib.import_module(home)
+
+
+def test_probe_matches_reality(siglip2_module):
+ missing = _image_processing_reexports_are_missing(siglip2_module)
+ assert missing == (not hasattr(siglip2_module, "filter_out_non_signature_kwargs"))
+
+
+def test_fix_restores_every_name_the_remote_code_reads(siglip2_module):
+ """Restore the names Phi-4-reasoning-vision reads, whichever are missing here."""
+ if not _image_processing_reexports_are_missing(siglip2_module):
+ pytest.skip("this transformers still re-exports the image helpers")
+
+ # The exact set the checkpoint's modeling file reads off the module.
+ names = [
+ "BatchFeature",
+ "ChannelDimension",
+ "PILImageResampling",
+ "convert_image_to_patches",
+ "convert_to_rgb",
+ "filter_out_non_signature_kwargs",
+ "get_image_size_for_max_num_patches",
+ "infer_channel_dimension_format",
+ "make_flat_list_of_images",
+ "pad_along_first_dim",
+ "resize",
+ "to_channel_dimension_format",
+ "to_numpy_array",
+ "valid_images",
+ "validate_preprocess_arguments",
+ ]
+ before = [n for n in names if not hasattr(siglip2_module, n)]
+ assert before, "nothing was missing, so this test would prove nothing"
+
+ assert _install_legacy_image_reexports(SIGLIP2) is True
+ for name in before:
+ assert getattr(siglip2_module, name, None) is not None, name
+
+
+def test_resolved_symbol_is_the_real_one(siglip2_module):
+ if not _image_processing_reexports_are_missing(siglip2_module):
+ pytest.skip("this transformers still re-exports the image helpers")
+ _install_legacy_image_reexports(SIGLIP2)
+ from transformers.utils import filter_out_non_signature_kwargs as real
+
+ assert siglip2_module.filter_out_non_signature_kwargs is real
+
+
+def test_unknown_names_still_raise(siglip2_module):
+ """A genuine typo must not turn into a confusing failure later on."""
+ _install_legacy_image_reexports(SIGLIP2)
+ with pytest.raises(AttributeError):
+ siglip2_module.unsloth_definitely_not_a_transformers_symbol
+
+
+def test_private_names_are_not_forwarded(siglip2_module):
+ _install_legacy_image_reexports(SIGLIP2)
+ with pytest.raises(AttributeError):
+ siglip2_module._unsloth_definitely_not_a_transformers_symbol
+
+
+def test_fix_is_idempotent(siglip2_module):
+ if not _image_processing_reexports_are_missing(siglip2_module):
+ pytest.skip("this transformers still re-exports the image helpers")
+ assert _install_legacy_image_reexports(SIGLIP2) is True
+ assert _install_legacy_image_reexports(SIGLIP2) is False
+
+
+def test_fix_can_be_undone(siglip2_module):
+ """Keep the original reachable, so the patch can be tested and undone."""
+ if not _image_processing_reexports_are_missing(siglip2_module):
+ pytest.skip("this transformers still re-exports the image helpers")
+ _install_legacy_image_reexports(SIGLIP2)
+ assert getattr(siglip2_module, _IMAGE_REEXPORT_FLAG, False) is True
+ restored = _fresh_module(SIGLIP2)
+ assert getattr(restored, _IMAGE_REEXPORT_FLAG, False) is False
+
+
+def test_every_target_module_is_real():
+ """A typo in the module list would make the fix quietly do nothing."""
+ for name in _IMAGE_PROCESSING_MODULES:
+ _import_or_skip(name)
+
+
+def test_import_unsloth_does_not_pull_in_the_image_stack():
+ """The fix must stay lazy: importing the siglip2 image module costs seconds."""
+ import subprocess
+ import sys
+
+ code = (
+ "import sys; import unsloth; "
+ "print('transformers.models.siglip2.image_processing_siglip2' in sys.modules)"
+ )
+ out = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True)
+ if out.returncode != 0:
+ # No import happened, so there is no laziness to measure; asserting here
+ # would test the runner. Not keyed on one exception: CPU runners produce
+ # at least two unrelated ones.
+ pytest.skip(
+ "import unsloth does not complete on this host; nothing to measure. "
+ + out.stderr.strip()[-400:]
+ )
+ assert out.stdout.strip().splitlines()[-1] == "False", out.stdout[-2000:]
+
+
+# Everything above passes with the `_gpu_init.py` call reverted: it proves the
+# helper works, never that it is wired up. The tests below close that gap.
+
+
+def _unsloth_import_or_skip():
+ """Skip when this host cannot finish `import unsloth` at all.
+
+ Callers assert on state that import installs without owning it, and a host
+ that never gets past `_gpu_init.py`'s device check would report the fix
+ missing for an unrelated reason. Any exception skips, not one keyed family:
+ CPU runners produced an accelerator NotImplementedError and an unrelated
+ unsloth_zoo ImportError in consecutive passes. Still failable, since a host
+ that CAN import unsloth does not skip.
+ """
+ try:
+ import unsloth # noqa: F401
+ except Exception as e:
+ pytest.skip(
+ f"import unsloth does not complete on this host "
+ f"({type(e).__name__}: {str(e)[:160]}); no import to measure"
+ )
+
+
+def test_the_fix_is_actually_installed_on_import():
+ from packaging.version import Version
+
+ _unsloth_import_or_skip()
+
+ if Version(transformers.__version__) < Version("5.0.0"):
+ pytest.skip("no re-exports were dropped before transformers 5")
+ from transformers import dynamic_module_utils
+
+ assert getattr(dynamic_module_utils, "_unsloth_patched_get_class_in_module", False)
+ assert hasattr(dynamic_module_utils.get_class_in_module, "__wrapped__")
+
+
+def test_remote_code_reading_siglip_helpers_loads(tmp_path):
+ """End to end through `get_class_in_module`, where the lazy fix installs.
+
+ Same module, decorator and class-body timing as the real checkpoint.
+ """
+ import pathlib
+
+ _unsloth_import_or_skip()
+
+ from transformers import dynamic_module_utils
+ from transformers.utils import HF_MODULES_CACHE
+
+ siglip2 = _fresh_module(SIGLIP2)
+ if not _image_processing_reexports_are_missing(siglip2):
+ pytest.skip("this transformers still re-exports the image helpers")
+
+ package = pathlib.Path(HF_MODULES_CACHE) / "unsloth_reexport_probe"
+ package.mkdir(parents = True, exist_ok = True)
+ (package / "__init__.py").write_text("")
+ (package / "image_processing_probe.py").write_text(
+ "import transformers.models.siglip2.image_processing_siglip2 as siglip2_ips\n"
+ "\n"
+ "class ProbeImageProcessor:\n"
+ " @siglip2_ips.filter_out_non_signature_kwargs()\n"
+ " def preprocess(self, images, **kwargs):\n"
+ " return siglip2_ips.to_numpy_array(images)\n"
+ )
+ try:
+ loaded = dynamic_module_utils.get_class_in_module(
+ "ProbeImageProcessor",
+ "unsloth_reexport_probe/image_processing_probe.py",
+ force_reload = True,
+ )
+ assert loaded.__name__ == "ProbeImageProcessor"
+ finally:
+ import shutil
+ shutil.rmtree(package, ignore_errors = True)
+
+
+# Helpers transformers 5 kept but re-specified numpy -> torch. A module
+# __getattr__ never fires for a name that still resolves, so these need
+# replacing rather than forwarding.
+
+
+def _numpy_image():
+ np = pytest.importorskip("numpy")
+ return np.arange(4 * 4 * 3, dtype = np.float32).reshape(4, 4, 3)
+
+
+def test_retained_helpers_accept_the_numpy_arrays_remote_code_passes(siglip2_module):
+ np = pytest.importorskip("numpy")
+ _install_legacy_image_reexports(SIGLIP2)
+
+ patches = siglip2_module.convert_image_to_patches(_numpy_image(), 2)
+ assert isinstance(patches, np.ndarray)
+ # 2x2 patches of 2x2x3 = 4 patches of 12 values, the transformers 4.x shape
+ assert patches.shape == (4, 12)
+
+ padded, mask = siglip2_module.pad_along_first_dim(patches, 6)
+ assert isinstance(padded, np.ndarray)
+ assert padded.shape == (6, 12)
+ assert mask.tolist() == [1, 1, 1, 1, 0, 0]
+
+
+def test_the_torch_contract_is_untouched(siglip2_module):
+ """transformers' own Siglip2ImageProcessor calls these with tensors.
+
+ Replacing them outright would fix the remote checkpoint by breaking the
+ model the module is named after, so the shim dispatches on the argument.
+ """
+ torch = pytest.importorskip("torch")
+ image = torch.arange(3 * 4 * 4, dtype = torch.float32).reshape(3, 4, 4)
+
+ try:
+ before = siglip2_module.convert_image_to_patches(image, 2).clone()
+ before_pad, before_mask = siglip2_module.pad_along_first_dim(before, 6)
+ except Exception:
+ # transformers 4.x specified these for numpy only, so there is no torch
+ # contract to preserve. Skipping rather than asserting one into existence.
+ pytest.skip("this transformers has no torch contract for these helpers")
+
+ _install_legacy_image_reexports(SIGLIP2)
+
+ after = siglip2_module.convert_image_to_patches(image, 2)
+ after_pad, after_mask = siglip2_module.pad_along_first_dim(after, 6)
+ assert torch.equal(after, before)
+ assert torch.equal(after_pad, before_pad)
+ assert torch.equal(after_mask, before_mask)
+
+
+def test_numpy_shim_is_idempotent_and_removable(siglip2_module):
+ _install_legacy_image_reexports(SIGLIP2)
+ once = siglip2_module.convert_image_to_patches
+ _install_legacy_image_reexports(SIGLIP2) # no-op, already flagged
+ assert siglip2_module.convert_image_to_patches is once
+
+ restored = _fresh_module(SIGLIP2)
+ assert not getattr(restored.convert_image_to_patches, "_unsloth_numpy_dispatch", False)
+
+
[email protected]("style", ["positional", "keyword", "legacy-keyword"])
+def test_numpy_dispatch_covers_the_keyword_forms(siglip2_module, style):
+ """Both helpers have a valid keyword form, and transformers renamed one.
+
+ pad_along_first_dim's first parameter went from `array` (4.x) to `tensor`
+ (5.x), so a 4.x caller using the keyword names something the current
+ implementation does not accept at all.
+ """
+ np = pytest.importorskip("numpy")
+ if not _image_processing_reexports_are_missing(siglip2_module):
+ # transformers 4.x: the shim is correctly a no-op, and the 5.x spelling
+ # of the first parameter does not exist there to be accepted.
+ pytest.skip("this transformers still re-exports the image helpers")
+ _install_legacy_image_reexports(SIGLIP2)
+ image = _numpy_image()
+
+ if style == "positional":
+ patches = siglip2_module.convert_image_to_patches(image, 2)
+ padded, mask = siglip2_module.pad_along_first_dim(patches, 6)
+ elif style == "keyword":
+ patches = siglip2_module.convert_image_to_patches(image = image, patch_size = 2)
+ padded, mask = siglip2_module.pad_along_first_dim(
+ tensor = patches,
+ target_length = 6,
+ )
+ else:
+ patches = siglip2_module.convert_image_to_patches(image = image, patch_size = 2)
+ padded, mask = siglip2_module.pad_along_first_dim(
+ array = patches,
+ target_length = 6,
+ )
+
+ assert isinstance(patches, np.ndarray) and patches.shape == (4, 12)
+ assert isinstance(padded, np.ndarray) and padded.shape == (6, 12)
+ assert mask.tolist() == [1, 1, 1, 1, 0, 0]
+
+
+def test_every_import_path_installs_the_fix():
+ """Both entry points must call it, not just the CUDA one.
+
+ `unsloth/__init__.py` returns early on Apple Silicon with MLX and never
+ reaches `_gpu_init.py`, so the call added there alone left macOS unpatched.
+ Caught by the macOS leg of cross-platform CI, held here so it fails
+ everywhere: the running host cannot exercise the branch it is not on.
+ """
+ import pathlib
+
+ root = pathlib.Path(__file__).parents[1] / "unsloth"
+ for site in ("_gpu_init.py", "__init__.py"):
+ source = (root / site).read_text(encoding = "utf-8")
+ assert "fix_transformers5_image_processing_reexports" in source, site
+
+
+def test_the_wrapper_is_reinstalled_after_a_module_reload():
+ """`importlib.reload` restores upstream get_class_in_module but keeps our flag.
+
+ Reload re-runs the module body in the EXISTING namespace, so the function
+ goes back to upstream while a module attribute we added survives. A guard
+ reading that attribute would then refuse to re-wrap a module that is once
+ again unpatched; the guard reads the live function instead.
+ """
+ from packaging.version import Version
+
+ if Version(transformers.__version__) < Version("5.0.0"):
+ pytest.skip("no re-exports were dropped before transformers 5")
+ _unsloth_import_or_skip()
+
+ from unsloth.import_fixes import fix_transformers5_image_processing_reexports
+ from transformers import dynamic_module_utils
+
+ wrapped = dynamic_module_utils.get_class_in_module
+ assert hasattr(wrapped, "__wrapped__")
+ try:
+ importlib.reload(dynamic_module_utils)
+ assert not hasattr(dynamic_module_utils.get_class_in_module, "__wrapped__")
+ # The module flag is exactly what survived, which is why it cannot be the guard.
+ assert getattr(dynamic_module_utils, "_unsloth_patched_get_class_in_module", False)
+
+ fix_transformers5_image_processing_reexports()
+ assert hasattr(dynamic_module_utils.get_class_in_module, "__wrapped__")
+ finally:
+ dynamic_module_utils.get_class_in_module = wrapped
+ dynamic_module_utils._unsloth_patched_get_class_in_module = True
+
+
+def test_the_module_shims_are_reinstalled_after_a_module_reload(siglip2_module):
+ """Reload restores the helpers the module body assigns; the flag survives.
+
+ Measured, not assumed: `__getattr__` survives because the source never
+ assigns it, while `convert_image_to_patches` and `pad_along_first_dim` are
+ assigned by the body and come back as upstream torch implementations. So
+ the module ends up HALF patched, and a guard reading the module flag would
+ call that done and leave remote-code preprocessing broken again.
+ """
+ if not _image_processing_reexports_are_missing(siglip2_module):
+ pytest.skip("this transformers still re-exports the image helpers")
+
+ _install_legacy_image_reexports(SIGLIP2)
+ dispatched = lambda: getattr(
+ siglip2_module.convert_image_to_patches, "_unsloth_numpy_dispatch", False
+ )
+ assert dispatched()
+ try:
+ assert importlib.reload(siglip2_module) is siglip2_module
+ assert getattr(siglip2_module, _IMAGE_REEXPORT_FLAG, False), "the flag survives"
+ assert not dispatched(), "the numpy dispatch does not"
+
+ assert _install_legacy_image_reexports(SIGLIP2) is True
+ assert dispatched()
+ finally:
+ _remove_legacy_image_reexports(SIGLIP2)
+
+
+# ---------------------------------------------------------------------------
+# The same numpy/torch split one level up: BACKEND METHODS on the remote class.
+#
+# transformers 5 put a torchvision backend in every image processor's MRO, so a
+# remote-code subclass that hands channel-last numpy to `self.normalize` reaches
+# torchvision and raises. These tests drive the real classes; nothing here
+# asserts on a version.
+
+from unsloth.import_fixes import ( # noqa: E402
+ _IMAGE_METHOD_BOUND,
+ _IMAGE_METHOD_PATCH_FLAG,
+ _LEGACY_NUMPY_IMAGE_METHODS,
+ _install_legacy_numpy_image_methods,
+ _is_remote_image_processor_class,
+ _remove_legacy_numpy_image_methods,
+ _resolved_image_method,
+)
+
+REMOTE_MODULE = "transformers_modules.unsloth_probe.image_processing_probe"
+
+
+def _backend_module():
+ """transformers 5's torchvision backend, or a skip where it cannot run.
+
+ The module imports cleanly even when torchvision is unusable but binds `tvF`
+ only behind `is_torchvision_available()`, so its methods then raise
+ `NameError: name 'tvF' is not defined` from inside transformers. Hence
+ transformers' own probe, not `import torchvision`, which succeeds anyway.
+ """
+ module = pytest.importorskip("transformers.image_processing_backends")
+ from transformers.utils import is_torchvision_available
+
+ if not is_torchvision_available() or not hasattr(module, "tvF"):
+ pytest.skip("torchvision is not usable here, so the backend cannot run")
+ return module
+
+
+def remote_processor_class():
+ """A real `Siglip2ImageProcessor` subclass with a remote `__module__`.
+
+ Only the module string is faked, so everything the classifier and probe read
+ is genuine.
+ """
+ siglip2 = _import_or_skip(SIGLIP2)
+ base = siglip2.Siglip2ImageProcessor
+
+ cls = type("ProbeImageProcessorNoUpscale", (base,), {})
+ cls.__module__ = REMOTE_MODULE
+ yield cls
+ _remove_legacy_numpy_image_methods(cls)
+
+
+def _probe_image():
+ np = pytest.importorskip("numpy")
+ return np.arange(4 * 4 * 3, dtype = np.uint8).reshape(4, 4, 3)
+
+
+def test_the_numpy_contract_is_restored_on_a_remote_subclass(remote_processor_class):
+ """The whole point: channel-last numpy through the methods remote code calls."""
+ np = pytest.importorskip("numpy")
+ image_transforms = importlib.import_module("transformers.image_transforms")
+ _backend_module()
+
+ assert _install_legacy_numpy_image_methods(remote_processor_class) == ["rescale", "normalize"]
+ inst = object.__new__(remote_processor_class)
+ image = _probe_image()
+
+ rescaled = inst.rescale(image = image, scale = 1.0 / 255.0, input_data_format = "channels_last")
+ expected = image_transforms.rescale(
+ image,
+ scale = 1.0 / 255.0,
+ input_data_format = "channels_last",
+ )
+ assert isinstance(rescaled, np.ndarray)
+ assert rescaled.dtype == expected.dtype
+ assert np.array_equal(rescaled, expected)
+
+ normalized = inst.normalize(
+ image = rescaled,
+ mean = [0.5, 0.5, 0.5],
+ std = [0.5, 0.5, 0.5],
+ input_data_format = "channels_last",
+ )
+ expected = image_transforms.normalize(
+ rescaled,
+ mean = [0.5, 0.5, 0.5],
+ std = [0.5, 0.5, 0.5],
+ input_data_format = "channels_last",
+ )
+ assert isinstance(normalized, np.ndarray)
+ assert normalized.dtype == expected.dtype
+ assert np.array_equal(normalized, expected)
+
+
+def test_rescale_is_in_scope_because_it_is_wrong_not_because_it_raises(remote_processor_class):
+ """Pins why the gate cannot be "did it raise": rescale accepts numpy and
+ returns float64 where 4.x returned float32, so patching only the raising
+ method leaves pixel_values float64 with nothing to notice.
+ """
+ np = pytest.importorskip("numpy")
+ siglip2 = importlib.import_module(SIGLIP2)
+ _backend_module()
+ image = _probe_image()
+
+ upstream = siglip2.Siglip2ImageProcessor().rescale(
+ image = image,
+ scale = 1.0 / 255.0,
+ input_data_format = "channels_last",
+ )
+ if upstream.dtype == np.float32:
+ pytest.skip("this transformers already returns the 4.x dtype from rescale")
+ assert upstream.dtype == np.float64, "the silent half changed shape; re-verify the gate"
+
+ _install_legacy_numpy_image_methods(remote_processor_class)
+ patched = object.__new__(remote_processor_class).rescale(
+ image = image,
+ scale = 1.0 / 255.0,
+ input_data_format = "channels_last",
+ )
+ assert patched.dtype == np.float32
+ assert np.allclose(patched, upstream)
+
+
+def test_transformers_own_image_processor_is_untouched(remote_processor_class):
+ """Negative control, and the invariant the whole design rests on."""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("PIL")
+ np = pytest.importorskip("numpy")
+ backends = _backend_module()
+ siglip2 = importlib.import_module(SIGLIP2)
+ from PIL import Image
+
+ own = siglip2.Siglip2ImageProcessor
+ image = Image.fromarray((np.random.RandomState(0).rand(64, 64, 3) * 255).astype(np.uint8))
+ before = own()(images = [image], return_tensors = "pt")
+
+ _install_legacy_numpy_image_methods(remote_processor_class)
+
+ for name in _LEGACY_NUMPY_IMAGE_METHODS:
+ assert name not in own.__dict__, f"{name} was set on transformers' own class"
+ assert getattr(own, name) is getattr(backends.TorchvisionBackend, name)
+ after = own()(images = [image], return_tensors = "pt")
+ for key in before:
+ assert torch.equal(
+ torch.as_tensor(before[key]),
+ torch.as_tensor(after[key]),
+ ), f"{key} moved on transformers' own processor"
+
+
+def test_the_probe_decides_not_the_version(remote_processor_class):
+ """A class already honouring numpy is left alone: subclassing
+ `BaseImageProcessor` directly reproduces the 4.x MRO, so swapping the probe
+ for a `Version(...)` compare turns this red on transformers 5.
+ """
+ utils = importlib.import_module("transformers.image_processing_utils")
+ cls = type("ProbeLegacyEraProcessor", (utils.BaseImageProcessor,), {})
+ cls.__module__ = REMOTE_MODULE
+ try:
+ owner, _ = _resolved_image_method(cls, "normalize")
+ if owner is None or "Torchvision" in owner.__name__:
+ pytest.skip("BaseImageProcessor itself is torchvision-backed on this build")
+ assert _install_legacy_numpy_image_methods(cls) == []
+ for name in _LEGACY_NUMPY_IMAGE_METHODS:
+ assert name not in cls.__dict__
+ finally:
+ _remove_legacy_numpy_image_methods(cls)
+
+
+def test_the_torch_contract_is_untouched_on_the_patched_class(remote_processor_class):
+ torch = pytest.importorskip("torch")
+ backends = _backend_module()
+
+ _install_legacy_numpy_image_methods(remote_processor_class)
+ inst = object.__new__(remote_processor_class)
+ tensor = torch.arange(3 * 4 * 4, dtype = torch.float32).reshape(3, 4, 4) / 255.0
+
+ assert torch.equal(
+ inst.normalize(tensor, mean = [0.5] * 3, std = [0.5] * 3),
+ backends.TorchvisionBackend.normalize(inst, tensor, mean = [0.5] * 3, std = [0.5] * 3),
+ )
+ assert torch.equal(
+ inst.rescale(tensor, scale = 2.0),
+ backends.TorchvisionBackend.rescale(inst, tensor, scale = 2.0),
+ )
+
+
+def test_the_classifier_rejects_everything_that_is_not_remote_remote(remote_processor_class):
+ siglip2 = importlib.import_module(SIGLIP2)
+ configuration_utils = importlib.import_module("transformers.configuration_utils")
+ processing_utils = importlib.import_module("transformers.processing_utils")
+
+ class NotAClass:
+ pass
+
+ remote_config = type("RemoteConfig", (configuration_utils.PretrainedConfig,), {})
+ remote_config.__module__ = REMOTE_MODULE
+ remote_processor = type("RemoteProcessor", (processing_utils.ProcessorMixin,), {})
+ remote_processor.__module__ = REMOTE_MODULE
+
+ assert _is_remote_image_processor_class(remote_processor_class) is True
+ for rejected in (
+ 42,
+ "a string",
+ NotAClass,
+ remote_config,
+ remote_processor,
+ siglip2.Siglip2ImageProcessor, # transformers' own, the one that must never match
+ ):
+ assert _is_remote_image_processor_class(rejected) is False, rejected
+
+
+def test_a_method_the_remote_code_owns_is_never_replaced():
+ np = pytest.importorskip("numpy")
+ _backend_module()
+ siglip2 = importlib.import_module(SIGLIP2)
+
+ sentinel = object()
+
+ def normalize(self, image, *args, **kwargs):
+ return sentinel
+
+ cls = type(
+ "ProbeOwnNormalize",
+ (siglip2.Siglip2ImageProcessor,),
+ {"normalize": normalize},
+ )
+ cls.__module__ = REMOTE_MODULE
+ try:
+ assert _install_legacy_numpy_image_methods(cls) == ["rescale"]
+ assert cls.__dict__["normalize"] is normalize
+ assert object.__new__(cls).normalize(_probe_image()) is sentinel
+ finally:
+ _remove_legacy_numpy_image_methods(cls)
+
+
+def test_install_is_idempotent_and_the_guard_reads_the_live_descriptor(remote_processor_class):
+ """Second install is a no-op; a method that went back to upstream re-patches."""
+ _backend_module()
+ assert _install_legacy_numpy_image_methods(remote_processor_class) == ["rescale", "normalize"]
+ first = remote_processor_class.__dict__["normalize"]
+
+ assert _install_legacy_numpy_image_methods(remote_processor_class) == []
+ assert remote_processor_class.__dict__["normalize"] is first
+
+ # What a redefinition of the class body looks like from here: the flagged
+ # function is gone while `_IMAGE_METHOD_BOUND` survives. A guard reading the
+ # class attribute would call this done.
+ delattr(remote_processor_class, "normalize")
+ assert getattr(remote_processor_class, _IMAGE_METHOD_BOUND, None) is not None
+ assert _install_legacy_numpy_image_methods(remote_processor_class) == ["normalize"]
+
+
+def test_a_subclass_of_a_patched_class_is_not_double_wrapped(remote_processor_class):
+ """It inherits one layer, and installing on it again does nothing."""
+ np = pytest.importorskip("numpy")
+ _backend_module()
+ _install_legacy_numpy_image_methods(remote_processor_class)
+
+ sub = type("ProbeSub", (remote_processor_class,), {})
+ sub.__module__ = REMOTE_MODULE
+ try:
+ assert _install_legacy_numpy_image_methods(sub) == []
+ assert "normalize" not in sub.__dict__
+ out = object.__new__(sub).rescale(
+ image = _probe_image(),
+ scale = 1.0 / 255.0,
+ input_data_format = "channels_last",
+ )
+ assert out.dtype == np.float32
+ finally:
+ _remove_legacy_numpy_image_methods(sub)
+
+
+def test_the_method_shim_is_fully_removable(remote_processor_class):
+ """Removal is delattr, because the method was always inherited."""
+ backends = _backend_module()
+ assert _install_legacy_numpy_image_methods(remote_processor_class) == ["rescale", "normalize"]
+
+ assert sorted(_remove_legacy_numpy_image_methods(remote_processor_class)) == [
+ "normalize",
+ "rescale",
+ ]
+ for name in _LEGACY_NUMPY_IMAGE_METHODS:
+ assert name not in remote_processor_class.__dict__
+ assert getattr(remote_processor_class, name) is getattr(backends.TorchvisionBackend, name)
+ assert not hasattr(remote_processor_class, _IMAGE_METHOD_BOUND)
+
+ assert _install_legacy_numpy_image_methods(remote_processor_class) == ["rescale", "normalize"]
+
+
+def test_the_dispatch_keeps_wraps_and_wrapped(remote_processor_class):
+ import inspect
+
+ backends = _backend_module()
+ _install_legacy_numpy_image_methods(remote_processor_class)
+
+ dispatch = remote_processor_class.__dict__["normalize"]
+ assert dispatch.__name__ == "normalize"
+ assert dispatch.__wrapped__ is backends.TorchvisionBackend.normalize
+ assert (
+ getattr(dispatch, _IMAGE_METHOD_PATCH_FLAG, False) is True
+ ), "the flag must be set AFTER functools.wraps, which copies __dict__"
+ assert inspect.signature(dispatch) is not None
+
+
+def test_no_shim_state_reaches_the_saved_config(remote_processor_class):
+ _backend_module()
+ siglip2 = importlib.import_module(SIGLIP2)
+
+ before = siglip2.Siglip2ImageProcessor().to_dict()
+ _install_legacy_numpy_image_methods(remote_processor_class)
+ instance = remote_processor_class()
+ saved = instance.to_dict()
+
+ assert not any(str(key).startswith("_unsloth") for key in saved), saved
+ assert siglip2.Siglip2ImageProcessor().to_dict() == before
+
+
+def test_the_remote_image_processor_finder_is_installed_once():
+ """The unpickle path: one finder, and it answers for nothing else."""
+ import sys
+
+ from unsloth.import_fixes import (
+ _REMOTE_IMAGE_FINDER_SENTINEL,
+ _install_remote_image_processor_finder,
+ )
+
+ _unsloth_import_or_skip()
+ _install_remote_image_processor_finder()
+ _install_remote_image_processor_finder()
+
+ installed = [
+ finder for finder in sys.meta_path if getattr(finder, _REMOTE_IMAGE_FINDER_SENTINEL, False)
+ ]
+ assert len(installed) == 1
+ assert installed[0].find_spec("json") is None
+ assert installed[0].find_spec("transformers_modules.nope.not_here") is None
+
+
+def test_one_thread_inside_the_finder_does_not_blind_another():
+ """The re-entrancy guard is per thread, so a concurrent import is still patched.
+
+ Deterministic rather than a race: the guard is raised by hand on this
+ thread while another asks for a real remote module. Shared as a plain
+ attribute the second thread is told "not mine" and the module is imported
+ UNPATCHED with nothing raised, which is the failure worth pinning.
+ """
+ import shutil
+ import sys
+ import threading
+
+ from unsloth.import_fixes import _RemoteImageProcessorFinder
+
+ _unsloth_import_or_skip()
+ package, module_name = _remote_probe_package()
+ finder = _RemoteImageProcessorFinder()
+ result = {}
+
+ def ask():
+ result["spec"] = finder.find_spec(module_name)
+
+ try:
+ finder._finding.active = True
+ thread = threading.Thread(target = ask)
+ thread.start()
+ thread.join()
+ # Still guarded on the thread that raised it, or find_spec recurses.
+ result["same_thread"] = finder.find_spec(module_name)
+ finally:
+ finder._finding.active = False
+ shutil.rmtree(package, ignore_errors = True)
+ sys.modules.pop(module_name, None)
+
+ assert result["spec"] is not None
+ assert type(result["spec"].loader).__name__ == "_RemoteImageProcessorLoader"
+ assert result["same_thread"] is None
+
+
+def test_remote_code_calling_the_backend_methods_on_numpy_loads_and_runs(tmp_path):
+ """End to end through `get_class_in_module`, the way a checkpoint does it.
+
+ The wiring test. Reverting the `_install_legacy_numpy_image_methods_now()`
+ call out of the wrapper makes this raise the TypeError it exists to stop.
+ """
+ import pathlib
+
+ np = pytest.importorskip("numpy")
+ _unsloth_import_or_skip()
+ _backend_module()
+
+ from transformers import dynamic_module_utils
+ from transformers.utils import HF_MODULES_CACHE
+
+ siglip2 = _fresh_module(SIGLIP2)
+ if not _image_processing_reexports_are_missing(siglip2):
+ pytest.skip("this transformers still re-exports the image helpers")
+
+ package = pathlib.Path(HF_MODULES_CACHE) / "unsloth_method_probe"
+ package.mkdir(parents = True, exist_ok = True)
+ (package / "__init__.py").write_text("")
+ (package / "image_processing_probe.py").write_text(
+ "import numpy as np\n"
+ "import transformers.models.siglip2.image_processing_siglip2 as siglip2_ips\n"
+ "\n"
+ "class ProbeImageProcessor(siglip2_ips.Siglip2ImageProcessor):\n"
+ " def preprocess_like_2024(self, image):\n"
+ " image = self.rescale(image = image, scale = 1 / 255.0,\n"
+ " input_data_format = 'channels_last')\n"
+ " return self.normalize(image = image, mean = [0.5] * 3, std = [0.5] * 3,\n"
+ " input_data_format = 'channels_last')\n"
+ )
+ try:
+ loaded = dynamic_module_utils.get_class_in_module(
+ "ProbeImageProcessor",
+ "unsloth_method_probe/image_processing_probe.py",
+ force_reload = True,
+ )
+ image = np.arange(4 * 4 * 3, dtype = np.uint8).reshape(4, 4, 3)
+ out = object.__new__(loaded).preprocess_like_2024(image)
+ assert isinstance(out, np.ndarray)
+ assert out.dtype == np.float32, "float64 here means rescale was left unpatched"
+ finally:
+ import shutil
+ shutil.rmtree(package, ignore_errors = True)
+
+
+# The unpickle path: pickle stores a processor by (module, qualname), so a spawn
+# worker rebuilds the class by IMPORTING the remote module, never through
+# `get_class_in_module`.
+
+
+def _remote_probe_package():
+ """A real package under the remote-code root, so its module name is realistic."""
+ import pathlib
+
+ from transformers.dynamic_module_utils import init_hf_modules
+ from transformers.utils import HF_MODULES_CACHE
+
+ # Puts HF_MODULES_CACHE on sys.path, or the spawn test errors on the harness.
+ init_hf_modules()
+
+ root = pathlib.Path(HF_MODULES_CACHE) / "transformers_modules"
+ package = root / "unsloth_spawn_probe"
+ package.mkdir(parents = True, exist_ok = True)
+ (root / "__init__.py").touch(exist_ok = True)
+ (package / "__init__.py").write_text("")
+ # The decorator is load-bearing: it is read while the CLASS BODY executes,
+ # as the real checkpoint's file does. Without it this probe passed while the
+ # loader still patched after delegating to the real `exec_module`.
+ (package / "image_processing_probe.py").write_text(
+ "import transformers.models.siglip2.image_processing_siglip2 as siglip2_ips\n"
+ "\n"
+ "class SpawnProbeImageProcessor(siglip2_ips.Siglip2ImageProcessor):\n"
+ " @siglip2_ips.filter_out_non_signature_kwargs()\n"
+ " def preprocess_like_2024(self, image):\n"
+ " image = self.rescale(image = image, scale = 1 / 255.0,\n"
+ " input_data_format = 'channels_last')\n"
+ " return self.normalize(image = image, mean = [0.5] * 3, std = [0.5] * 3,\n"
+ " input_data_format = 'channels_last')\n"
+ )
+ importlib.invalidate_caches()
+ return package, "transformers_modules.unsloth_spawn_probe.image_processing_probe"
+
+
+_SPAWN_CHILD = """
+import pickle, sys
+{preamble}
+import numpy as np
+# The modules root is handed over in argv rather than recomputed from the
+# environment. `init_hf_modules()` alone left the child with
+# ModuleNotFoundError: No module named 'transformers_modules' on CI, because
+# parent and child need not resolve HF_MODULES_CACHE to the same place, and the
+# test would then be measuring the harness.
+sys.path.insert(0, sys.argv[2])
+# Marks the preamble as survived, so a runner where `import unsloth` cannot
+# finish is told apart from a real failure of the thing under test.
+print("PREAMBLE_OK")
+with open(sys.argv[1], "rb") as handle:
+ processor = pickle.load(handle)
+image = np.arange(4 * 4 * 3, dtype = np.uint8).reshape(4, 4, 3)
+print("DTYPE", processor.preprocess_like_2024(image).dtype)
+"""
+
+
+def _run_spawn_child(pickled, preamble):
+ import subprocess
+ import sys
+
+ target, modules_root = pickled
+ return subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ _SPAWN_CHILD.format(preamble = preamble),
+ str(target),
+ str(modules_root),
+ ],
+ capture_output = True,
+ text = True,
+ )
+
+
+def pickled_remote_processor(tmp_path):
+ import pickle
+ import shutil
+ import sys
+
+ _unsloth_import_or_skip()
+ _backend_module()
+ siglip2 = _fresh_module(SIGLIP2)
+ if not _image_processing_reexports_are_missing(siglip2):
+ pytest.skip("this transformers still re-exports the image helpers")
+
+ package, module_name = _remote_probe_package()
+ try:
+ module = importlib.import_module(module_name)
+ target = tmp_path / "processor.pkl"
+ with open(target, "wb") as handle:
+ pickle.dump(module.SpawnProbeImageProcessor(), handle)
+ # The root the child must put on sys.path: the parent of the
+ # `transformers_modules` package, not the package itself.
+ yield target, package.parent.parent
+ finally:
+ shutil.rmtree(package, ignore_errors = True)
+ sys.modules.pop(module_name, None)
+
+
+def test_a_spawn_started_worker_rebuilds_a_patched_class(pickled_remote_processor):
+ """The finder's test: a fresh interpreter must still honour numpy."""
+ out = _run_spawn_child(pickled_remote_processor, "import unsloth")
+ # The sentinel, not a list of stderr strings: a CPU runner where the child
+ # has no accelerator for `import unsloth` says nothing about the finder,
+ # and sniffing for each way that can read leaves the real failure skipped
+ # too. Past the sentinel, every failure is this test's to report.
+ if "PREAMBLE_OK" not in out.stdout:
+ pytest.skip(f"the child could not import unsloth: {out.stderr.strip()[-400:]}")
+ assert out.returncode == 0, out.stderr[-2000:]
+ assert "DTYPE float32" in out.stdout, (out.stdout, out.stderr[-2000:])
+
+
+def test_a_spawn_started_worker_without_unsloth_is_the_documented_limit(pickled_remote_processor):
+ """Negative control: proves the finder is what fixes the test above.
+
+ Also pins the boundary honestly. A child that never imports unsloth is
+ unpatched, and the failure is loud rather than a silent dtype change.
+ """
+ out = _run_spawn_child(pickled_remote_processor, "")
+ assert "PREAMBLE_OK" in out.stdout, out.stderr[-2000:]
+ assert out.returncode != 0, out.stdout
+ # Either failure mode counts: unpatched, the child now dies earlier on the
+ # class-body decorator rather than later on numpy `normalize`, and pinning
+ # only the second would go red on the deeper break.
+ assert (
+ "filter_out_non_signature_kwargs" in out.stderr
+ or "Functional F.normalize" in out.stderr
+ or "numpy" in out.stderr
+ ), out.stderr[-2000:]
+
+
+def test_deepcopy_and_pickle_keep_the_override_in_process(pickled_remote_processor):
+ """Both keep `instance.__class__` by reference, so the patch travels with it."""
+ import copy
+ import pickle
+
+ np = pytest.importorskip("numpy")
+ with open(pickled_remote_processor[0], "rb") as handle:
+ processor = pickle.load(handle)
+ image = np.arange(4 * 4 * 3, dtype = np.uint8).reshape(4, 4, 3)
+
+ assert processor.preprocess_like_2024(image).dtype == np.float32
+ assert copy.deepcopy(processor).preprocess_like_2024(image).dtype == np.float32
+ revived = pickle.loads(pickle.dumps(processor))
+ assert revived.preprocess_like_2024(image).dtype == np.float32
diff --git a/tests/test_import_fixes_drift.py b/tests/test_import_fixes_drift.py
index e324c99e417..e3f63f94a3c 100644
--- a/tests/test_import_fixes_drift.py
+++ b/tests/test_import_fixes_drift.py
@@ -1714,6 +1714,100 @@ def test_a_per_layer_snapshot_never_becomes_a_scalar_rope_theta():
assert not isinstance(getattr(config, "rope_theta", None), dict)
+def test_the_torchvision_backend_still_breaks_the_4x_numpy_contract():
+ """DRIFT DETECTOR for the method shim: `normalize` refuses ndarray and
+ `rescale` silently returns float64 where 4.x returned float32. Both halves
+ are asserted; if upstream restores either, drop that entry from
+ `_LEGACY_NUMPY_IMAGE_METHODS` rather than wrap a method with itself.
+ """
+ transformers = pytest.importorskip("transformers")
+ np = pytest.importorskip("numpy")
+ from packaging.version import Version
+
+ if Version(transformers.__version__) < Version("5.0.0"):
+ pytest.skip("the torchvision backend does not exist before transformers 5")
+ # transformers' own probe, not `import torchvision`: an unusable wheel still
+ # imports while `tvF` goes unbound, and the backend then raises NameError.
+ backends = pytest.importorskip("transformers.image_processing_backends")
+ from transformers.utils import is_torchvision_available
+
+ if not is_torchvision_available() or not hasattr(backends, "tvF"):
+ pytest.skip("torchvision is not usable here, so the backend cannot run")
+ siglip2 = pytest.importorskip("transformers.models.siglip2.image_processing_siglip2")
+
+ processor = siglip2.Siglip2ImageProcessor()
+ image = np.arange(4 * 4 * 3, dtype = np.uint8).reshape(4, 4, 3)
+
+ rescaled = processor.rescale(
+ image = image,
+ scale = 1 / 255.0,
+ input_data_format = "channels_last",
+ )
+ assert rescaled.dtype == np.float64, (
+ "DRIFT DETECTED: BaseImageProcessor.rescale no longer returns float64 on numpy, so "
+ "the 4.x dtype contract may be back. Re-verify before keeping `rescale` in "
+ "`_LEGACY_NUMPY_IMAGE_METHODS`."
+ )
+
+ with pytest.raises(TypeError):
+ processor.normalize(
+ image = rescaled,
+ mean = [0.5, 0.5, 0.5],
+ std = [0.5, 0.5, 0.5],
+ input_data_format = "channels_last",
+ )
+
+
+def test_the_4x_numpy_helpers_the_method_shim_forwards_to_still_exist():
+ """DRIFT DETECTOR: the shim forwards to transformers' own 4.x functions.
+
+ Drop them upstream and there is no verified implementation left to restore,
+ so the shim must be reconsidered rather than reimplemented.
+ """
+ pytest.importorskip("transformers")
+ np = pytest.importorskip("numpy")
+ from transformers import image_transforms
+
+ image = np.arange(4 * 4 * 3, dtype = np.uint8).reshape(4, 4, 3)
+ for name in ("rescale", "normalize"):
+ assert callable(getattr(image_transforms, name, None)), (
+ f"DRIFT DETECTED: transformers.image_transforms.{name} is gone, so the numpy "
+ "image method shim has nothing to forward to."
+ )
+
+ rescaled = image_transforms.rescale(
+ image,
+ scale = 1 / 255.0,
+ input_data_format = "channels_last",
+ )
+ assert rescaled.dtype == np.float32, (
+ "DRIFT DETECTED: image_transforms.rescale stopped defaulting to float32, which is "
+ "the dtype the shim exists to restore."
+ )
+ normalized = image_transforms.normalize(
+ rescaled,
+ mean = [0.5, 0.5, 0.5],
+ std = [0.5, 0.5, 0.5],
+ input_data_format = "channels_last",
+ )
+ assert normalized.dtype == np.float32
+ assert normalized.shape == image.shape
+
+
+def test_the_numpy_image_method_shim_is_wired_into_the_remote_code_hook():
+ """The installer must be reachable from the hook, or real loads never see it."""
+ source = Path(__file__).resolve().parent.parent / "unsloth" / "import_fixes.py"
+ source = source.read_text(encoding = "utf-8")
+ assert "_install_legacy_numpy_image_methods_now(loaded)" in source, (
+ "DRIFT DETECTED: the numpy image method shim is defined but never called from the "
+ "get_class_in_module wrapper, so a checkpoint's own image processor is never patched."
+ )
+ assert "_install_remote_image_processor_finder()" in source, (
+ "DRIFT DETECTED: the meta path finder is never installed, so a spawn-started worker "
+ "rebuilds an unpatched class when it unpickles a processor."
+ )
+
+
# ===========================================================================
# transformers -- a submodule's prefix renaming leaks into the composite model
# ===========================================================================
diff --git a/unsloth/__init__.py b/unsloth/__init__.py
index f88b4d93a3c..d1f0a89e891 100644
--- a/unsloth/__init__.py
+++ b/unsloth/__init__.py
@@ -188,6 +188,17 @@ if _IS_MLX:
del _check_tf_deps
except Exception:
pass
+ try:
+ # Same reason: remote code reaches transformers' get_class_in_module on this platform
+ # too, and the wrap is what restores the image helpers transformers 5 stopped
+ # re-exporting. Costs nothing until a checkpoint's own modeling file is loaded.
+ from .import_fixes import (
+ fix_transformers5_image_processing_reexports as _fix_image_reexports,
+ )
+ _fix_image_reexports()
+ del _fix_image_reexports
+ except Exception:
+ pass
try:
import unsloth_zoo
except ImportError as _e:
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index a68e226000d..f64963526cb 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -245,6 +245,7 @@ from .device_type import arch_lacks_bf16, hip_visible_archs
from .import_fixes import (
fix_transformers5_bare_annotation_configs,
+ fix_transformers5_image_processing_reexports,
fix_transformers_composite_prefix_renaming,
fix_transformers_fully_masked_rows,
fix_transformers_rope_scaling_drops_theta,
@@ -306,6 +307,10 @@ del check_transformers_prequantized_vlm_quant_state
# RoPE base frequency. Ordered here, before any config is built, so the object-style delegation
# retry in models/llama.py sees a config that kept its base (#2405).
fix_transformers_rope_scaling_drops_theta()
+# Probe-gated and lazy: only wraps get_class_in_module, so the siglip image
+# modules are imported and patched when a checkpoint's own modeling file runs,
+# not on every `import unsloth`.
+fix_transformers5_image_processing_reexports()
fix_xformers_performance_issue()
# Must run AFTER fix_xformers_performance_issue (it rewrites xformers' cutlass.py on disk) and
# BEFORE models/_utils.py imports xformers.ops.
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index dd1e2cd895d..bed79e718a2 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -687,6 +687,776 @@ def fix_transformers5_bare_annotation_configs():
logger.info(f"Unsloth: Failed patching PretrainedConfig ({e})")
+# Where the image helpers that `modeling_*.py` files reach for actually live.
+# Ordered so the image modules win: `resize` exists in image_transforms and is
+# the one a preprocessor means, and `transformers.utils` is last because it is
+# broad enough to shadow a name by accident.
+_IMAGE_PROCESSING_SYMBOL_HOMES = (
+ "transformers.image_transforms",
+ "transformers.image_utils",
+ "transformers.image_processing_utils",
+ "transformers.feature_extraction_utils",
+ "transformers.utils",
+)
+
+# Vision backbones whose image-processing module third-party remote code imports
+# as a namespace (`import ... as siglip2_ips`) and then reads helpers off.
+_IMAGE_PROCESSING_MODULES = (
+ "transformers.models.siglip2.image_processing_siglip2",
+ "transformers.models.siglip.image_processing_siglip",
+)
+
+_IMAGE_REEXPORT_FLAG = "_unsloth_legacy_image_reexports"
+
+# Names this fix bound onto a module, so the patch can be fully undone: the
+# forwarder caches each hit with setattr, and removing only __getattr__ would
+# leave those bindings behind.
+_IMAGE_REEXPORT_BOUND = "_unsloth_legacy_image_bound"
+
+# One name per module that transformers 5 stopped re-exporting, used to decide
+# whether this environment is affected at all.
+_IMAGE_REEXPORT_PROBE = "filter_out_non_signature_kwargs"
+
+# Set on the wrapper AND on the module. The wrapper's copy is the one the guard reads.
+_GET_CLASS_PATCH_FLAG = "_unsloth_patched_get_class_in_module"
+
+
+def _image_processing_reexports_are_missing(module):
+ """Is this module missing the helpers remote code expects on it?
+
+ Asked of the live module rather than of a transformers version, because the
+ re-export lists were trimmed per model over several releases and a version
+ window would mislabel builds that lost them early or kept them late.
+ """
+ return not hasattr(module, _IMAGE_REEXPORT_PROBE)
+
+
+def _image_reexports_are_installed(module):
+ """Are the live bindings ours, right now?
+
+ Asked of the FUNCTIONS rather than of a flag on the module, for the reason
+ spelled out in `_sdpa_mask_is_patched`: `importlib.reload` re-runs the module
+ body in the EXISTING namespace, so every name the source assigns goes back to
+ upstream while anything we merely added survives. Measured on
+ `image_processing_siglip2`: the module-level `__getattr__` survives a reload
+ because the source never assigns it, but `convert_image_to_patches` and
+ `pad_along_first_dim` do not, so the numpy dispatch is silently gone while the
+ flag that would gate reinstalling it is still True.
+
+ Both halves must be live, so a half-installed module re-runs.
+ """
+ if not getattr(getattr(module, "__getattr__", None), _IMAGE_REEXPORT_FLAG, False):
+ return False
+ for name in _LEGACY_NUMPY_IMAGE_HELPERS:
+ current = getattr(module, name, None)
+ if current is not None and not getattr(current, "_unsloth_numpy_dispatch", False):
+ return False
+ return True
+
+
+def _install_legacy_image_reexports(module_name):
+ """Resolve dropped image helpers off `module_name` from their current homes.
+
+ A module-level ``__getattr__`` (PEP 562) rather than a fixed list of names:
+ the set that was dropped differs per transformers release, and a list
+ written today would miss the next one. Only names transformers still
+ defines somewhere resolve, so a genuine typo in remote code keeps raising
+ ``AttributeError`` instead of turning into a confusing failure later.
+ """
+ try:
+ module = importlib.import_module(module_name)
+ except Exception:
+ return False
+ if _image_reexports_are_installed(module):
+ return False
+ # A surviving forwarder answers for every missing name, so the probe below would report
+ # the re-exports as present and bail with the numpy half still unpatched. Reinstall just
+ # that half: reload wiped only the names the module body assigns.
+ if getattr(getattr(module, "__getattr__", None), _IMAGE_REEXPORT_FLAG, False):
+ try:
+ _install_legacy_numpy_image_helpers(module)
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping numpy image helper shim for {module_name} ({e})")
+ return True
+ if not _image_processing_reexports_are_missing(module):
+ return False
+
+ previous = getattr(module, "__getattr__", None)
+ bound = set()
+
+ def __getattr__(name):
+ # Dunders are looked up on the type for real modules; anything private
+ # is not a re-export, so leave both alone.
+ if not name.startswith("_"):
+ for home in _IMAGE_PROCESSING_SYMBOL_HOMES:
+ try:
+ source = importlib.import_module(home)
+ except Exception:
+ continue
+ if hasattr(source, name):
+ value = getattr(source, name)
+ # Bind it so later reads skip this lookup entirely.
+ setattr(module, name, value)
+ bound.add(name)
+ return value
+ if previous is not None:
+ return previous(name)
+ raise AttributeError(f"module {module_name!r} has no attribute {name!r}")
+
+ # Keep the original reachable, so the patch can be tested and undone.
+ __getattr__.__wrapped__ = previous
+ # On the function, so the guard above survives a reload of the module.
+ setattr(__getattr__, _IMAGE_REEXPORT_FLAG, True)
+ module.__getattr__ = __getattr__
+ setattr(module, _IMAGE_REEXPORT_FLAG, True)
+ setattr(module, _IMAGE_REEXPORT_BOUND, bound)
+ # Names that still resolve never reach __getattr__, so the ones whose
+ # contract changed from numpy to torch are handled separately.
+ try:
+ _install_legacy_numpy_image_helpers(module)
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping numpy image helper shim for {module_name} ({e})")
+ return True
+
+
+# Helpers transformers 5 KEPT on these modules but re-specified from numpy
+# (channel-last) to torch (channel-first). A module __getattr__ never fires for
+# a name that still resolves, so these need replacing rather than forwarding.
+# Phi-4-reasoning-vision-15B's modeling_phi4_visionr.py reaches both off the
+# siglip2 namespace at lines 347-348, having built numpy arrays at line 302, so
+# without this the class loads and then preprocessing fails:
+# "cannot reshape array of size 150528 into shape (224,14,16,0,16)".
+_IMAGE_REEXPORT_LEGACY_BOUND = "_unsloth_legacy_image_numpy_bound"
+
+
+def _legacy_convert_image_to_patches(image, patch_size):
+ """transformers 4.x semantics: (height, width, channels) numpy in."""
+ image_height, image_width, num_channels = image.shape
+ num_patches_height = image_height // patch_size
+ num_patches_width = image_width // patch_size
+ patched_image = image.reshape(
+ num_patches_height, patch_size, num_patches_width, patch_size, num_channels
+ )
+ patched_image = patched_image.transpose(0, 2, 1, 3, 4)
+ return patched_image.reshape(num_patches_height * num_patches_width, -1)
+
+
+def _legacy_pad_along_first_dim(
+ array,
+ target_length,
+ pad_value = 0,
+):
+ """transformers 4.x semantics: numpy in, numpy array and mask out."""
+ import numpy as np
+
+ current_length = array.shape[0]
+ padding_length = target_length - current_length
+ mask = np.ones((target_length,), dtype = np.int32)
+ if padding_length > 0:
+ paddings = [(0, padding_length)] + [(0, 0)] * (array.ndim - 1)
+ array = np.pad(array, paddings, mode = "constant", constant_values = pad_value)
+ mask[-padding_length:] = 0
+ return array, mask
+
+
+# The keyword the first argument goes by, per era. transformers 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 form names something the current
+# implementation does not accept at all.
+_LEGACY_NUMPY_IMAGE_HELPERS = {
+ "convert_image_to_patches": (_legacy_convert_image_to_patches, ("image",)),
+ "pad_along_first_dim": (_legacy_pad_along_first_dim, ("array", "tensor")),
+}
+
+
+def _install_legacy_numpy_image_helpers(module):
+ """Dispatch the retained helpers on the argument type.
+
+ A numpy array takes the 4.x implementation, anything else (a torch tensor)
+ goes to whatever the module already had, so transformers' OWN
+ Siglip2ImageProcessor keeps calling the current code unchanged. Replacing
+ them outright would fix the remote checkpoint by breaking the model the
+ module is named after.
+ """
+ import numpy as np
+
+ bound = []
+ for name, (legacy, first_names) in _LEGACY_NUMPY_IMAGE_HELPERS.items():
+ current = getattr(module, name, None)
+ if current is None or getattr(current, "_unsloth_numpy_dispatch", False):
+ continue
+
+ def make(
+ current = current,
+ legacy = legacy,
+ first_names = first_names,
+ ):
+ @functools.wraps(current)
+ def dispatch(*args, **kwargs):
+ # The first argument may arrive positionally or under either
+ # era's keyword, so check all of them before deciding.
+ first = args[0] if args else None
+ if first is None:
+ for key in first_names:
+ if key in kwargs:
+ first = kwargs[key]
+ break
+ if isinstance(first, np.ndarray):
+ # Normalise onto the 4.x keyword the legacy function names,
+ # so a caller using the current era's spelling still works.
+ if not args:
+ for key in first_names[1:]:
+ if key in kwargs:
+ kwargs = dict(kwargs)
+ kwargs[first_names[0]] = kwargs.pop(key)
+ break
+ return legacy(*args, **kwargs)
+ return current(*args, **kwargs)
+
+ dispatch.__wrapped__ = current
+ dispatch._unsloth_numpy_dispatch = True
+ return dispatch
+
+ setattr(module, name, make())
+ bound.append(name)
+ if bound:
+ setattr(module, _IMAGE_REEXPORT_LEGACY_BOUND, bound)
+ return bound
+
+
+def _remove_legacy_numpy_image_helpers(module):
+ for name in getattr(module, _IMAGE_REEXPORT_LEGACY_BOUND, ()):
+ current = getattr(module, name, None)
+ original = getattr(current, "__wrapped__", None)
+ if original is not None:
+ setattr(module, name, original)
+ try:
+ delattr(module, _IMAGE_REEXPORT_LEGACY_BOUND)
+ except AttributeError:
+ pass
+
+
+# The same numpy/torch split one level up: BACKEND METHODS on the class.
+# transformers 5 put a torchvision backend in every image processor's MRO, so a
+# remote-code subclass handing channel-last numpy to `self.normalize` raises.
+# `rescale` is the quieter half and the reason this cannot gate on exceptions:
+# it accepts numpy and returns float64 where 4.x returned float32, so patching
+# only the raising method leaves pixel_values float64 with nothing raised.
+_IMAGE_METHOD_PATCH_FLAG = "_unsloth_numpy_image_method"
+
+# Names installed on a class, so the patch can be fully undone.
+_IMAGE_METHOD_BOUND = "_unsloth_numpy_image_methods"
+
+# Where transformers puts every module it builds out of a checkpoint's own code.
+_REMOTE_IMAGE_MODULE_PREFIX = "transformers_modules."
+
+# Every transformers image processor descends from one of these. Matched by NAME
+# on the already-loaded MRO rather than by isinstance, so classifying the configs
+# and models that also come through `get_class_in_module` costs a string compare
+# and imports nothing.
+_IMAGE_PROCESSOR_BASE_NAMES = frozenset(
+ (
+ "ImageProcessingMixin",
+ "BaseImageProcessor",
+ "BaseImageProcessorFast",
+ )
+)
+
+
+def _legacy_rescale(
+ self,
+ image,
+ scale,
+ data_format = None,
+ input_data_format = None,
+ **kwargs,
+):
+ """transformers 4.x `BaseImageProcessor.rescale`, which was this and nothing else.
+
+ BY KEYWORD: the function's 4th positional is `dtype` and the method's was
+ `input_data_format`, so a positional splat crosses them.
+ """
+ from transformers.image_transforms import rescale
+ return rescale(
+ image,
+ scale = scale,
+ data_format = data_format,
+ input_data_format = input_data_format,
+ **kwargs,
+ )
+
+
+def _legacy_normalize(
+ self,
+ image,
+ mean,
+ std,
+ data_format = None,
+ input_data_format = None,
+ **kwargs,
+):
+ """transformers 4.x `BaseImageProcessor.normalize`, which was this and nothing else."""
+ from transformers.image_transforms import normalize
+ return normalize(
+ image,
+ mean = mean,
+ std = std,
+ data_format = data_format,
+ input_data_format = input_data_format,
+ **kwargs,
+ )
+
+
+# name -> (4.x implementation, kwargs valid on a probe image). Only methods that
+# were THIN PASSTHROUGHS to the identically named `image_transforms` function in
+# 4.x, so the legacy half is transformers' own code. `resize`, `center_crop` and
+# `pad` are absent because their 4.x methods converted a dict `size` first, so
+# forwarding them is not signature compatible; `convert_to_rgb` was never a 4.x
+# method and is already bit-identical on numpy.
+_LEGACY_NUMPY_IMAGE_METHODS = {
+ "rescale": (_legacy_rescale, {"scale": 1.0 / 255.0}),
+ "normalize": (_legacy_normalize, {"mean": [0.5, 0.5, 0.5], "std": [0.5, 0.5, 0.5]}),
+}
+
+
+def _is_remote_image_processor_class(obj):
+ """Is this an image processor defined by a checkpoint's own code?
+
+ Names and module strings off the in-memory MRO, no imports, since every
+ config and model class comes through the same hook. The `transformers.`
+ exclusion is the hard guarantee that a base class is never touched.
+ """
+ if not isinstance(obj, type):
+ return False
+ module = getattr(obj, "__module__", "") or ""
+ if module == "transformers" or module.startswith("transformers."):
+ return False
+ try:
+ mro = obj.__mro__
+ except Exception:
+ return False
+ for base in mro:
+ base_module = getattr(base, "__module__", "") or ""
+ if base_module.startswith("transformers.") and base.__name__ in _IMAGE_PROCESSOR_BASE_NAMES:
+ return True
+ return False
+
+
+def _resolved_image_method(cls, name):
+ """The class that owns `name`, and the function it owns.
+
+ Where it came from is the rule: a method the remote code wrote itself is
+ never ours to replace, and `getattr` alone cannot tell.
+ """
+ try:
+ mro = cls.__mro__
+ except Exception:
+ return None, None
+ for base in mro:
+ if name in base.__dict__:
+ return base, base.__dict__[name]
+ return None, None
+
+
+def _numpy_image_method_needs_legacy(cls, name, legacy, probe_kwargs):
+ """Does the live method still behave like transformers 4.x on numpy?
+
+ The gate, and the only reason this is a no-op on 4.57.6. Equivalence, not
+ acceptance, and by CALLING both on a real array rather than comparing
+ versions: the backend arrived per model over several releases. `object.__new__`
+ gives a receiver without `__init__`, which could read files; the probed
+ methods are pure.
+ """
+ import numpy as np
+
+ image = np.arange(2 * 2 * 3, dtype = np.uint8).reshape(2, 2, 3)
+ kwargs = dict(probe_kwargs)
+ # Stated rather than inferred, so the two calls cannot disagree about layout.
+ kwargs["input_data_format"] = "channels_last"
+ try:
+ probe_self = object.__new__(cls)
+ except Exception:
+ return False
+ try:
+ expected = legacy(probe_self, image.copy(), **kwargs)
+ except Exception:
+ return False # no 4.x contract available here, so there is nothing to restore
+ try:
+ actual = getattr(cls, name)(probe_self, image.copy(), **kwargs)
+ except Exception:
+ return True # rejects numpy outright: the loud half
+ if not isinstance(actual, np.ndarray):
+ return True
+ if actual.dtype != expected.dtype or actual.shape != expected.shape:
+ return True # the quiet half: right numbers, wrong dtype
+ try:
+ return not np.allclose(actual, expected, rtol = 1e-5, atol = 1e-6)
+ except Exception:
+ return True
+
+
+def _install_legacy_numpy_image_methods(cls):
+ """Dispatch ONE remote class's backend methods on the argument type.
+
+ Set on the remote subclass only: numpy takes the 4.x implementation,
+ anything else goes to whatever the class resolved before, so transformers'
+ own Siglip2ImageProcessor is unreachable from here rather than merely
+ unpatched.
+ """
+ import numpy as np
+
+ if not _is_remote_image_processor_class(cls):
+ return []
+
+ bound = []
+ for name, (legacy, probe_kwargs) in _LEGACY_NUMPY_IMAGE_METHODS.items():
+ owner, current = _resolved_image_method(cls, name)
+ if current is None:
+ continue
+ # Read off the LIVE descriptor, per `_sdpa_mask_is_patched`: a class
+ # flag outlives what it describes. Also makes a subclass a no-op.
+ if getattr(current, _IMAGE_METHOD_PATCH_FLAG, False):
+ continue
+ owner_module = getattr(owner, "__module__", "") or ""
+ if not owner_module.startswith("transformers."):
+ continue # the remote code wrote this one itself
+ if not _numpy_image_method_needs_legacy(cls, name, legacy, probe_kwargs):
+ continue # transformers 4.x, or a transformers 5 that already honours numpy
+
+ def make(current = current, legacy = legacy):
+ @functools.wraps(current)
+ def dispatch(self, image, *args, **kwargs):
+ # `image` is the parameter name in BOTH eras, so the keyword form
+ # remote code uses (`self.normalize(image=..., mean=...)`) binds
+ # here exactly as the positional one does.
+ if isinstance(image, np.ndarray):
+ return legacy(self, image, *args, **kwargs)
+ return current(self, image, *args, **kwargs)
+
+ # Keep the original reachable, so the patch can be tested and undone.
+ dispatch.__wrapped__ = current
+ # AFTER functools.wraps, which copies the wrapped function's __dict__
+ # and would otherwise be able to drop the mark. Do not reorder.
+ setattr(dispatch, _IMAGE_METHOD_PATCH_FLAG, True)
+ return dispatch
+
+ try:
+ setattr(cls, name, make())
+ except Exception as e:
+ logger.info(f"Unsloth: Could not shim {cls.__name__}.{name} ({e})")
+ continue
+ bound.append(name)
+
+ if bound:
+ try:
+ setattr(cls, _IMAGE_METHOD_BOUND, tuple(bound))
+ except Exception:
+ pass
+ logger.info(
+ "Unsloth: Restoring transformers 4.x numpy image processing on "
+ f"{cls.__module__}.{cls.__qualname__} ({', '.join(bound)})"
+ )
+ return bound
+
+
+def _remove_legacy_numpy_image_methods(cls):
+ """Undo `_install_legacy_numpy_image_methods`.
+
+ `delattr`, not a restoring `setattr`: the method was always inherited, so
+ putting it back on the subclass would leave the class owning its base's
+ function and the next install would refuse to touch it.
+ """
+ removed = []
+ for name in tuple(cls.__dict__.get(_IMAGE_METHOD_BOUND, ())):
+ current = cls.__dict__.get(name)
+ if not getattr(current, _IMAGE_METHOD_PATCH_FLAG, False):
+ continue
+ try:
+ delattr(cls, name)
+ except AttributeError:
+ continue
+ removed.append(name)
+ try:
+ delattr(cls, _IMAGE_METHOD_BOUND)
+ except AttributeError:
+ pass
+ return removed
+
+
+def _install_legacy_numpy_image_methods_on_module(module):
+ """Patch every remote image processor a freshly executed module defines.
+
+ Only classes this module itself defined, so a remote file that imports
+ `Siglip2ImageProcessor` to subclass it does not get the base patched.
+ """
+ bound = []
+ for value in list(vars(module).values()):
+ if not isinstance(value, type):
+ continue
+ if getattr(value, "__module__", None) != getattr(module, "__name__", None):
+ continue
+ try:
+ bound.extend(_install_legacy_numpy_image_methods(value))
+ except Exception as e:
+ logger.info(f"Unsloth: numpy image method shim skipped for {value!r} ({e})")
+ return bound
+
+
+def _install_legacy_numpy_image_methods_now(loaded = None):
+ """Patch the module `loaded` came from, and every remote module alongside it.
+
+ The class itself is not enough: an image processor is usually defined beside
+ the model and read off the module, so it never comes through the hook. Both
+ halves are needed -- the sweep catches a sibling imported earlier in the same
+ load, `loaded` catches code placed outside `transformers_modules`.
+ """
+ seen = set()
+ bound = []
+ targets = []
+ loaded_module = sys.modules.get(getattr(loaded, "__module__", None) or "")
+ if loaded_module is not None:
+ targets.append(loaded_module)
+ for module_name, module in list(sys.modules.items()):
+ if module is not None and module_name.startswith(_REMOTE_IMAGE_MODULE_PREFIX):
+ targets.append(module)
+ for module in targets:
+ if id(module) in seen:
+ continue
+ seen.add(id(module))
+ try:
+ bound.extend(_install_legacy_numpy_image_methods_on_module(module))
+ except Exception as e:
+ logger.info(f"Unsloth: numpy image method shim skipped for {module!r} ({e})")
+ return bound
+
+
+def _remove_legacy_image_reexports(module_name):
+ """Undo `_install_legacy_image_reexports`, including the cached bindings."""
+ module = sys.modules.get(module_name)
+ if module is None or not getattr(module, _IMAGE_REEXPORT_FLAG, False):
+ return False
+ _remove_legacy_numpy_image_helpers(module)
+ for name in getattr(module, _IMAGE_REEXPORT_BOUND, ()): # drop cached hits
+ try:
+ delattr(module, name)
+ except AttributeError:
+ pass
+ previous = getattr(module.__getattr__, "__wrapped__", None)
+ if previous is None:
+ try:
+ del module.__getattr__
+ except AttributeError:
+ pass
+ else:
+ module.__getattr__ = previous
+ for attr in (_IMAGE_REEXPORT_FLAG, _IMAGE_REEXPORT_BOUND):
+ try:
+ delattr(module, attr)
+ except AttributeError:
+ pass
+ return True
+
+
+def _install_legacy_image_reexports_now():
+ """Patch every target module, importing the ones not yet loaded."""
+ patched = []
+ for module_name in _IMAGE_PROCESSING_MODULES:
+ try:
+ if _install_legacy_image_reexports(module_name):
+ patched.append(module_name.rsplit(".", 1)[-1])
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping image re-export fix for {module_name} ({e})")
+ if patched:
+ logger.info(
+ "Unsloth: Restoring transformers 4.x image processing re-exports on "
+ + ", ".join(patched)
+ )
+ return patched
+
+
+_REMOTE_IMAGE_FINDER_SENTINEL = "_unsloth_remote_image_processor_finder"
+
+
+class _RemoteImageProcessorLoader:
+ """Wraps the real loader so a remote module is patched as soon as it executes."""
+
+ def __init__(self, loader):
+ self._loader = loader
+
+ def create_module(self, spec):
+ create = getattr(self._loader, "create_module", None)
+ if create is None:
+ return None
+ return create(spec)
+
+ def exec_module(self, module):
+ # BEFORE delegating: `exec_module` runs the module body, and a
+ # checkpoint reads the dropped re-exports while its CLASS BODY executes,
+ # so patching afterwards is already too late.
+ try:
+ _install_legacy_image_reexports_now()
+ except Exception:
+ pass
+ self._loader.exec_module(module)
+ # After, because the classes do not exist until the body has run.
+ try:
+ _install_legacy_numpy_image_methods_on_module(module)
+ except Exception:
+ pass
+
+ def __getattr__(self, attribute):
+ return getattr(self._loader, attribute)
+
+
+class _RemoteImageProcessorFinder(importlib.abc.MetaPathFinder):
+ """Inserted at the FRONT of sys.meta_path: the module really exists on disk.
+
+ The one path `get_class_in_module` cannot cover: pickle stores a processor by
+ (module, qualname), so a spawn worker IMPORTS the remote module to rebuild
+ the class. A string compare per import, then out of the way.
+ """
+
+ __slots__ = (_REMOTE_IMAGE_FINDER_SENTINEL, "_finding")
+
+ def __init__(self):
+ setattr(self, _REMOTE_IMAGE_FINDER_SENTINEL, True)
+ # find_spec below walks sys.meta_path again, so it has to know it is
+ # already inside itself. Thread-local, not a plain attribute: two
+ # threads importing remote modules at once (a threaded DataLoader is
+ # the realistic case) would otherwise read each other's flag, and the
+ # loser is handed back an UNPATCHED module with nothing raised.
+ self._finding = threading.local()
+
+ def find_spec(
+ self,
+ fullname,
+ path = None,
+ target = None,
+ ):
+ if getattr(self._finding, "active", False):
+ return None
+ if not fullname.startswith(_REMOTE_IMAGE_MODULE_PREFIX):
+ return None
+ self._finding.active = True
+ try:
+ spec = importlib.util.find_spec(fullname)
+ except Exception:
+ return None
+ finally:
+ self._finding.active = False
+ if spec is None or spec.loader is None:
+ return None
+ if not hasattr(spec.loader, "exec_module"):
+ return None # a loader from before PEP 451; leave the import entirely alone
+ try:
+ spec.loader = _RemoteImageProcessorLoader(spec.loader)
+ except Exception:
+ return None
+ return spec
+
+
+def _install_remote_image_processor_finder():
+ """Install the unpickle-path finder once.
+
+ At `import unsloth` time, not on first patch: in a spawn child nothing is
+ patched before the unpickle import, so a lazy finder would not yet exist.
+ """
+ for finder in sys.meta_path:
+ if getattr(finder, _REMOTE_IMAGE_FINDER_SENTINEL, False):
+ return False
+ sys.meta_path.insert(0, _RemoteImageProcessorFinder())
+ return True
+
+
+def fix_transformers5_image_processing_reexports():
+ """Let remote-code image processors keep reading helpers off siglip modules.
+
+ transformers 5 stopped re-exporting the generic image helpers
+ (``filter_out_non_signature_kwargs``, ``resize``, ``to_numpy_array``,
+ ``ChannelDimension`` and friends) from each model's ``image_processing_*``
+ module. Remote code pinned to the 4.x layout does
+ ``import transformers.models.siglip2.image_processing_siglip2 as siglip2_ips``
+ and then uses ``@siglip2_ips.filter_out_non_signature_kwargs()`` at class
+ definition time, so the import raises ``AttributeError`` and the model
+ cannot be loaded at all. microsoft/Phi-4-reasoning-vision-15B is one such
+ checkpoint.
+
+ The helpers themselves were not removed, only the re-exports, so this
+ forwards attribute reads to wherever transformers keeps them now. No-op on
+ transformers 4.x, where the names are still there.
+
+ Applied when remote code is about to run rather than at import: plain
+ ``import transformers`` does not pull in the siglip2 image-processing
+ module, and importing it eagerly to patch it costs every user about three
+ seconds of PIL and torchvision setup for a checkpoint they may never load.
+ """
+ try:
+ import transformers
+ if Version(transformers.__version__) < Version("5.0.0"):
+ return
+ from transformers import dynamic_module_utils
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping image processing re-export fix ({e})")
+ return
+
+ # Before anything else, because the path it covers is an import in a CHILD
+ # process, where nothing has run yet: pickle rebuilds a processor by
+ # importing the remote module directly, never through get_class_in_module.
+ try:
+ _install_remote_image_processor_finder()
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping remote image processor finder ({e})")
+
+ # Anything already imported can be fixed right now for free.
+ for module_name in _IMAGE_PROCESSING_MODULES:
+ if module_name in sys.modules:
+ try:
+ _install_legacy_image_reexports(module_name)
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping image re-export fix for {module_name} ({e})")
+
+ # Asked of the live FUNCTION, not of the module flag: `importlib.reload` re-runs the
+ # module body in the existing namespace, so `get_class_in_module` goes back to upstream
+ # while any attribute we added survives. Gating on the flag would then refuse to re-wrap
+ # a module that is once again unpatched, which is the opposite of what an idempotence
+ # guard is for. Same reasoning as `_sdpa_mask_is_patched` below.
+ original = getattr(dynamic_module_utils, "get_class_in_module", None)
+ if original is None:
+ return
+ if getattr(original, _GET_CLASS_PATCH_FLAG, False):
+ return
+
+ @functools.wraps(original)
+ def get_class_in_module(*args, **kwargs):
+ # Runs immediately before a checkpoint's own modeling file is executed,
+ # which is the only place the missing re-exports are read.
+ try:
+ _install_legacy_image_reexports_now()
+ except Exception as e:
+ logger.info(f"Unsloth: image re-export fix skipped ({e})")
+ loaded = original(*args, **kwargs)
+ # Now the checkpoint's own modules exist, which is the only place the
+ # numpy backend methods can be corrected without touching transformers'
+ # own. The module sweep rather than `loaded` alone, because an image
+ # processor is usually defined beside the model and read off the module,
+ # so it never comes through here itself.
+ try:
+ _install_legacy_numpy_image_methods_now(loaded)
+ except Exception as e:
+ logger.info(f"Unsloth: numpy image method shim skipped ({e})")
+ return loaded
+
+ # Keep the original reachable, so the patch can be tested and undone.
+ get_class_in_module.__wrapped__ = original
+ # On the function, so the guard above survives a reload of the module.
+ setattr(get_class_in_module, _GET_CLASS_PATCH_FLAG, True)
+ try:
+ dynamic_module_utils.get_class_in_module = get_class_in_module
+ setattr(dynamic_module_utils, _GET_CLASS_PATCH_FLAG, True)
+ except Exception as e:
+ logger.info(f"Unsloth: Failed patching get_class_in_module ({e})")
+
+
_SDPA_MASK_PATCH_FLAG = "_unsloth_patched_sdpa_mask"