Skip to content

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

Merged
danielhanchen merged 26 commits into
mainfrom
fix/composite-prefix-renaming
Sep 22, 2026
Merged

danielhanchen merged 26 commits into
mainfrom
fix/composite-prefix-renaming

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

What this does

Stacked on #11450. Base that PR first.

That PR keeps a new resolve clear of transformers 5.4.0 and 5.5.x, where a prequantized bnb-4bit multimodal checkpoint loads with every quant_state set to None. It does nothing for an environment already inside the window, and on Apple Silicon unsloth-zoo/pyproject.toml:85,133 caps transformers at <=5.5.0 by platform marker, so those users are held there by our own metadata. This PR repairs the load at runtime instead.

Approach

A wrapper on transformers.conversion_mapping.get_model_conversion_mapping re-scopes any renaming the recursion collected from a submodule, and rewrites the parent's own weight names off the map. For Qwen3.5 it produces

^model.language_model.model.language_model.  ->  model.language_model.model.

which matches the semantics upstream 5.6.2 builds through PrefixChange.with_submodel_prefix. Checked key by key over a 5561 key universe: 5559 agree, and the 2 that diverge are keys a checkpoint cannot contain. A user crossing into 5.6.0 therefore sees no change in behaviour at the boundary.

Two alternatives were rejected. Exempting the bitsandbytes sidecar suffixes from renaming treats the symptom and leaves the packed weight on the rescue path. Reattaching sidecars after load is what unsloth-zoo#1132 already attempts and cannot work, because module.quant_state is None unless from_prequantized ran.

Neither gate is a version number

The install gate asks whether this transformers has any of the three shapes upstream has used for per submodule scoping: a model_prefix argument, PrefixChange.with_submodel_prefix, or a scope_prefix field. Across 19 releases tested it installs on exactly two, 5.4.0 and 5.5.4, and on none of 4.57.6, 5.0 to 5.3, or 5.6 to 5.17.

The call gate only touches a renaming that demonstrably rewrites this model's real parameter names into names it does not have. That is what separates the composite model, where the entry is destructive, from the standalone text model it was written for, where it matches nothing.

Measured

Real unsloth/qwen3.8-27b-unsloth-bnb-4bit, 22.3 GB, plain transformers, B200. quant_state is None out of 352:

transformers without with forward with patch
5.3.0 0 0 ok, -3.877289056777954
5.4.0 352 0 ok, -3.877289056777954
5.5.4 352 0 ok, -3.877289056777954
5.6.2 0 0 ok, -3.877289056777954
5.17.0 0 0 ok, -3.877257823944092

The repaired logits mean matches the known good releases to all 16 digits, so the recovered state is the same state and not merely a non null one. Gemma 3n goes from 439 of 439 to 138 of 439 at 5.5.4, which is the count every working release gives.

Through FastModel.from_pretrained at 5.5.4: before, the packed weight RuntimeError; after, FORWARD OK logits (1, 8, 248320) -3.876821994781494. That run also exercises it composing with unsloth-zoo's own wrapper on the same function.

Blast radius

Proved rather than argued, on 10 real checkpoints across 12 model families: 53 cells, 52 bit identical, 1 intentional repair, 0 violations, with the wrapper provably installed in 20 of them.

An earlier revision of this description cited a 49 tensor sha256 comparison on a synthetic fixture. That fixture randomly re initialises its vision tower, so 8 of its 49 hashes move between two identical loads and three loads produce three different sha256 sets. The conclusion held, but that evidence did not support it and has been replaced with the real checkpoint matrix above. _rescope_conversions returns the caller's own list object for a non composite. The standalone text model keeps its renaming. The wrapper is idempotent and carries __wrapped__ so it can be undone.

One hazard found during the build and fixed: the rebinding sweep must read module.__dict__ rather than getattr, or transformers' lazy modules emit several hundred alias deprecation notices at import.

Side effect worth having

This also repairs the save side, on 5.4.0 as well as 5.5.x. Saving a composite writes a key set no other release can read, and the two broken releases are broken differently: 5.4.0 writes 808ef73994cb96f0 and 5.5.4 writes 0e18df9bc13c8cdc. Patched, both normalise to 0385fdc8f9e48471, which is what the working releases write.

Tests

tests/test_composite_prefix_renaming.py, 29 tests on real meta device models with no downloads, plus 135 lines added to tests/test_import_fixes_drift.py and 551 to tests/test_prequantized_vlm_quant_state_guard.py.

Three defects were found and fixed while checking this branch against its rebased base, each reproduced on transformers 5.5.3 with torch 2.14.0 CPU before the fix and each with a negative control:

  • 670ab8e85: the base merge left two top-level definitions of _transformers_rescopes_submodule_prefix_renamings in different regions of the file, so git reported no conflict while Python bound the later one. inspect.getsourcelines on the imported module pointed at line 3703, not 921. The dead copy answered differently when core_model_loading could not import.
  • 14ca4cf11: _uninstall_runtime_repair imported transformers unconditionally, so a pytest-only environment got 2 failures out of a file documented to run in isolation. Measured 2 failed / 19 passed before, 20 passed / 1 skipped after, against 20 passed on the base.
  • d6180c68e: _gpu_init called the quant_state check twice, and the first call logged the downgrade advice before the repair installed. The check also recognised only our own mark, so the supported unsloth_zoo-installed-first path still warned.

96 passed and 13 skipped on 5.17.0. 73 passed and 21 skipped on 4.57.6. On 5.5.4, 97 passed, 11 skipped and 1 failed, and that failure is the drift detector behaving as designed: it fails rather than skips while the upstream pathology is active, and will go green on its own once the window is behind us. ruff check clean.

Not covered

Apple Silicon, Windows and WSL were not exercised. The code has no platform branch and passes on CPU as well as GPU, but the motivating case is Mac and no Mac ran it. torch 2.6.0 and TRL 0.22.2 arms were not run, nor Qwen3.5-MoE end to end, nor any training run.

Known, measured, not blocking

The idempotency guard is defeated once unsloth_zoo wraps the same function on top, so an
explicit second call installs a second wrapper. Measured inert: bit identical state dict,
identical logits, and the chain saturates at depth 4. Hardening it is optional.

What it looks like in Studio

Two isolated Studio installs, each built by its own tree's install.sh --local: BEFORE is this PR's merge base, AFTER is its head. Same checkpoint, same prompt, same machine. Both sides resolve transformers 5.5.0 from this repo's own <=5.5.0 ceiling, which is what puts a default install inside the window.

before and after

unsloth/gemma-3n-E2B-it-unsloth-bnb-4bit, asked "What is the capital of France? Answer in one word."

BEFORE (merge base) AFTER (this PR)
model loads, toast says loaded loads, toast says loaded
the turn Response interrupted / An internal error occurred. after 1.68s answers Paris, 41 tokens at 1.3 tok/s
backend log 303 x no quant_state found, then mat1 and mat2 shapes cannot be multiplied (38x2048 and 1x7864320) no quant_state line at all

The backend error in the BEFORE log is the same one the linked issues report. Both halves show the model loaded and the prompt echoed, so the difference is not a missed selection.

…t_state

transformers 5.4.0 through 5.5.4 drop the bitsandbytes quant_state sidecar
tensors of pre-quantized composite (multimodal) checkpoints, so every quantized
Linear loads with quant_state None and the first forward fails with a misleading
shape error. Reported as #9867, #10010, #10017 and #10276, where the consensus
was that the published checkpoint needed regenerating. It does not.

transformers 5.4.0 (PR #44300) made the conversion mapping recurse into
PreTrainedModel submodules, which pulled the text model's
^model.language_model. -> ^model. WeightRenaming into the composite model's
mapping. Renamings run before the bitsandbytes converter, so weight.absmax,
weight.quant_map, weight.nested_absmax, weight.nested_quant_map and
weight.quant_state.bitsandbytes__nf4 all renamed to keys the model does not have
and were discarded as unexpected, while the packed weight loaded raw.
transformers PR #45567 fixed it in 5.6.0.

Measured on one B200 with unsloth/qwen3.8-27b-unsloth-bnb-4bit: 352 of 352
quantized Linear modules lose quant_state on 5.4.0 and 5.5.4, and 0 of 352 on
5.2.0, 5.3.0 and every release from 5.6.2 to 5.17.0. unsloth/gemma-3n-E2B-it-
unsloth-bnb-4bit behaves the same way, 439 of 439 at 5.5.4 against 138 of 439 at
5.3.0 and 5.6.2.

The exclusions are added rather than the ceiling moved, so they stay correct
whenever that ceiling is raised. The import-time check names the cause before
the shape error appears; it warns rather than raises because a run that loads no
pre-quantized multimodal checkpoint is unaffected.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T14:18:48.184106Z 857fca7 Manual request
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: cb289afdf3

ℹ️ About Codex in GitHub

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

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

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

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed main only has the peft stub for get_model_conversion_mapping in import_fixes.py, so the rescoping repair is not there yet and the 5.4 and 5.5 load really does drop quant_state. This is conflicting and stacked on #11450, so rebase once the ceiling lift lands and confirm the stack order it should merge in.

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen danielhanchen self-assigned this Sep 22, 2026
…exclusions

The pin half of this PR could not land and the detector was wrong on source
installs. Both are addressed here.

The exclusions are reverted. `unsloth_zoo==2026.9.6` declares
`transformers<=5.5.0` in its own metadata, and every extra here that names
transformers also names the zoo, so the resolver intersects to 5.5.0 no matter
what this file says. Excluding 5.5.0 therefore resolves backwards, and
`unsloth/models/loader.py:86` requires 5.5.0 or newer for Gemma 4, so a fresh
install traded a multimodal bnb defect for every Gemma 4 load. Measured with
`uv pip compile` on python 3.12:

    main                       transformers==5.5.0
    this branch, before        transformers==5.3.0
    #11016 alone               transformers==5.5.0
    #11016 plus this branch    transformers==5.3.0

so lifting the ceiling in #11016 is not sufficient either: the exclusions wait
on unslothai/unsloth-zoo#1227 reaching a published zoo release. A test now
states that, and fails if 5.5.0 is excluded again while the zoo still caps it.

The detector no longer reads a version interval. It asks the installed
transformers whether `extract_weight_conversions_for_model` scopes a
submodule's conversions to where the submodule lives, in the three spellings
upstream has used: the `model_prefix` argument of 5.6 to 5.9,
`PrefixChange.with_submodel_prefix` over the same range, and the `scope_prefix`
field carried from 5.10 on. The interval was wrong at both ends for anyone on
git main, which reported 5.3.0.dev0 at the commit that introduced the defect
and 5.6.0.dev0 at the commit that fixed it. Verified against thirteen real
installed releases: it fires on 5.4.0 and 5.5.0 through 5.5.4, and stays silent
on 4.57.6, 5.2.0, 5.3.0, 5.6.0, 5.6.2, 5.14.1 and 5.17.0.

The warning also no longer tells the user to install something this repository
forbids without saying how, and stays warn only.
danielhanchen and others added 3 commits September 22, 2026 10:14
Reverting the exclusions took the file from current main, which carries an
unrelated hf-xet requirement added since this branch forked. The PR now shows
no pyproject.toml change at all, which is the intent.
This is the only check in `_gpu_init` that imports transformers instead of
reading its metadata: `from transformers import conversion_mapping` pulls in
271 transformers submodules. It was being called at line 98, eight lines above
`disable_torchaudio_if_cuda_mismatched`, which is there precisely because
anything that reaches transformers.processing_utils, and through it
transformers.audio_utils and torchaudio, before that guard runs takes the whole
`import unsloth` down on a torchaudio that raises at extension init.

Measured on transformers 5.17.0, the probe's import does not itself reach
processing_utils, audio_utils or torchaudio, so this was a latent ordering
hazard rather than a live failure. Nothing holds that true for the next
release, and the check has no reason to run early, so it now runs after
`fix_huggingface_hub` and still before `import unsloth_zoo`.
`test_the_check_runs_after_the_torchaudio_guard` reads the call order out of
the module with `ast` and keeps it there.
danielhanchen and others added 4 commits September 22, 2026 11:55
….4 and 5.5

transformers 5.4.0 made get_model_conversion_mapping recurse into PreTrainedModel
submodules and merge each one's conversion mapping into the parent's, verbatim. The
standalone Qwen3.5, Qwen3.5-MoE and Gemma 3n text models register a prefix renaming,
^model.language_model. to ^model., which is right for themselves and wrong for the
composite model whose weights really are named model.language_model.... Renamings run
before the bitsandbytes converter, so every sidecar tensor of a pre-quantized checkpoint
(absmax, quant_map, nested_absmax, nested_quant_map, quant_state.bitsandbytes__nf4) is
renamed onto a key the model does not have and discarded as unexpected, while the packed
uint8 weight is rescued by original key with no converter attached. Every Linear4bit then
has quant_state None and the first forward raises.

Measured with plain transformers and no unsloth in the process, on a real
unsloth/qwen3.8-27b-unsloth-bnb-4bit: 352 of 352 Linear4bit with quant_state None at
5.4.0 and 5.5.4, 0 of 352 with this fix, logits mean identical to 5.3.0 and 5.6.2.
Gemma 3n goes 439 of 439 to the same 138 that every working version leaves unquantized.

Upstream fixed this in 5.6.0 (PR #45567) by scoping a submodule's mapping to where the
submodule lives. This is that correction, for a transformers that does not have it:
^model.language_model. to ^model. collected from the submodule at model.language_model
becomes ^model.language_model.model.language_model. to model.language_model.model., which
is the pair 5.6.2 builds for the same model and can only fire on a doubled prefix.

Two gates, neither a version number. The install probe asks whether this transformers has
any of the three shapes upstream has used for the scoping (the model_prefix argument,
PrefixChange.with_submodel_prefix, or the scope_prefix field), and declines if so, which
is every release outside 5.4.0 to 5.5.4 including 4.57.6. The wrapper then only touches a
renaming that demonstrably rewrites this model's own parameter names into names it does
not have, so it is inert for a non-composite model and for the standalone text model the
entry was written for.

Also repairs the save side: saving a composite model under 5.5.4 writes
model.language_model.visual... keys that no other release can read, and with the fix the
key set is identical to the one 5.3.0 writes.
…the repair

unsloth_zoo patches the same function in temporary_patches/moe_utils_bnb4bit.py
without functools.wraps and without __wrapped__, setting only its own marker. When
zoo goes first, the getattr(original, "__wrapped__", original) unwrap cannot see
past it, so 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 the
identity test left it bound to the unscoped mapping. transformers.integrations.peft
is exactly that module, imported during modeling_utils init, and load_adapter() then
renamed Qwen3.5 and Gemma 3n adapter keys away from their real model.language_model.*
modules. Rebind any binding under that name that is not already ours. Zoo's own fix is
preserved because our wrapper wraps original, which is zoo's wrapper when zoo went first.

The version warning also fired on exactly the releases the repair covers, telling users
to downgrade or upgrade away from a version that had just been fixed. It now runs after
the repair and reads the live attribute, so it stays silent when the repair installed
and still warns when it declined.
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
rebinds any binding under that name. Unrestricted that is too broad: a notebook or
plugin defining its own get_model_conversion_mapping before importing unsloth would
have it replaced with the transformers wrapper. Restrict the walk to transformers,
peft, unsloth_zoo and unsloth. The new test fails with the restriction removed and
the pre-zoo rebinding still passes with it in place.
@danielhanchen
danielhanchen force-pushed the fix/composite-prefix-renaming branch from c89288f to f6d4882 Compare September 22, 2026 11:58
… where it runs

The sweep replaced any callable bound under `get_model_conversion_mapping` in any module
whose root package was transformers, peft, unsloth_zoo or unsloth. Measured on
transformers 5.5.0, that really does clobber an unrelated helper living inside one of
those namespaces. It now rebinds three things and nothing else: the object it wrapped, a
function whose `__module__` is transformers' own `conversion_mapping`, and a wrapper
carrying unsloth_zoo's marker. The pre-zoo case the breadth existed for still works, and
`transformers.integrations.peft` is still rebound.

The test that claimed this safety only ever planted its helper outside those four
packages, and passed on 5.17.0 without the sweep running at all: the repair declines
there, so four tests skipped and three passed vacuously. A `forced_install` fixture now
opens the gate for the tests of what installation DOES, restoring every binding on the
way out, so they run on every release and the unrelated-helper case is parametrized
across all four package namespaces plus one outside.

On transformers 5.5.0, the falsification set is 12 of 12: the aliases are rebound, no
unrelated callable is, the caller's list is never mutated, re-scoping is idempotent, the
standalone text model keeps its renaming, and composing with unsloth_zoo in either order
leaves no destructive renaming behind.
Rebased onto #11450's current head, which moved three commits while this was measured. The
merge of the two test files keeps both sides: the base branch's `_build_broken` stand-in
and this branch's `_uninstall_runtime_repair`, uninstall first because the stand-in module
has no `get_model_conversion_mapping` for the uninstall to read.
@danielhanchen
danielhanchen force-pushed the fix/composite-prefix-renaming branch from f6d4882 to 2d2b2fc Compare September 22, 2026 11:59
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Compatibility corners, run against the branch as it stands now (128e150f1, on top of the zoo-deferral and comment-trim commits). One real gap found and fixed, one test portability defect found and fixed.

vLLM holds its own copy, and was not being rebound

vllm/model_executor/models/transformers/base.py does from transformers.conversion_mapping import get_model_conversion_mapping at import time and builds its WeightsMapper from the result. Measured with the real vllm 0.30.0 module imported before the repair, on transformers 5.5.4:

vllm backend binding rebound
before False, so a fast_inference path in that import order maps a composite model's weights with the unscoped renaming
after True

vllm is now in owning_packages. The alias test added earlier is what makes that safe: a callable planted under vllm.* that is not an alias of the function being wrapped is still left alone, measured, and a regression test models the backend module without paying vllm's half-minute import.

Test portability on the torch floor

import unsloth.import_fixes as import_fixes inside a test re-runs unsloth/__init__, which requires unsloth_zoo. On a torch 2.6.0 floor environment without it, that turned 9 tests into collection errors, including the three zoo-deferral tests added in e3fa51ca4, while the rest of the file ran fine. All four call sites now reuse the module the file already imported from.

environment before after
torch 2.6.0+cpu, transformers 5.5.4, no unsloth_zoo 15 passed, 9 errors 50 passed

The matrix

corner result
transformers 4.57.6, 5.0.0, 5.2.0, 5.3.0, 5.4.0, 5.5.0-5.5.4, 5.6.0, 5.6.2, 5.9.0, 5.10.0, 5.17.0 30 cells (15 releases x Qwen3.5 and Gemma 3n), probe decision equals real upstream behaviour in all 30
torch 2.6.0 floor (CPU) + transformers 5.5.4 probe False, repair installs, leak confirmed, 50 passed
torch 2.13.0 + transformers 5.5.4 / 5.17.0 50 passed / 47 passed 3 skipped
peft 0.18.0, 0.19.1, 0.20.0, 0.21.0 x transformers 5.5.4 installed in each, every holder rebound, 0 stale, 50 passed each
peft 0.21.0 x transformers 5.17.0 declines as it should, 5 holders, 0 stale, 47 passed 3 skipped
TRL 0.22.2 and TRL 1.13.0 x transformers 5.5.4, repaired Gemma 3n load, 10 LoRA steps both load 0 of 301 null, forward ok, and produce identical loss and grad-norm sequences: 10.3752, 10.7603, 4.0889 ... 0.8409, 0.7128, final training loss 3.3076 in both
vllm 0.30.0, Transformers backend binding rebound after the fix, unrelated vllm.* callable untouched
falsification set on 5.5.0, re-run on this branch state 12 of 12
real checkpoint re-check on this branch state Gemma 3n at 5.5.0 repaired: 138 of 439, state dict sha256 93cdcc5e4b8bbc29 and quant-state sha256 both equal to the 5.3.0 healthy reference over all 3062 tensors

Surfaces that cannot be reached by this diff

Checked rather than assumed, by grepping the added lines: no sys.platform, os.name, platform., darwin, win32, cuda or device predicate anywhere in the new code, and no reference to unsloth_compiled_cache, so there is no compiled forward to regenerate and no MLX or GPU-vendor branch to isolate. The new code imports from transformers only. Browser engines are not in scope: nothing in this diff runs in a browser.

Still not proven: Apple Silicon, Windows and WSL as real runners. The staging legs (ubuntu-latest, macos-15, windows-latest) and the org CI legs were still queued at the time of writing, so nothing there is quoted as a pass. A real vLLM fast_inference GRPO run was not executed either; what is measured is the binding vLLM would use.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

unsloth_zoo now marks its wrapper chain explicitly: `moe_utils_bnb4bit.py` publishes
`common.WRAPPER_INNER_ATTR` pointing at whatever it wrapped. It cannot publish `__wrapped__`
instead, because zoo's own 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.

Both walkers here still followed `__wrapped__` only, and both docstrings claimed to see past
the MoE wrapper on that basis. zoo registers the re-scope BEFORE the MoE patch, so the MoE
wrapper is on top in the ordinary case, not a corner: `_composite_prefix_renaming_repaired`
would answer False for a repair that is live and put the downgrade advice back into the
Linear4bit guard's message, and `_zoo_composite_prefix_renaming_installed` would answer False
and stack a second re-scope wrapper for nothing. Exactly the two outcomes those functions
exist to prevent.

Both now follow `__wrapped__` or the link, through one `_next_in_wrapper_chain` helper. The
attribute is spelled as a literal, like the flag above it, so a zoo too old to define it
cannot turn a skipped repair into an ImportError.

The test that claimed to cover this built its wrapper with `__wrapped__`, which is the one
thing the real MoE wrapper does not set, so it passed either way. It now drives the real
patch and asserts the absence of `__wrapped__` as part of the contract, and skips rather than
fails against an unsloth_zoo predating the link, where the repair genuinely is invisible from
here and nothing this side can fix it. Dropping the link fails it: 1 failed, 28 passed.

Plus a bound check on both walkers against a mutually-wrapping pair.

Suites against the zoo checkout: 108 passed, 4 skipped. Across transformers 5.4.0, 5.5.0 and
5.5.4, 56 passed; 5.6.2, 53 passed 3 skipped; 4.57.6, 26 passed 30 skipped. Against an older
installed zoo the new test skips, 52 passed 4 skipped. Narrow ruff gate clean.
danielhanchen added a commit that referenced this pull request Sep 22, 2026
…'s bnb quant state (#11450)

Loading a pre-quantized bnb-4bit multimodal checkpoint on transformers 5.4.0 or 5.5.x leaves every quantized Linear4bit with quant_state set to None, and the first forward dies with a shape error that reads like a corrupt checkpoint. Reported as #9867, #10010, #10017 and #10276, where reporters were told to delete and redownload checkpoints that were never wrong.

This warns at import, before the misleading error appears, by asking the installed transformers whether it scopes a submodule's conversions to where the submodule lives. It never reads a version number: upstream main reported 5.3.0.dev0 at the commit that introduced the defect (transformers PR #44300) and 5.6.0.dev0 at the commit that fixed it (PR #45567), so a closed version interval is wrong at both ends on a source install. The probe accepts all three spellings upstream has used for the scoping, and answers healthy on anything it does not recognise.

Verified against thirteen real installed releases: it fires on 5.4.0 and 5.5.0 through 5.5.4, and stays silent on 4.57.6, 5.2.0, 5.3.0, 5.6.0, 5.6.2, 5.14.1 and 5.17.0.

The check runs below disable_torchaudio_if_cuda_mismatched, because it is the only check in _gpu_init that imports transformers rather than reading its metadata, and a test reads that call order out of the module with ast.

pyproject.toml is unchanged. An earlier revision excluded the affected releases, which resolved backwards to 5.3.0 and broke every Gemma 4 load, because unsloth_zoo caps transformers at 5.5.0 in its own published metadata and unsloth/models/loader.py requires 5.5.0 or newer for Gemma 4. Those exclusions wait on unslothai/unsloth-zoo#1227 reaching a published release, and a test fails if 5.5.0 is excluded again while that is still true.

Warn only, on every platform. It does not repair the load. The repair is #11452.
Base automatically changed from fix/prequantized-vlm-quant-state to main September 22, 2026 13:44
The installer took `original.__wrapped__` unconditionally before wrapping. Any wrapper
that plays by the rules publishes `__wrapped__` through functools.wraps, so the level
removed was somebody else's: measured on transformers 5.5.4 with a third-party wrapper
installed first, it stopped being called at all (0 invocations), and the alias sweep then
spread the replacement to every module holding it. It now wraps whatever is live, and the
already-installed test walks the chain rather than reading the top object, so a foreign
wrapper on top of ours does not stack a second copy that would walk every submodule again
per load. After the fix, same scenario: third-party wrapper still in the chain, invoked
once per call, zero destructive renamings left, and a second install is a no-op.

Regression test added, plus two portability fixes to the tests: the remaining
`import unsloth.import_fixes` call sites re-run `unsloth/__init__`, which needs
unsloth_zoo, and turned the new bounded-walk test into an error on a torch 2.6.0 floor
environment. 56 passed on transformers 5.4.0, 5.5.4 and 5.5.4 with torch 2.6.0, 53 passed
on 5.17.0.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

#11450 landed on main as one squashed commit, so GitHub retargeted this PR to
main and the merge no longer recognised the base commits this branch already
carried. Three conflicts, all of the same shape: this branch adds a block where
main has none, so HEAD wins in each. The rest of import_fixes.py auto merged,
which matters because main moved on separately, and the resolution keeps that
work: nothing in main's copy of any of the three files is missing here.

The part the merge got wrong on its own: main carries the quant_state check at
_gpu_init.py:110 with its `del` at 123, and this branch moved the call below
the repair with its own `del`. Auto merge kept both, which is not merely the
duplicate warning #11452 already fixed once, it is a NameError on `import
unsloth`, since the second `del` deletes a name the first already removed.
`test_the_check_is_called_once_and_after_the_repair` catches the duplicate call
that causes it. Resolved to one call, after the repair, and one `del`.

Verified after resolving: no duplicate top-level definitions, 106 passed and 4
skipped across the three suites, and 24 passed with 1 skipped in a venv holding
only pytest and packaging.

test_formatter_fixed_point reports studio/backend/tests/test_diffusion_xpu_training.py
and tests/test_omni_auto_class_resolution.py as not fixed points. Both arrived
from main today, in #9534 and #11467, and the same test fails on main itself at
b7aca55, so they are pre-existing and not touched here.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9f6f31d691

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread unsloth/import_fixes.py
Comment on lines +1155 to +1159
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Track every prefix for duplicate renaming signatures

When a transformers 5.4/5.5 composite contains two distinct nested model types that register the same WeightRenaming signature, this condition discards the second submodule's prefix; built-in gemma3n_text and qwen3_5_text, for example, both register the same language-model prefix change. _rescope_conversions subsequently replaces every matching conversion using the first prefix, so the second submodule loses its correctly scoped conversion and checkpoints using that submodule's standalone/legacy key form cannot load correctly. Preserve an ordered entry for each occurrence rather than collapsing leaked renamings into a signature-keyed dictionary.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured rather than argued, and it does not reproduce. I built every composite architecture transformers 5.5.4 ships on the meta device, 94 of them, and asked which ones have two distinct nested model types contributing the same renaming signature at different prefixes: zero. gemma3n_text and qwen3_5_text do register the same prefix change, but no single architecture nests both, and the walk only considers a submodule whose model_type has not been seen, so one type cannot supply two entries.

The consequence in the hypothetical case is also narrower than described. A rescoped entry is anchored at its own prefix and can only fire on a doubled prefix, so for the second submodule the entry ends up matching nothing, which is what a real checkpoint wants. It would differ from upstream 5.6 only for a checkpoint that actually carries the doubled prefix form under that second submodule. Rejecting under the bar for reachable correctness bugs. What would change my mind is one architecture from that scan, or a published checkpoint with those doubled keys.

ruff-format-with-kwargs rewrites these on the next edit, so pre-commit.ci would
fail the following PR that touches them.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e0ca2d49bf

ℹ️ About Codex in GitHub

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

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

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

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

Post-convergence comment pass, comments and docstrings only, AST verified. The three
longest docstrings and the two multi-paragraph sweep comments collapse to the fact plus
its citation: 112 docstring lines across this PR's functions to 78, and the two sweep
blocks from 26 lines to 11. Every survivor names a mistake the next reader would make,
the measured counts stay in the PR description where they belong.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 857fca7a73

ℹ️ About Codex in GitHub

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

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

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

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

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 22, 2026
@danielhanchen
danielhanchen merged commit 151517f into main Sep 22, 2026
3 of 28 checks passed
@danielhanchen
danielhanchen deleted the fix/composite-prefix-renaming branch September 22, 2026 14:26
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
…ow (unslothai#11572)

* Let the composite renaming tests run inside the transformers 5.4 window

The Repo tests (CPU, rest) lane pins transformers<5.5 and so installs 5.4.0,
the exact release fix_transformers_composite_prefix_renaming exists for. unslothai#11452
added five tests there whose own lane was cancelled before it reported, and all
five fail on main at that pin:

- the drift test failed whenever the probe answered unscoped, which on 5.4.0 is
  the expected answer. It now fails when the probe answers unscoped on a
  release that ships upstream's fix (the probe drifted), or when no repair,
  unsloth's or unsloth_zoo's, is live inside the window.
- the install gate read only the top of the chain. unsloth_zoo's MoE wrapper
  sits on top of the repair and publishes no __wrapped__, so a live repair
  read as missing. It now walks the chain by both links.
- forced_install measured installs from whatever the import left live, where
  the repair is already in the chain and declines. It now starts from the
  bare upstream function, through monkeypatch so a test that monkeypatches the
  same attribute cannot restore the stripped function on teardown.

* Skip the composite renaming tests on unsloth's own stand-in modules

On transformers 4.x, importing unsloth installs inert stand-ins for
transformers.core_model_loading and transformers.conversion_mapping so peft
can import. The helpers found them and ran four tests against a WeightRenaming
that renames nothing; at 4.57.6 those four fail. A real module is a file on
disk, and the stand-ins are not.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…'s bnb quant state (unslothai#11450)

Loading a pre-quantized bnb-4bit multimodal checkpoint on transformers 5.4.0 or 5.5.x leaves every quantized Linear4bit with quant_state set to None, and the first forward dies with a shape error that reads like a corrupt checkpoint. Reported as unslothai#9867, unslothai#10010, unslothai#10017 and unslothai#10276, where reporters were told to delete and redownload checkpoints that were never wrong.

This warns at import, before the misleading error appears, by asking the installed transformers whether it scopes a submodule's conversions to where the submodule lives. It never reads a version number: upstream main reported 5.3.0.dev0 at the commit that introduced the defect (transformers PR #44300) and 5.6.0.dev0 at the commit that fixed it (PR #45567), so a closed version interval is wrong at both ends on a source install. The probe accepts all three spellings upstream has used for the scoping, and answers healthy on anything it does not recognise.

Verified against thirteen real installed releases: it fires on 5.4.0 and 5.5.0 through 5.5.4, and stays silent on 4.57.6, 5.2.0, 5.3.0, 5.6.0, 5.6.2, 5.14.1 and 5.17.0.

The check runs below disable_torchaudio_if_cuda_mismatched, because it is the only check in _gpu_init that imports transformers rather than reading its metadata, and a test reads that call order out of the module with ast.

pyproject.toml is unchanged. An earlier revision excluded the affected releases, which resolved backwards to 5.3.0 and broke every Gemma 4 load, because unsloth_zoo caps transformers at 5.5.0 in its own published metadata and unsloth/models/loader.py requires 5.5.0 or newer for Gemma 4. Those exclusions wait on unslothai/unsloth-zoo#1227 reaching a published release, and a test fails if 5.5.0 is excluded again while that is still true.

Warn only, on every platform. It does not repair the load. The repair is unslothai#11452.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…4 and 5.5 (unslothai#11452)

* Exclude the transformers releases that discard pre-quantized bnb quant_state

transformers 5.4.0 through 5.5.4 drop the bitsandbytes quant_state sidecar
tensors of pre-quantized composite (multimodal) checkpoints, so every quantized
Linear loads with quant_state None and the first forward fails with a misleading
shape error. Reported as unslothai#9867, unslothai#10010, unslothai#10017 and unslothai#10276, where the consensus
was that the published checkpoint needed regenerating. It does not.

transformers 5.4.0 (PR #44300) made the conversion mapping recurse into
PreTrainedModel submodules, which pulled the text model's
^model.language_model. -> ^model. WeightRenaming into the composite model's
mapping. Renamings run before the bitsandbytes converter, so weight.absmax,
weight.quant_map, weight.nested_absmax, weight.nested_quant_map and
weight.quant_state.bitsandbytes__nf4 all renamed to keys the model does not have
and were discarded as unexpected, while the packed weight loaded raw.
transformers PR #45567 fixed it in 5.6.0.

Measured on one B200 with unsloth/qwen3.8-27b-unsloth-bnb-4bit: 352 of 352
quantized Linear modules lose quant_state on 5.4.0 and 5.5.4, and 0 of 352 on
5.2.0, 5.3.0 and every release from 5.6.2 to 5.17.0. unsloth/gemma-3n-E2B-it-
unsloth-bnb-4bit behaves the same way, 439 of 439 at 5.5.4 against 138 of 439 at
5.3.0 and 5.6.2.

The exclusions are added rather than the ceiling moved, so they stay correct
whenever that ceiling is raised. The import-time check names the cause before
the shape error appears; it warns rather than raises because a run that loads no
pre-quantized multimodal checkpoint is unaffected.

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

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

* Ask transformers whether it scopes submodule renamings, and drop the exclusions

The pin half of this PR could not land and the detector was wrong on source
installs. Both are addressed here.

The exclusions are reverted. `unsloth_zoo==2026.9.6` declares
`transformers<=5.5.0` in its own metadata, and every extra here that names
transformers also names the zoo, so the resolver intersects to 5.5.0 no matter
what this file says. Excluding 5.5.0 therefore resolves backwards, and
`unsloth/models/loader.py:86` requires 5.5.0 or newer for Gemma 4, so a fresh
install traded a multimodal bnb defect for every Gemma 4 load. Measured with
`uv pip compile` on python 3.12:

    main                       transformers==5.5.0
    this branch, before        transformers==5.3.0
    unslothai#11016 alone               transformers==5.5.0
    unslothai#11016 plus this branch    transformers==5.3.0

so lifting the ceiling in unslothai#11016 is not sufficient either: the exclusions wait
on unslothai/unsloth-zoo#1227 reaching a published zoo release. A test now
states that, and fails if 5.5.0 is excluded again while the zoo still caps it.

The detector no longer reads a version interval. It asks the installed
transformers whether `extract_weight_conversions_for_model` scopes a
submodule's conversions to where the submodule lives, in the three spellings
upstream has used: the `model_prefix` argument of 5.6 to 5.9,
`PrefixChange.with_submodel_prefix` over the same range, and the `scope_prefix`
field carried from 5.10 on. The interval was wrong at both ends for anyone on
git main, which reported 5.3.0.dev0 at the commit that introduced the defect
and 5.6.0.dev0 at the commit that fixed it. Verified against thirteen real
installed releases: it fires on 5.4.0 and 5.5.0 through 5.5.4, and stays silent
on 4.57.6, 5.2.0, 5.3.0, 5.6.0, 5.6.2, 5.14.1 and 5.17.0.

The warning also no longer tells the user to install something this repository
forbids without saying how, and stays warn only.

* Restore pyproject.toml to the merge base

Reverting the exclusions took the file from current main, which carries an
unrelated hf-xet requirement added since this branch forked. The PR now shows
no pyproject.toml change at all, which is the intent.

* Call the quant_state check below the torchaudio guard

This is the only check in `_gpu_init` that imports transformers instead of
reading its metadata: `from transformers import conversion_mapping` pulls in
271 transformers submodules. It was being called at line 98, eight lines above
`disable_torchaudio_if_cuda_mismatched`, which is there precisely because
anything that reaches transformers.processing_utils, and through it
transformers.audio_utils and torchaudio, before that guard runs takes the whole
`import unsloth` down on a torchaudio that raises at extension init.

Measured on transformers 5.17.0, the probe's import does not itself reach
processing_utils, audio_utils or torchaudio, so this was a latent ordering
hazard rather than a live failure. Nothing holds that true for the next
release, and the check has no reason to run early, so it now runs after
`fix_huggingface_hub` and still before `import unsloth_zoo`.
`test_the_check_runs_after_the_torchaudio_guard` reads the call order out of
the module with `ast` and keeps it there.

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

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

* Load pre-quantized multimodal checkpoints correctly on transformers 5.4 and 5.5

transformers 5.4.0 made get_model_conversion_mapping recurse into PreTrainedModel
submodules and merge each one's conversion mapping into the parent's, verbatim. The
standalone Qwen3.5, Qwen3.5-MoE and Gemma 3n text models register a prefix renaming,
^model.language_model. to ^model., which is right for themselves and wrong for the
composite model whose weights really are named model.language_model.... Renamings run
before the bitsandbytes converter, so every sidecar tensor of a pre-quantized checkpoint
(absmax, quant_map, nested_absmax, nested_quant_map, quant_state.bitsandbytes__nf4) is
renamed onto a key the model does not have and discarded as unexpected, while the packed
uint8 weight is rescued by original key with no converter attached. Every Linear4bit then
has quant_state None and the first forward raises.

Measured with plain transformers and no unsloth in the process, on a real
unsloth/qwen3.8-27b-unsloth-bnb-4bit: 352 of 352 Linear4bit with quant_state None at
5.4.0 and 5.5.4, 0 of 352 with this fix, logits mean identical to 5.3.0 and 5.6.2.
Gemma 3n goes 439 of 439 to the same 138 that every working version leaves unquantized.

Upstream fixed this in 5.6.0 (PR #45567) by scoping a submodule's mapping to where the
submodule lives. This is that correction, for a transformers that does not have it:
^model.language_model. to ^model. collected from the submodule at model.language_model
becomes ^model.language_model.model.language_model. to model.language_model.model., which
is the pair 5.6.2 builds for the same model and can only fire on a doubled prefix.

Two gates, neither a version number. The install probe asks whether this transformers has
any of the three shapes upstream has used for the scoping (the model_prefix argument,
PrefixChange.with_submodel_prefix, or the scope_prefix field), and declines if so, which
is every release outside 5.4.0 to 5.5.4 including 4.57.6. The wrapper then only touches a
renaming that demonstrably rewrites this model's own parameter names into names it does
not have, so it is inert for a non-composite model and for the standalone text model the
entry was written for.

Also repairs the save side: saving a composite model under 5.5.4 writes
model.language_model.visual... keys that no other release can read, and with the fix the
key set is identical to the one 5.3.0 writes.

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

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

* Rebind every alias of the conversion mapping, and stop contradicting the repair

unsloth_zoo patches the same function in temporary_patches/moe_utils_bnb4bit.py
without functools.wraps and without __wrapped__, setting only its own marker. When
zoo goes first, the getattr(original, "__wrapped__", original) unwrap cannot see
past it, so 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 the
identity test left it bound to the unscoped mapping. transformers.integrations.peft
is exactly that module, imported during modeling_utils init, and load_adapter() then
renamed Qwen3.5 and Gemma 3n adapter keys away from their real model.language_model.*
modules. Rebind any binding under that name that is not already ours. Zoo's own fix is
preserved because our wrapper wraps original, which is zoo's wrapper when zoo went first.

The version warning also fired on exactly the releases the repair covers, telling users
to downgrade or upgrade away from a version that had just been fixed. It now runs after
the repair and reads the live attribute, so it stays silent when the repair installed
and still warns when it declined.

* Sweep only the packages that import this name from transformers

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
rebinds any binding under that name. Unrestricted that is too broad: a notebook or
plugin defining its own get_model_conversion_mapping before importing unsloth would
have it replaced with the transformers wrapper. Restrict the walk to transformers,
peft, unsloth_zoo and unsloth. The new test fails with the restriction removed and
the pre-zoo rebinding still passes with it in place.

* Rebind only the aliases of the conversion mapping, and test the sweep where it runs

The sweep replaced any callable bound under `get_model_conversion_mapping` in any module
whose root package was transformers, peft, unsloth_zoo or unsloth. Measured on
transformers 5.5.0, that really does clobber an unrelated helper living inside one of
those namespaces. It now rebinds three things and nothing else: the object it wrapped, a
function whose `__module__` is transformers' own `conversion_mapping`, and a wrapper
carrying unsloth_zoo's marker. The pre-zoo case the breadth existed for still works, and
`transformers.integrations.peft` is still rebound.

The test that claimed this safety only ever planted its helper outside those four
packages, and passed on 5.17.0 without the sweep running at all: the repair declines
there, so four tests skipped and three passed vacuously. A `forced_install` fixture now
opens the gate for the tests of what installation DOES, restoring every binding on the
way out, so they run on every release and the unrelated-helper case is parametrized
across all four package namespaces plus one outside.

On transformers 5.5.0, the falsification set is 12 of 12: the aliases are rebound, no
unrelated callable is, the caller's list is never mutated, re-scoping is idempotent, the
standalone text model keeps its renaming, and composing with unsloth_zoo in either order
leaves no destructive renaming behind.
Rebased onto unslothai#11450's current head, which moved three commits while this was measured. The
merge of the two test files keeps both sides: the base branch's `_build_broken` stand-in
and this branch's `_uninstall_runtime_repair`, uninstall first because the stand-in module
has no `get_model_conversion_mapping` for the uninstall to read.

* Defer to unsloth_zoo when it installed this repair first

unsloth_zoo now carries the same re-scope, in
temporary_patches/conversion_mapping_rescope.py. It owns the bitsandbytes Linear4bit patch
that reports this failure, is importable without unsloth, and caps transformers at 5.5.0 on
Apple Silicon in its own pyproject, which puts every Mac install inside the defect window by
construction -- so the repair has to be reachable from there too.

Both copies installing is measurably inert, because 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 whose two versions
disagree.

The detector walks the whole __wrapped__ chain rather than reading the top object, because
zoo also wraps the same function in moe_utils_bnb4bit.py without setting __wrapped__, so the
repair can sit underneath another wrapper. Bounded, so a malformed chain cannot spin. The
zoo flag is spelled as a literal rather than imported, so a zoo too old to define it cannot
turn a skipped repair into an ImportError.

Three tests in tests/test_composite_prefix_renaming.py: the deferral itself, finding the
mark under an unmarked wrapper, and the cycle bound.

Verified against the real checkpoint on one B200. unsloth/qwen3.8-27b-unsloth-bnb-4bit at
transformers 5.5.4, 352 Linear4bit: this repair and zoo's each take quant_state is None from
352 of 352 to 0 of 352, and both produce logits mean -2.5380659103393555, the same value to
all 16 digits, so the two implementations recover the same state.

tests/test_composite_prefix_renaming.py 18 passed 5 skipped,
tests/test_prequantized_vlm_quant_state_guard.py and tests/test_import_fixes_drift.py green.
Against transformers 5.4.0 and 5.5.4, 45 passed; 5.6.2, 39 passed 6 skipped. Narrow ruff
gate clean.

* Cut the comments this PR added

Comment-only, AST verified. 84 comment lines removed across the three files:
the test file goes 104 to 63 (27.4 percent to 18.4 percent of non-blank lines),
import_fixes.py loses 37 and _gpu_init.py 6. Every survivor states something the
code does not: which real transformers build each fake models, why each unknown
answers healthy, why the call sits below the torchaudio guard, and the two
nightly SHAs that make a version interval the wrong instrument.

* Use the AGPL-3.0 header new files in this repo carry

The file was opened with the LGPL block copied from an older test. Every test
added recently carries the two-line SPDX AGPL-3.0-only header instead, and
pr_review/agpl_header_check.py rejects the LGPL one.

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

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

* Drop the copy of the rescoping probe that the base merge shadowed

unslothai#11450 moved `_transformers_rescopes_submodule_prefix_renamings` into this
branch's base. Merging that base left both copies in the file, in different
regions, so git reported no conflict and Python bound the later one. The
earlier copy at line 921 stopped running, and it was not equivalent: it
imported `conversion_mapping` and `core_model_loading` together, so a process
where `core_model_loading` cannot import answered True and skipped the repair,
while the live copy imports them separately and still reads the
`extract_weight_conversions_for_model` signature.

Verified rather than reasoned about: `inspect.getsourcelines` on the imported
module pointed at line 3703, not 921, so the dead copy was already the one
nobody ran. Removing it changes no behaviour and leaves one definition.

`test_no_top_level_definition_is_shadowed_by_a_later_one` reads import_fixes.py
with `ast` and fails on any module-level name defined twice. Confirmed it fails
with a duplicate re-added and passes once removed.

* Keep the guard test runnable with pytest alone

`_uninstall_runtime_repair` imported transformers unconditionally, and this
branch's two repair-specific cases call it, so a pytest-only environment got
two ModuleNotFoundError failures out of a file whose own docstring says it runs
in isolation with no torch. Reproduced in a venv holding only pytest and
packaging: 2 failed, 19 passed before, 20 passed and 1 skipped after. The base
branch passes 20 there, so this branch is what regressed it, and the staging
cross-platform legs install exactly that lightweight set.

The helper now returns when transformers cannot be imported, which is correct
rather than merely quiet: nothing can have installed the repair without it, so
there is nothing to undo, and the caller installs a stand-in module next.
`test_warning_is_silent_once_the_runtime_repair_is_installed` genuinely needs
the live module, since it installs the repair onto it, so it takes
`pytest.importorskip` instead.

* Rebind vllm's own copy of the conversion mapping too

vllm's Transformers backend holds this function by value:
`vllm/model_executor/models/transformers/base.py` does `from
transformers.conversion_mapping import get_model_conversion_mapping` at import time and
builds its `WeightsMapper` from the result. Measured on transformers 5.5.4 with vllm
0.30.0 imported first, the binding was NOT rebound, so a fast_inference path in that
order would map a composite model's weights with the unscoped renaming, which is the
defect this branch exists to remove. Adding vllm to the owning packages rebinds it; the
alias test added earlier is what makes that safe, and an unrelated callable planted under
`vllm.*` is still left alone (both measured).

Also: the forced_install fixture now reuses the already-imported import_fixes module
instead of re-importing the package. On a torch 2.6.0 floor environment without
unsloth_zoo installed, `import unsloth.import_fixes` re-runs `unsloth/__init__` and
turned 9 tests into collection errors; reusing the module makes the file pass 24 of 24
there. Corners run: peft 0.18.0, 0.19.1, 0.20.0 and 0.21.0 against transformers 5.5.4,
every holder rebound and none stale, 45 passed each; torch 2.6.0 with transformers 5.5.4
on CPU, probe and install correct.

* Warn once, after the repair, and count either repair as repaired

Two findings from this round, both reproduced on a real affected build before
fixing, transformers 5.5.3 with torch 2.14.0 CPU.

`_gpu_init` called the quant_state check twice: once at line 110, inherited
from this branch's base, and once at line 304 after
`fix_transformers_composite_prefix_renaming`. Running that sequence by hand,
the first call logs the full downgrade advice and the second is correctly
silent, so an affected user was told to move off a version the repair fixes
moments later, and a silent second call cannot retract a warning already
logged. The earlier call is gone; the surviving one keeps the note about
sitting below `disable_torchaudio_if_cuda_mismatched`, which is why the base
placed it late.

The check also recognised only our own mark. When unsloth_zoo installs its copy
first, `fix_transformers_composite_prefix_renaming` deliberately yields and the
live function carries `_ZOO_COMPOSITE_PREFIX_RENAMING_FLAG` instead, so that
supported configuration still got the warning.
`_composite_prefix_renaming_repaired` now accepts either mark and walks the
whole `__wrapped__` chain, for the same reason
`_zoo_composite_prefix_renaming_installed` does: zoo wraps the same function
elsewhere without setting `__wrapped__`, so a mark can sit under another
wrapper. Verified silent for our mark, for the zoo mark, and for a zoo mark
buried under an unmarked wrapper, and still warning for a wrapper carrying
neither.

Three tests, each confirmed to fail with its fix reverted:
`test_the_check_is_called_once_and_after_the_repair` reads the call order out of
`_gpu_init` with `ast`, `test_either_repair_silences_the_warning` is
parametrised over both marks, and
`test_an_unmarked_wrapper_does_not_count_as_repaired` is the negative control.

Also formats tests/test_composite_prefix_renaming.py, which the previous commit
left off the hook's fixed point.

* Follow the link zoo's MoE wrapper actually publishes

unsloth_zoo now marks its wrapper chain explicitly: `moe_utils_bnb4bit.py` publishes
`common.WRAPPER_INNER_ATTR` pointing at whatever it wrapped. It cannot publish `__wrapped__`
instead, because zoo's own 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.

Both walkers here still followed `__wrapped__` only, and both docstrings claimed to see past
the MoE wrapper on that basis. zoo registers the re-scope BEFORE the MoE patch, so the MoE
wrapper is on top in the ordinary case, not a corner: `_composite_prefix_renaming_repaired`
would answer False for a repair that is live and put the downgrade advice back into the
Linear4bit guard's message, and `_zoo_composite_prefix_renaming_installed` would answer False
and stack a second re-scope wrapper for nothing. Exactly the two outcomes those functions
exist to prevent.

Both now follow `__wrapped__` or the link, through one `_next_in_wrapper_chain` helper. The
attribute is spelled as a literal, like the flag above it, so a zoo too old to define it
cannot turn a skipped repair into an ImportError.

The test that claimed to cover this built its wrapper with `__wrapped__`, which is the one
thing the real MoE wrapper does not set, so it passed either way. It now drives the real
patch and asserts the absence of `__wrapped__` as part of the contract, and skips rather than
fails against an unsloth_zoo predating the link, where the repair genuinely is invisible from
here and nothing this side can fix it. Dropping the link fails it: 1 failed, 28 passed.

Plus a bound check on both walkers against a mutually-wrapping pair.

Suites against the zoo checkout: 108 passed, 4 skipped. Across transformers 5.4.0, 5.5.0 and
5.5.4, 56 passed; 5.6.2, 53 passed 3 skipped; 4.57.6, 26 passed 30 skipped. Against an older
installed zoo the new test skips, 52 passed 4 skipped. Narrow ruff gate clean.

* Wrap whatever is live, and read our own mark through the chain

The installer took `original.__wrapped__` unconditionally before wrapping. Any wrapper
that plays by the rules publishes `__wrapped__` through functools.wraps, so the level
removed was somebody else's: measured on transformers 5.5.4 with a third-party wrapper
installed first, it stopped being called at all (0 invocations), and the alias sweep then
spread the replacement to every module holding it. It now wraps whatever is live, and the
already-installed test walks the chain rather than reading the top object, so a foreign
wrapper on top of ours does not stack a second copy that would walk every submodule again
per load. After the fix, same scenario: third-party wrapper still in the chain, invoked
once per call, zero destructive renamings left, and a second install is a no-op.

Regression test added, plus two portability fixes to the tests: the remaining
`import unsloth.import_fixes` call sites re-run `unsloth/__init__`, which needs
unsloth_zoo, and turned the new bounded-walk test into an error on a torch 2.6.0 floor
environment. 56 passed on transformers 5.4.0, 5.5.4 and 5.5.4 with torch 2.6.0, 53 passed
on 5.17.0.

* Format the files the merge left off the hook's fixed point

ruff-format-with-kwargs rewrites these on the next edit, so pre-commit.ci would
fail the following PR that touches them.

* Cut the comment load of this repair's own block

Post-convergence comment pass, comments and docstrings only, AST verified. The three
longest docstrings and the two multi-paragraph sweep comments collapse to the fact plus
its citation: 112 docstring lines across this PR's functions to 78, and the two sweep
blocks from 26 lines to 11. Every survivor names a mistake the next reader would make,
the measured counts stay in the PR description where they belong.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…ow (unslothai#11572)

* Let the composite renaming tests run inside the transformers 5.4 window

The Repo tests (CPU, rest) lane pins transformers<5.5 and so installs 5.4.0,
the exact release fix_transformers_composite_prefix_renaming exists for. unslothai#11452
added five tests there whose own lane was cancelled before it reported, and all
five fail on main at that pin:

- the drift test failed whenever the probe answered unscoped, which on 5.4.0 is
  the expected answer. It now fails when the probe answers unscoped on a
  release that ships upstream's fix (the probe drifted), or when no repair,
  unsloth's or unsloth_zoo's, is live inside the window.
- the install gate read only the top of the chain. unsloth_zoo's MoE wrapper
  sits on top of the repair and publishes no __wrapped__, so a live repair
  read as missing. It now walks the chain by both links.
- forced_install measured installs from whatever the import left live, where
  the repair is already in the chain and declines. It now starts from the
  bare upstream function, through monkeypatch so a test that monkeypatches the
  same attribute cannot restore the stripped function on teardown.

* Skip the composite renaming tests on unsloth's own stand-in modules

On transformers 4.x, importing unsloth installs inert stand-ins for
transformers.core_model_loading and transformers.conversion_mapping so peft
can import. The helpers found them and ran four tests against a WeightRenaming
that renames nothing; at 4.57.6 those four fail. A real module is a file on
disk, and the stand-ins are not.

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

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

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant