Repository navigation
Clear ALLOW_BITSANDBYTES when the bitsandbytes native kernels are not real - #7578
Conversation
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 003aab51bd
ℹ️ 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".
| # A broken wheel imports but never binds its submodules, so probe what we | ||
| # actually use. Trusting the top-level import alone let `bnb.functional` | ||
| # raise below, which is the failure this guard exists to prevent. | ||
| bnb.__version__, bnb.functional.get_ptr |
There was a problem hiding this comment.
Mark the broken wheel unavailable globally
When bitsandbytes imports but lacks functional, this probe sets only the kernels module's local bnb to None; unsloth/device_type.py has already left ALLOW_BITSANDBYTES=True because its probe checks only the import. Both loader paths downgrade 4-bit/8-bit requests only when that flag is false, so the default load_in_4bit=True is still forwarded and later fails instead of taking the advertised 16-bit fallback. Apply the same functional capability probe to the global flag or share a single availability result.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 13d392e. Confirmed the disagreement: device_type.py's comment claimed all three modules treat a broken wheel as unavailable, but its probe was import-only, so ALLOW_BITSANDBYTES stayed true while kernels/utils.py fell back to the stub and loader.py kept forwarding load_in_4bit.
There is now one shared result. New leaf module unsloth/bnb_availability.py (imports nothing from unsloth, takes the device type as an argument, so no cycle with device_type.py). device_type.py exports BITSANDBYTES from it, kernels/utils.py binds that instead of importing bitsandbytes itself, and _gpu_init.py runs the same check. The flag and the stubs are now the same fact.
Measured with BNB_CUDA_VERSION=999, which makes bitsandbytes install its ErrorHandlerMockBNBNativeLibrary: before, from_pretrained(load_in_4bit=True) died with 'Attempted to use bitsandbytes native library functionality but it is not available'; after, it prints the 16bit fallback and loads bfloat16 with quantization_config=None.
| # "module 'bitsandbytes' has no attribute 'functional'". | ||
| broken = types.ModuleType("bitsandbytes") | ||
| broken.__version__ = "0.50.0" | ||
| broken.__spec__ = importlib.machinery.ModuleSpec("bitsandbytes", loader = None) |
There was a problem hiding this comment.
Make the broken-wheel stand-in survive reloads
On a root CUDA environment, unsloth/_gpu_init.py enters its geteuid()==0 recovery path and calls importlib.reload(bnb). This loader-less stand-in is then either replaced from a healthy installed bitsandbytes package, making the final stub assertion fail, or raises because no package spec is discoverable. Use a deterministic loader that reloads back into the broken state so this regression test also works in the root GPU containers commonly used for training.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 13d392e. Reproduced it first: with geteuid forced to 0, _gpu_init.py:343 reloaded the stand-in from the real installed wheel, so the final stub assertion failed on a healthy host. importlib.reload re-runs sys.meta_path rather than reusing an injected spec, so a loader-less ModuleSpec cannot survive it.
The stand-in is now a sys.meta_path finder with a real loader that rebuilds the same broken state on reload. I also wrapped the reload calls in _gpu_init.py: they sit inside an except: recovery block, so an exception there took down import unsloth in exactly the situation the block exists to repair.
| # A broken wheel imports but never binds its submodules, so probe what we | ||
| # actually use. Trusting the top-level import alone let `bnb.functional` | ||
| # raise below, which is the failure this guard exists to prevent. | ||
| bnb.__version__, bnb.functional.get_ptr |
There was a problem hiding this comment.
Probe every module-scope bitsandbytes symbol
For a partially loaded or backend-mismatched wheel where functional.get_ptr exists but the native functional.lib lacks one of the backend kernels, this probe succeeds and the module still raises at lines 267–278 while binding cdequantize_blockwise_* or cgemm/cgemv_*. Those are also unconditional module-scope accesses, so include the applicable bindings in the guarded capability check or move all of the bindings into the guarded block; otherwise only one particular broken-wheel shape receives the new fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 13d392e, and the problem was worse than described. Probing by attribute access is inert on bitsandbytes 0.46 and later: BNBNativeLibrary.getattr swallows a missing symbol and returns a throw_on_call closure, and a wheel whose native library failed to load is replaced wholesale by ErrorHandlerMockBNBNativeLibrary, which does that for every name. Measured on 0.50.0, a bogus symbol does not raise at all.
So the probe resolves every symbol kernels/utils.py binds at module scope and checks each handle has a restype, which a real ctypes function pointer has and a deferred-failure closure does not. The xpu/non-xpu split is honoured, since probing the cgemv names on cuda would write off a good wheel. A test asserts the probed set matches the bnb.functional.lib.* reads in kernels/utils.py in both directions, so the two cannot drift.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7c0d23d204
ℹ️ 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".
|
|
||
|
|
||
| def _run_broken_wheel_probe(shape, fake_root = False): | ||
| env = dict(os.environ, BROKEN_BNB_SHAPE = shape) |
There was a problem hiding this comment.
Propagate the CPU import spoof to probe subprocesses
In the CPU-only repo jobs I checked (.github/workflows/studio-backend-ci.yml Repo tests and .github/workflows/consolidated-tests-ci.yml Core), the GPU spoof from tests/conftest.py only exists in the parent pytest process; this child process inherits only BROKEN_BNB_SHAPE, so import unsloth.kernels.utils runs real device detection on ubuntu-latest and fails before reaching the broken-wheel assertions. Please pass the CPU fallback/spoof into the subprocess, or avoid importing through the package init in the child, so these new behavioral tests do not make CPU CI red.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a392aba. Reproduced it first, which confirmed this would have made CPU CI red: with no accelerator visible, 5 of the subprocess tests failed with 'Unsloth cannot find any torch accelerator? You need a GPU.' before reaching any assertion.
My first attempt, patching torch.cuda.is_available in the child, was worse: it made torchao and triton probe a device that is not there. tests/conftest.py avoids that by restoring is_available immediately after exec'ing device_type. So the child now executes tests/conftest.py itself rather than restating its harness, which also means the two cannot drift. It no-ops when a real accelerator answers, so DEVICE_TYPE and the device-dependent symbol sets stay honest.
Verified both ways: CUDA_VISIBLE_DEVICES='' gives 15 passed, and 15 passed with GPUs visible.
| @@ -0,0 +1,95 @@ | |||
| # SPDX-License-Identifier: AGPL-3.0-only | |||
There was a problem hiding this comment.
Use the core package license for this helper
This new helper is imported by core unsloth.device_type, but it is marked AGPL-3.0-only while the repository metadata declares the project as Apache-2.0 and LICENSE:190 says files under unsloth/* are Apache-2.0, with AGPL reserved for optional Studio/CLI components. Shipping a required core import-path file as AGPL-only changes the license obligations users see for the package, so this should use the same Apache header as neighboring core modules unless the core package is intentionally being relicensed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a392aba, and you were right about the obligation. LICENSE:190 says 'Files under unsloth/, tests/, scripts/* are Apache 2.0 licensed' with AGPL reserved for studio/* and unsloth_cli/*, pyproject.toml declares the package Apache-2.0, and device_type.py, kernels/utils.py and _gpu_init.py all carry the Apache header. The new file now uses the same one.
Worth flagging: unsloth/models/_uma_safetensors.py carries an SPDX AGPL-3.0-only header under the same Apache subtree, which is where this one was copied from. I have left it alone here, but it looks mislabelled by the same reasoning.
| """ | ||
| if importlib.util.find_spec("bitsandbytes") is None: | ||
| return | ||
| from bitsandbytes.cextension import ErrorHandlerMockBNBNativeLibrary |
There was a problem hiding this comment.
Guard the 0.46-only bitsandbytes test import
When this test file is run in an environment using the supported bitsandbytes==0.45.5 floor/pins from pyproject.toml, find_spec("bitsandbytes") is true but ErrorHandlerMockBNBNativeLibrary is not exported by that release, so the test fails with ImportError before checking the actual probe behavior. Please version-gate this case or skip it when the newer mock class is unavailable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a392aba. The guard was find_spec-only, so it skipped when bitsandbytes was absent but not when it was present without the class. The import is now wrapped and the case skips on ImportError, with a note that 0.45.5 fails differently (functional.lib is None), which the lib_is_none shape already covers.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Pushed Also triaged the cross-platform staging run for this branch: it went red on ubuntu-latest, macos-14 and windows-latest with |
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Pushed WhyThe single probe answered two different questions with one verdict, and the strict half was doing the deciding. A deferred-failure handle ( Measured on this branch before the change, in a venv matching the failing job ( Collection went green, but the whole CPU matrix would have run with bitsandbytes disabled and What changed
So a wheel that only dies inside a kernel keeps
VerificationSame CPU-only venv, after: Real B200, nothing regressed:
Also switched the new module to the Note that #7582 has since merged, so |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d21f245762
ℹ️ 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".
| BITSANDBYTES_KERNELS_READY: bool = BITSANDBYTES is not None and native_kernels_ready( | ||
| BITSANDBYTES, DEVICE_TYPE | ||
| ) | ||
| if not BITSANDBYTES_KERNELS_READY: | ||
| ALLOW_PREQUANTIZED_MODELS = False | ||
| ALLOW_BITSANDBYTES = False |
There was a problem hiding this comment.
Preserve working 8-bit loading when only 4-bit probes fail
When a usable bitsandbytes native library lacks just one of the 4-bit dequantization/GEMM symbols probed here, this sets the general ALLOW_BITSANDBYTES flag to false even though its 8-bit kernels may still work. Both loader paths interpret that flag by unconditionally clearing load_in_8bit (for example, models/loader.py:505-510), so an explicit, otherwise valid 8-bit request is silently converted to 16-bit. Track 4-bit and 8-bit capabilities separately, or avoid using this 4-bit-only probe to disable 8-bit loading.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in 60151e3. Confirmed the mechanism: loader.py:505-510 clears load_in_8bit alongside load_in_4bit off this one flag, so a library exporting the 8bit kernels but missing one 4bit symbol would have had a valid LLM.int8 request silently downgraded to 16bit.
The check now fails only when NO probed handle is a ctypes function pointer, which is the dead-library case it exists for (CPU-only builds, ErrorHandlerMockBNBNativeLibrary). A library that exports some and not others is alive and keeps its flags. A genuinely missing symbol raises where kernels/utils.py binds it at module scope, so it is a crash no capability flag can rescue, and not worth trading 8bit for.
There was a problem hiding this comment.
Following up: this got reversed in ea69131, and the reason is worth recording here.
Your point held while native_kernels_ready only gated the flags. It stopped holding once the same verdict also gated the module-scope ctypes binds in kernels/utils.py (the P1 on bnb_availability.py:74): under "at least one handle is native", a partially exporting library passes the probe and then raises AttributeError at the bind. The verdict now requires every probed handle.
So partial export does now cost 8bit, which is the downgrade you flagged. Doing better needs a flag separate from ALLOW_BITSANDBYTES in loader.py:505-510; that is a follow-up rather than part of this PR.
| try: | ||
| importlib.reload(triton) | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
Do not continue after a partially failed Triton reload
On a root CUDA host where the bitsandbytes probe enters this recovery path, any exception raised while reloading Triton is now discarded. importlib.reload executes in the existing module namespace and is not transactional, so a failed reload can leave triton partially updated; the following validation block merely emits a warning on failure and import then continues into modules that rely on Triton. Propagate the reload error or otherwise restore/validate a usable Triton module instead of continuing with potentially inconsistent state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not applicable to this PR any more. It is anchored to d21f245, an earlier revision that touched unsloth/_gpu_init.py; the PR was rewritten and now changes only device_type.py, bnb_availability.py and the new test, so that file is no longer in the diff.
The underlying observation is about the importlib.reload(triton) recovery path that exists on main independently of this change, and it is speculative rather than reproduced, so it is not something to fold in here.
… real From bitsandbytes 0.46 a wheel whose native library never loaded still imports and resolves every ctypes handle: BNBNativeLibrary.__getattr__ returns a throw_on_call closure, and a dead library is replaced wholesale by ErrorHandlerMockBNBNativeLibrary, which does the same for every name. Nothing raises while kernels/utils.py binds them at module scope, so device_type.py's guarded import sees a healthy wheel, ALLOW_BITSANDBYTES stays true, loader.py forwards the default load_in_4bit=True and the run dies inside a kernel instead of degrading to 16bit. Probe the handles the kernels actually bind and clear the flags when they are not native. A real handle is a ctypes function pointer and carries restype; a deferred failure is a Python function and does not. Scoped to the capability flags on purpose. The module stays bound and get_ptr keeps pointing at bitsandbytes, because these shapes import perfectly well and treating them as absent would disable a wheel whose Python side works - a CPU-only install is exactly that shape.
d21f245 to
f4449ae
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 716bcf824f
ℹ️ 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".
| @@ -0,0 +1,153 @@ | |||
| # SPDX-License-Identifier: AGPL-3.0-only | |||
There was a problem hiding this comment.
Use the repository's Apache license for tests
This new file lives under tests/*, but its SPDX tag marks it as AGPL-only even though LICENSE:190 declares files under tests/* are Apache-2.0 licensed. Leaving this header as AGPL causes package/source scanners to report stronger obligations for a test file than the project license promises, so it should use the same Apache header as the rest of the Apache-scoped tree.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The LICENSE line is quoted accurately, but making this one file Apache would put it at odds with the tree it lives in. 113 files under tests/ carry the AGPL-3.0 SPDX tag against 10 with the Apache header, including tests/conftest.py, which was merged two hours ago in #7582.
So the real inconsistency is between LICENSE:190 and the prevailing convention, and resolving it means either updating that line or relicensing 113 files. Either is a deliberate licensing decision, not something to settle inside a bitsandbytes capability-flag PR. Leaving this file matching its neighbours.
…xporting ALLOW_BITSANDBYTES gates 8bit as well as 4bit - loader.py:505-510 clears both - so failing the check on one missing 4bit symbol would silently downgrade an otherwise valid LLM.int8 request to 16bit. A library that exports some of these handles is alive; only one where none of them is a ctypes function pointer is dead, which is the CPU-only and ErrorHandlerMockBNBNativeLibrary case this exists for. A genuinely missing symbol raises where kernels/utils.py binds it, so it is a crash no capability flag can rescue and not something to trade 8bit for.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 60151e34fc
ℹ️ 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".
| if lib is None: | ||
| # 0.45.5, the floor in pyproject.toml, on a native-load failure. | ||
| raise AttributeError("Unsloth: `bitsandbytes.functional.lib` is None.") |
There was a problem hiding this comment.
Make the lib-none verdict survive the package import
When bitsandbytes 0.45.5 imports with functional.lib = None after a native-load failure, this branch correctly marks the kernels unavailable, but import unsloth subsequently reaches unsloth/kernels/utils.py:261-264, where the successfully imported bnb is still treated as usable and bnb.functional.lib.cdequantize_blockwise_fp32 raises before either loader can apply the 16-bit fallback. Fresh evidence in this revision is the new explicit lib is None branch (and its test), while the base kernel-binding path still only guards bnb is None; propagate this verdict to that binding path so the documented broken-wheel shape remains importable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in e7aa032.
Confirmed the shape rather than assumed it: bitsandbytes 0.45.5 cextension.py ends with try: lib = get_native_library() / except Exception: lib = None, and functional.py does from bitsandbytes.cextension import lib, so import bitsandbytes succeeds with functional.lib is None. bnb is None was the only guard on the bind block, so None.cdequantize_blockwise_fp32 raised at module scope and import unsloth died before either loader could fall back to 16bit - exactly the fallback the cleared flag exists to reach.
if bnb is None: is now if bnb is None or not native_kernels_ready(bnb, DEVICE_TYPE):, so the bind path and the flag path return the same verdict from the same function. Only the guard expression changed; the binds themselves are untouched, which keeps this off the lines #7580 rewrites.
Re-verified on a B200 that a healthy wheel is unaffected: ALLOW_BITSANDBYTES True, get_ptr is bnb.functional.get_ptr True, 109 Linear4bit modules, 10/10 steps with finite loss, generation clean, 1.52 GB peak.
Clearing ALLOW_BITSANDBYTES is not enough on its own. kernels/utils.py guarded the bnb.functional.lib.* binds on `bnb is None` alone, so an importable but dead wheel still reached them at module scope: bitsandbytes 0.45.5, the floor in pyproject.toml, sets functional.lib = None when the native library fails to load, and None.cdequantize_blockwise_fp32 raises right there. That kills import unsloth outright instead of degrading to 16bit, which is the fallback the cleared flag exists to reach. Reuse native_kernels_ready so the bind path and the flag path agree, and take the _bnb_required branch when they say the library is dead. Touches only the guard expression, not the binds themselves.
|
@codex review |
|
Verification for CPU-only host (torch 2.10.0+cpu, bitsandbytes 0.50.0, no GPU) — the shape this guard fires on. Full
Identical failures on both sides ( Healthy CUDA wheel is untouched — B200, bitsandbytes 0.50.0: |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2dd60e6f8a
ℹ️ 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".
| if hasattr(handle, "restype"): | ||
| return # a ctypes function pointer, so the library really loaded |
There was a problem hiding this comment.
Require every 4-bit handle before enabling 4-bit
When a loaded native library exports one probed symbol but lacks another, this early return marks bitsandbytes ready; kernels/utils.py:266-277 then unconditionally binds all five handles, so a missing attribute either breaks import unsloth or becomes a deferred-failure closure while the default 4-bit request remains enabled and later crashes. Fresh evidence in this revision is test_a_partially_exporting_library_stays_ready, which deliberately accepts this exact shape. Preserve 8-bit separately if needed, but only enable and bind the 4-bit path when every required device-specific handle is native.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it catches an interaction I introduced. Fixed in ea69131.
"At least one handle is native" was the right question while this verdict only gated the flags - that was your earlier P2 about not writing off 8bit over a missing 4bit symbol, which I agreed with. Once the same verdict started gating the module-scope binds in kernels/utils.py, it stopped being the right question: a library that resolves one symbol and not another passes the probe and then raises AttributeError at the bind the probe exists to prevent.
check_native_kernels now requires every symbol in bitsandbytes_symbols(device_type) to carry restype, and a missing attribute is itself a failed check rather than a skip. That does cost 8bit in the partial case, since ALLOW_BITSANDBYTES gates both - but a wheel missing a symbol is a shape no flag makes safe, and refusing it beats crashing on it. Splitting 4bit from 8bit properly needs a second flag in loader.py:505-510, which is a wider change than this PR should carry; noted as a follow-up.
test_a_partially_exporting_library_stays_ready is flipped to ..._is_not_ready, plus a new test_one_dead_handle_among_live_ones_is_not_ready for the more realistic shape (library loaded, one symbol still a closure).
Re-verified: 10/10 unit tests; full tests/python paired against main with junitxml, and the only differing tests are the 10 new ones, all passing; B200 4bit run unchanged (ALLOW_BITSANDBYTES True, get_ptr real, 109 Linear4bit, 10/10 steps, 1.52 GB peak).
| @@ -0,0 +1,87 @@ | |||
| # SPDX-License-Identifier: AGPL-3.0-only | |||
There was a problem hiding this comment.
Restore the core package's Apache license
This required core helper is marked AGPL-3.0-only, while the project metadata declares Apache-2.0 and LICENSE:190 explicitly assigns files under unsloth/* to Apache-2.0. Shipping this module under AGPL therefore imposes obligations inconsistent with the declared core-package license. Fresh evidence is that the reviewed commit's newly added file still contains the AGPL SPDX tag despite the earlier thread reporting it corrected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and I had this wrong. Fixed in ea69131.
LICENSE:190 is explicit ("Files under unsloth/, tests/, scripts/* are Apache 2.0 licensed"), and 87 of the 90 modules under unsloth/ carry the Apache header. I had matched unsloth/models/_uma_safetensors.py, which turns out to be one of only 3 AGPL outliers there. unsloth/bnb_availability.py now carries the standard Apache 2.0 header.
Not changing the test file for the same reason, which is the distinction behind my earlier reply on that thread: all 113 SPDX-tagged files under tests/ are AGPL, unanimously, so flipping one would make it the odd file out. That tests/ are AGPL in practice while LICENSE:190 names them Apache is a repo-wide inconsistency worth settling separately, not in this PR.
…est of unsloth The readiness verdict now gates the module-scope ctypes binds as well as the flags, so "at least one handle is native" is no longer the right question. A library that resolves one symbol and not another passed the probe and then raised AttributeError at the bind the probe exists to prevent. Require all of them. That costs 8bit in the partial case, since ALLOW_BITSANDBYTES gates both, but a wheel missing a symbol is a shape no flag can make safe and refusing it beats crashing on it. Flipped the test that encoded the old behaviour and added the more realistic shape: the library loaded, one symbol is still a deferred-failure closure. LICENSE:190 assigns files under unsloth/* to Apache 2.0, and 87 of the 90 modules there carry that header, so use it here rather than AGPL.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ea691316ac
ℹ️ 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".
| if not native_kernels_ready(_bnb_probe, DEVICE_TYPE): | ||
| ALLOW_PREQUANTIZED_MODELS = False | ||
| ALLOW_BITSANDBYTES = False |
There was a problem hiding this comment.
Separate 4-bit readiness from the 8-bit flag
When a usable native library is missing only one of these 4-bit dequantization/GEMM handles, this sets the general ALLOW_BITSANDBYTES flag to false even though its LLM.int8 kernels may still work; both loader paths then clear load_in_8bit (for example, models/loader.py:505-508), silently converting an explicit valid 8-bit request to 16-bit. Fresh evidence in this final revision is test_a_partially_exporting_library_is_not_ready and the helper's new comment explicitly accepting that this verdict also costs 8-bit. Track 4-bit and 8-bit capabilities separately so failure of this 4-bit-only probe does not disable working 8-bit loading.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is right but the premise does not hold, so I am leaving this as a follow-up rather than expanding the PR.
"Its LLM.int8 kernels may still work" is the load-bearing claim, and I measured it on the actual broken wheel this PR exists for (bitsandbytes 0.50.0, CPU-only torch, lib a real BNBNativeLibrary):
4bit cdequantize_blockwise_fp32 native=False
4bit cgemm_4bit_inference_naive_bf16 native=False (all 5: False)
8bit cigemmlt_32 native=False
8bit cdequant_mm_int32_fp16 native=False
8bit cint8_vector_quant native=False (all 7: False)
When the native library is dead, BNBNativeLibrary.__getattr__ hands back a throw_on_call closure for every name, 8-bit included. There is no 8-bit capability left to preserve, so clearing ALLOW_BITSANDBYTES costs nothing real and the strict and lenient verdicts agree.
They only diverge for a wheel whose library loads natively and exports some 4-bit symbols but not others. bitsandbytes builds either export the whole 4-bit API or fail to load outright, so I could not construct that shape outside a test double. Splitting the flag means threading a second capability through loader.py:505-510 and every consumer, which is real blast radius for a case I cannot reproduce.
Worth noting the branch is not a regression even there: kernels/utils.py on main binds all five handles unconditionally, so a partial wheel yields deferred-failure closures and 4-bit dies mid-run. This turns that into a 16-bit fallback. If a real partial-export wheel ever shows up, the separate flag is the right fix and I will file it then.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d2d8fc01c9
ℹ️ 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".
| if functional is None: | ||
| # A part-initialised bitsandbytes leaves the parent without the attribute while | ||
| # the submodule stays in sys.modules, which `import x.y as z` reads directly. | ||
| import bitsandbytes.functional as functional |
There was a problem hiding this comment.
Reattach functional to partially initialized parents
When bitsandbytes is re-imported after a failed initialization, bitsandbytes.functional can remain cached while the new parent module lacks its functional attribute—the exact zombie state documented in tests/conftest.py. This import returns the cached child but does not restore that parent attribute, so kernels/utils.py:156 still raises at bnb.functional.get_ptr before the new readiness guard can provide its fallback. Fresh evidence in this revision is this explicit cached-submodule recovery branch, which therefore needs to reattach the child or make the later code use the recovered module directly.
Useful? React with 👍 / 👎.
) #7578 and #7580 landed within a minute of each other and compose correctly in kernels/utils.py, but the source-text assertion #7578 added does not: it looked for the literal "bnb.functional.lib" under the guard, and #7580 renamed that binding to "bnb_functional.lib" to survive a half-imported bitsandbytes. Git merged both cleanly because they touch different lines, so the break only shows at test time. Match "lib.cdequantize_blockwise_fp32" instead. That still pins the binds to the guard, which is what the test is for, and no longer breaks when the module alias changes. Co-authored-by: unslothai <[email protected]>
Picks up the bitsandbytes test-collection fixes (unslothai#7578, unslothai#7580, unslothai#7582), which landed after the last run on this branch and are what the red Core jobs were failing on. Conflict was the Bucket-A file list only: main appended tests/test_raw_text_json_loading.py where this branch appended tests/test_map_eos_token.py. Kept both.
Rewritten and rebased on
main. The original scope is gone: #7582 fixed the CI failure and #7580 covers the runtime crash, so what is left here is one narrow behaviour change that neither of those makes.Problem
From bitsandbytes 0.46 a wheel whose native library never loaded still imports and resolves every ctypes handle.
BNBNativeLibrary.__getattr__returns athrow_on_callclosure, and a dead library is replaced wholesale byErrorHandlerMockBNBNativeLibrary, which does the same for every name. So all five handleskernels/utils.pybinds at module scope resolve, nothing raises,device_type.py's guarded import sees a healthy wheel,ALLOW_BITSANDBYTESstays true,loader.pyforwards the defaultload_in_4bit=True, and the run dies inside a kernel:instead of degrading to 16bit up front, which is what the guard exists to do. The realistic host is a mismatched CUDA or ROCm wheel.
Change
Probe the handles the kernels actually bind, and clear
ALLOW_BITSANDBYTES/ALLOW_PREQUANTIZED_MODELSwhen they are not native. A real handle is a ctypes function pointer and carriesrestype; a deferred failure is a Python function and does not.unsloth/bnb_availability.pyis a leaf module - it imports nothing from unsloth, sodevice_type.pycan use it despite being imported very early - and takes the device type as an argument, because 4bit inference binds the gemv pair on xpu and the naive gemm pair everywhere else. Probing the wrong pair would write off a good wheel.Deliberately narrow
This decides the capability flags only, never whether the module is importable.
bnbstays bound andget_ptrkeeps pointing atbitsandbytes.functional.get_ptr, because these shapes import perfectly well and treating them as absent would disable a wheel whose Python side works. A CPU-only install is exactly that shape.It also touches neither
kernels/utils.pynor_gpu_init.py, so it does not overlap #7580 and the two can land in either order.Verification
CPU-only, matching the repo runners (
torch 2.10.0+cpu, bitsandbytes 0.50.0, no GPU) - the flags go false, the module stays usable:Real B200, nothing regressed:
Full CPU suite in that environment, this branch against
main, same harness:Identical failure count - those 24 are environment gaps present on both - and the branch passes the 8 new tests. So clearing the flag on a CPU-only host breaks nothing in the suite.
tests/python/test_bitsandbytes_kernel_readiness.pycovers the shapes: deferred-failure closure, real ctypes handle,lib is None(0.45.5), a lib missing one symbol, absent bitsandbytes, the device split, and that the probe's symbol list still matches the module-scope binds inkernels/utils.py. 19 passed together with the existing bitsandbytes tests.