Skip to content

Keep import unsloth working when bitsandbytes is absent - #7502

Merged
danielhanchen merged 16 commits into
mainfrom
bnb-optional-import
Jul 28, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
bnb-optional-import

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

unsloth/device_type.py already handles a missing bitsandbytes: it prints

Unsloth: bitsandbytes is not installed - 4bit QLoRA unallowed, but 16bit and full finetuning works.

and clears ALLOW_BITSANDBYTES / ALLOW_PREQUANTIZED_MODELS. But the import chain still hard-required the module, so import unsloth raised ModuleNotFoundError instead of taking the 16bit path the message promises.

#7354 made that state reachable. The gfx906 install path deliberately uninstalls the generic bitsandbytes wheel (it carries no gfx906 kernels), which currently leaves an MI50 / Radeon VII host unable to import unsloth at all.

Sites fixed

File Import
unsloth/kernels/utils.py:136 import bitsandbytes as bnb
unsloth/save.py:35-36 Bnb_Linear4bit, peft Linear4bit
unsloth/models/granite.py:34,40 Bnb_Linear4bit, peft Linear4bit
unsloth/_gpu_init.py:377 import bitsandbytes as bnb (xpu branch)

peft is in the table because peft.tuners.lora re-exports Linear4bit only when bitsandbytes imported cleanly, so it fails on exactly the same hosts.

Approach

  • kernels/utils.py: guard the import; bind get_ptr and the five 4bit ctypes handles to a stub that raises a clear message if a 4bit path is actually entered. HAS_CUDA_STREAM stays False, which is the correct route.
  • save.py, models/granite.py: placeholder classes. Both names only feed isinstance checks, so a class nothing can be an instance of is an exact stand-in.
  • _gpu_init.py: same degradation on the xpu branch that the cuda branch above it already has.

Nothing changes when bitsandbytes is installed: the try succeeds and every binding is what it was.

Verification

On a Strix Halo (gfx1151, DEVICE_TYPE=hip, torch 2.11.0+rocm7.13.0), with bitsandbytes blocked via sys.modules["bitsandbytes"] = None so find_spec returns None and the import raises, exactly as when the package is absent:

Before:

ModuleNotFoundError: import of bitsandbytes halted; None in sys.modules
    unsloth/models/llama.py:82        from ..kernels import *
    unsloth/kernels/__init__.py:15    from .cross_entropy_loss import (
    unsloth/kernels/cross_entropy_loss.py:18  from .utils import (
    unsloth/kernels/utils.py:136      import bitsandbytes as bnb

After:

PASS  import unsloth ok
PASS  FastLanguageModel / FastModel importable
      kernels.utils bnb=None  HAS_CUDA_STREAM=False
PASS  4bit stub raises cleanly -> Unsloth: 4bit QLoRA needs `bitsandbytes`, which is
      not installed. 16bit LoRA and full finetuning work without it.
      DEVICE_TYPE=hip ALLOW_BITSANDBYTES=False ALLOW_PREQUANTIZED=False

With bitsandbytes present, same host: HAS_CUDA_STREAM=True, Bnb_Linear4bit=bitsandbytes.nn.modules.Linear4bit, ALLOW_BITSANDBYTES=True, ALLOW_PREQUANTIZED=True.

Tests

tests/python/test_import_without_bitsandbytes.py walks the import unsloth module graph with ast and fails on any unguarded module-level bitsandbytes or peft Linear4bit import, reporting the file, line and chain. Imports inside a try, or under an ALLOW_BITSANDBYTES branch, count as guarded. A second test pins the 4bit stub fallbacks so they cannot silently become NameErrors.

Negative control: reverting kernels/utils.py and save.py to main makes both tests fail with the three real sites listed.

Targeted suites (tests/python, tests/saving, tests/studio/install, gemv dispatch): 702 passed, 18 skipped.

Needs unslothai/unsloth-zoo#953, which fixes the same import in unsloth_zoo/saving_utils.py (reached from unsloth/save.py).

device_type.py already prints "bitsandbytes is not installed - 4bit QLoRA
unallowed, but 16bit and full finetuning works" and clears
ALLOW_BITSANDBYTES / ALLOW_PREQUANTIZED_MODELS, but the import chain then
hard-required the module anyway, so `import unsloth` raised instead.

#7354 made this reachable: the gfx906 install path uninstalls the generic
bitsandbytes wheel (no gfx906 kernels in it), which leaves an MI50 / Radeon VII
host unable to import unsloth at all, not on the 16bit path the message
promises.

- kernels/utils.py: guard the bnb import; bind get_ptr and the five 4bit ctypes
  handles to a stub that raises a clear message if a 4bit path is entered.
  HAS_CUDA_STREAM stays False, which is the correct route.
- save.py, models/granite.py: guard Bnb_Linear4bit and peft's Linear4bit
  (peft exports it only when bnb imported cleanly) with placeholder classes.
  Both names only feed isinstance checks, so nothing matching is exact.
- _gpu_init.py: same degradation on the xpu branch as the cuda branch above.

Verified on a Strix Halo (gfx1151, DEVICE_TYPE=hip, torch 2.11.0+rocm7.13.0)
by blocking bitsandbytes with sys.modules["bitsandbytes"] = None, so
find_spec returns None and the import raises exactly as when the package is
absent. Before: ModuleNotFoundError at kernels/utils.py:136. After: import
succeeds, FastLanguageModel/FastModel import, ALLOW_BITSANDBYTES=False,
ALLOW_PREQUANTIZED=False, and the 4bit stub raises with the real cause. With
bitsandbytes present, every binding is unchanged.

New test walks the `import unsloth` module graph with ast and fails on any
unguarded bitsandbytes (or peft Linear4bit) import; verified it catches the
old code. Targeted suites: 702 passed, 18 skipped.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner July 27, 2026 13:03
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Jul 27, 2026
saving_utils is on the `import unsloth` chain (unsloth/save.py imports it at
module level), so its unconditional `import bitsandbytes as bnb` made a
bnb-less host unable to import unsloth at all.

That host is now reachable: unsloth#7354 uninstalls the generic bitsandbytes
wheel on gfx906 (MI50 / Radeon VII) because it carries no gfx906 kernels, and
unsloth's own message there promises 16bit LoRA and full finetuning still work.

Guard the import and route the one use site through a _BNB_LINEAR4BIT tuple,
empty when bnb is missing. isinstance against an empty tuple is False, which is
exact: with no bnb there are no 4bit layers, so those modules fall through to
the torch.nn.Linear branch as they should.

Pairs with unslothai/unsloth#7502. Verified on a Strix Halo (gfx1151,
DEVICE_TYPE=hip, torch 2.11.0+rocm7.13.0) with bitsandbytes blocked via
sys.modules["bitsandbytes"] = None: `import unsloth` succeeds and
_BNB_LINEAR4BIT is (). With bitsandbytes present it is
(bitsandbytes.nn.modules.Linear4bit,), unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex 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: ef2cac5f1b

ℹ️ 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".

rel = path.relative_to(REPO_ROOT).as_posix()
offenders.append(f"{rel}:{lineno} {source}\n via {' -> '.join(chain + [module])}")
pending.extend(
(edge, chain + [module]) for edge in edges if edge.split(".")[0] == ROOT_MODULE

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 Require the bitsandbytes-optional unsloth_zoo release

When users upgrade this package while retaining any already-installed unsloth_zoo>=2026.7.6, import unsloth can still reach the unguarded bitsandbytes import in unsloth_zoo.saving_utils through unsloth/save.py; the commit itself notes that the external #953 fix is required, but the dependency minimum is not bumped. This test misses that failure because it explicitly follows only edges whose root is unsloth, so it passes even though the supported dependency set remains unimportable without bitsandbytes. Either guard that external import locally or require the first unsloth_zoo release containing #953.

Useful? React with 👍 / 👎.

Comment thread unsloth/kernels/utils.py
Comment on lines +138 to +142
except Exception:
# device_type.py already degrades to 16bit/full finetuning when bnb is missing
# (e.g. gfx906, whose generic wheel has no kernels). Keep the import working and
# fail only if a 4bit path is actually entered.
bnb = None

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 Disable bitsandbytes loading when the fallback is active

On CUDA and XPU hosts without bitsandbytes, this fallback leaves the local device_type.ALLOW_BITSANDBYTES and ALLOW_PREQUANTIZED_MODELS values at their default True, because device_type.py only clears them inside its HIP branch. Consequently the now-importable package still lets the default FastLanguageModel.from_pretrained(load_in_4bit=True) pass the guard in models/loader.py:476 and select a bitsandbytes model before failing later, rather than taking the advertised non-4-bit path. Clear the capability flags whenever this fallback is selected, not only on HIP.

Useful? React with 👍 / 👎.

ROOT_MODULE = "unsloth"


def _module_path(name: str) -> Path | None:

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 Use a Python 3.9-compatible return annotation

On Python 3.9, which remains supported by requires-python = ">=3.9,<3.15", importing this test module evaluates Path | None without postponed annotations and raises TypeError during pytest collection because PEP 604 type unions are only supported from Python 3.10. Use Optional[Path] or add from __future__ import annotations so the new regression test does not break the supported 3.9 test suite.

Useful? React with 👍 / 👎.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Jul 28, 2026
saving_utils is on the `import unsloth` chain (unsloth/save.py imports it at
module level), so its unconditional `import bitsandbytes as bnb` made a
bnb-less host unable to import unsloth at all.

That host is now reachable: unsloth#7354 uninstalls the generic bitsandbytes
wheel on gfx906 (MI50 / Radeon VII) because it carries no gfx906 kernels, and
unsloth's own message there promises 16bit LoRA and full finetuning still work.

Guard the import and route the one use site through a _BNB_LINEAR4BIT tuple,
empty when bnb is missing. isinstance against an empty tuple is False, which is
exact: with no bnb there are no 4bit layers, so those modules fall through to
the torch.nn.Linear branch as they should.

Pairs with unslothai/unsloth#7502. Verified on a Strix Halo (gfx1151,
DEVICE_TYPE=hip, torch 2.11.0+rocm7.13.0) with bitsandbytes blocked via
sys.modules["bitsandbytes"] = None: `import unsloth` succeeds and
_BNB_LINEAR4BIT is (). With bitsandbytes present it is
(bitsandbytes.nn.modules.Linear4bit,), unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex 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: ffcbbc15e1

ℹ️ 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/save.py
Comment on lines +37 to +40
try:
from bitsandbytes.nn import Linear4bit as Bnb_Linear4bit
from peft.tuners.lora import Linear4bit as Peft_Linear4bit
except Exception:

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 Require the matching optional-bnb unsloth-zoo release

When bitsandbytes is absent and a currently supported unsloth_zoo version such as the declared minimum 2026.7.6 is installed, this guard is insufficient: save.py later imports unsloth_zoo.saving_utils at module scope, and versions before the companion optional-bnb fix still import bitsandbytes themselves. Consequently import unsloth continues to fail for a dependency combination allowed by pyproject.toml; raise the minimum zoo version to the release containing that fix or guard the downstream import as well.

Useful? React with 👍 / 👎.

Comment thread unsloth/_gpu_init.py
Comment on lines +381 to +385
except Exception:
print(
"Unsloth: `bitsandbytes` is not installed - 4bit QLoRA unallowed, but 16bit and full finetuning works!"
)
bnb = None

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 Clear 4-bit capability flags when XPU bnb import fails

On an XPU host without bitsandbytes, this exception path lets the package import but leaves device_type.ALLOW_BITSANDBYTES and ALLOW_PREQUANTIZED_MODELS set to True, because those flags are only adjusted for HIP. FastLanguageModel.from_pretrained defaults to load_in_4bit=True and consults those flags before selecting a bnb checkpoint, so the normal entry point still proceeds into unavailable bnb functionality despite this branch announcing that 4-bit was disabled. Update the shared capability flags when this import fails so the loader takes its 16-bit fallback path.

Useful? React with 👍 / 👎.

ROOT_MODULE = "unsloth"


def _module_path(name: str) -> Path | None:

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 Keep the new test importable on Python 3.9

The project declares Python 3.9 support, but this test does not enable postponed annotation evaluation and Path | None only works as a type union starting in Python 3.10. Under Python 3.9 the annotation is evaluated while pytest imports the module and raises TypeError during collection, so the Python test suite cannot run on a supported interpreter; add from __future__ import annotations or use Optional[Path].

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits July 28, 2026 05:40
…ction

Three findings, each reproduced first and negative-controlled after.

1. The fix still needed an unreleased unsloth_zoo (P1). save.py imported
   unsloth_zoo.saving_utils at module scope, and any zoo without the companion
   #953 fix imports bitsandbytes there, so `import unsloth` kept failing for a
   dependency set pyproject.toml allows. Raising the floor was not an option:
   PyPI's newest zoo is 2026.7.6 and #953 is merged but unreleased, so a bump
   would break every install today. Both names it pulled in are used only inside
   functions, so the import is now lazy at those two call sites, matching what
   determine_base_model_source in the same file already does. Verified against a
   real pre-#953 zoo checkout with bitsandbytes blocked: import succeeds, and
   restoring the eager import reproduces the failure at saving_utils.py:70.
   This PR no longer depends on a zoo release.

2. Capability flags were only cleared on hip (P2). device_type.py probed
   bitsandbytes inside its DEVICE_TYPE == "hip" branch, so a cuda or xpu host
   without bnb imported fine but still reported ALLOW_BITSANDBYTES=True, and the
   default load_in_4bit=True path in models/loader.py would select a 4bit
   checkpoint before failing. Clear both flags whenever the module is absent, on
   every backend, via find_spec so a working install pays nothing. A cuda host
   with bnb blocked now reports False/False; with bnb present nothing changes.

3. The new test could not be collected on Python 3.9 (P2). `Path | None` is a
   PEP 604 union and requires-python still allows 3.9, so pytest raised
   TypeError at import. Added `from __future__ import annotations`. Checked in
   real uv venvs on 3.9, 3.10 and 3.13: 2 passed each; removing the future
   import reproduces "unsupported operand type(s) for |" on 3.9 only.

The xpu branch in _gpu_init.py needs no separate flag handling now that the
probe is backend-independent.

@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: b78d879848

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/device_type.py Outdated
# No bitsandbytes at all: 4bit is unavailable on every backend, not just hip, so
# clear the flags the loader reads before it selects a 4bit checkpoint. find_spec
# rather than import, so a working install pays nothing here.
if importlib.util.find_spec("bitsandbytes") is None:

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 Disable 4-bit paths when bnb import fails

Fresh evidence after the earlier flag is that this new guard only checks find_spec, while the added fallbacks in _gpu_init.py and kernels/utils.py treat any import bitsandbytes exception as unavailable. On hosts where a bitsandbytes package is present but unusable, such as a bad CUDA/ROCm wheel or missing shared library, find_spec is non-None so ALLOW_BITSANDBYTES stays true; FastLanguageModel.from_pretrained then skips the fallback at models/loader.py:476 and keeps the default 4-bit path even though the import fallback already determined bnb cannot be used. Set these flags from the same guarded import/probe result rather than from spec presence alone.

Useful? React with 👍 / 👎.

Comment thread unsloth/device_type.py Outdated
# No bitsandbytes at all: 4bit is unavailable on every backend, not just hip, so
# clear the flags the loader reads before it selects a 4bit checkpoint. find_spec
# rather than import, so a working install pays nothing here.
if importlib.util.find_spec("bitsandbytes") is None:

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 Disable 8-bit loads when bnb is absent

When this new no-bnb fallback runs on CUDA/XPU, explicit 8-bit loads are still left enabled: FastLanguageModel.from_pretrained(load_in_4bit=False, load_in_8bit=True) delegates before the first ALLOW_BITSANDBYTES guard, and the later guards only reset load_in_4bit even though they print for load_in_8bit too. In the newly supported environment where import unsloth succeeds without bitsandbytes, that request still reaches Transformers with load_in_8bit=True and fails in bnb instead of being rejected or downgraded consistently with the fallback. Clear or reject load_in_8bit whenever these flags disable bitsandbytes.

Useful? React with 👍 / 👎.

danielhanchen and others added 3 commits July 28, 2026 06:15
…me guard

1. The capability probe used find_spec while the fallbacks in kernels/utils.py
   and _gpu_init.py treat any import failure as unavailable, so an installed but
   unusable wheel would leave ALLOW_BITSANDBYTES true while the kernels had
   already bound the stub. Probe with the same guarded import instead, so all
   three agree by construction. No new cost on any path: _gpu_init.py already
   imports bnb before device_type is reached on cuda, and device_type's own hip
   block imports it a few lines later.

   Worth recording that the state this prevents is currently unreachable for an
   unrelated reason: a broken wheel takes `import unsloth` down earlier, in
   transformers/integrations/bitsandbytes.py:20 via
   unsloth_zoo/patching_utils.py:680, whichever exception it raises (OSError also
   escapes the zoo moe_utils `except ImportError`). So this is correctness for
   when those imports get guarded, not an observable fix today.

2. Both loader guards printed for load_in_4bit or load_in_8bit but only cleared
   load_in_4bit, so an explicit load_in_8bit=True survived and reached
   Transformers, which builds the bnb quantizer and fails there. Clear both. The
   message no longer says AMD either: the flag now goes false whenever bnb is
   unusable on any backend.

Tests: the probe must not use find_spec, and an ast walk requires every
ALLOW_BITSANDBYTES guard in loader.py to clear both flags, so a third guard
cannot be added with the same omission. Dropping either fix reddens them (1 and
2 failures respectively). 4 passed on 3.9, 3.13 and the ROCm venv; absent and
healthy bnb both stay consistent across hip and cuda.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex 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: e999dad82e

ℹ️ 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/models/loader.py
Comment on lines 1158 to +1159
load_in_4bit = False
load_in_8bit = False

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 Remove bnb quantization configs during fallback

When bitsandbytes is unavailable and the caller supplies a BitsAndBytesConfig or equivalent dictionary, these assignments clear only the local flags; the original kwargs["quantization_config"] remains intact and is forwarded to FastBaseModel.from_pretrained at lines 1745-1777. Transformers therefore still constructs a bitsandbytes quantizer and fails, despite this branch reporting that 4-bit/8-bit was disabled. Remove or neutralize the bnb quantization config as part of the fallback, or reject this request explicitly.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/loader.py Outdated
Comment on lines 475 to 476
# bitsandbytes unusable (absent, or unstable as on some AMD stacks)
if not ALLOW_BITSANDBYTES and not use_exact_model_name:

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 Apply the missing-bnb fallback to exact model names

On a host without bitsandbytes, setting use_exact_model_name=True bypasses this guard entirely, so the default load_in_4bit=True (or an explicit 8-bit request) remains enabled and is passed into the downstream loader. use_exact_model_name should suppress repository-name remapping, but it cannot make bitsandbytes available; apply the capability fallback regardless of this option so exact-name 16-bit loads work in the newly supported environment.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits July 28, 2026 06:40
…bnb config

Both findings hold up, so both are fixed.

1. use_exact_model_name=True skipped the guard entirely. load_in_4bit defaults
   to True, so on a host without bitsandbytes
   FastLanguageModel.from_pretrained(name, use_exact_model_name=True) kept 4bit
   set and failed downstream. That option suppresses repo-name remapping and
   cannot make bitsandbytes available, so it has no business gating a capability
   check. Ungated at both sites.

2. A user-supplied quantization_config survived the fallback. It sets
   load_in_4bit/8bit at the top of from_pretrained and stays in kwargs, so
   clearing the local flags still let Transformers rebuild the bnb quantizer.
   Now dropped as part of the fallback.

One correction to the second suggestion: it cannot be dropped whenever the
fallback runs. quantization_config also carries GPTQ, AWQ, fp8 and torchao
configs, which have nothing to do with bitsandbytes and must reach the loader
untouched. The pop is gated on the config actually requesting load_in_4bit or
load_in_8bit, reusing the same dict/attr probe from the top of the function.

Behaviour, exercising the real guard block against synthetic inputs with
use_exact_model_name=True and bnb unusable:

  default 4bit, no cfg          4bit=False 8bit=False
  explicit 8bit, no cfg         4bit=False 8bit=False
  BitsAndBytesConfig(4bit/8bit) 4bit=False 8bit=False  config dropped
  dict bnb config               4bit=False 8bit=False  config dropped
  GPTQ config                   4bit=False 8bit=False  config SURVIVES
  fp8 dict                      4bit=False 8bit=False  config SURVIVES

Nothing changes when bitsandbytes works: the whole block is inside
`if not ALLOW_BITSANDBYTES`.

Tests: an ast walk requires neither guard to reference use_exact_model_name in
its test, and requires each to pop quantization_config behind a _wants_bnb
check, so an unconditional pop fails too. Re-gating one guard or removing one
pop reddens a test each. 6 passed on 3.9, 3.13 and the ROCm venv.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex 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: f739912296

ℹ️ 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/models/loader.py
# bitsandbytes unusable (absent, or unstable as on some AMD stacks). This is
# a capability check, so it is not gated on use_exact_model_name: that only
# suppresses repo-name remapping and cannot make bitsandbytes available.
if not ALLOW_BITSANDBYTES:

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 Disable unavailable bnb before validating load modes

When bitsandbytes is absent, FastModel.from_pretrained(..., load_in_16bit=True) still has the default load_in_4bit=True, so the mutually-exclusive-mode check at lines 1145–1154 raises before this new guard can clear the unavailable 4-bit request. This breaks the explicitly advertised 16-bit fallback for FastModel/vision users unless they also know to override load_in_4bit=False; move the capability handling ahead of that validation.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/loader.py
# bitsandbytes unusable (absent, or unstable as on some AMD stacks). This is
# a capability check, so it is not gated on use_exact_model_name: that only
# suppresses repo-name remapping and cannot make bitsandbytes available.
if not ALLOW_BITSANDBYTES:

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 Skip the bitsandbytes compiler patch when bnb is absent

On every bitsandbytes-free FastModel.from_pretrained call, execution invokes patch_compiling_bitsandbytes() at line 1134 before reaching this capability guard, but the installed unsloth_zoo.patching_utils.patch_compiling_bitsandbytes unconditionally executes import bitsandbytes. Consequently FastModel, vision loads, full-finetuning delegations, and unsupported-model delegations still raise ModuleNotFoundError rather than taking the promised non-4-bit path; guard or skip that patch before invoking it.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits July 28, 2026 07:07
… path

Both findings are real, and the second one meant this PR did not actually
deliver what it advertises for FastModel or vision loads. Reproduced first.

1. patch_compiling_bitsandbytes() ran unguarded at the top of
   FastModel.from_pretrained, and unsloth_zoo's copy imports bitsandbytes
   unconditionally (patching_utils.py:40). So every FastModel call on a
   bnb-less host died there, whatever the arguments:

     FastModel(load_in_16bit=True)    -> ModuleNotFoundError at patching_utils.py:40
     FastModel(full_finetuning=True)  -> ModuleNotFoundError at patching_utils.py:40

   The FastLanguageModel path already wraps this call in try/except with a
   warning, and its comment even says "Mirror FastModel" - FastModel was the
   unwrapped one. Wrapped it the same way, so behaviour is unchanged wherever
   bitsandbytes imports.

2. The mode-exclusivity check ran before the capability fallback. load_in_4bit
   defaults to True, so load_in_16bit=True made
   int(load_in_4bit) + int(load_in_16bit) == 2 and raised "Can only load in 4bit
   or 8bit or 16bit" before the fallback could clear the unavailable 4bit
   request. Moved the fallback ahead of that check.

After both, the same three calls get past every bitsandbytes gate and reach
model resolution, failing only on the deliberately fake repo name used by the
probe. Nothing changes when bitsandbytes works: the fallback is still inside
`if not ALLOW_BITSANDBYTES`, and the wrapper only swallows an import that
previously crashed the load.

Tests: the mode check must be preceded by an ALLOW_BITSANDBYTES fallback in the
same function, and no call to patch_compiling_bitsandbytes may sit outside a
try. The ordering assertion is scoped to the enclosing function on purpose - my
first version compared line numbers file-wide, so the other loader's guard
satisfied it and the negative control passed when it should have failed. With
the scoping fixed, moving the fallback back after the mode check reddens it, as
does unwrapping the patch call. 8 passed on 3.9, 3.13 and the ROCm venv.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8b3f9a8168

ℹ️ 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
danielhanchen merged commit 52a9601 into main Jul 28, 2026
46 of 52 checks passed
@danielhanchen
danielhanchen deleted the bnb-optional-import branch July 28, 2026 15:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant