Skip to content

Fix bitsandbytes ROCm GPU arch and warp size detection on Windows - #6127

Merged
danielhanchen merged 5 commits into
mainfrom
fix/windows-rocm-bnb-detection
Jun 11, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix/windows-rocm-bnb-detection

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Problem

On Windows ROCm, import bitsandbytes shells out to rocminfo (bnb 0.47.0 to 0.49.2) or hipinfo.exe (bnb main, since bitsandbytes-foundation/bitsandbytes#1846) via PATH to detect the GPU architecture at import time. Neither tool is normally on PATH: the HIP SDK does not add its bin directory, and AMD's PyTorch wheels ship hipInfo.exe into the venv Scripts directory, which is only on PATH while the venv is activated. Running through uv run, invoking python.exe directly, or embedding the interpreter all hit this. Every import then logs:

ERROR Could not detect ROCm GPU architecture: [WinError 2] The system cannot find the file specified
WARNING ROCm GPU architecture detection failed despite ROCm being available.

and ROCM_GPU_ARCH degrades to "unknown".

On bnb 0.49.0 to 0.49.2 it is worse: get_rocm_warpsize() defaults to 64 on failure, which is wrong for every Windows ROCm GPU (RDNA is wave 32). That mis-gates 4-bit blocksize selection inside bitsandbytes and flips ALLOW_PREQUANTIZED_MODELS to False through device_type.py, silently disabling pre-quantized 4-bit models on Windows AMD boxes.

I proposed the fix upstream in bitsandbytes-foundation/bitsandbytes#1969, but shipping it here covers every bitsandbytes version users already have installed.

Fix

New fix_bitsandbytes_rocm_arch_detection() in import_fixes.py, called from the early fix block of _gpu_init.py. It has to run there: on ROCm the first bitsandbytes import happens inside import unsloth_zoo (device_type.py imports bitsandbytes at module scope), long before the late fix block.

  • Installs a MetaPathFinder for exactly bitsandbytes.cuda_specs. The module executes normally, then get_rocm_gpu_arch (and get_rocm_warpsize where present) are swapped before cextension.py calls them at module scope. The noise is prevented rather than suppressed and the constants are computed correctly from the start. The finder stays installed (same lifecycle as the existing causal_conv1d and vllm blockers) so importlib.reload(bitsandbytes.cuda_specs) re-applies the patch; it matches a single module name and repeat hits are idempotent.
  • The replacements read torch.cuda.get_device_properties(0) first (gcnArchName, warp_size): no subprocess, PATH independent. The fallback runs hipInfo.exe by absolute path (PATH, venv scripts dir, conda Scripts, HIP_PATH / ROCM_PATH, AMD installer dirs) with a timeout and no console window. The last resort returns upstream's own defaults, quietly.
  • If bitsandbytes was imported before unsloth, the values are repaired in place instead, including the by-value copies of ROCM_WARP_SIZE_64 in functional.py / nn/modules.py / backends/cuda/ops.py.
  • Strict no-op on non-Windows, non-ROCm torch builds, missing bitsandbytes, and future bitsandbytes versions that fix this upstream: the patch inspects the helper's code object and declines when it already consults device properties. Opt out with UNSLOTH_DISABLE_BNB_ROCM_FIX=1.
  • Adds a drift test that fails if bitsandbytes ever rewrites detection into a shape the patch would silently decline to handle.

Compatibility

  • NVIDIA / Intel / CPU / Mac: never reached (win32 and ROCm-build gates; the MLX path never imports _gpu_init).
  • Linux ROCm: byte identical behavior, the fix is Windows gated.
  • bitsandbytes <= 0.46 (no helpers), 0.47 to 0.48 (arch only), 0.49.x (arch plus warpsize), main (hipinfo): all handled. Unrecognized future shapes are left untouched.
  • transformers 4.57.x / 5.x, TRL 0.22 to 1.x, vLLM: none of them touch these symbols. The hook imports nothing at install time, matches a single module name, fires once and removes itself.
  • Coexists with the Studio-side workaround from Windows/WSL installer: fix winget msstore cert failure, amd-smi DiskPart prompt, and enable AMD GPU (Strix Halo gfx1151) #5940 (different mechanism, sentinel guarded).

Testing

Verified on a gfx1151 (Strix Halo) Windows 11 machine, torch 2.11.0+rocm7.13.0, with the venv not activated so hipinfo.exe is not PATH resolvable. 12 scenarios against three bitsandbytes trees (main, 0.49.2, and a torch-props-fixed variant), each in a fresh interpreter:

  • Broken baselines reproduce the ERROR / WARNING, the unknown arch, and the wrong ROCM_WARP_SIZE_64 = True on 0.49.2.
  • With the fix: ROCM_GPU_ARCH = "gfx1151", ROCM_WARP_SIZE_64 = False (including the copy in backends/cuda/ops.py), zero ERROR / WARNING records captured.
  • Disabling subprocess.run proves the arch comes from torch device properties; blinding torch.cuda.is_available proves the absolute-path hipInfo.exe fallback also returns gfx1151.
  • Retroactive repair (bnb imported first), idempotency (exactly one finder no matter how often the fix runs), opt-out, bnb-absent, non-ROCm interpreter, and the upstream-fixed no-op all pass.
  • AST checks confirm the diff is purely additive against main, every pre-existing definition is unchanged, and the committed functions are AST-identical to the versions the suite ran against.

Follow-up simulation matrix (all passing):

  • Environment layouts: conda (python.exe at the env root), embedded interpreters (empty sys.executable, broken sysconfig), Program Files\AMD\ROCm scan with newest-version-first ordering, hipInfo paths containing spaces and unicode, a hanging probe binary (bounded by the timeout), zero-byte probe binaries.
  • Helper shapes: bnb 0.45.5 (no ROCm helpers), 0.47.0 (arch only), 0.49.2, main, the upstream-fixed shape, an lru_cache wrapped broken helper (unwrapped and patched), a C-function helper (declined), an unrecognized rewrite (declined by design, covered by the new drift test).
  • Import dynamics: importlib.reload(bitsandbytes.cuda_specs) re-applies the patch (this run caught that the original one-shot finder regressed on reload, fixed by keeping the finder installed), failed-import-then-retry, two threads importing concurrently, a multiprocessing spawn child, and a dormant finder leaving unrelated imports untouched.
  • Platforms and interpreters: real ROCm torch on WSL Linux behaves byte-identically with and without the fix (rocminfo on and off PATH), darwin and linux gates install nothing, a real CPU-torch venv installs nothing, a stale HIP_PATH on CPU torch stays value-identical to upstream, and Python 3.10 through 3.13 gates all pass in isolated uv venvs.
  • Coexistence: the full _gpu_init early fix-block call order, Studio's PATH prepend, and UNSLOTH_ENABLE_LOGGING=1 all work unchanged.

danielhanchen and others added 2 commits June 9, 2026 22:35
bitsandbytes resolves the ROCm GPU architecture (and warp size on
0.49.x) by shelling out to rocminfo / hipinfo.exe via PATH at import
time. On Windows neither tool is normally on PATH (AMD torch wheels
ship hipInfo.exe into the venv Scripts dir, only on PATH while
activated), so every `import bitsandbytes` logs an ERROR and WARNING,
ROCM_GPU_ARCH degrades to unknown, and the 0.49.x warp size defaults
to 64, which is wrong on RDNA (wave 32) and silently disables
pre-quantized 4-bit models via ALLOW_PREQUANTIZED_MODELS.

Install a one-shot MetaPathFinder before unsloth_zoo is imported (the
first bitsandbytes import on ROCm) that swaps get_rocm_gpu_arch and
get_rocm_warpsize for torch-device-properties-first implementations
right after bitsandbytes.cuda_specs executes, before cextension reads
them. Falls back to running hipInfo.exe by absolute path (venv
Scripts, conda Scripts, HIP SDK / AMD installer dirs). Repairs the
constants in place when bitsandbytes was imported first. Strict no-op
on non-Windows, non-ROCm builds, missing bitsandbytes, and versions
that fix this upstream. Opt out with UNSLOTH_DISABLE_BNB_ROCM_FIX=1.

Proposed upstream in bitsandbytes-foundation/bitsandbytes#1969;
shipped here so all bitsandbytes versions are covered. Verified on
gfx1151 Strix Halo, Windows 11, torch 2.11.0+rocm7.13.0 against
bitsandbytes main, 0.49.2, and a torch-props-fixed variant.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a fix for bitsandbytes ROCm architecture and warp-size detection on Windows by installing a custom import hook to patch bitsandbytes.cuda_specs at import time, replacing subprocess-based detection with a torch-device-properties-first approach. It also adds a drift test to ensure compatibility with future bitsandbytes updates. A review comment suggests defensively decoding props.gcnArchName in case it is returned as a bytes object in certain PyTorch builds, preventing potential failures in architecture detection.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread unsloth/import_fixes.py
except Exception:
pass
for hipinfo_path in _iter_hipinfo_paths():
match = re.search(r"gcnArchName:\s+gfx([a-zA-Z\d]+)", _run_hipinfo(hipinfo_path))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

In some PyTorch builds or custom environments, props.gcnArchName can be returned as a bytes object rather than a str. Calling str(props.gcnArchName) on a bytes object results in a string representation like "b'gfx90a'", which will fail the subsequent .startswith("gfx") check. Defensively decoding the attribute if it is an instance of bytes ensures robust architecture detection.

            arch = props.gcnArchName.decode("utf-8", errors="ignore") if isinstance(props.gcnArchName, bytes) else str(props.gcnArchName)
            arch = arch.split(":")[0].strip()

Comment and docstring pass only. AST comparison with docstrings
stripped confirms every definition is identical to the version the
12 scenario suite ran against, and the suite plus the drift test
pass unchanged on the edited files.
Simulation testing caught a regression in the one-shot design:
importlib.reload(bitsandbytes.cuda_specs) re-resolves the spec through
sys.meta_path, so with the finder already removed the reload reinstalled
the unpatched upstream detector and the Windows ROCm noise returned.
Keep the finder on sys.meta_path permanently, matching the lifecycle of
the existing causal_conv1d and vllm import blockers. The finder matches
a single module name and patching stays idempotent via the sentinel
flags, so repeat hits are no-ops.

Validated on gfx1151 Windows 11: 22 simulation scenarios (conda and
embedded layouts, Program Files scan ordering, paths with spaces and
unicode, hanging probe timeout, lru-wrapped and C-function helper
shapes, reload, failed-import retry, threads, spawn, dormant finder,
Studio PATH coexistence, early fix-block ordering, bnb 0.45.5 / 0.47.0
/ 0.49.2 / main / upstream-fixed) plus the original 12 scenario suite,
CPU-torch and stale-HIP_PATH sandboxes, Python 3.10 to 3.13 gates, and
a WSL Linux leg proving byte-identical Linux behavior with and without
the fix, with and without rocminfo on PATH.
@danielhanchen
danielhanchen merged commit 12a890e into main Jun 11, 2026
44 checks passed
@danielhanchen
danielhanchen deleted the fix/windows-rocm-bnb-detection branch June 11, 2026 13:27
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