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.

Load prequantized multimodal checkpoints correctly on transformers 5.4 and 5.5 (#11452)

Daniel Han151517f44fc2
diff --git a/tests/test_composite_prefix_renaming.py b/tests/test_composite_prefix_renaming.py
new file mode 100644
index 00000000000..5fa7973bf9d
--- /dev/null
+++ b/tests/test_composite_prefix_renaming.py
@@ -0,0 +1,759 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A submodule's prefix renaming must not be applied to the composite model.
+
+transformers 5.4.0 (PR #44300) made `get_model_conversion_mapping` recurse into
+`PreTrainedModel` submodules and merge their conversion mappings into the parent's.
+The standalone Qwen3.5 / Qwen3.5-MoE / Gemma 3n text models register
+`^model.language_model.` -> `^model.`, which is correct for themselves and wrong for
+the composite model whose weights really are named `model.language_model....`. Renamings
+run before the bitsandbytes converter, so a pre-quantized checkpoint loses every
+`absmax` / `quant_map` / `nested_absmax` / `nested_quant_map` /
+`quant_state.bitsandbytes__nf4` sidecar and every `Linear4bit` comes back with
+`quant_state is None`: measured 352 of 352 on `unsloth/qwen3.8-27b-unsloth-bnb-4bit` and
+439 of 439 on `unsloth/gemma-3n-E2B-it-unsloth-bnb-4bit`, at 5.4.0 and at 5.5.4.
+Upstream fixed it in 5.6.0 with PR #45567.
+
+Every test here drives the real functions against a real transformers model built on the
+meta device, so nothing asserts on a hand-written mapping that the code did not produce.
+The pathology tests are conditioned on what the installed transformers actually does, not
+on its version number: on a build that leaks they prove the fix removes the leak, and on a
+build that does not leak they prove the fix leaves it alone.
+"""
+
+import sys
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("transformers")
+
+from unsloth.import_fixes import ( # noqa: E402
+ _COMPOSITE_PREFIX_RENAMING_FLAG,
+ _leaked_submodule_prefix_renamings,
+ _prefixed_pattern,
+ _renaming_destroys_keys,
+ _renaming_signature,
+ _rescope_conversions,
+ _rescoped_renaming,
+ _transformers_rescopes_submodule_prefix_renamings,
+ fix_transformers_composite_prefix_renaming,
+)
+
+
+def _weight_renaming():
+ """transformers 4.x has no `core_model_loading`, and so no pathology to test."""
+ try:
+ from transformers.core_model_loading import WeightRenaming
+ except Exception:
+ pytest.skip("this transformers has no core_model_loading.WeightRenaming")
+ return WeightRenaming
+
+
+def _conversion_mapping():
+ try:
+ from transformers import conversion_mapping
+ except Exception:
+ pytest.skip("this transformers has no conversion_mapping module")
+ if not hasattr(conversion_mapping, "get_model_conversion_mapping"):
+ pytest.skip("this transformers has no get_model_conversion_mapping")
+ return conversion_mapping
+
+
+def _unpatched_mapping_fn():
+ """The upstream function, underneath every wrapper installed over it.
+
+ `__wrapped__` alone is not enough: unsloth_zoo patches the same function
+ (`temporary_patches/moe_utils_bnb4bit.patch_bnb4bit_model_conversion_mapping`, which
+ prepends per-expert converters for quantized MoE) and keeps its original in a closure
+ cell rather than in `__wrapped__`. A test that stopped at the first wrapper would be
+ measuring this fix through this fix, and would report no pathology on a transformers
+ that really has one.
+ """
+ fn = _conversion_mapping().get_model_conversion_mapping
+ seen = set()
+ while id(fn) not in seen:
+ seen.add(id(fn))
+ nxt = getattr(fn, "__wrapped__", None)
+ if nxt is None:
+ for cell in getattr(fn, "__closure__", None) or ():
+ try:
+ candidate = cell.cell_contents
+ except ValueError:
+ continue
+ if callable(candidate) and getattr(candidate, "__name__", "") == (
+ "get_model_conversion_mapping"
+ ):
+ nxt = candidate
+ break
+ if nxt is None:
+ return fn
+ fn = nxt
+ return fn
+
+
+def _meta_model(model_type, shrink, auto_class):
+ """A real transformers model with no memory behind it.
+
+ Built on `meta` so a composite multimodal model costs milliseconds and no VRAM. Its
+ parameter NAMES are the entire subject of this fix, and those are identical to a
+ materialised model's.
+ """
+ import transformers
+ from transformers.models.auto.configuration_auto import CONFIG_MAPPING
+
+ if model_type not in CONFIG_MAPPING:
+ pytest.skip(f"this transformers has no {model_type} model type")
+ factory = getattr(transformers, auto_class, None)
+ if factory is None:
+ pytest.skip(f"this transformers has no {auto_class}")
+ config = CONFIG_MAPPING[model_type]()
+ shrink(config)
+ try:
+ with torch.device("meta"):
+ return factory.from_config(config)
+ except Exception as exc:
+ pytest.skip(f"cannot build a meta {model_type}: {exc!r}")
+
+
+def _shrink_qwen3_5(config):
+ text = config.text_config
+ text.num_hidden_layers = 2
+ text.layer_types = ["linear_attention", "full_attention"]
+ if hasattr(text, "mtp_num_hidden_layers"):
+ text.mtp_num_hidden_layers = 0
+ config.vision_config.depth = 1
+
+
+def composite_model():
+ """A composite Qwen3.5: a text `PreTrainedModel` nested under `model.language_model`."""
+ model = _meta_model("qwen3_5", _shrink_qwen3_5, "AutoModelForImageTextToText")
+ names = {name for name, _ in model.named_parameters(remove_duplicate = False)}
+ assert any(
+ name.startswith("model.language_model.") for name in names
+ ), "this model is not the nested shape the fix is about"
+ return model
+
+
+def standalone_text_model():
+ """The model the offending renaming was actually written for."""
+ from transformers.models.auto.configuration_auto import CONFIG_MAPPING
+
+ if "qwen3_5_text" not in CONFIG_MAPPING:
+ pytest.skip("this transformers has no qwen3_5_text model type")
+ config = CONFIG_MAPPING["qwen3_5_text"]()
+ config.num_hidden_layers = 2
+ config.layer_types = ["linear_attention", "full_attention"]
+ if hasattr(config, "mtp_num_hidden_layers"):
+ config.mtp_num_hidden_layers = 0
+ try:
+ from transformers import AutoModelForCausalLM
+ with torch.device("meta"):
+ return AutoModelForCausalLM.from_config(config)
+ except Exception as exc:
+ pytest.skip(f"cannot build a meta qwen3_5_text: {exc!r}")
+
+
+def _destructive_renamings(model, conversions):
+ """Which of `conversions` rewrite this model's own parameter names off the map?
+
+ This is the pathology itself, measured rather than assumed: it is what makes the
+ bitsandbytes sidecars land on keys the model does not have.
+ """
+ WeightRenaming = _weight_renaming()
+
+ keys = {name for name, _ in model.named_parameters(remove_duplicate = False)}
+ keys |= {name for name, _ in model.named_buffers(remove_duplicate = False)}
+ found = []
+ for conversion in conversions:
+ if not isinstance(conversion, WeightRenaming):
+ continue
+ for key in sorted(keys):
+ renamed, matched = conversion.rename_source_key(key)
+ if matched is not None and renamed != key and renamed not in keys:
+ found.append((conversion, key, renamed))
+ break
+ return found
+
+
+# --- the pattern helpers -----------------------------------------------------------
+
+
+def test_prefixed_pattern_keeps_a_start_anchor_anchored():
+ assert _prefixed_pattern("^model.language_model.", "model.language_model") == (
+ "^model.language_model.model.language_model."
+ )
+
+
+def test_prefixed_pattern_does_not_invent_an_anchor():
+ assert _prefixed_pattern("model.", "model.language_model") == "model.language_model.model."
+
+
+def test_signature_reads_the_unprocessed_patterns_when_they_are_kept():
+ """`__post_init__` rewrites the live patterns, so two copies must still compare equal."""
+ WeightRenaming = _weight_renaming()
+
+ one = WeightRenaming(source_patterns = r"^a.b.", target_patterns = r"^a.(?!b.)")
+ two = WeightRenaming(source_patterns = r"^a.b.", target_patterns = r"^a.(?!b.)")
+ assert _renaming_signature(one) == _renaming_signature(two)
+ assert _renaming_signature(one) != _renaming_signature(
+ WeightRenaming(source_patterns = r"^a.c.", target_patterns = r"^a.(?!c.)")
+ )
+
+
+# --- the discriminator -------------------------------------------------------------
+
+
+def test_a_renaming_that_lands_on_a_real_key_is_not_destructive():
+ WeightRenaming = _weight_renaming()
+
+ renaming = WeightRenaming(source_patterns = r"^old.", target_patterns = "new.")
+ assert not _renaming_destroys_keys(renaming, ["old.w"], {"new.w"})
+
+
+def test_a_renaming_that_lands_off_the_map_is_destructive():
+ WeightRenaming = _weight_renaming()
+
+ renaming = WeightRenaming(source_patterns = r"^old.", target_patterns = "new.")
+ assert _renaming_destroys_keys(renaming, ["old.w"], {"old.w"})
+
+
+def test_a_renaming_that_matches_nothing_is_not_destructive():
+ """The standalone case in miniature: the entry exists for checkpoint keys, not model keys."""
+ WeightRenaming = _weight_renaming()
+
+ renaming = WeightRenaming(source_patterns = r"^old.", target_patterns = "new.")
+ assert not _renaming_destroys_keys(renaming, ["other.w"], {"other.w"})
+
+
+def test_one_landing_on_a_real_key_outvotes_the_rest():
+ WeightRenaming = _weight_renaming()
+
+ renaming = WeightRenaming(source_patterns = r"^old.", target_patterns = "new.")
+ assert not _renaming_destroys_keys(renaming, ["old.a", "old.b"], {"new.a"})
+
+
+# --- the re-scoping ----------------------------------------------------------------
+
+
+def test_rescoped_renaming_matches_upstreams_doubled_prefix_semantics():
+ """What `PrefixChange.with_submodel_prefix` produces, on a transformers without one."""
+ WeightRenaming = _weight_renaming()
+
+ renaming = WeightRenaming(
+ source_patterns = r"^model.language_model.", target_patterns = r"^model.(?!language_model.)"
+ )
+ real = "model.language_model.layers.0.mlp.up_proj.weight"
+ doubled = "model.language_model.model.language_model.layers.0.mlp.up_proj.weight"
+ rescoped = _rescoped_renaming(renaming, "model.language_model", [real], {real})
+ assert rescoped is not None
+ assert rescoped.rename_source_key(real) == (real, None)
+ assert rescoped.rename_source_key(doubled)[0] == (
+ "model.language_model.model.layers.0.mlp.up_proj.weight"
+ )
+
+
+def test_rescoping_refuses_a_replacement_that_is_still_destructive():
+ """An unanchored renaming cannot be scoped away, and must not be claimed to be."""
+ WeightRenaming = _weight_renaming()
+
+ renaming = WeightRenaming(source_patterns = r"\.gate\.", target_patterns = ".router.")
+ key = "model.language_model.layers.0.gate.weight"
+ assert _rescoped_renaming(renaming, "model.language_model", [key], {key}) is None
+
+
+# --- the composite model, end to end -----------------------------------------------
+
+
+def test_the_probe_agrees_with_what_this_transformers_really_does(composite_model):
+ """The install gate must answer for the behaviour, on whatever version is installed."""
+ conversions = _unpatched_mapping_fn()(composite_model)
+ leaks = _destructive_renamings(composite_model, conversions)
+ rescopes = _transformers_rescopes_submodule_prefix_renamings()
+ assert bool(leaks) != bool(rescopes), (
+ f"probe says rescopes={rescopes} but the real mapping "
+ f"{'does' if leaks else 'does not'} rewrite this model's own weight names "
+ f"({[(c.source_patterns, k, r) for c, k, r in leaks]})"
+ )
+
+
+def test_rescoping_removes_every_destructive_renaming_from_a_composite(composite_model):
+ """The fix itself: after `_rescope_conversions`, nothing rewrites a real key off the map.
+
+ Fails on an unfixed transformers without the patch -- that is the whole point -- and
+ passes on a fixed one, where the input already had no leak and the output is the input.
+ """
+ conversions = _unpatched_mapping_fn()(composite_model)
+ rescoped = _rescope_conversions(composite_model, conversions)
+ assert _destructive_renamings(composite_model, rescoped) == []
+
+
+def test_rescoping_keeps_every_conversion_that_was_not_destructive(composite_model):
+ """Only the leaked entries may change: everything else must come back identical."""
+ conversions = _unpatched_mapping_fn()(composite_model)
+ leaked, _ = _leaked_submodule_prefix_renamings(composite_model)
+ rescoped = _rescope_conversions(composite_model, conversions)
+
+ kept = [c for c in conversions if _renaming_signature(c) not in leaked]
+ survivors = [_renaming_signature(c) for c in rescoped]
+ for conversion in kept:
+ assert _renaming_signature(conversion) in survivors
+ assert len(rescoped) == len(conversions)
+
+
+def test_the_standalone_text_model_keeps_its_own_renaming(standalone_text_model):
+ """The entry belongs to this model, and the fix must never take it away.
+
+ `^model.language_model.` -> `^model.` is how the standalone text model reads a
+ checkpoint saved from the composite one. Fired against its own weight names it matches
+ nothing, which is exactly why the discriminator leaves it alone.
+ """
+ conversions = _unpatched_mapping_fn()(standalone_text_model)
+ leaked, _ = _leaked_submodule_prefix_renamings(standalone_text_model)
+ assert leaked == {}
+ rescoped = _rescope_conversions(standalone_text_model, conversions)
+ assert [_renaming_signature(c) for c in rescoped] == [
+ _renaming_signature(c) for c in conversions
+ ]
+
+
+def test_a_non_composite_model_is_untouched():
+ """A flat text-only model has no nested `PreTrainedModel`, so there is nothing to leak."""
+ model = _meta_model(
+ "llama", lambda config: setattr(config, "num_hidden_layers", 2), "AutoModelForCausalLM"
+ )
+ conversions = _unpatched_mapping_fn()(model)
+ leaked, _ = _leaked_submodule_prefix_renamings(model)
+ assert leaked == {}
+ assert _rescope_conversions(model, conversions) is conversions
+
+
+# --- installation ------------------------------------------------------------------
+
+
+def forced_install(monkeypatch):
+ """Open the gate so the tests of what installation DOES are never vacuous.
+
+ Outside the defect window the probe declines, which is the right answer and is what
+ `test_installation_is_gated_on_the_probe` measures. It also meant every test of the
+ installation itself either skipped or, worse, passed on a release where the code it
+ names never ran: the sweep tests below reported green on 5.17.0 without sweeping
+ anything. Forcing the gate open keeps the two questions apart -- whether to install,
+ and whether installing is done correctly -- and lets the second one be answered on any
+ release. Everything the installer rebinds is restored on the way out.
+ """
+ # The module this file already imported from, not a fresh `import unsloth.import_fixes`:
+ # re-entering the package import runs `unsloth/__init__` again, which needs unsloth_zoo
+ # installed. Measured on a torch 2.6.0 floor environment without it, that turned 9 of
+ # these tests into collection errors while the rest of the file ran fine.
+ import_fixes = sys.modules[_transformers_rescopes_submodule_prefix_renamings.__module__]
+
+ conversion_mapping = _conversion_mapping()
+ live = conversion_mapping.get_model_conversion_mapping
+ holders = [
+ (module, module.__dict__["get_model_conversion_mapping"])
+ for module in list(sys.modules.values())
+ if isinstance(getattr(module, "__dict__", None), dict)
+ and "get_model_conversion_mapping" in module.__dict__
+ ]
+ monkeypatch.setattr(
+ import_fixes, "_transformers_rescopes_submodule_prefix_renamings", lambda: False
+ )
+ try:
+ yield import_fixes
+ finally:
+ conversion_mapping.get_model_conversion_mapping = live
+ for module, binding in holders:
+ module.get_model_conversion_mapping = binding
+
+
+def test_installation_is_gated_on_the_probe():
+ conversion_mapping = _conversion_mapping()
+ fix_transformers_composite_prefix_renaming()
+ installed = getattr(
+ conversion_mapping.get_model_conversion_mapping, _COMPOSITE_PREFIX_RENAMING_FLAG, False
+ )
+ assert installed == (not _transformers_rescopes_submodule_prefix_renamings())
+
+
+def test_the_patch_is_idempotent_and_undoable(forced_install):
+ conversion_mapping = _conversion_mapping()
+ forced_install.fix_transformers_composite_prefix_renaming()
+ first = conversion_mapping.get_model_conversion_mapping
+ forced_install.fix_transformers_composite_prefix_renaming()
+ assert (
+ conversion_mapping.get_model_conversion_mapping is first
+ ), "a second call wrapped the wrapper"
+ original = first.__wrapped__
+ assert not getattr(original, _COMPOSITE_PREFIX_RENAMING_FLAG, False)
+ conversion_mapping.get_model_conversion_mapping = original
+ try:
+ assert conversion_mapping.get_model_conversion_mapping is original
+ finally:
+ conversion_mapping.get_model_conversion_mapping = first
+
+
+def test_the_patch_rebinds_the_copies_other_modules_imported(forced_install):
+ """`from .conversion_mapping import get_model_conversion_mapping` holds the object."""
+ conversion_mapping = _conversion_mapping()
+ import transformers.modeling_utils as modeling_utils
+
+ if "get_model_conversion_mapping" not in modeling_utils.__dict__:
+ pytest.skip("this transformers' modeling_utils does not hold its own binding")
+ forced_install.fix_transformers_composite_prefix_renaming()
+ assert getattr(
+ modeling_utils.get_model_conversion_mapping, _COMPOSITE_PREFIX_RENAMING_FLAG, False
+ )
+
+
+def test_the_wrapper_returns_the_upstream_mapping_when_it_cannot_reason(
+ composite_model, forced_install
+):
+ """A model it cannot walk must cost the caller nothing but the upstream answer."""
+ conversion_mapping = _conversion_mapping()
+ forced_install.fix_transformers_composite_prefix_renaming()
+
+ class Unwalkable:
+ """Walks for upstream, refuses to walk for us."""
+
+ config = composite_model.config
+
+ def modules(self):
+ return iter(())
+
+ def named_modules(self, *args, **kwargs):
+ raise RuntimeError("no")
+
+ def named_parameters(self, *args, **kwargs):
+ raise RuntimeError("no")
+
+ def named_buffers(self, *args, **kwargs):
+ raise RuntimeError("no")
+
+ # Upstream has to survive this object for the question to mean anything: from 5.6 on it
+ # walks `named_modules` itself to set `scope_prefix`, so it raises here too and there is
+ # no upstream answer to preserve. That is a fact about the release, not about the fix.
+ try:
+ upstream = _unpatched_mapping_fn()(Unwalkable())
+ except Exception as e:
+ pytest.skip(f"upstream cannot walk this object either on this release ({e!r})")
+ through_patch = conversion_mapping.get_model_conversion_mapping(Unwalkable())
+ assert [_renaming_signature(c) for c in through_patch] == [
+ _renaming_signature(c) for c in upstream
+ ]
+
+
+def test_a_module_holding_the_pre_zoo_function_is_still_rebound(monkeypatch, forced_install):
+ """unsloth_zoo patches the same function first, WITHOUT `__wrapped__`.
+
+ `temporary_patches/moe_utils_bnb4bit.py` sets only `_unsloth_moe_patched`, no
+ functools.wraps, so the `getattr(original, "__wrapped__", original)` unwrap cannot see
+ past it and `original` stays zoo's wrapper. A module that imported the name before zoo
+ ran still holds the underlying upstream function and matches neither object, so an
+ identity test leaves it bound to the unscoped mapping and
+ `PeftAdapterMixin.load_adapter()` renames Qwen3.5 and Gemma 3n adapter keys away from
+ their real `model.language_model.*` modules.
+ """
+ import types
+
+ from transformers import conversion_mapping
+
+ import_fixes = forced_install
+
+ # Pin the starting state: importing unsloth may already have installed this patch.
+ pristine = conversion_mapping.get_model_conversion_mapping
+ while getattr(pristine, import_fixes._COMPOSITE_PREFIX_RENAMING_FLAG, False):
+ unwrapped = getattr(pristine, "__wrapped__", None)
+ if unwrapped is None:
+ break
+ pristine = unwrapped
+
+ # Zoo's wrapper, spelled the way zoo really spells it: no functools.wraps, no
+ # __wrapped__, just its own marker attribute.
+ def zoo_wrapper(
+ model,
+ key_mapping = None,
+ hf_quantizer = None,
+ add_legacy = True,
+ ):
+ return pristine(model, key_mapping, hf_quantizer, add_legacy)
+
+ zoo_wrapper._unsloth_moe_patched = True
+ assert not hasattr(zoo_wrapper, "__wrapped__"), "this test models zoo's real wrapper"
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", zoo_wrapper)
+
+ # A module that imported the function BEFORE zoo wrapped, so it holds `pristine`.
+ early = types.ModuleType("transformers._unsloth_test_early_importer")
+ early.get_model_conversion_mapping = pristine
+ monkeypatch.setitem(sys.modules, early.__name__, early)
+
+ import_fixes.fix_transformers_composite_prefix_renaming()
+
+ patched = conversion_mapping.get_model_conversion_mapping
+ assert patched is not zoo_wrapper, "the repair declined even with the gate forced open"
+ assert (
+ early.get_model_conversion_mapping is patched
+ ), "a module holding the pre-zoo function was left bound to the unscoped mapping"
+
+
+def test_a_third_party_wrapper_is_kept_in_the_chain(forced_install):
+ """A library that wrapped this function first must keep running after we install.
+
+ An unconditional `original.__wrapped__` took one level off the chain, and any wrapper
+ that plays by the rules publishes `__wrapped__` through functools.wraps, so the level
+ removed was THEIRS: measured on transformers 5.5.4, the third-party wrapper stopped
+ being called at all, and the alias sweep then spread the replacement to every module
+ holding it. Ours goes on top instead, and the already-installed test reads the chain.
+ """
+ import functools
+
+ conversion_mapping = _conversion_mapping()
+ # From the unwrapped function, so an earlier test's wrapper is not what gets wrapped here,
+ # and without the flags functools.wraps copies out of its target's __dict__ -- inheriting
+ # this repair's own mark would make the installer decline and prove nothing.
+ live = _unpatched_mapping_fn()
+ calls = []
+
+ @functools.wraps(live)
+ def third_party(*args, **kwargs):
+ calls.append(1)
+ return live(*args, **kwargs)
+
+ third_party.__dict__.pop(_COMPOSITE_PREFIX_RENAMING_FLAG, None)
+ conversion_mapping.get_model_conversion_mapping = third_party
+ forced_install.fix_transformers_composite_prefix_renaming()
+
+ patched = conversion_mapping.get_model_conversion_mapping
+ assert getattr(patched, _COMPOSITE_PREFIX_RENAMING_FLAG, False), "the repair declined"
+ assert patched.__wrapped__ is third_party, "the third-party wrapper was discarded"
+
+ # And a second install underneath someone else's wrapper must not stack another copy.
+ @functools.wraps(patched)
+ def someone_else(*args, **kwargs):
+ return patched(*args, **kwargs)
+
+ conversion_mapping.get_model_conversion_mapping = someone_else
+ forced_install.fix_transformers_composite_prefix_renaming()
+ assert conversion_mapping.get_model_conversion_mapping is someone_else
+
+
+def test_a_vllm_module_holding_its_own_copy_is_rebound(monkeypatch, forced_install):
+ """vLLM's Transformers backend imports this function by value, at import time.
+
+ `vllm/model_executor/models/transformers/base.py` does `from
+ transformers.conversion_mapping import get_model_conversion_mapping` and builds its
+ `WeightsMapper` from the result, so a process that imported vllm before this repair ran
+ would map a composite model's weights with the unscoped renaming. Measured on
+ transformers 5.5.4 with the real vllm 0.30.0 module: not rebound before `vllm` joined
+ the owning packages, rebound after. Modelled here rather than importing vllm, which
+ costs half a minute and is not installed everywhere this suite runs.
+ """
+ import types
+
+ conversion_mapping = _conversion_mapping()
+ # The object the installer is about to wrap, not `_unpatched_mapping_fn()`: an earlier
+ # test in this file can leave a stand-in in place, and then the deepest function in the
+ # chain belongs to this test module rather than to transformers.
+ backend = types.ModuleType("vllm.model_executor.models.transformers.base")
+ backend.get_model_conversion_mapping = conversion_mapping.get_model_conversion_mapping
+ monkeypatch.setitem(sys.modules, backend.__name__, backend)
+
+ forced_install.fix_transformers_composite_prefix_renaming()
+
+ patched = conversion_mapping.get_model_conversion_mapping
+ assert getattr(patched, _COMPOSITE_PREFIX_RENAMING_FLAG, False), "the repair declined"
+ assert (
+ backend.get_model_conversion_mapping is patched
+ ), "vllm's own copy was left bound to the unscoped mapping"
+
+
+ "module_name",
+ [
+ "some_user_notebook_helper",
+ "transformers._unsloth_test_unrelated",
+ "peft._unsloth_test_unrelated",
+ "unsloth_zoo._unsloth_test_unrelated",
+ "unsloth._unsloth_test_unrelated",
+ "vllm._unsloth_test_unrelated",
+ ],
+)
+def test_an_unrelated_module_keeps_its_own_same_named_function(
+ monkeypatch, forced_install, module_name
+):
+ """The sweep must not touch a helper somebody else happens to call the same thing.
+
+ The binding test cannot be an identity test, because unsloth_zoo wraps without
+ `__wrapped__` and the pre-zoo upstream function matches neither object. So the sweep
+ asks whether the binding IS an alias of the function it is replacing: `original`
+ itself, something whose `__module__` is transformers' own `conversion_mapping`, or a
+ wrapper carrying unsloth_zoo's marker. The package restriction alone is not enough --
+ these four packages are large, and something inside their namespace may legitimately
+ define its own helper under this name, which is why the cases below include modules
+ inside them as well as outside.
+ """
+ import types
+
+ def mine(*args, **kwargs):
+ return "mine"
+
+ outsider = types.ModuleType(module_name)
+ outsider.get_model_conversion_mapping = mine
+ monkeypatch.setitem(sys.modules, module_name, outsider)
+
+ forced_install.fix_transformers_composite_prefix_renaming()
+
+ assert outsider.get_model_conversion_mapping is mine
+ assert outsider.get_model_conversion_mapping() == "mine"
+
+
+def test_it_defers_to_the_unsloth_zoo_copy_of_the_same_repair(monkeypatch):
+ """Two packages carry this repair; exactly one of them must install it.
+
+ unsloth_zoo owns the bitsandbytes Linear4bit patch that reports the failure and is
+ importable without unsloth, so it carries the same re-scope in
+ `temporary_patches/conversion_mapping_rescope.py`. A second wrapper on top of the first
+ is measurably inert -- the first pass leaves no leaked signature for the second to match
+ -- but it is still a wrapper nobody needs, and one of the two has to yield. This one does.
+ """
+ conversion_mapping = pytest.importorskip("transformers.conversion_mapping")
+ # The module this file already imported from: a fresh `import unsloth.import_fixes`
+ # re-runs `unsloth/__init__`, which needs unsloth_zoo installed, and turns this into
+ # a collection error on a minimal floor environment (measured on torch 2.6.0).
+ import_fixes = sys.modules[_transformers_rescopes_submodule_prefix_renamings.__module__]
+
+ if import_fixes._transformers_rescopes_submodule_prefix_renamings():
+ pytest.skip("this transformers carries the upstream fix; neither copy installs")
+
+ before = conversion_mapping.get_model_conversion_mapping
+
+ def zoo_wrapper(*args, **kwargs):
+ return before(*args, **kwargs)
+
+ zoo_wrapper.__wrapped__ = before
+ setattr(zoo_wrapper, "_unsloth_zoo_patched_composite_prefix_renaming", True)
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", zoo_wrapper)
+
+ import_fixes.fix_transformers_composite_prefix_renaming()
+
+ assert conversion_mapping.get_model_conversion_mapping is zoo_wrapper
+ assert not getattr(
+ conversion_mapping.get_model_conversion_mapping,
+ "_unsloth_patched_composite_prefix_renaming",
+ False,
+ )
+
+
+def test_it_finds_the_zoo_mark_under_an_unmarked_wrapper(monkeypatch):
+ """unsloth_zoo's moe_utils_bnb4bit wraps the same function without `__wrapped__`.
+
+ The detector therefore walks the whole chain rather than reading only the top object.
+ """
+ conversion_mapping = pytest.importorskip("transformers.conversion_mapping")
+ # The module this file already imported from: a fresh `import unsloth.import_fixes`
+ # re-runs `unsloth/__init__`, which needs unsloth_zoo installed, and turns this into
+ # a collection error on a minimal floor environment (measured on torch 2.6.0).
+ import_fixes = sys.modules[_transformers_rescopes_submodule_prefix_renamings.__module__]
+
+ def zoo_repair():
+ pass
+
+ setattr(zoo_repair, "_unsloth_zoo_patched_composite_prefix_renaming", True)
+
+ def moe_wrapper():
+ pass
+
+ moe_wrapper.__wrapped__ = zoo_repair
+
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", moe_wrapper)
+ assert import_fixes._zoo_composite_prefix_renaming_installed() is True
+
+
+def test_the_zoo_detector_cannot_spin_on_a_cycle(monkeypatch):
+ conversion_mapping = pytest.importorskip("transformers.conversion_mapping")
+ # The module this file already imported from: a fresh `import unsloth.import_fixes`
+ # re-runs `unsloth/__init__`, which needs unsloth_zoo installed, and turns this into
+ # a collection error on a minimal floor environment (measured on torch 2.6.0).
+ import_fixes = sys.modules[_transformers_rescopes_submodule_prefix_renamings.__module__]
+
+ def a():
+ pass
+
+ def b():
+ pass
+
+ a.__wrapped__ = b
+ b.__wrapped__ = a
+
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", a)
+ assert import_fixes._zoo_composite_prefix_renaming_installed() is False
+
+
+def test_both_probes_see_the_repair_under_the_real_moe_wrapper(monkeypatch):
+ """unsloth_zoo's MoE wrapper publishes no `__wrapped__`, on purpose.
+
+ zoo's re-scope unwraps `__wrapped__` to choose what to wrap, so a MoE wrapper carrying one
+ would be REPLACED rather than sat on top of, silently dropping its per-expert converters.
+ It publishes `_unsloth_wrapper_inner` instead. zoo also registers the re-scope before the
+ MoE patch, so the MoE wrapper is on top in the normal case -- meaning a `__wrapped__`-only
+ walk reports no repair for one that is live, which would put the downgrade advice back in
+ the guard's message and stack a second wrapper here.
+
+ Driven through the real patch, not a stand-in: a stand-in that sets `__wrapped__` exercises
+ the one thing the real wrapper does not do, and passes either way.
+ """
+ conversion_mapping = pytest.importorskip("transformers.conversion_mapping")
+ moe = pytest.importorskip("unsloth_zoo.temporary_patches.moe_utils_bnb4bit")
+ if not hasattr(moe, "patch_bnb4bit_model_conversion_mapping"):
+ pytest.skip("this unsloth_zoo has no MoE conversion-mapping patch")
+ # The module this file already imported from: a fresh `import unsloth.import_fixes`
+ # re-runs `unsloth/__init__`, which needs unsloth_zoo installed (measured: 9 collection
+ # errors on a torch 2.6.0 floor environment without it).
+ import_fixes = sys.modules[_transformers_rescopes_submodule_prefix_renamings.__module__]
+
+ def zoo_repair(*args, **kwargs):
+ pass
+
+ setattr(zoo_repair, "_unsloth_zoo_patched_composite_prefix_renaming", True)
+
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", zoo_repair)
+ moe.patch_bnb4bit_model_conversion_mapping()
+ live = conversion_mapping.get_model_conversion_mapping
+ if live is zoo_repair:
+ pytest.skip("the MoE patch declined to install on this transformers")
+
+ assert (
+ getattr(live, "__wrapped__", None) is None
+ ), "the MoE wrapper must not publish __wrapped__; see the docstring"
+ if getattr(live, "_unsloth_wrapper_inner", None) is None:
+ # An unsloth_zoo predating the link attribute. The repair really is invisible from
+ # here, and nothing this side can fix, so this is a skip and not a failure.
+ pytest.skip("this unsloth_zoo's MoE wrapper publishes no link to what it wrapped")
+
+ assert import_fixes._zoo_composite_prefix_renaming_installed() is True
+ assert import_fixes._composite_prefix_renaming_repaired() is True
+
+
+def test_the_chain_walk_is_bounded(monkeypatch):
+ conversion_mapping = pytest.importorskip("transformers.conversion_mapping")
+ # The module this file already imported from: a fresh `import unsloth.import_fixes`
+ # re-runs `unsloth/__init__`, which needs unsloth_zoo installed (measured: 9 collection
+ # errors on a torch 2.6.0 floor environment without it).
+ import_fixes = sys.modules[_transformers_rescopes_submodule_prefix_renamings.__module__]
+
+ def a():
+ pass
+
+ def b():
+ pass
+
+ a.__wrapped__ = b
+ b.__wrapped__ = a
+
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", a)
+ assert import_fixes._zoo_composite_prefix_renaming_installed() is False
+ assert import_fixes._composite_prefix_renaming_repaired() is False
diff --git a/tests/test_import_fixes_drift.py b/tests/test_import_fixes_drift.py
index 41cf41a98c8..bed27a62494 100644
--- a/tests/test_import_fixes_drift.py
+++ b/tests/test_import_fixes_drift.py
@@ -1712,3 +1712,138 @@ def test_a_per_layer_snapshot_never_becomes_a_scalar_rope_theta():
written = config.rope_parameters.get("rope_theta", None)
assert not isinstance(written, dict), written
assert not isinstance(getattr(config, "rope_theta", None), dict)
+
+
+# ===========================================================================
+# transformers -- a submodule's prefix renaming leaks into the composite model
+# ===========================================================================
+
+
+def test_transformers_scopes_a_submodules_conversion_mapping():
+ """``fix_transformers_composite_prefix_renaming``: transformers 5.4.0 to 5.5.4
+ merge a submodule's own prefix renaming into the parent's conversion mapping
+ verbatim, which renames a composite model's real weight names into names it does
+ not have and throws away the bitsandbytes quant_state sidecars with them."""
+ pytest.importorskip("transformers")
+ from unsloth.import_fixes import _transformers_rescopes_submodule_prefix_renamings
+
+ if not _transformers_rescopes_submodule_prefix_renamings():
+ pytest.fail(
+ "DRIFT DETECTED: this transformers recurses into submodules for "
+ "conversion mappings without scoping them to where the submodule lives "
+ "(no model_prefix argument, no PrefixChange.with_submodel_prefix, no "
+ "scope_prefix field) -- fix_transformers_composite_prefix_renaming would "
+ "wrap get_model_conversion_mapping. Pre-quantized multimodal checkpoints "
+ "load with quant_state=None here; install transformers>=5.6.0."
+ )
+
+
+def test_composite_renaming_probe_agrees_with_the_real_mapping():
+ """The install gate is a claim about behaviour, so check it against the behaviour.
+
+ Builds a real composite Qwen3.5 on the meta device -- no weights, no download --
+ and asks whether the mapping transformers really produces rewrites that model's
+ own parameter names into names it does not have.
+ """
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("transformers")
+ from unsloth.import_fixes import _transformers_rescopes_submodule_prefix_renamings
+
+ try:
+ import transformers
+ from transformers.conversion_mapping import get_model_conversion_mapping
+ from transformers.core_model_loading import WeightRenaming
+ from transformers.models.auto.configuration_auto import CONFIG_MAPPING
+ except Exception as exc:
+ pytest.skip(f"this transformers has no conversion mapping machinery: {exc!r}")
+ if "qwen3_5" not in CONFIG_MAPPING:
+ pytest.skip("this transformers has no qwen3_5 model type")
+
+ config = CONFIG_MAPPING["qwen3_5"]()
+ config.text_config.num_hidden_layers = 2
+ config.text_config.layer_types = ["linear_attention", "full_attention"]
+ if hasattr(config.text_config, "mtp_num_hidden_layers"):
+ config.text_config.mtp_num_hidden_layers = 0
+ config.vision_config.depth = 1
+ try:
+ with torch.device("meta"):
+ model = transformers.AutoModelForImageTextToText.from_config(config)
+ except Exception as exc:
+ pytest.skip(f"cannot build a meta qwen3_5: {exc!r}")
+
+ # Past EVERY wrapper, not just the first: unsloth_zoo patches the same function and
+ # keeps its original in a closure cell, so stopping at `__wrapped__` would measure this
+ # fix through this fix and report no pathology on a transformers that has one.
+ mapping = get_model_conversion_mapping
+ seen = set()
+ while id(mapping) not in seen:
+ seen.add(id(mapping))
+ nxt = getattr(mapping, "__wrapped__", None)
+ if nxt is None:
+ for cell in getattr(mapping, "__closure__", None) or ():
+ try:
+ candidate = cell.cell_contents
+ except ValueError:
+ continue
+ if callable(candidate) and getattr(candidate, "__name__", "") == (
+ "get_model_conversion_mapping"
+ ):
+ nxt = candidate
+ break
+ if nxt is None:
+ break
+ mapping = nxt
+ keys = {name for name, _ in model.named_parameters(remove_duplicate = False)}
+ keys |= {name for name, _ in model.named_buffers(remove_duplicate = False)}
+ leaks = []
+ for conversion in mapping(model):
+ if not isinstance(conversion, WeightRenaming):
+ continue
+ for key in sorted(keys):
+ renamed, matched = conversion.rename_source_key(key)
+ if matched is not None and renamed != key and renamed not in keys:
+ leaks.append((conversion.source_patterns, key, renamed))
+ break
+
+ rescopes = _transformers_rescopes_submodule_prefix_renamings()
+ assert bool(leaks) != bool(rescopes), (
+ f"DRIFT DETECTED: the probe says rescopes={rescopes}, but the mapping this "
+ f"transformers builds for a composite Qwen3.5 {'does' if leaks else 'does not'} "
+ f"rewrite the model's own weight names off the map: {leaks[:3]}"
+ )
+
+
+def test_composite_renaming_patch_wired_into_gpu_init():
+ """The patch must be installed at startup, not only importable."""
+ source = Path(__file__).resolve().parent.parent / "unsloth" / "_gpu_init.py"
+ source = source.read_text(encoding = "utf-8")
+ assert "fix_transformers_composite_prefix_renaming()" in source, (
+ "DRIFT DETECTED: fix_transformers_composite_prefix_renaming is defined but "
+ "never called in _gpu_init.py, so real imports never install it."
+ )
+
+
+def test_no_top_level_definition_is_shadowed_by_a_later_one():
+ """A second `def` of the same name silently wins and the first becomes dead code.
+
+ This branch stacks on #11450, which moved `_transformers_rescopes_submodule_prefix_renamings`
+ into the base. The merge landed both copies in different regions of the file, so git
+ reported no conflict while Python bound the later one and the earlier one, which
+ answered differently when `core_model_loading` failed to import, stopped running.
+ """
+ import ast
+ from collections import Counter
+
+ source = (Path(__file__).resolve().parent.parent / "unsloth" / "import_fixes.py").read_text(
+ encoding = "utf-8"
+ )
+ counts = Counter(
+ node.name
+ for node in ast.parse(source).body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ )
+ shadowed = {name: n for name, n in counts.items() if n > 1}
+ assert not shadowed, (
+ f"DRIFT DETECTED: import_fixes.py defines these names more than once at module "
+ f"level, so every copy but the last is dead code: {shadowed}"
+ )
diff --git a/tests/test_prequantized_vlm_quant_state_guard.py b/tests/test_prequantized_vlm_quant_state_guard.py
index f46b9edd030..e8364c349be 100644
--- a/tests/test_prequantized_vlm_quant_state_guard.py
+++ b/tests/test_prequantized_vlm_quant_state_guard.py
@@ -311,9 +311,38 @@ def test_a_fixed_nightly_is_not_told_it_is_broken(import_fixes, monkeypatch, cap
# The warning
+def _uninstall_runtime_repair(import_fixes, monkeypatch):
+ """Put the live attribute back to an unpatched function.
+
+ The check is silent once the runtime repair is installed, which is the point: the
+ repair covers exactly these releases, so advising a downgrade would contradict it.
+ These tests are about the message shown when the repair is NOT in effect, so they
+ have to say so rather than depend on whether an earlier test installed it.
+
+ A missing transformers is not an error here: nothing can have installed the repair,
+ so there is nothing to undo, and the caller goes on to install a stand-in module.
+ This file runs with pytest alone.
+ """
+ try:
+ from transformers import conversion_mapping
+ except Exception:
+ return
+
+ current = conversion_mapping.get_model_conversion_mapping
+ while getattr(current, import_fixes._COMPOSITE_PREFIX_RENAMING_FLAG, False):
+ unwrapped = getattr(current, "__wrapped__", None)
+ if unwrapped is None:
+ break
+ current = unwrapped
+ monkeypatch.setattr(conversion_mapping, "get_model_conversion_mapping", current)
+
+
def test_warning_names_the_cause_and_the_remedy(import_fixes, monkeypatch, caplog):
monkeypatch.setattr(import_fixes, "importlib_version", lambda name: "5.5.4")
monkeypatch.delenv("UNSLOTH_SKIP_TRANSFORMERS_QUANT_STATE_CHECK", raising = False)
+ # Uninstall first: `_build_broken` swaps in a stand-in conversion_mapping module that
+ # has no `get_model_conversion_mapping` at all, and the uninstall reads that attribute.
+ _uninstall_runtime_repair(import_fixes, monkeypatch)
_build_broken(monkeypatch)
with caplog.at_level(logging.WARNING):
import_fixes.check_transformers_prequantized_vlm_quant_state()
@@ -427,3 +456,96 @@ def test_the_check_runs_after_the_torchaudio_guard():
assert order.index("check_transformers_prequantized_vlm_quant_state") > order.index(
"disable_torchaudio_if_cuda_mismatched"
), "the quant_state check imports transformers and must not precede the torchaudio guard"
+
+
+def test_warning_is_silent_once_the_runtime_repair_is_installed(import_fixes, monkeypatch, caplog):
+ """Telling a user to downgrade away from a version we just repaired is worse than silence."""
+ import logging as _logging
+
+ monkeypatch.setattr(import_fixes, "importlib_version", lambda name: "5.5.4")
+ monkeypatch.delenv("UNSLOTH_SKIP_TRANSFORMERS_QUANT_STATE_CHECK", raising = False)
+ # This one really does need the live module: it installs the repair onto it. Skipping
+ # keeps the rest of the file runnable with pytest alone.
+ transformers = pytest.importorskip("transformers")
+ conversion_mapping = pytest.importorskip("transformers.conversion_mapping")
+ del transformers
+
+ import_fixes.fix_transformers_composite_prefix_renaming()
+ installed = getattr(
+ conversion_mapping.get_model_conversion_mapping,
+ import_fixes._COMPOSITE_PREFIX_RENAMING_FLAG,
+ False,
+ )
+ if not installed:
+ pytest.skip("this transformers is outside the defect window, so the repair declines")
+ with caplog.at_level(_logging.WARNING):
+ import_fixes.check_transformers_prequantized_vlm_quant_state()
+ assert "quant_state" not in caplog.text
+
+
+def test_the_check_is_called_once_and_after_the_repair():
+ """Two calls warned before the repair and could not retract it.
+
+ `_gpu_init` gained a call from this branch's base and a second one after
+ `fix_transformers_composite_prefix_renaming`. On an affected transformers the first
+ emitted the downgrade advice moments before the repair made that advice wrong, and a
+ later silent call cannot unlog it.
+ """
+ import ast
+
+ source = (_ROOT / "unsloth" / "_gpu_init.py").read_text(encoding = "utf-8")
+ order = [
+ node.value.func.id
+ for node in ast.parse(source).body
+ if isinstance(node, ast.Expr)
+ and isinstance(node.value, ast.Call)
+ and isinstance(node.value.func, ast.Name)
+ ]
+ assert order.count("check_transformers_prequantized_vlm_quant_state") == 1, (
+ "the quant_state check must be called exactly once; a call before the repair warns "
+ "about a version the repair then fixes"
+ )
+ assert order.index("check_transformers_prequantized_vlm_quant_state") > order.index(
+ "fix_transformers_composite_prefix_renaming"
+ ), "the check reads the live attribute, so it has to run after the repair installs"
+
+
+def _install_repaired(monkeypatch, import_fixes, flag_name):
+ """An affected build whose conversion mapping already carries a repair mark."""
+ _build_broken(monkeypatch)
+ import sys as _sys
+
+ conversion_mapping = _sys.modules["transformers.conversion_mapping"]
+
+ def get_model_conversion_mapping(model):
+ return []
+
+ setattr(get_model_conversion_mapping, getattr(import_fixes, flag_name), True)
+ conversion_mapping.get_model_conversion_mapping = get_model_conversion_mapping
+
+
+ "flag_name",
+ ["_COMPOSITE_PREFIX_RENAMING_FLAG", "_ZOO_COMPOSITE_PREFIX_RENAMING_FLAG"],
+)
+def test_either_repair_silences_the_warning(import_fixes, monkeypatch, caplog, flag_name):
+ """When unsloth_zoo installs first, ours yields and only the zoo mark is on the function."""
+ monkeypatch.setattr(import_fixes, "importlib_version", lambda name: "5.5.4")
+ monkeypatch.delenv("UNSLOTH_SKIP_TRANSFORMERS_QUANT_STATE_CHECK", raising = False)
+ _install_repaired(monkeypatch, import_fixes, flag_name)
+ with caplog.at_level(logging.WARNING):
+ import_fixes.check_transformers_prequantized_vlm_quant_state()
+ assert "quant_state" not in caplog.text
+
+
+def test_an_unmarked_wrapper_does_not_count_as_repaired(import_fixes, monkeypatch, caplog):
+ """Negative control: a wrapper carrying neither mark must still warn."""
+ monkeypatch.setattr(import_fixes, "importlib_version", lambda name: "5.5.4")
+ monkeypatch.delenv("UNSLOTH_SKIP_TRANSFORMERS_QUANT_STATE_CHECK", raising = False)
+ _build_broken(monkeypatch)
+ import sys as _sys
+
+ _sys.modules["transformers.conversion_mapping"].get_model_conversion_mapping = lambda model: []
+ with caplog.at_level(logging.WARNING):
+ import_fixes.check_transformers_prequantized_vlm_quant_state()
+ assert "quant_state" in caplog.text
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index 0d18482e1ce..a68e226000d 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -104,10 +104,6 @@ torchvision_compatibility_check()
disable_torchaudio_if_cuda_mismatched()
fix_diffusers_warnings()
fix_huggingface_hub()
-# Below the torchaudio guard, not up with the other version checks: this is the only check
-# here that IMPORTS transformers rather than reading its metadata, and that is the ordering
-# the guard above exists to prevent.
-check_transformers_prequantized_vlm_quant_state()
del configure_amdgpu_asic_id_table_path
del fix_bitsandbytes_rocm_arch_detection
del disable_broken_causal_conv1d
@@ -120,7 +116,6 @@ del propagate_torchao_fix_to_subprocesses
del check_fbgemm_gpu_version
del check_transformers_dependency_versions
del check_triton_py_ssize_t_clean
-del check_transformers_prequantized_vlm_quant_state
del torchvision_compatibility_check
del fix_diffusers_warnings
del fix_huggingface_hub
@@ -250,6 +245,7 @@ from .device_type import arch_lacks_bf16, hip_visible_archs
from .import_fixes import (
fix_transformers5_bare_annotation_configs,
+ fix_transformers_composite_prefix_renaming,
fix_transformers_fully_masked_rows,
fix_transformers_rope_scaling_drops_theta,
fix_xformers_performance_issue,
@@ -293,6 +289,19 @@ fix_transformers5_bare_annotation_configs()
# nothing. Ordered here, before anything imports a model, so a plain transformers.generate in the
# same process is covered too (#9708).
fix_transformers_fully_masked_rows()
+# Probe-gated: no-ops unless this transformers merges a submodule's own prefix renaming into a
+# composite model's conversion mapping. Ordered here, before anything loads a checkpoint, so a
+# plain transformers.from_pretrained in the same process keeps its bitsandbytes quant_state too.
+fix_transformers_composite_prefix_renaming()
+# After the repair above, never before it, and this is the ONLY call: on exactly the releases
+# the repair covers, warning first tells users to downgrade away from a version that now works,
+# and a second call cannot retract a warning already logged. The check reads the live attribute,
+# so a repair that declined to install still warns. Being this late also keeps it below
+# `disable_torchaudio_if_cuda_mismatched`, which matters because this is the only check here
+# that IMPORTS transformers rather than reading its metadata.
+# A run that loads no pre-quantized multimodal checkpoint never fails either way.
+check_transformers_prequantized_vlm_quant_state()
+del check_transformers_prequantized_vlm_quant_state
# Probe-gated: no-ops unless replacing config.rope_scaling on this transformers really loses the
# 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).
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 10313113169..dd1e2cd895d 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -884,6 +884,408 @@ def fix_transformers_fully_masked_rows():
logger.info(f"Unsloth: Failed patching sdpa_mask ({e})")
+_COMPOSITE_PREFIX_RENAMING_FLAG = "_unsloth_patched_composite_prefix_renaming"
+
+# unsloth_zoo marks its own copy of this repair with this. Spelled as a literal rather than
+# imported, so a zoo too old to define it cannot turn a skipped repair into an ImportError.
+_ZOO_COMPOSITE_PREFIX_RENAMING_FLAG = "_unsloth_zoo_patched_composite_prefix_renaming"
+
+# zoo's `temporary_patches/common.py:WRAPPER_INNER_ATTR`: the explicit link a wrapper on that
+# same function publishes to whatever it wrapped. Following it matters because zoo's MoE
+# wrapper (`temporary_patches/moe_utils_bnb4bit.py`) deliberately does NOT publish
+# `__wrapped__` -- zoo's re-scope unwraps `__wrapped__` to pick what to wrap, so a MoE wrapper
+# carrying one would be replaced rather than sat on top of, dropping its per-expert converters.
+# zoo registers the re-scope BEFORE the MoE patch, so the MoE wrapper is on top in the normal
+# case, and a `__wrapped__`-only walk stops there and reports no repair for one that is
+# running underneath. Spelled as a literal, like the flag above, so a zoo too old to define it
+# cannot turn a skipped repair into an ImportError.
+_ZOO_WRAPPER_INNER_ATTR = "_unsloth_wrapper_inner"
+
+
+def _next_in_wrapper_chain(function):
+ """The callable `function` wraps, by either link, or None at the end of the chain."""
+ return getattr(function, "__wrapped__", None) or getattr(
+ function, _ZOO_WRAPPER_INNER_ATTR, None
+ )
+
+
+def _composite_prefix_renaming_repaired():
+ """Is the live conversion mapping repaired, by either copy of the fix?
+
+ Ours and unsloth_zoo's are interchangeable here: whichever installed first, the mapping
+ is re-scoped and the downgrade advice would contradict it. The whole chain, by either
+ link, for the reason `_zoo_composite_prefix_renaming_installed` gives.
+ """
+ try:
+ from transformers import conversion_mapping
+ except Exception:
+ return False
+ function = getattr(conversion_mapping, "get_model_conversion_mapping", None)
+ seen = 0
+ while function is not None and seen < 8:
+ for flag in (_COMPOSITE_PREFIX_RENAMING_FLAG, _ZOO_COMPOSITE_PREFIX_RENAMING_FLAG):
+ if getattr(function, flag, False):
+ return True
+ function = _next_in_wrapper_chain(function)
+ seen += 1
+ return False
+
+
+def _own_composite_prefix_renaming_installed(function):
+ """Is THIS repair already somewhere in the chain hanging off `function`?
+
+ Through the chain rather than on the top object, because another library may have wrapped
+ us since we installed, and a top-only test would then stack a second copy of this repair
+ that walks every submodule again for nothing. Same bound as the zoo check.
+ """
+ seen = 0
+ while function is not None and seen < 8:
+ if getattr(function, _COMPOSITE_PREFIX_RENAMING_FLAG, False):
+ return True
+ function = _next_in_wrapper_chain(function)
+ seen += 1
+ return False
+
+
+def _zoo_composite_prefix_renaming_installed():
+ """Has unsloth_zoo's copy of this repair already wrapped the function?
+
+ The whole chain, following `__wrapped__` OR `_unsloth_wrapper_inner`, because zoo also
+ wraps the same function in `temporary_patches/moe_utils_bnb4bit.py` and that wrapper
+ publishes only the latter -- see `_ZOO_WRAPPER_INNER_ATTR`. Since zoo installs the repair
+ first, the MoE wrapper is normally on top, so a `__wrapped__`-only walk answers False for a
+ repair that is live and stacks a second wrapper for nothing. Bounded, so a malformed chain
+ cannot spin.
+ """
+ try:
+ from transformers import conversion_mapping
+ except Exception:
+ return False
+ function = getattr(conversion_mapping, "get_model_conversion_mapping", None)
+ seen = 0
+ while function is not None and seen < 8:
+ if getattr(function, _ZOO_COMPOSITE_PREFIX_RENAMING_FLAG, False):
+ return True
+ function = _next_in_wrapper_chain(function)
+ seen += 1
+ return False
+
+
+# How many of a submodule's own parameter names to try a renaming against. A prefix renaming
+# either matches every name under the submodule or none of them, so one would do; eight costs
+# nothing and covers a mapping that only rewrites some leaf names.
+_COMPOSITE_RENAMING_SAMPLE = 8
+
+
+def _renaming_signature(conversion):
+ """Identity of a renaming by VALUE, because the mapping is handed out as deep copies.
+
+ `get_checkpoint_conversion_mapping` returns `deepcopy(...)`, so the object this module
+ collects from a submodule is never the object that ended up in the parent's list, and
+ `is` can never match them. The patterns are what a renaming is, so compare those. The
+ unprocessed ones when they are kept (5.5+), since `__post_init__` rewrites the live ones.
+ """
+ source = getattr(conversion, "_original_source_patterns", None) or conversion.source_patterns
+ target = getattr(conversion, "_original_target_patterns", None) or conversion.target_patterns
+ return (type(conversion).__name__, tuple(source), tuple(target))
+
+
+def _sample_submodule_keys(submodule, prefix):
+ """A few of the submodule's real parameter names, spelled as the PARENT spells them."""
+ keys = []
+ try:
+ for name, _ in submodule.named_parameters(recurse = True):
+ keys.append(f"{prefix}.{name}")
+ if len(keys) >= _COMPOSITE_RENAMING_SAMPLE:
+ return keys
+ for name, _ in submodule.named_buffers(recurse = True):
+ keys.append(f"{prefix}.{name}")
+ if len(keys) >= _COMPOSITE_RENAMING_SAMPLE:
+ break
+ except Exception:
+ return []
+ return keys
+
+
+def _renaming_destroys_keys(conversion, sample_keys, model_keys):
+ """Does this renaming rewrite the model's OWN parameter names into names it does not have?
+
+ The whole discriminator, and a behaviour rather than a name: a renaming maps CHECKPOINT
+ keys onto MODEL keys, so one that fires on a real name and lands off the map drops that
+ weight. It separates the two directions of the same entry -- against the standalone text
+ model `^model.language_model.` -> `^model.` matches nothing, against the composite it
+ matches everything. One real landing answers False; a mapping doing its job wins.
+ """
+ destroys = False
+ for key in sample_keys:
+ try:
+ renamed, matched = conversion.rename_source_key(key)
+ except Exception:
+ return False
+ if matched is None or renamed == key:
+ continue
+ if renamed in model_keys:
+ return False
+ destroys = True
+ return destroys
+
+
+def _prefixed_pattern(pattern, prefix):
+ """Push a pattern down into `prefix`, keeping a start anchor anchored."""
+ if pattern.startswith("^"):
+ return f"^{prefix}.{pattern[1:]}"
+ return f"{prefix}.{pattern}"
+
+
+def _rescoped_renaming(conversion, prefix, sample_keys, model_keys):
+ """The same renaming, scoped to the submodule it came from, or None if that cannot be built.
+
+ What upstream's `PrefixChange.with_submodel_prefix` produces, for a transformers without
+ it: collected at `model.language_model`, `^model.language_model.` -> `^model.` becomes
+ `^model.language_model.model.language_model.` -> `model.language_model.model.`, which can
+ only fire on a doubled prefix. 5.6.2 builds the same pair for the same model.
+
+ Anchored patterns only, as upstream: prefixing an unanchored one means neither thing, so
+ answer None and let the caller drop an entry already shown to be destructive. Returned
+ only after checking the result is inert on this model's real names.
+ """
+ from transformers.core_model_loading import WeightRenaming
+
+ source = getattr(conversion, "_original_source_patterns", None) or conversion.source_patterns
+ target = getattr(conversion, "_original_target_patterns", None) or conversion.target_patterns
+ if not all(pattern.startswith("^") for pattern in source):
+ return None
+
+ patterns = {
+ "source_patterns": [_prefixed_pattern(p, prefix) for p in source],
+ "target_patterns": [_prefixed_pattern(p, prefix) for p in target],
+ }
+ try:
+ rescoped = type(conversion)(**patterns)
+ except Exception:
+ # A subclass whose __init__ takes something else entirely -- upstream's `PrefixChange`
+ # takes prefixes, not patterns. It is still a WeightRenaming, and a renaming is all
+ # this produces, so fall back to the base class rather than giving up.
+ try:
+ rescoped = WeightRenaming(**patterns)
+ except Exception:
+ return None
+ for key in sample_keys:
+ try:
+ renamed, matched = rescoped.rename_source_key(key)
+ except Exception:
+ return None
+ if matched is not None and renamed != key and renamed not in model_keys:
+ return None
+ return rescoped
+
+
+def _leaked_submodule_prefix_renamings(model):
+ """Which renamings did the recursion merge into `model`'s mapping where they do not belong?
+
+ Walks the submodules the way `get_model_conversion_mapping` walks them -- same order, same
+ "first model type wins" rule -- so the entries found here are the entries it collected.
+ A renaming that the parent registers for ITSELF is never considered, even if a submodule
+ registers the same one: re-scoping something the parent asked for by name would be a
+ different change from the one upstream made.
+
+ Returns `(signature -> (prefix, sample_keys), model_keys)`, empty when nothing leaked.
+ """
+ from transformers.conversion_mapping import extract_weight_conversions_for_model
+ from transformers.core_model_loading import WeightRenaming
+ from transformers.modeling_utils import PreTrainedModel
+
+ def extract(module, prefix):
+ # 5.6 to 5.9 take the submodule's dotted path as a second argument, everything else
+ # takes the module alone. Asked of the function rather than of a version.
+ try:
+ return extract_weight_conversions_for_model(module, prefix)
+ except TypeError:
+ return extract_weight_conversions_for_model(module)
+
+ model_keys = set()
+ for name, _ in model.named_parameters(remove_duplicate = False):
+ model_keys.add(name)
+ for name, _ in model.named_buffers(remove_duplicate = False):
+ model_keys.add(name)
+
+ own = set()
+ seen_model_types = set()
+ own_conversions = extract(model, "")
+ if own_conversions is not None:
+ seen_model_types.add(getattr(model.config, "model_type", None))
+ own.update(_renaming_signature(c) for c in own_conversions)
+
+ leaked = {}
+ for name, submodule in model.named_modules():
+ if submodule is model or not name or not isinstance(submodule, PreTrainedModel):
+ continue
+ model_type = getattr(getattr(submodule, "config", None), "model_type", None)
+ if model_type is None or model_type in seen_model_types:
+ continue
+ conversions = extract(submodule, name)
+ if conversions is None:
+ continue
+ seen_model_types.add(model_type)
+ sample_keys = _sample_submodule_keys(submodule, name)
+ if not sample_keys:
+ continue
+ for conversion in conversions:
+ if not isinstance(conversion, WeightRenaming):
+ continue
+ signature = _renaming_signature(conversion)
+ if signature in own or signature in leaked:
+ continue
+ if _renaming_destroys_keys(conversion, sample_keys, model_keys):
+ leaked[signature] = (name, sample_keys)
+ return leaked, model_keys
+
+
+def _rescope_conversions(model, conversions):
+ """Replace every leaked renaming in `conversions` with its scoped form, or drop it."""
+ from transformers.core_model_loading import WeightRenaming
+
+ leaked, model_keys = _leaked_submodule_prefix_renamings(model)
+ if not leaked:
+ return conversions
+
+ rescoped_conversions = []
+ fixed = 0
+ dropped = 0
+ for conversion in conversions:
+ scoped_by_transformers = isinstance(conversion, WeightRenaming) and (
+ getattr(conversion, "scope_prefix", None) is not None
+ )
+ entry = (
+ leaked.get(_renaming_signature(conversion))
+ if isinstance(conversion, WeightRenaming) and not scoped_by_transformers
+ else None
+ )
+ if entry is None:
+ rescoped_conversions.append(conversion)
+ continue
+ prefix, sample_keys = entry
+ replacement = _rescoped_renaming(conversion, prefix, sample_keys, model_keys)
+ if replacement is None:
+ dropped += 1
+ continue
+ rescoped_conversions.append(replacement)
+ fixed += 1
+
+ if fixed or dropped:
+ logger.info(
+ f"Unsloth: re-scoped {fixed} and dropped {dropped} checkpoint renaming(s) that "
+ f"transformers merged into {type(model).__name__}'s conversion mapping from a "
+ f"submodule, where they rewrite the model's own weight names into names it does "
+ f"not have (transformers PR #45567, released in 5.6.0)"
+ )
+ return rescoped_conversions
+
+
+def fix_transformers_composite_prefix_renaming():
+ """Stop a pre-quantized multimodal checkpoint loading with no quantization metadata.
+
+ transformers 5.4.0 (PR #44300) merges a submodule's conversion mapping into the parent's
+ without re-scoping it, so the text model's `^model.language_model.` -> `^model.` fires on
+ the composite model's own names, and every bitsandbytes sidecar renames onto a key that
+ does not exist and is dropped. 352 of 352 Linear4bit come back with `quant_state is None`
+ on `unsloth/qwen3.8-27b-unsloth-bnb-4bit` at 5.4.0 and 5.5.4 (Gemma 3n: 439 of 439), and
+ the first forward raises `ValueError: quant_state is required`. The checkpoints are fine.
+ Fixed upstream in 5.6.0 by PR #45567; a runtime repair because unsloth-zoo caps
+ transformers at 5.5.0 on Apple Silicon, putting those users inside the window.
+
+ Neither gate is a version: the probe above reads the API, and the wrapper only touches a
+ renaming that rewrites THIS model's own names into names it does not have.
+ """
+ if _transformers_rescopes_submodule_prefix_renamings():
+ return
+ # unsloth_zoo carries the same repair, in temporary_patches/conversion_mapping_rescope.py,
+ # because it owns the bitsandbytes Linear4bit patch that reports this failure and is
+ # importable without unsloth. When it installed first there is nothing left to do: a second
+ # wrapper is measurably inert -- the first pass leaves no leaked signature for the second to
+ # match -- but it is still a wrapper nobody needs, and one of the two has to yield. This one
+ # does, so the newer implementation wins on a stack where the two versions disagree.
+ if _zoo_composite_prefix_renaming_installed():
+ return
+ try:
+ from transformers import conversion_mapping
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping the composite renaming fix ({e})")
+ return
+
+ original = getattr(conversion_mapping, "get_model_conversion_mapping", None)
+ if original is None:
+ return
+ # Through the chain, not the top object: another library may have wrapped us since, and a
+ # second copy walks every submodule again per load.
+ if _own_composite_prefix_renaming_installed(original):
+ return
+ # Wrap whatever is live, never `original.__wrapped__`: functools.wraps publishes that
+ # link, so unwrapping discards a third-party wrapper instead of one of ours.
+
+ @functools.wraps(original)
+ def get_model_conversion_mapping(*args, **kwargs):
+ conversions = original(*args, **kwargs)
+ try:
+ model = kwargs["model"] if "model" in kwargs else (args[0] if args else None)
+ if model is None or not conversions:
+ return conversions
+ return _rescope_conversions(model, conversions)
+ except Exception as e:
+ # A mapping we could not reason about is still the mapping transformers built.
+ logger.info(f"Unsloth: Could not re-scope the conversion mapping ({e})")
+ return conversions
+
+ # functools.wraps sets __wrapped__, but set it explicitly: the probe and the tests both
+ # read it, and a wraps-less edit must not make the patch un-probeable and un-undoable.
+ get_model_conversion_mapping.__wrapped__ = original
+ setattr(get_model_conversion_mapping, _COMPOSITE_PREFIX_RENAMING_FLAG, True)
+
+ try:
+ conversion_mapping.get_model_conversion_mapping = get_model_conversion_mapping
+ # `from ... import get_model_conversion_mapping` binds the object, not the attribute,
+ # so every holder needs rebinding: transformers.modeling_utils, transformers.
+ # integrations.peft, peft itself, and vllm's Transformers backend, which builds its
+ # WeightsMapper from it (vllm/model_executor/models/transformers/base.py).
+ owning_packages = ("transformers", "peft", "unsloth_zoo", "unsloth", "vllm")
+ upstream_module = getattr(conversion_mapping, "__name__", "transformers.conversion_mapping")
+ for module_name, module in list(sys.modules.items()):
+ if module is None or module is conversion_mapping:
+ continue
+ root = module_name.partition(".")[0]
+ if root not in owning_packages:
+ continue
+ namespace = getattr(module, "__dict__", None)
+ if not isinstance(namespace, dict):
+ continue
+ # `__dict__`, never `getattr`: transformers' lazy modules answer any name through
+ # `__getattr__` and print several hundred deprecation notices.
+ # Rebound only if it IS an alias of what we wrapped: `original` itself, upstream's
+ # own function (a module that imported the name before zoo wrapped it holds that,
+ # transformers.integrations.peft does), or zoo's marked wrapper. An identity test
+ # alone misses the first case; any-callable-by-name clobbers a package-local
+ # helper. Rebinding zoo's wrapper keeps its fix, since ours wraps it.
+ try:
+ bound = namespace.get("get_model_conversion_mapping", None)
+ if not callable(bound) or bound is get_model_conversion_mapping:
+ continue
+ is_alias = (
+ bound is original
+ or getattr(bound, "__module__", None) == upstream_module
+ or getattr(bound, "_unsloth_moe_patched", False)
+ )
+ if is_alias:
+ module.get_model_conversion_mapping = get_model_conversion_mapping
+ except Exception:
+ continue
+ logger.info(
+ "Unsloth: Patching transformers `get_model_conversion_mapping` so a pre-quantized "
+ "multimodal checkpoint keeps its bitsandbytes quant_state (transformers PR #45567)"
+ )
+ except Exception as e:
+ logger.info(f"Unsloth: Failed patching get_model_conversion_mapping ({e})")
+
+
_ROPE_SCALING_PATCH_FLAG = "_unsloth_patched_rope_scaling_setter"
@@ -3343,6 +3745,16 @@ def check_transformers_prequantized_vlm_quant_state():
except Exception:
transformers_version = "unknown"
+ # The runtime repair covers exactly these releases, and it is installed in the same
+ # import. Warning anyway would tell users to downgrade or upgrade away from a version
+ # that now works, which is worse than saying nothing: the advice contradicts the fix.
+ # Checked on the live attribute, so a repair that declined to install still warns.
+ # Either repair counts: when unsloth_zoo installed its copy first,
+ # `fix_transformers_composite_prefix_renaming` deliberately yields and the live function
+ # carries the zoo mark instead of ours, which is repaired all the same.
+ if _composite_prefix_renaming_repaired():
+ return
+
logger.warning(
f"Unsloth: transformers=={transformers_version} drops the bitsandbytes "
f"quant_state of pre-quantized multimodal checkpoints while loading them, so "