Skip to content

AMD: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux - #7354

Merged
danielhanchen merged 16 commits into
unslothai:mainfrom
LeoBorcherding:mi50-gfx906-legacy-support
Jul 27, 2026
Merged

danielhanchen merged 16 commits into
unslothai:mainfrom
LeoBorcherding:mi50-gfx906-legacy-support

Conversation

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Context

gfx906 (MI50 / Radeon VII, Vega 20) predates the officially supported AMD lineup, but there's an active community running local LLM work on these 32GB HBM2 cards, and several asked for Unsloth support on the r/unsloth AMD announcement thread. u/VuaNam1234's MI50 lab independently documents a working Unsloth stack on this card (Gemma4-31B QLoRA on 32GB, with benchmark evidence) and confirms which torch wheels and runtime settings hold up in practice. This PR makes the installer and runtime handle gfx906 automatically, so those users get a working setup without manual environment surgery. No code from that repository is used; the changes follow this repo's existing Strix/RDNA2 reroute patterns, with the lab serving as verification evidence.

Why gfx906 needs special handling

AMD dropped gfx906 kernels from ROCm's newer libraries, so rocm6.4+/7.x torch wheels no longer run on it (rocBLAS TensileLibrary.dat ... not read for gfx906, ROCm/TheRock#1844); the rocm6.3 index is the last wheel family that supports the arch, and TheRock publishes a gfx906 SDK index but no torch wheels. Since the installer selects the index by host ROCm version, a gfx906 card on a modern ROCm host currently receives wheels its GPU can't execute. Separately, the lab's verified environment requires Dynamo/Inductor disabled on this arch: compiled paths are unstable on gfx906 while eager mode (including Unsloth's Triton kernels) trains cleanly, so this PR defaults compile off there, overridable via env.

Changes

  • install.sh: when the runtime GPU is gfx906 and the picked index is newer than rocm6.3, route torch to the rocm6.3 index and reset the constraint trio to the default <2.11 window (the rocm7.2 pick raises the floor to 2.11, which rocm6.3 doesn't serve). Mirrors the Strix reroute: honors UNSLOTH_PYTORCH_MIRROR, respects explicit pins, skips mixed hosts whose visible-device selection targets a different GPU, and clears the Radeon-repo flag so a Radeon VII isn't re-rerouted.
  • install_python_stack.py: same logic in _ensure_rocm_torch (also migrates an existing +rocm7.x torch to rocm6.3, and leaves a working rocm6.3 install untouched so studio update stays idempotent).
  • device_type.py: on gfx906, setdefault TORCHDYNAMO_DISABLE=1 / TORCH_COMPILE_DISABLE=1 / UNSLOTH_COMPILE_DISABLE=1, so an explicit user override always wins.
  • import_fixes.py: extend the existing try/except idiom to the one importlib_version("vllm") probe that didn't have it yet (a partial vllm install makes it raise at import; independently hit and documented by the gfx906 lab).

No arch-specific version pin, following the #7277 convention. Windows allowlists intentionally untouched: repo.amd.com publishes no gfx906 wheel family (verified during #7277), so this stays a Linux path. 16-bit LoRA and full finetuning work with no extra steps; 4-bit QLoRA additionally needs a source-built bitsandbytes (gfx906:sramecc-:xnack-), and the installer warning says so up front.

Tests

TestGfx906LegacyReroute in test_rocm_support.py: floor boundaries, ROCm 7.2 host routes to rocm6.3, existing +rocm7.x torch migrates, rocm6.3 install left alone, mixed-host skip, sh/py parity. Full file 354 passed / 2 skipped; selection + cross-platform parity suites 291 passed; bash -n install.sh clean.

Reviewer note

The default window resolves torch 2.8/2.9 from the rocm6.3 index; the community has these running on gfx906 for inference (vllm-gfx906), while the lab's training verification is on 2.7.0. Not pinning to 2.7.0 is deliberate: that release predates torch.distributed.checkpoint.hf_storage, which transformers 5.x expects (the lab shims it manually). Happy to add a ceiling if you'd prefer the verified release; an MI50 smoke test would settle it, and u/VuaNam1234 has offered to help maintain this path going forward.

…n VII)

rocm6.4+/7.x torch wheels bundle ROCm libraries whose Tensile kernels
dropped gfx906 (rocBLAS 'TensileLibrary.dat ... not read for gfx906',
ROCm/TheRock#1844), so on MI50/Vega 20 hosts with newer ROCm the
installer picked wheels that fail at the first BLAS call. The rocm6.3
index is the last one whose wheels run on gfx906 (torch 2.7.0 verified
on MI50 32GB, up to 2.9 in community use). Dynamo/Inductor codegen is
also broken on this arch, crashing compiled graphs that train fine in
eager mode.

- install.sh: when the runtime GPU is gfx906 and the picked index is
  newer than rocm6.3, reroute torch to the rocm6.3 index and reset the
  constraint trio to the default <2.11 window (a rocm7.2 pick raises
  the floor to 2.11, which rocm6.3 cannot satisfy), with a legacy-path
  warning.
- install_python_stack.py: mirror the reroute in _ensure_rocm_torch
  using the _default pkg specs, including repairing an existing
  +rocm7.x torch and leaving a working rocm6.3 install alone.
- device_type.py: default TORCHDYNAMO_DISABLE / TORCH_COMPILE_DISABLE /
  UNSLOTH_COMPILE_DISABLE on gfx906 (setdefault, user override wins).

Windows allowlists are untouched: repo.amd.com publishes no gfx906
wheel family (verified in the RDNA2 enablement PR). 16-bit LoRA and
full finetuning work out of the box; 4-bit QLoRA needs a source-built
bitsandbytes for gfx906. Based on the verified MI50 32GB setup in
namnguyen0503/mi50-gfx906-unsloth-bnb4bit-lab.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@LeoBorcherding LeoBorcherding changed the title Add community-maintained legacy support path for gfx906 (MI50 / Radeon VII) Installer: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 23, 2026

@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: 6d7166a454

ℹ️ 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 studio/install_python_stack.py Resolved
Comment thread install.sh Resolved
Comment thread studio/install_python_stack.py Resolved
LeoBorcherding and others added 2 commits July 23, 2026 00:54
…e-dup)

Merge upstream/main (resolve the _ensure_rocm_torch elif chain against
unslothai#7305's inferred-gfx path: keep the gfx906 branch, adopt the new
'elif not rocm_torch_ready' fallback), then fix three Codex findings:

- Skip the prebuilt bitsandbytes wheel on gfx906 (install.sh + studio
  install_python_stack.py). It ships no gfx906 kernels and would clobber
  a user's source-built bnb on every studio update; gate both bnb call
  sites on a gfx906 target and print source-build guidance instead.
- Honor UNSLOTH_ROCM_GFX_ARCH in the gfx906 reroute decision (was only
  consulted for the display label / Windows path), so a runtime-only
  ROCm host whose rocminfo/amd-smi emit no gfx token can still opt in.
- Only auto-reroute when gfx906 is the SOLE distinct detected arch.
  _detect_amd_gfx_codes()/_gfx_all de-duplicate arches, losing per-device
  ordinals, so a mixed host with duplicate arches could downgrade a
  non-gfx906 selection to rocm6.3. Mixed gfx906+dGPU hosts opt in via
  UNSLOTH_ROCM_GFX_ARCH.

New/updated tests: _runtime_target_is_gfx906 selection matrix, env
override reroute, mixed-host skip, and generic-bnb skip. rocm_support +
selection + cross-platform parity: 664 passed, 17 skipped; bash -n clean.

@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: 8cc9d0a19d

ℹ️ 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 studio/install_python_stack.py Resolved
Comment thread install.sh Resolved
Comment thread studio/install_python_stack.py Resolved
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Addressed all three review findings in e8673e3 (also merged latest main, resolving the _ensure_rocm_torch elif chain against #7305's inferred-gfx path).

Skip generic bitsandbytes on gfx906. rocm_torch_ready flowed into the shared bnb block and force-reinstalled the prebuilt wheel, which ships no gfx906 kernels and would clobber a source-built bnb on every studio update. Both entry points now skip it:

  • install_python_stack.py: the bnb install is gated elif rocm_torch_ready behind a new if rocm_torch_ready and _runtime_is_gfx906 that prints source-build guidance instead. _runtime_is_gfx906 is computed independently of the ROCm version, so a native rocm6.3 gfx906 host is covered too.
  • install.sh: both _install_bnb_rocm call sites are guarded by _is_gfx906_bnb_skip.

Honor the gfx arch override before rerouting. The reroute keyed on probe output only. Both sides now consult UNSLOTH_ROCM_GFX_ARCH first (new _runtime_target_is_gfx906() in Python, _gfx906_env in install.sh), so a runtime-only host whose rocminfo/amd-smi emit no gfx token can opt in — matching how #7305's _infer_linux_amd_gfx_arch treats the override as authoritative.

Preserve device ordinals for mixed gfx906 hosts. _detect_amd_gfx_codes() / _gfx_all de-duplicate arches, so an out-of-range ordinal on a mixed host silently falls back to index 0. Rather than index into a de-duped list, auto-reroute now fires only when gfx906 is the sole distinct arch, so a non-gfx906 selection is never downgraded to rocm6.3. Mixed gfx906+dGPU hosts opt in explicitly with UNSLOTH_ROCM_GFX_ARCH=gfx906 (which is how the reference lab runs its mixed MI50 + dGPU rig anyway).

New/updated tests: _runtime_target_is_gfx906 selection matrix (override / sole-arch / mixed / empty), env-override reroute with no probe tokens, mixed-host skip, and generic-bnb skip. test_rocm_support + test_selection_logic + test_cross_platform_parity: 664 passed, 17 skipped; bash -n install.sh clean.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator 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: 8cc9d0a19d

ℹ️ 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 studio/install_python_stack.py Resolved
Comment thread studio/install_python_stack.py Resolved
LeoBorcherding and others added 7 commits July 23, 2026 02:53
- Compute the gfx906 runtime-target flag independently of any torch-index
  pin or Strix override, so the bitsandbytes skip still applies when a user
  pins the ROCm index and sets UNSLOTH_ROCM_GFX_ARCH=gfx906 (the pin
  suppresses the torch reroute, not the bnb skip). Probe only when no pin
  is set (an explicit pin means don't second-guess it, matching the Strix
  path's asserted no-probe invariant); an explicit gfx906 override needs
  no probe.
- Let UNSLOTH_ROCM_GFX_ARCH=gfx906 suppress the Strix reroute (both
  install.sh and install_python_stack.py) so a mixed Strix + MI50 host
  routes to rocm6.3 instead of the gfx1151 wheels probe order would pick.
- Fix test_hardcoded_torch_constraint: the default <2.11 window literal now
  legitimately appears on two TORCH_CONSTRAINT= assignments (default + the
  gfx906 reroute reset after the rocm7.2 floor bump); assert it only ever
  appears on assignment lines, never on a pip install line (its real intent).

New tests: bnb skipped under an explicit pin, gfx906 override wins over
Strix, install.sh suppresses Strix on the override. rocm_support +
selection + cross-platform parity: 667 passed; structural constraint 9/9.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator 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: 9e1b95cbb7

ℹ️ 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 install.sh Resolved
Comment thread studio/install_python_stack.py Resolved
Comment thread install.sh Resolved
Comment thread install.sh Resolved
LeoBorcherding and others added 2 commits July 23, 2026 17:31
…ed overrides

Address the four Codex P2 findings on unslothai#7354:

- bnb skip under a pinned index (install.sh + install_python_stack.py):
  a real gfx906 host that pins UNSLOTH_TORCH_INDEX_URL to rocm6.3 without also
  setting UNSLOTH_ROCM_GFX_ARCH no longer reinstalls the generic bitsandbytes
  wheel over a source-built gfx906 bnb. A pin now suppresses only the torch
  reroute, not the gfx906 detection used for the bnb skip (Python drops the pin
  gate on _runtime_is_gfx906; bash _is_gfx906_bnb_skip probes via
  _probe_amd_gfx_arch when the index is pinned).

- clear the Radeon marketing-name flag for every gfx906 target, not only when
  the >=6.4 reroute fires, so a Radeon VII already on rocm6.3 does not divert to
  the repo.radeon.com branch (whose wheels lack gfx906 kernels).

- normalize a copied HIP gcnArchName (gfx906:sramecc-:xnack- -> gfx906) before
  the exact comparisons in install.sh and install_python_stack.py, mirroring
  device_type.py.

Tests: relax the three Strix-pin tests (the gfx probe may now run for the bnb
flag but must not reroute the pinned index) and add coverage for the pinned
bnb skip, the suffixed override, and the bash Radeon-clear / pinned-probe paths.

@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: 311c82310b

ℹ️ 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 install.sh Resolved
Comment thread studio/install_python_stack.py Resolved
Follow-up review polish:
- import_fixes: log at info level when the vLLM aimv2 fix is skipped because
  the dist metadata is unreadable, so the skip is diagnosable instead of silent.
- test_rocm_support: bound the gfx906 install.sh source-scan on the ';;' that
  closes its case arm via a shared _gfx906_reroute_block helper, replacing the
  brittle fixed-length (3200/3800) slices that shift when the block grows.
…rity)

The bash gfx906 comparisons lowercased and stripped the gfx906:… feature
suffix but not surrounding whitespace, while the Python paths do .strip().
A stray newline (e.g. export UNSLOTH_ROCM_GFX_ARCH=$(cmd)) would make bash
miss gfx906 while Python catches it. Trim with `tr -d '[:space:]'` at both
comparison sites so the reroute target and bnb-skip agree across bash/Python.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

ci failures are unrelated to this pr
image

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 59fc94ecc6

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

@namnguyen0503

Copy link
Copy Markdown
Tested this PR on a real 32 GB AMD MI50 / gfx906 system.

## Hardware and host stack

- GPU: AMD MI50, 31.98 GiB
- Reported architecture: `gfx906:sramecc-:xnack-`
- Host ROCm/HIP: `6.3.42134-a9a80e791`
- OS: Linux
- Clean installation performed in a separate ext4 environment

## Clean installer results

The installer correctly:

- detected `gfx906`;
- selected the ROCm 6.3 PyTorch index:
  `https://download.pytorch.org/whl/rocm6.3`;
- installed `torch 2.9.1+rocm6.3`;
- imported the PR source successfully as Unsloth `2026.7.5`;
- set the expected compatibility flags:

```text
TORCHDYNAMO_DISABLE=1
TORCH_COMPILE_DISABLE=1
UNSLOTH_COMPILE_DISABLE=1

PyTorch successfully detected the card and executed a real FP16 GEMM:

Torch: 2.9.1+rocm6.3
HIP: 6.3.42134-a9a80e791
CUDA available: True
Device count: 1
Device name: AMD Radeon Graphics
GCN arch: gfx906:sramecc-:xnack-
VRAM: 31.98 GiB
FP16 GEMM: PASS

So the gfx906 detection, ROCm 6.3 rerouting, basic PyTorch runtime, and compile-disable behavior all work on real MI50 hardware.

bitsandbytes issue

The installer printed:

gfx906: skipping prebuilt bitsandbytes
(no gfx906 kernels); build from source for 4-bit QLoRA

However, the resulting clean environment still contained:

bitsandbytes 0.49.2

It appears to have been installed transitively despite the explicit skip logic.

Running:

python -m bitsandbytes

fails with:

Error invalid device function at line 107 in file /src/csrc/ops.hip

Therefore, the current logic does not fully prevent an incompatible generic bitsandbytes package from entering the gfx906 environment.

The package should either be excluded from dependency resolution on gfx906 or clearly replaced only after a compatible source build is installed.

Triton note

The clean environment installed mainstream Triton packages and emitted hip_utils.so loading warnings on gfx906.

My verified setup does not use mainstream Triton. It uses the gfx906-specific fork:

  • nlzy/triton-gfx906 3.3.0

Therefore, this clean installer test validates the eager PyTorch path, but it does not reproduce the Triton-enabled gfx906 stack used for the memory-optimized Gemma 4 workload.

Known-working gfx906 training baseline

My existing verified environment uses:

  • torch 2.7.0+rocm6.3
  • nlzy/triton-gfx906 3.3.0
  • source-built bitsandbytes 0.50.0.dev0

I confirmed that this PR source imports successfully when overlaid onto that environment:

torch: 2.7.0+rocm6.3
triton: 3.3.0
bnb: 0.50.0.dev0
unsloth: <PR checkout>/unsloth/__init__.py
PR SOURCE LOADED: PASS

The known-working baseline also completed a real Gemma 4 31B 4-bit LoRA/CPT workload with:

  • sequence length: 8192
  • LoRA rank: 64
  • optimizer steps: 3/3 completed
  • peak VRAM: 29.68 GiB
  • final status: OK

The workload uses custom gfx906 Triton attention and fused cross-entropy patches.

For accuracy: that three-step training run used Unsloth 2026.5.6, so I am reporting it as the verified gfx906 baseline, not yet as a full training pass of this PR branch.

Summary

  • gfx906 detection: PASS
  • ROCm 6.3 rerouting: PASS
  • Torch 2.9.1 GPU execution: PASS
  • PR import/runtime compatibility: PASS
  • compile disabling: PASS
  • generic bitsandbytes exclusion: FAIL
  • complete Triton-enabled gfx906 stack: not installed by the clean installer

The main actionable issue I found is that generic bitsandbytes 0.49.2 is still installed transitively and fails with invalid device function, despite the installer reporting that prebuilt bitsandbytes was skipped.

I can provide the complete installer and diagnostic logs if a specific section is needed.

@LeoBorcherding LeoBorcherding changed the title Installer: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux [Bug] Unsloth Studio: Installer enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 24, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] Unsloth Studio: Installer enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux [Bug] Unsloth Studio Installer: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 24, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] Unsloth Studio Installer: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux [Bug] Unsloth Studio: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 24, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] Unsloth Studio: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux [Bug] AMD: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 24, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] AMD: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux [Bug] AMD: enable ROCm torch on gfx906 for MI50 / Radeon VII on Linux Jul 24, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] AMD: enable ROCm torch on gfx906 for MI50 / Radeon VII on Linux [Bug] AMD: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 24, 2026
@LeoBorcherding LeoBorcherding changed the title [Bug] AMD: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux AMD: enable ROCm torch on gfx906 (MI50 / Radeon VII) on Linux Jul 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Pushed a fix for the bitsandbytes issue @namnguyen0503 hit on the MI50.

The skip only suppressed the prebuilt AMD wheel, but the unsloth package declares bitsandbytes>=0.45.5 as an unconditional dependency, so the base pip install unsloth (run with deps, after the skip) re-added a generic CUDA-only bitsandbytes with no gfx906 kernels. That is the invalid device function crash. The existing tests mock away the unsloth install, so they only assert the wheel-skip and could not catch the transitive pull, which is why CI stayed green.

The fix snapshots whether bitsandbytes is present before the base install and drops a freshly pulled generic wheel afterwards, in both install.sh (_gfx906_bnb_snapshot / _gfx906_bnb_prune) and studio/install_python_stack.py (_ensure_rocm_torch). A bitsandbytes that was already present before the base install (a user's source build) is left untouched, so studio update stays idempotent.

Verified in uv venv sandboxes: reproduced the transitive 0.49.2 pull, confirmed the prune removes it on a fresh install and preserves a source-built 0.50.0.dev0. Re-ran the gfx906 decision matrix across OS x GPU x ROCm version x override (480 cells): the reroute, bnb skip and compile-disable still fire only for sole gfx906 or an explicit UNSLOTH_ROCM_GFX_ARCH=gfx906, and never for NVIDIA, other AMD, CPU, Mac or Windows.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator 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: c75d09d52c

ℹ️ 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 install.sh
Comment on lines +277 to +279
if [ -z "$_bnb_gfx_env" ] && [ "${_torch_index_pinned:-false}" = true ]; then
_bnb_gfx_probe=$(_probe_amd_gfx_arch | awk 'NF && !seen[$0]++')
[ "$_bnb_gfx_probe" = "gfx906" ] && return 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.

P2 Badge Honor the pinned GPU target before probing gfx906

When an explicit index targets another architecture for a cross-install (for example, UNSLOTH_TORCH_INDEX_URL=.../gfx1151) but the machine running the installer has only a gfx906 GPU, this probe classifies the installation as gfx906 anyway. The subsequent install skips the ROCm bitsandbytes wheel and prunes the generic dependency, leaving the explicitly targeted Strix environment without bitsandbytes. studio/install_python_stack.py has the same issue because line 2014 calls _runtime_target_is_gfx906() even with a pin. A per-gfx pinned leaf should determine the target, or host probing under a pin should be limited to pins that do not identify another architecture.

Useful? React with 👍 / 👎.

Comment on lines +2918 to +2920
global _GFX906_BNB_ABSENT_BEFORE_BASE
if not skip_base:
_GFX906_BNB_ABSENT_BEFORE_BASE = not _bitsandbytes_installed()

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 Remove incompatible prebuilt bitsandbytes during upgrades

On a gfx906 environment created by an earlier installer, bitsandbytes is already present because the previous ROCm path installed the prebuilt wheel unconditionally. This presence-only snapshot therefore sets _GFX906_BNB_ABSENT_BEFORE_BASE to false, and the later gfx906 cleanup preserves that incompatible wheel as though it were a source build. Running studio update consequently leaves 4-bit loading enabled with a wheel that has no gfx906 kernels, leading to runtime kernel failures instead of the intended missing-bitsandbytes warning. The shell migration path has the same presence-only behavior; the cleanup needs to distinguish a gfx906 source build from the previously installed generic/prebuilt wheel.

Useful? React with 👍 / 👎.

Comment on lines +2019 to +2023
_gfx906_override = (
_runtime_is_gfx906
and _gfx906_needs_legacy_index(ver)
and _explicit_rocm_torch_index_url() is None
and _strix_override_url 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 Route explicit gfx906 targets without a readable ROCm version

When a fresh or runtime-only gfx906 host has /dev/kfd available and sets UNSLOTH_ROCM_GFX_ARCH=gfx906, but has no ROCm userspace metadata from which _detect_rocm_version() can read a version, the function substitutes (0, 0). This predicate then remains false, the inferred AMD per-arch path cannot handle gfx906 because it is absent from _GFX_TO_AMD_INDEX_ARCH, and no ROCm torch is installed even though the explicit arch uniquely determines the required rocm6.3 index. install.sh similarly keeps the initially selected CPU index because its gfx906 reroute is nested under a rocm* leaf. The explicit gfx906 override should select rocm6.3 directly in this version-unreadable setup.

Useful? React with 👍 / 👎.

Comment thread unsloth/device_type.py
Comment on lines +130 to +132
os.environ.setdefault("TORCHDYNAMO_DISABLE", "1")
os.environ.setdefault("TORCH_COMPILE_DISABLE", "1")
os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")

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 Make the advertised compile override effective

On gfx906, setting any one of the advertised variables to enable compilation does not override the default: for example, UNSLOTH_COMPILE_DISABLE=0 is preserved, but the two torch-level variables are still defaulted to 1, while TORCHDYNAMO_DISABLE=0 still leaves TORCH_COMPILE_DISABLE=1 and the Unsloth flag disabled. Thus an explicit user value only wins if the user knows to set all three variables, contrary to the stated user-overridable behavior. Treat an explicit compile-enable value as suppressing the whole default-disable bundle, or expose one canonical override.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

Went through this on a Strix Halo box (Radeon 8060S, gfx1151). No gfx906 hardware here, so I checked the premise, the blast radius on non-gfx906 hosts, and the resolver behaviour rather than the training path.

The premise checks out

  • ROCm/ROCm#4625 is the exact failure, still open, and the reporter states plainly that "rocm 6.3 worked fine". TheRock#1844 shows the same missing TensileLibrary.dat from the torch side.
  • AMD's install-on-linux page now lists MI50 / Radeon VII / Radeon PRO VII as Unsupported outright, not deprecated.
  • TheRock does publish a gfx906 SDK index but no torch wheels: rocm.nightlies.amd.com/v2/gfx906/ is a 200, /v2/gfx906/torch/ is a 404.
  • repo.amd.com/rocm/whl/gfx906/ is a 403, so keeping this a Linux-only path and leaving the Windows allowlists alone is right.

Blast radius on non-gfx906 hosts is nil

Confirmed live on gfx1151: _gcn_arch resolves to gfx1151, none of the three env vars get set, and the Strix reroute is only suppressed when UNSLOTH_ROCM_GFX_ARCH=gfx906 is explicit. test_strixhalo_wsl_reroute.sh passes 53/53, and the rocm support suite is 387 passed both on the branch and merged with current main (this is 31 commits behind, but it still merges clean and adds no failures).

I did look hard at torch.cuda.get_device_properties(0) running at import, since that forces HIP init on every ROCm host. It is a non-issue: main already initialises HIP during import unsloth via the bitsandbytes block below it. Measured torch.cuda.is_initialized() as True after import on both.

The version question is the real one, and the evidence is thinner than the note suggests

The reset window resolves cleanly, I checked it against the live index:

uv pip install --dry-run --index-url https://download.pytorch.org/whl/rocm6.3 \
    "torch>=2.4,<2.11.0" "torchvision>=0.19,<0.26.0" "torchaudio>=2.4,<2.11.0"

 + torch==2.9.1+rocm6.3
 + torchvision==0.24.1+rocm6.3
 + torchaudio==2.9.1+rocm6.3
 + pytorch-triton-rocm==3.5.1

So the trio is internally consistent. The reviewer note leans on vllm-gfx906 for the "up to 2.9 in community use" half of the argument. Two things about that:

  • vllm-gfx906 is now archived. The maintainer's note says models outgrew their capacity and MI50 prices rose. Its install line is indeed torch==2.9 on the rocm6.3 index, so the 2.9 claim is real, but it is for vLLM inference.
  • The only training verification anywhere is the lab, which pins 2.7.0+rocm6.3, a source-built bnb for gfx906:sramecc-:xnack-, and a torch.distributed.checkpoint.hf_storage shim.

Unsloth is the training case, so the 2.9 evidence does not really transfer, and the installer will land these users on 2.9.1 rather than the one configuration anyone has trained on. I would rather not merge that gap silently. Either add the ceiling you offered so it resolves to the verified 2.7.x, or get one MI50 smoke test on 2.9.1 and then keep the wider window on purpose. Your call which, but it should be a decision rather than a default.

Minor: the lab sets TORCH_INDUCTOR_DISABLE=1 where device_type.py sets UNSLOTH_COMPILE_DISABLE. Fine in practice since TORCHDYNAMO_DISABLE=1 gates Inductor anyway, just noting the substitution.

No code changes pushed here. Everything left is a hardware question, and I do not have the card.

@namnguyen0503

namnguyen0503 commented Jul 25, 2026 •

Copy link
Copy Markdown

Retested commit c75d09d on the real 32 GB MI50/gfx906 system.

The new transitive bitsandbytes pruning fix works:

PASS: generic bitsandbytes has been pruned

However, this exposes another blocker for the claimed 16-bit/full-finetuning path.

During import, Unsloth first reports:

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

but the import then fails before any model can be loaded:

File "unsloth/kernels/utils.py", line 136, in <module>
    import bitsandbytes as bnb
ModuleNotFoundError: No module named 'bitsandbytes'

Therefore, after correctly pruning the incompatible generic bitsandbytes
wheel, a clean gfx906 installation cannot currently import Unsloth at all,
including for 16-bit LoRA or full finetuning.

This prevented the requested torch 2.9.1+rocm6.3 forward/backward/optimizer
smoke test from starting.

It appears that bitsandbytes must be treated as an optional import in the
non-4-bit path, or the affected kernel modules must not be imported when
bitsandbytes is unavailable.

I did not reinstall the generic wheel because it is known to fail on this
card with:

Error invalid device function at line 107 in file /src/csrc/ops.hip

One conflict, in the Strix reroute arch case. Both sides were wanted:

- this branch wraps the case in `[ "$_gfx906_env" != "gfx906" ]` so an explicit
  UNSLOTH_ROCM_GFX_ARCH=gfx906 suppresses the Strix reroute on a mixed host;
- main added gfx1152 (Krackan Point) to the arch list in unslothai#7431.

Resolved by keeping the gfx906 guard around main's three-arch list.

Verified: bash -n install.sh, rocm support + arch parity suites 465 passed,
test_strixhalo_wsl_reroute.sh 53 passed, and the tokenizers/torch-constraint
file fails the same 14 pre-existing E2E sandbox tests it fails on main.
@danielhanchen

Copy link
Copy Markdown
Member

Merged main in and resolved the conflict. One collision, in the Strix reroute arch case, and both sides were wanted: this branch wraps it in [ "$_gfx906_env" != "gfx906" ] so an explicit UNSLOTH_ROCM_GFX_ARCH=gfx906 suppresses the Strix reroute on a mixed host, and main added gfx1152 (Krackan Point) to the arch list in #7431. Kept the gfx906 guard around main's three-arch list.

Verified after the merge: bash -n install.sh clean, rocm support and arch parity suites 465 passed, test_strixhalo_wsl_reroute.sh 53 passed, and test_tokenizers_and_torch_constraint.py fails the same 14 pre-existing E2E sandbox tests it fails on main (host environment, not this branch). GitHub now reports the PR mergeable.

The version question is answered

@namnguyen0503's MI50 run settles the thing I was most unsure about. I had flagged that the reset window resolves to 2.9.1 while the only training verification anywhere was 2.7.0, and that the 2.9 evidence came from vllm-gfx906, which is inference-only and now archived. Their report shows 2.9.1 actually executing on the card:

Torch: 2.9.1+rocm6.3
GCN arch: gfx906:sramecc-:xnack-
VRAM: 31.98 GiB
FP16 GEMM: PASS

Plus detection, the rocm6.3 reroute, the compile-disable flags and PR import all passing. That is the hardware evidence this needed, and I no longer think a 2.7.0 ceiling is warranted.

The bitsandbytes finding may already be fixed

The one FAIL in that report is generic bitsandbytes 0.49.2 arriving transitively despite the skip, then dying with invalid device function. Worth checking the timing before acting on it: the report is dated 2026-07-24T05:34Z, and c75d09d "gfx906: remove generic bitsandbytes pulled in transitively after the skip" landed at 2026-07-24T11:19Z, about six hours later. So the test almost certainly ran against the pre-fix branch.

@namnguyen0503 if you have the MI50 available, a re-run of the clean install on the current head would confirm whether _gfx906_bnb_prune closes it. That is the last open item I can see, and it is the difference between 4-bit QLoRA working out of the box and failing at first use.

The Triton note is fair and I would not try to solve it here. Mainstream Triton warning on gfx906 while the verified stack uses the nlzy/triton-gfx906 fork is a separate problem from wheel selection, and the PR already documents 16-bit LoRA and full finetuning as the supported path.

@danielhanchen
danielhanchen merged commit f03e669 into unslothai:main Jul 27, 2026
66 of 67 checks passed
@namnguyen0503

Copy link
Copy Markdown

I already reran the clean install on commit c75d09d.

_gfx906_bnb_prune does close the original transitive-wheel issue:

PASS: generic bitsandbytes has been pruned

However, after the prune, import unsloth fails because
unsloth/kernels/utils.py still imports bitsandbytes unconditionally:

File "unsloth/kernels/utils.py", line 136, in <module>
    import bitsandbytes as bnb
ModuleNotFoundError: No module named 'bitsandbytes'

So the incompatible generic wheel is now correctly absent, but the documented
16-bit/full-finetuning path cannot currently start without installing a
bitsandbytes package.

This is separate from Triton and occurs before model loading or training.

danielhanchen added a commit that referenced this pull request Jul 27, 2026
test_torch_constraint.sh asserted how many times each pin appears in install.sh.
Every hardware branch assigns its own torch/torchvision/torchaudio triple, so
#7354 adding gfx906 pushed three of those counts up by one and Backend CI has
been red on main since:

  FAIL: default TORCH_CONSTRAINT assignment exists (expected '1', got '2')
  FAIL: hardcoded torch>=2.4 appears exactly once (expected '1', got '2')
  FAIL: torchvision bounded (<0.26) at default + custom-leaf (expected '2', got '3')
  FAIL: torchaudio bounded (<2.11) at default + custom-leaf (expected '2', got '3')

install.sh is correct; the numbers were the stale part. Assert the invariants
instead, so the next hardware branch is not a test edit:

- the default assignment is the top-level one, so anchor the grep at column 0
  rather than counting every occurrence. An indented branch pin no longer
  satisfies it, which the old count did not distinguish either.
- what "appears exactly once" really guarded is that no pip install line spells
  a pin out instead of using "$TORCH_CONSTRAINT", so check that directly.
- companions must be bounded everywhere, so compare bounded assignments against
  total assignments rather than pinning a count of 2. That is strictly stronger:
  it now covers all 7, not the 2 the old numbers happened to name.

45 pass, 0 fail. Each new assertion fails when its property is broken: a bare or
unbounded companion, a hardcoded pin on an install line, or a missing top-level
default.
danielhanchen added a commit that referenced this pull request Jul 27, 2026
Resolve tests/sh/test_torch_constraint.sh by keeping main's invariant
based structure from #7503 and restating it against this branch's
composed ceiling variables.

Both sides rewrote the same assertions in the same spirit. #7503
replaced brittle occurrence counts with invariants after #7354's gfx906
branch pushed three counts up by one and left Backend CI red. This
branch had independently rewritten them because the default torch range
is no longer a literal, it is composed from _TORCH_CEILING="2.12.0".

The resolution keeps both:

- The column 0 anchor for the default assignment now reads the composed
  form TORCH_CONSTRAINT="torch>=2.4,<${_TORCH_CEILING}", so an indented
  per branch pin still cannot satisfy it. _TORCH_CEILING="2.12.0" is
  asserted separately so the anchor keeps its teeth.
- The tightened macOS py3.13 assignment is an existence check rather
  than a count, per #7503.
- Both stray literal checks are kept. They are complementary: #7503's
  sees through shell escaped quotes on an install or echoed command
  line, this branch's catches the two default ranges copied onto any
  assignment that is not TORCH_CONSTRAINT=.
- The gfx906 sub 2.11 cap assertion is kept, converted from a count to
  an indented existence check so a second hardware branch adding its own
  sub 2.11 cap is not a test edit.
- #7503's every assignment upper bound checks for torchvision and
  torchaudio are kept, widened to accept the composed ceiling alongside
  a literal bound.

install.sh, install.ps1, studio/setup.ps1 and studio/install_python_stack.py
are untouched by this merge. The gfx906 literal cap and the three ROCm
2.11 floors stay literal, and the test permits them without forcing them
to track the ceiling.

tests/sh/test_torch_constraint.sh: 49 pass, 0 fail.
danielhanchen added a commit that referenced this pull request Jul 28, 2026
* Keep `import unsloth` working when bitsandbytes is absent

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.

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

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

* Address the review on #7502: zoo coupling, non-hip flags, py3.9 collection

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.

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

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

* Address the second review on #7502: guarded probe, and 8bit in the same 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.

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

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

* Drop the importlib import left over from the find_spec probe on #7502

* Address the third review on #7502: exact-name bypass and a forwarded 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.

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

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

* Address the fourth review on #7502: FastModel never reached the 16bit 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.

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

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

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants