Skip to content

Warn when the installed transformers drops a pre-quantized checkpoint's bnb quant state - #11450

Merged
danielhanchen merged 8 commits into
mainfrom
fix/prequantized-vlm-quant-state
Sep 22, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
fix/prequantized-vlm-quant-state

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

What this does

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

RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x5120 and 1x15728640)

That error reads like a corrupt checkpoint, and the reporters on #9867, #10010, #10017 and #10276 were told to delete and redownload. The checkpoints are fine: their safetensors headers carry 352 packed blobs, 352 absmax and all five sidecars per layer, unchanged since 2026-08-25. This PR warns, before the misleading shape error appears, that the loader threw the quantization metadata away.

Root cause, upstream

transformers/conversion_mapping.py:152-156. transformers 5.4.0 (huggingface/transformers#44300) made the conversion mapping recurse into PreTrainedModel submodules without re-scoping a submodule's renamings to where that submodule lives, which pulled the standalone text model's ^model.language_model. to ^model. renaming 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 are renamed to keys the model does not have and discarded as unexpected, while the packed weight loads raw. Fixed upstream in 5.6.0 by huggingface/transformers#45567.

This is not specific to GatedDeltaNet. Bisected on the real 22.3 GB checkpoint with plain transformers and no unsloth in the process, counting Linear4bit with quant_state is None out of 352:

transformers 5.2.0 5.3.0 5.4.0 5.5.4 5.6.2 5.7 to 5.17.0
None 0 0 352 352 0 0
forward ok ok fails fails ok ok

352 of 352 is every quantized Linear, and Gemma 3n is a second measured family at 439 of 439.

The change

  • import_fixes.py adds _transformers_rescopes_submodule_prefix_renamings, a warn only check that asks the installed transformers whether it scopes a submodule's conversions to where the submodule lives.
  • _gpu_init.py wires it in next to the other version checks, after them and before import unsloth_zoo.
  • tests/test_prequantized_vlm_quant_state_guard.py, 20 tests. The last one reads the
    call order out of _gpu_init.py with ast: this is the only check there that IMPORTS
    transformers rather than reading its metadata, 271 submodules of it, so it has to stay
    below disable_torchaudio_if_cuda_mismatched.

Why it asks the API and not the version number

A closed version interval is the wrong instrument for a source install. Upstream main reported 5.3.0.dev0 at the commit that introduced the regression and 5.6.0.dev0 at the commit that fixed it, so an interval is wrong at both ends: a git-main install carries the bug and escapes the warning, and a fixed nightly is told it is broken. import_fixes.py probes behaviour everywhere else, and this now does too.

The probe accepts all three spellings upstream has used for the scoping: the model_prefix argument of 5.6 to 5.9, PrefixChange.with_submodel_prefix over the same range, and the scope_prefix field every transform carries from 5.10 on. Anything unrecognisable answers healthy, because a warning that fires on builds nobody can show are broken is worth nothing.

Verified against thirteen real installed releases, not reasoned about:

fires 5.4.0, 5.5.0, 5.5.1, 5.5.2, 5.5.3, 5.5.4
silent 4.57.6, 5.2.0, 5.3.0, 5.6.0, 5.6.2, 5.14.1, 5.17.0

What this no longer does, and why

An earlier revision of this branch also excluded 5.4.0 and 5.5.0 to 5.5.4 in pyproject.toml. Those exclusions are reverted, because they cannot land yet and they cost more than they buy while they cannot.

unsloth_zoo==2026.9.6 declares transformers<=5.5.0 in its own published metadata, and every extra here that names transformers also names the zoo, so the resolver intersects down to 5.5.0 whatever this file says. Excluding 5.5.0 therefore has nowhere to resolve but backwards, and unsloth/models/loader.py:86 requires 5.5.0 or newer for Gemma 4, so the exclusions traded a multimodal bnb defect for every Gemma 4 load. Measured with uv pip compile on python 3.12:

resolved transformers
main 5.5.0
this branch, earlier revision 5.3.0
#11016 alone 5.5.0
#11016 plus that revision 5.3.0

So lifting the ceiling in #11016 is necessary and still not sufficient: the exclusions wait on unslothai/unsloth-zoo#1227 reaching a published zoo release, not merely on #11016 merging. test_pyproject_still_allows_a_working_version states that and fails if 5.5.0 is excluded again while the zoo caps us to it.

Out of scope for the same reason: the transformers==5.5.0 pins in studio/install_python_stack.py and extras-no-deps.txt, and the UV_OVERRIDE at install.sh:2526-2550 pointing at overrides-darwin-arm64.txt. Those are pin sites, they move with the cap, and #11016 documents why the darwin window must not track the published cap on its own.

Scope

Warn only, on every platform. It does not repair the load. The repair is #11452, stacked on this branch, which rescopes the leaked renamings at runtime and is where the exclusions belong once the zoo cap ships.

…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 ⚠️ Failed 2026-09-22T13:44:32.014553Z 843918b Draft marked ready
ℹ️ 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 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: 31cdcd448d

ℹ️ 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 pyproject.toml Outdated
# #10276. Affected text sub-types are qwen3_5_text, qwen3_5_moe_text and gemma3n_text;
# flat text-only checkpoints have no `model.language_model.` prefix and are fine.
# These exclusions stay correct when the <=5.5.0 ceiling above is later raised.
"transformers>=4.51.3,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,!=5.4.0,!=5.5.0,!=5.5.1,!=5.5.2,!=5.5.3,!=5.5.4,<=5.5.0",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep a Transformers release installable for Gemma 4

With the ceiling still at <=5.5.0, excluding 5.5.0 leaves no permitted release that satisfies the repository's Gemma 4 floor: unsloth/models/loader.py:86 requires Transformers 5.5.0 or newer, and lines 1563-1565 explicitly reject older versions. Consequently, a fresh unsloth[huggingface] installation resolves below 5.5 and every advertised Gemma 4 load fails; the dependency range needs to admit a fixed 5.6+ release (and align the zoo constraint) or avoid globally excluding the only currently allowed Gemma 4-capable version.

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.

Correct, and it is worse than the resolver downgrade I had already found. Confirmed against main:

  • unsloth/models/loader.py:86: SUPPORTS_GEMMA4 = transformers_version >= Version("5.5.0")
  • loader.py:1564-1565: raise RuntimeError("Unsloth: Gemma 4 requires transformers >= 5.5.0")

With the ceiling left at <=5.5.0, excluding 5.5.0 leaves no permitted release at or above the Gemma 4 floor, so every Gemma 4 load raises. Measured resolve, --no-deps, python 3.12:

base  -> transformers==5.5.0
head  -> transformers==5.3.0

That is the whole problem with this PR as written: the exclusions have nowhere to go but backwards while the ceiling is unchanged, so they cost more than they buy. This is already in draft for that reason.

The order it needs: #11016 lifts the ceiling to 5.17.0 and resolves clear of the defect window with no downgrade, and git merge-tree shows the two conflict in pyproject.toml. Landing #11016 first makes these exclusions free rather than destructive, and they also have to be mirrored into unsloth_zoo, which is the only source of a transformers requirement on the install the README documents.

The detector needs reworking regardless of the pin question: it reads a static version window, which import_fixes.py deliberately avoids, and upstream main reported 5.3.0.dev0 at the commit that introduced the regression and 5.6.0.dev0 at the commit that fixed it, so a git-main install is misjudged at both ends.

@danielhanchen
danielhanchen marked this pull request as draft September 21, 2026 13:26
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@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: 3a0c300e3a

ℹ️ 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 pyproject.toml Outdated
# #10276. Affected text sub-types are qwen3_5_text, qwen3_5_moe_text and gemma3n_text;
# flat text-only checkpoints have no `model.language_model.` prefix and are fine.
# These exclusions stay correct when the <=5.5.0 ceiling above is later raised.
"transformers>=4.51.3,!=4.52.0,!=4.52.1,!=4.52.2,!=4.52.3,!=4.53.0,!=4.54.0,!=4.55.0,!=4.55.1,!=4.57.0,!=4.57.4,!=4.57.5,!=5.0.0,!=5.1.0,!=5.4.0,!=5.5.0,!=5.5.1,!=5.5.2,!=5.5.3,!=5.5.4,<=5.5.0",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Update Studio's exact 5.5.0 pin too

In the Python >=3.10 Studio install path, studio/install_python_stack.py:11085-11094 later installs extras-no-deps.txt with --no-deps, and that file still pins transformers==5.5.0 at line 31. Because this is a separate no-dependencies operation, the new optional-extra exclusion is never consulted and a fresh Studio environment ends on the exact broken release. Studio advertises prequantized Gemma3n checkpoints in studio/backend/utils/models/model_config.py:231-237, one of the affected model types named above, so these users still lose quant_state and fail on the first forward; the Studio requirement and corresponding default/sidecar pins need to move off 5.5.0 as part of this change.

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.

Confirmed independently before this round, and it is worse than a missed pin: it makes the PR inert on the platform that motivated it.

install.sh:2526-2550 exports UV_OVERRIDE pointing at studio/backend/requirements/single-env/overrides-darwin-arm64.txt, whose line 21 pins transformers>=5.5.0,<=5.5.0. A uv override REPLACES rather than intersects, so the exclusions in pyproject.toml never apply there. Measured on head with that override in place: transformers==5.5.0, which is inside the defect window.

So Apple Silicon Studio users stay exactly where they were, which matters because unsloth-zoo/pyproject.toml:85,133 also caps arm64 at <=5.5.0 by platform marker.

This PR is in draft while the ordering is resolved: #11016 has to land first, then the exclusions go into unsloth_zoo and this override together, or they achieve nothing on the paths that matter.

Comment thread unsloth/import_fixes.py Outdated
Comment on lines +3297 to +3298
low, high = _BROKEN_PREQUANTIZED_VLM_TRANSFORMERS
return TrueVersion(low) <= parsed < TrueVersion(high)

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 Detect nightly builds by behavior, not release bounds

For Transformers Git/nightly installs, which this repository explicitly supports in unsloth/models/loader.py:1554 and unsloth/import_fixes.py:2605-2610, the version denotes the upcoming release rather than the behavioral commit: a regression-bearing 5.3.0.dev0 sorts below this lower bound and receives no warning, while a fixed 5.6.0.dev0 sorts below the final 5.6.0 and is falsely warned as broken. Consequently source users can either reach the corrupting load without advance notice or receive an incorrect downgrade recommendation; probe the conversion-mapping behavior or otherwise account for development revisions instead of using only this final-release interval.

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.

Agreed, and this is the strongest argument against the detector as written.

import_fixes.py deliberately probes behaviour rather than parsing a version, and this is the first closed version window in the file. Verified against upstream git rather than reasoned about: transformers main reported __version__ = "5.3.0.dev0" at the commit that INTRODUCED the regression (PR #44300) and 5.6.0.dev0 at the commit that FIXED it (PR #45567). So a git-main install carries the bug, escapes the warning, and satisfies the new specifier, while a fixed nightly is told it is broken. Wrong at both ends.

The behavioural probe already exists and is the right instrument: the sibling in #11452 gates on whether this transformers exposes any of the three shapes upstream uses for per-submodule scoping (model_prefix, PrefixChange.with_submodel_prefix, scope_prefix), and across 24 real builds it installs on exactly the six affected releases and declines on the other 18, nightlies included.

The detector will be rebuilt on that probe when this PR is restructured. It is in draft meanwhile, since the pin half has to wait for #11016 regardless.

…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 danielhanchen changed the title Keep a new install clear of the transformers releases that drop bnb-4bit quant state Warn when the installed transformers drops a pre-quantized checkpoint's bnb quant state Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 46636e0, which changes what this PR is.

Both P1s are resolved by reverting the pyproject.toml exclusions rather than by moving a pin. The exclusions cannot land yet, and the reason is one step deeper than the ceiling: unsloth_zoo==2026.9.6 declares transformers<=5.5.0 in its own published metadata, and every extra here that names transformers also names the zoo, so the resolver intersects to 5.5.0 whatever pyproject.toml says. Measured with uv pip compile, python 3.12:

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

So #11016 landing first is necessary and not sufficient. The exclusions wait on unslothai/unsloth-zoo#1227 reaching a published zoo release. test_pyproject_still_allows_a_working_version now asserts 5.5.0 stays installable while that is true, so this cannot be reintroduced by accident.

That also settles the Studio pin: with no exclusion in pyproject.toml, extras-no-deps.txt and the darwin UV_OVERRIDE have nothing to diverge from, and they move with the cap rather than with this PR.

The P2 is fixed as described. The detector asks extract_weight_conversions_for_model whether it scopes a submodule's conversions, in all three spellings upstream has used (model_prefix in 5.6 to 5.9, PrefixChange.with_submodel_prefix over the same range, scope_prefix from 5.10 on). Verified against thirteen real installed releases: fires on 5.4.0 and 5.5.0 to 5.5.4, silent on 4.57.6, 5.2.0, 5.3.0, 5.6.0, 5.6.2, 5.14.1 and 5.17.0. A git-main build reporting 5.3.0.dev0 with the defect is now warned, and one reporting 5.6.0.dev0 with the fix is not.

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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: acf6b02e62

ℹ️ 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-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.
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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
danielhanchen added a commit that referenced this pull request Sep 22, 2026
#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.
@danielhanchen
danielhanchen marked this pull request as ready for review September 22, 2026 13:44
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@danielhanchen
danielhanchen merged commit b7aca55 into main Sep 22, 2026
30 of 36 checks passed
@danielhanchen
danielhanchen deleted the fix/prequantized-vlm-quant-state branch September 22, 2026 13:44
danielhanchen added a commit that referenced this pull request Sep 22, 2026
#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.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 22, 2026
… 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.
danielhanchen added a commit that referenced this pull request Sep 22, 2026
…4 and 5.5 (#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 #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.

* [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
    #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.

* 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 #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

#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
…'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>
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