Skip to content

Fix bitsandbytes zombie module breaking test collection on CPU runners - #7580

Merged
danielhanchen merged 3 commits into
mainfrom
fix/bitsandbytes-zombie-module-import
Jul 29, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fix/bitsandbytes-zombie-module-import

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Scope narrowed after #7582 landed on main.

#7582 added the tests/conftest.py pre-import, which stops the test harness creating a half-imported bitsandbytes. That half of this PR is now redundant and has been dropped; the branch takes main's version verbatim.

What remains is the runtime half, which main does not have. unsloth/kernels/utils.py:155 still reads get_ptr = bnb.functional.get_ptr, and that fails whenever an earlier import bitsandbytes died inside __init__ from any cause, not just the test spoof. The realistic user path is a broken or mismatched CUDA wheel: unsloth/device_type.py:127 imports bitsandbytes inside a bare except Exception: pass, so the failure is swallowed and the damage stays invisible until a later import trips over it.

CPython evicts only the parent package on that failure and keeps the submodules it already loaded, so a retry re-executes __init__ against a fresh module object whose from .x import y lines are all served from cache, and never rebinds functional as an attribute. Reproduced against torch 2.10.0+cpu and bitsandbytes 0.50.0:

first import raised: AttributeError
bitsandbytes in sys.modules: False
bitsandbytes.functional cached: True
plain attribute access works: False
import-as works: True

import bitsandbytes.functional as bnb_functional reads sys.modules directly and survives this; plain attribute access does not. A bare import bitsandbytes.functional does not work either, because _gcd_import short-circuits on the cache hit without setting the parent attribute.

Also included: the same rename at unsloth/_gpu_init.py:312 and :354, which read bnb.functional.lib... inside bare try/except blocks. With a half-imported bitsandbytes they fall through silently and emit a misleading UserWarning about CUDA not being linked properly, advising an ldconfig command that has nothing to do with the real cause. That warning was observed in the original reproduction.

A partially failed `import bitsandbytes` leaves the package half-imported:
CPython evicts only the parent from sys.modules and keeps every submodule it
had already loaded. The next import re-executes __init__ but every
`from .x import y` is served from cache, so the submodule attributes are never
rebound. The package imports "successfully" while `bnb.functional` is gone.

Bind the submodule via `import bitsandbytes.functional as bnb_functional`,
which reads sys.modules directly and survives that state, and import
bitsandbytes in tests/conftest.py on the real CPU path before
torch.cuda.is_available() is mocked, so the half-imported state is never
created in the first place.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner July 28, 2026 22:03
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 265650e822

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

Verified in CI, not just locally. The org queue is currently ~400 runs deep, so I replicated this branch onto a fork running the same consolidated-tests-ci.yml and all three Core matrix legs pass:

success  Core (HF=4.57.6 + TRL<1)
success  Core (HF=default + TRL=default)
success  Core (HF=latest + TRL=latest)
success  llama.cpp build + smoke

Those are the jobs that fail on main with AttributeError: module 'bitsandbytes' has no attribute 'functional' at unsloth/kernels/utils.py:155.

Local collection numbers on a matching environment (torch 2.10.0+cpu, bitsandbytes 0.50.0, transformers 5.4.0):

collected collection errors bitsandbytes AttributeError
before 4508 52 34
after 4870 20 0

The 20 remaining errors are pre-existing and unrelated (Hub network access, pin_memory on CPU, a sentencepiece/protobuf mismatch).

One unrelated latent bug this surfaces, worth a separate fix: four files under tests/saving/text_to_speech_models call require_python_package("soundfile"), which does a bare sys.exit(1) and crashes pytest with INTERNALERROR ... caught unexpected SystemExit (tests/utils/os_utils.py:120). It was unreachable while collection died earlier, so it may start showing up now.

…ie-module-import

# Conflicts:
#	tests/conftest.py
@danielhanchen

Copy link
Copy Markdown
Member Author

Independently reproduced and verified this on the CI environment shape (torch 2.10.0+cpu, bitsandbytes 0.50.0, no GPU).

To test the runtime half rather than the harness half, I deliberately recreated the zombie state by disabling the tests/conftest.py pre-import that #7582 added, so the first import bitsandbytes fails inside __init__ and leaves the parent evicted with its submodules cached. On main that is the state which kills import unsloth at kernels/utils.py:155. On this branch:

zombie present     : True      (parent module has no `functional`)
import unsloth     : OK
get_ptr is real    : True      (get_ptr is bitsandbytes.functional.get_ptr)
ctypes bind real   : True      (cdequantize_blockwise_fp32 is F.lib.cdequantize_blockwise_fp32)

So it does not merely survive the zombie module, it keeps every handle bound to the real objects. That is the property that matters: the alternative shapes of this fix trade the crash for bnb = None, which disables 4bit on a wheel that works.

The import x.y as z reasoning holds up: the import system consults sys.modules for the submodule and binds the local name from there, so it is unaffected by the parent's missing attribute, while bnb.functional is a plain attribute lookup on the re-executed parent and is not.

Two notes:

The rename at _gpu_init.py:312 and :354 is worth keeping for its own sake. With a half-imported bitsandbytes those reads fall through the bare except and emit the "CUDA is not linked properly / run ldconfig" warning, which is actively misleading - I hit exactly that warning while tracing the original failure and it cost time.

This is complementary to #7582 rather than overlapping: that one stops the harness manufacturing the zombie, this one makes the runtime immune to it whatever the cause. The realistic non-CI trigger is a mismatched CUDA/ROCm wheel, where device_type.py swallows the first failure in a bare except Exception.

@danielhanchen
danielhanchen merged commit 7b06809 into main Jul 29, 2026
52 checks passed
@danielhanchen
danielhanchen deleted the fix/bitsandbytes-zombie-module-import branch July 29, 2026 04:18
danielhanchen added a commit that referenced this pull request Jul 29, 2026
)

#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]>
vineethsaivs added a commit to vineethsaivs/unsloth that referenced this pull request Jul 30, 2026
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.
danielhanchen added a commit that referenced this pull request Aug 9, 2026
* Detect and report a mismatched xformers build at import

xformers wheels are compiled against one torch release and one CUDA major, but
nothing at install time enforces it: the wheels are abi3/none-tagged and
--no-deps skips Requires-Dist entirely, so a cu128 wheel drops cleanly next to a
cu130 runtime and only fails inside torch.ops.load_library, which xformers
catches and downgrades to a logger warning.

_utils.py made that worse in two ways: it silenced the xformers logger to ERROR
immediately before the import, and it reported the resulting failure only under
UNSLOTH_ENABLE_LOGGING. The net effect was a silent fall back to SDPA attention.
Its torch<->xformers version table also stopped at torch 2.4.

New unsloth/xformers_compat.py (stdlib only, imports neither torch nor xformers)
carries the version knowledge up to torch 2.10 / xformers 0.0.35 and reads the
installed wheel's own xformers/cpp_lib.json to learn what it was really built
against. The tables and the cpp_lib.json shape were read off the published
wheels, not inferred.

0.0.35 is the case worth calling out: it is the first release to declare a range
(torch>=2.10) while its _C is still a single build against 2.10.0, so pip will
pair it with torch 2.11+ and the extension will not load. No xformers release is
built for torch 2.11 or later, so xformers_for_torch returns None there rather
than recommending the install that produces the bug.

Because the check runs off the file before the import, the mismatch is known in
time to leave xformers' own diagnostic un-silenced in exactly the case where it
is the bug report, and to print a single actionable message naming the torch,
CUDA and Python the wheel was built for versus what is running. A Python version
difference alone is never reported as a break: _C loads through
torch.ops.load_library, not the CPython ABI.

XFORMERS_BUILD_METADATA and XFORMERS_BROKEN_REASON are exported so callers can
report what broke instead of guessing.

* Probe the xformers kernel on every CUDA capability, and keep the reason

_xformers_disabled_for_capability returned early below sm_120 with the comment
"Below sm_120 xformers always works; skip the probe". That holds only when the
wheel matches the runtime. A cu128-built xformers on a cu130 torch is dead on an
sm_90 Hopper exactly as it is on an sm_120, and the early return meant the one
piece of code that actually runs the kernel never looked. The gate also skipped
the probe whenever flash-attn was installed, so those machines could never report
a dead xformers at all.

Now the real op decides on every capability, including with flash-attn present.
The extra cost is one 1x8x1x64 forward on a CUDA context torch has already
initialised, since _XFORMERS_FP32_UNSUPPORTED just below forces the same lazy
init unconditionally.

The probe also caches why it failed in XFORMERS_PROBE_REASON, surfaced as
XFORMERS_DISABLED_REASON alongside XFORMERS_BROKEN_REASON from _utils, so a
caller can report what is wrong rather than only that xformers is off. It still
never raises: it runs at import, so a diagnostic must not be what breaks the
import.

The #4631 regressions are kept and extended: a working kernel is still kept on
sm_120, and now the probe-means-disable failure mode is pinned on every other
capability too.

* Report the accelerator stack in the Studio hardware detail

get_package_versions() covered unsloth, torch, transformers and torch's CUDA/HIP
version, and nothing else. An xformers built for a different torch reports its
version happily and has no memory-efficient attention, so the report a user sends
with a bug looked identical whether the acceleration stack worked or not. There
was no Python version either, which is half of what a mismatch report needs.

get_package_versions() now also carries python, xformers, flash_attn, torchao and
bitsandbytes as plain version strings. Still flat str-or-None, so every existing
consumer is untouched.

The part that costs a real import lives in the new get_accelerator_report(),
returned under /api/system/hardware?include_details=true only -- the default
response is polled for training-method selection and must stay cheap. Per package
it separates installed / imports / runs, and for xformers reads the wheel's own
cpp_lib.json to say what it was compiled against, which is the part that names
the fix. The cpp_lib.json read is a deliberate copy of the one in
unsloth.xformers_compat rather than a call to it: this module has to keep working
with no torch installed, and importing unsloth would execute unsloth/__init__.py.

Cached per process, deep-copied out, never raises, and skippable with
UNSLOTH_SKIP_ACCELERATOR_PROBE=1 for an install where importing a broken native
wheel is worse than not knowing.

Deliberately does not gate startup. NVIDIA asked to block release when optimized
kernels cannot load; blocking the app instead would turn a slower-but-working
install into a dead one. Detection and loud reporting, not refusal to run.

Ran it here and it immediately found a real one: torchao 0.18.0+cu130 against
torch 2.9.1+cu128 does not import.

* Surface dead optimized kernels in Settings

The About tab showed a version string per runtime and nothing else, which a
mismatched xformers reports exactly as happily as a working one, and no Python
version at all -- the other half of every "built for 3.10, running 3.13" report.

About gains a Python row and an Optimized kernels section listing xFormers,
FlashAttention, torchao and bitsandbytes, each as installed / not installed /
working / not loading rather than as a version. A broken one shows what its wheel
was built for, with the full reason behind the row's info hint.

The banner sits in the Settings dialog rather than on the About tab, above
whichever tab is showing: a kernel that is installed and cannot load produces no
symptom other than being slower, so a user has no reason to go looking in About.
It mounts inside DialogContent, which Radix only renders while the dialog is
open, so the detail fetch and the native imports behind it stay off app startup.

Status is never colour-only -- each state carries its own word -- so it survives
a greyscale screenshot in a bug report, which is where this will mostly be read.

Parsing moved to hooks/accelerator-report.ts so it is importable without react or
the auth chain, which is what makes it unit testable. A backend that predates the
field parses to null, not to an empty healthy report: "cannot tell" must not
render as "all fine".

Also drops the misleading half of the CLI fix hint. On a torch newer than any
xformers release there is no version to pin, and naming one would send the user
back into the same mismatch, so it now says so and points at a source build.

* Move the accelerator-report tests into the hardware test namespace

The suite is routinely run as `pytest studio/backend/tests -k "hardware or
system"`, and only 1 of the 15 matched under the old filename. It is the
hardware module's report, so name it that way.

* Never report a degraded stack on a host these kernels do not run on

bitsandbytes is a dependency on every platform but only loads on CUDA/XPU, so on
a Mac or a CPU-only host its import failure is the expected outcome, not a broken
acceleration stack. Probing there pinned a permanent false banner to those
installs, which is exactly the credibility problem that makes people stop reading
banners.

The probe now runs only when get_device() is CUDA or XPU, and "we did not look"
stays distinguishable from "you told us not to look": "not used on this device"
versus "not probed".

The probe tests pinned get_device to CUDA as well. Without that they passed on a
CPU-only runner by never probing at all -- green for the wrong reason.

* Keep the About Python row on a host with no GPU

It sat inside the Hardware section, which only renders when there is a GPU or an
accelerator runtime to show. On a CPU-only host that hid the one field a bug
report most needs.

* Probe the accelerator stack out of process, and stop guessing at the reason

Review of the first pass turned up four things that were worse than the problem
being reported, three of them measured on this host.

Importing the packages in the web-server process was wrong three ways. A package
whose __init__ raises leaves every submodule it already executed in sys.modules,
so the next import returns a half-built module -- this repo already documents
that hazard and ships purge_partial_import for it (#7580);
torchao left 40 stale submodules behind here. `import bitsandbytes` latches a
CUDA context, and the backend deliberately never had one: main.py pins
CUDA_DEVICE_ORDER before any torch import and the export planner budgets from
free VRAM read before a context exists, so a diagnostic was about to take several
hundred MB off every later VRAM reading for the rest of the session. And a badly
broken native wheel can abort the interpreter rather than raise, which in the
server means the app dies on exactly the installs this is meant to describe.

It now runs in one throwaway child with CUDA_VISIBLE_DEVICES emptied. Measured
after the change: no CUDA context, no leaked modules, 3.5s once per process.

_describe_xformers_break asserted a version mismatch whenever build metadata
merely existed, without ever comparing it to the runtime, and dropped the real
exception on the floor. [WinError 126] with a perfectly matching wheel -- a
missing VC++ runtime or CUDA DLL, the most common Windows xformers failure that
is NOT a mismatch -- was reported as "built for X but runs X". It now compares
first and hands back the real error otherwise.

The Mac/CPU gate let ROCm and Intel XPU through: ROCm hosts report
DeviceType.CUDA internally, and the stock bitsandbytes is CUDA-only on both. Same
permanent false banner, just moved to AMD and Intel users.

The report also moves off include_details onto its own include_accelerators flag.
The detail path is read by Export, Video and onboarding, none of which should pay
for this, so the frontend gets a separate hook used only by the Settings surfaces.

Also: read xformers' already-recorded _cpp_library_load_exception instead of
re-calling the private _register_extensions (whose absence was being reported as
"broken"), cap reason strings that land in an aria-label, name the subprocess
encoding so Windows paths survive, and carry hip through to the UI so a ROCm
wheel shows a build at all.

Tests: the probe seam is faked everywhere, so none of them import the host's
native wheels; added the matching-build, python-only, cuda-minor, ROCm, XPU and
could-not-be-checked cases that let those defects through.

* Do not let the probe silently disable xformers, or mislabel what it caught

Review of the first pass found the new probe reintroducing the failure mode it
was written to remove, plus two ways of stating the wrong cause.

The gate turned any probe exception into HAS_XFORMERS = False for the whole
process, and printed nothing. Before, capability[0] < 12 returned early, so
sm_70-sm_100 could not lose xformers this way at all. A full device 0, a device
claimed by another rank under EXCLUSIVE_PROCESS, a MIG slice: each of those now
cost memory-efficient attention for the session, silently, because of the
diagnostic. Those failures are now inconclusive -- xformers stays on and the real
forward decides -- and a conclusive one is announced through the same path as an
ABI mismatch, so XFORMERS_DISABLED_REASON is no longer written and never read.

The probe also targeted device 0 for everybody. Under torchrun each rank owns a
different GPU, and on a mixed box device 0 is often the small display card, so a
wheel with no kernel for the weakest GPU disabled xformers on the good ones. It
now probes LOCAL_RANK's device.

The loud warning was reflowing every exception into "its optimized kernels cannot
load ... install the matching build". That arm also catches the sm_100/110/120
FA3 guard and the three old-torch guards, whose messages are multi-line, fenced
and already actionable; the template stated the wrong cause and mangled the text.
Only a real build mismatch gets the version-pin treatment now.

xformers_compat: a .dev/rc build no longer folds onto its release. The fourteen
0.0.35.devNNNN wheels on PyPI are built against torch nightlies, so answering
"0.0.35, therefore torch 2.10.0" for one was confidently wrong; unknown is the
honest answer. And declared_torch_pin's docstring claimed it returns None for a
range pin when it falls back to the build table -- the code is right, the
docstring was not.

Tests: test_warning_is_printed_once was vacuous (a fresh subprocess reaches the
announcement once whether or not the guard exists), so it now counts in-process;
_mismatched_build synthesizes a CUDA-major difference and is skipped where there
is no running CUDA major; the probe tests patch the globals they write through
instead of leaking them into the session; and there is now a test that a healthy
install prints nothing at all, which is the half of "never cry wolf" nothing
covered.

* Let the P0 xformers tests run on a host with no GPU

Both subprocess tests in tests/utils/test_xformers_broken_warning.py failed on
the cross-platform runners for two independent reasons, neither of them the
warning they are meant to prove.

First, the child ran a bare `python -c`. Everything else under tests/ gets
tests/conftest.py, the GPU-free harness that forces DEVICE_TYPE to "cuda" and
stubs the torch.cuda probes unsloth fires at import time; the child got none of
it, so unsloth/_gpu_init.py's module-scope torch.cuda.get_device_capability()
raised "Found no NVIDIA driver" and the import exited 1. That is also why the
in-process `import unsloth` in test_xformers_capability_gate.py was green on the
same runner. The child now loads that same harness by path before importing
unsloth, so the subprocess and the parent agree about the host. On a real
accelerator the harness is a no-op.

Second, the stub xformers was an importable module with no .dist-info, and
`import unsloth` asks importlib.metadata for the xformers version twice. With no
xformers on the host that raised PackageNotFoundError straight out of
fix_xformers_performance_issue(); with one, it silently answered from the HOST's
xformers, which is exactly what this file's docstring promises not to depend on.
The stub now ships its own metadata and the child asserts the version it reads
back is the stub's.

test_a_healthy_install_says_nothing additionally needs a healthy install to
exist, so it now skips when importlib.util.find_spec("xformers") is None instead
of reaching its "this host's xformers is genuinely broken" skip, which would
have been the wrong reason for a host that simply has no xformers.

Tests only - no change to the detection in unsloth/models/_utils.py,
unsloth/xformers_compat.py or unsloth/utils/attention_dispatch.py.

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

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

* Keep the probe on this rank's device, and stop it crashing the import

Widening the probe from sm_120-only to every capability put it on the standard
multi-GPU path for the first time, and it does not survive there. Both of
these reproduce on a real two-GPU torchrun; neither happens on main.

The probe placed q on cuda:{LOCAL_RANK} but built the attn_bias with
BlockDiagonalCausalMask.from_seqlens, which allocates on the CURRENT device --
still cuda:0 on every rank at import time, because launchers set LOCAL_RANK in
the environment while torch.cuda.set_device happens later inside the trainer.
So the two tensors disagreed, xformers rejected the pair with "Attention bias
and Query/Key/Value should be on the same device", and since that text is not
an inconclusive marker the gate hard-disabled xformers. Measured on two
healthy identical B200s: rank 0 kept xformers, rank 1 lost it. On an 8-GPU
node that is 7 ranks silently dropping to SDPA at double the attention memory
-- the exact regression the inconclusive guard was written to prevent, caused
by the diagnostic itself, and reported to the user as a broken install. It
also allocated on cuda:0 from every rank, pinning a second context per rank,
about 700 MB each. Running the whole probe under torch.cuda.device fixes both.

Separately, LOCAL_RANK is a rank and not an index into the devices a process
can see. Slurm with --gpus-per-task=1, and anything that narrows
CUDA_VISIBLE_DEVICES per rank, gives a rank one visible device while still
exporting its global rank; accelerate and transformers both use -1 to mean
"not distributed". torch.cuda.get_device_capability raises on an invalid
ordinal and that call is at module scope, so `import unsloth` died outright
with AssertionError: Invalid device id. Verified for LOCAL_RANK of 3, 1, 07
and -1 against one visible device; all four now import and fall back to
device 0, which is the only device such a rank has.

Clamping is the fix rather than a try/except around the capability read: with
an out-of-range index the probe fails with "invalid device ordinal", which is
not an inconclusive marker either, so catching the crash alone would have
converted it into the silent disable above. Those two strings are added to the
inconclusive list regardless, so that path can never again be read as evidence
about the build.

Two more things this turned up. The probe's reason is a captured exception,
and xformers answers a capability rejection with a dozen lines listing every
operator it considered -- announced verbatim, that is what every RTX 50-series
user would see on every import. Print the first line and put the rest behind
UNSLOTH_ENABLE_LOGGING, truncating at the call site because the announcer's
other callers pass deliberately fenced, copy-pasteable text that has to arrive
intact. And re-silence the xformers logger once the extensions turn out to
have loaded: skipping the silencing on a PREDICTED break is right, but the
prediction is read off cpp_lib.json and is wrong in the healthy direction
whenever a wheel records a torch patch it still loads against, and leaving the
logger open is permanent and process-wide.

_XFORMERS_FP32_UNSUPPORTED now reads the same device the probe used, which is
what its comment already claimed.

Tests: the rank-targeting test stubs torch.cuda.device so it runs on a host
with any GPU count and asserts the context index, not just the tensor's; new
tests cover the clamp invariant and a real subprocess import under five
hostile LOCAL_RANK values, which is the regression the mocked test could not
catch.

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

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

* Tell the accelerator probe child to emit UTF-8

The probe decodes its child as UTF-8, but the child's own stdout defaults to
locale.getpreferredencoding(), which on Windows is the ANSI code page. That is exactly
where this probe's value is: native import errors quote DLL and file paths, and a
non-ASCII path would come back mangled. Route the env through utf8_child_env, as the
repo's own contract test requires.

* Report what the accelerator stack can actually do, not what imported

- the xFormers probe picked bf16 from device 0 while probing this rank's GPU,
  so a mixed box with a Turing card wrote off a healthy install.
- the fix hint pinned a version but no index; all three CUDA families publish
  the same version string and PyPI carries only cu128, so on the reported case
  it reinstalled the identical broken wheel.
- both mismatch diagnoses (unsloth and Studio) called a stable-ABI wheel on a
  later torch a mismatch, and the Studio one compared full version strings, so
  2.10.0+cu126 vs 2.10.0+cu128 hid the real error before the CUDA-major check
  could give the accurate one.
- the probe reported bitsandbytes and torchao as working on an import alone,
  which is exactly the state where 4-bit dies mid-run and torchao has no
  kernels; both now check their native side, bitsandbytes through the same
  leaf module the loader gates on.
- xFormers loading its library is not the same as having a kernel for this
  GPU; a capability rejection now reads as degraded instead of Working.
- ROCm hosts probed nothing at all, though Unsloth enables flash-attn there.
- and a child that dies without answering no longer erases the whole report:
  the survivors keep their answers and the package that killed it is named.

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

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

* Ask the GPU the app can actually use, and let each row say if it was checked

Five things the probe got wrong once it started answering "does this run".

nvidia-smi lists physical devices and ignores CUDA_VISIBLE_DEVICES, so on a mixed
host masked to the sm_120 card the verdict was computed against row 0's sm_90 op
table, and xFormers read as working on a GPU that has no kernel for it. The mask is
resolved in the parent now, by index or by (abbreviated) UUID, and handed to the
child as UNSLOTH_PROBE_DEVICE_CC, because the child is started with the mask cleared
and cannot recover it.

bitsandbytes picks its native library from torch.cuda.is_available(), so hiding the
GPUs from the child made a healthy CUDA install report dead handles and light the
banner. It gets its own child now, with the mask the app itself runs under. The
server still never holds a context: that child exits immediately.

On Intel XPU the applicable set was empty, so a broken XPU bitsandbytes wheel was
"not used on this device" and never reached degraded, while the loader gates 4-bit
on native_kernels_ready(_bnb_probe, DEVICE_TYPE) with XPU symbols. It is probed.

torch.ops.<ns> materialises an empty _OpNamespace on attribute access, and its dir()
already lists __name__ and friends, so dir(torch.ops.torchao) was non-empty for the
no-extension case the check exists to catch. Counted off the dispatcher instead.

And the About table read one report-wide "probed" flag onto every row, so a package
the backend deliberately skipped rendered "Not loading" as soon as any other package
was probed -- red for something that is fine, and absent from the banner. Each entry
carries its own probed flag; the report-wide one is the fallback for an older backend.

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

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

* Keep the capability read out of module scope, and let the model code see the verdict

Two ways the probe could hurt the thing it was added to protect.

The gate read torch.cuda.get_device_capability() at the call site, at module scope, and
CUDA refuses that query when the device is busy, in exclusive-compute mode or otherwise
unavailable. There it raised before the probe could classify the failure as
inconclusive, so a diagnostic whose worst answer is "keep xformers on and let the
forward decide" turned `import unsloth` into a crash. The argument is gone (the gate
asks the kernel, not the number), and the fp32 read below it now degrades to unknown
through a guarded helper. A test walks the module's top-level statements and fails on
any capability query that runs at import.

And llama.py recomputed HAS_XFORMERS as `xformers is not None`, so turning the
dispatcher's flag off never reached the model code. Mistral answers "xFormers is on" by
skipping the 4D sliding-window mask and letting the xFormers bias carry the window; with
the dispatcher already on SDPA, that mask is the only thing making the window local, so
a sequence longer than config.sliding_window attended to the whole causal history. It
takes the probed flag from the dispatcher now.

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

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

* Answer for every visible GPU, and say unknown where the probe cannot tell

Five follow-ups, all the same shape: a diagnostic that overstates what it knows.

Mistral's training branch takes `elif self.training: pass`, so no 4D mask is synthesized,
and its AttentionContext never carried sliding_window at all. With xFormers off and
flash-attn absent, nothing was left holding the window and every sequence past
config.sliding_window attended its whole causal history. The context carries the window
now, and the SDPA path builds a windowed keep mask even with no padding mask to hang it
off, since is_causal is full causal and has no window of its own.

The capability resolver truncated the mask to its first entry, so with
CUDA_VISIBLE_DEVICES=0,1 across a mixed pair a rank on the second card fell back to SDPA
while the verdict from the first said Working. Every visible device is resolved and
handed to the child now, and one uncovered card makes the whole install degraded.

flash-attn recorded runs=true on the strength of importing its interface. Our own
installer refuses prebuilt wheels on sm_100+ because none covers those cards, so a wheel
that got there another way could load and still fail on its first launch. That is
unknown, with the reason, rather than a verdict this child would have to launch a kernel
to earn.

The About table read runs=null as Working. A probe that ran and could not decide -- an
unrecognised xformers layout, a missing bitsandbytes checker, a torch with no dispatcher
table, the flash-attn case above -- is unknown, and nothing else would have corrected it
since those packages are not in degraded either.

And xformers_for_torch returned None above 2.10, which contradicted this module's own
describe_xformers_mismatch: it accepts a 2.10-built wheel on 2.11 under the stable ABI,
then the fix hint told the user no release exists and to downgrade torch or build from
source. Above the floor the answer is 0.0.35, and the hint already names the CUDA index
that repairs the family.

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

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

* Stop the probe calling a supported fallback broken, and normalise a zero window

Five more, all cases where the report claimed more than it knew, plus one bug of mine.

torchao with no registered operators is the MANAGED stack: install_python_stack pins
0.17 on torch 2.10+cu130 knowing its extension is cleanly skipped, and torchao keeps
running through its Python fallbacks with only the optimized kernels gone. Calling that
degraded put a destructive banner on the standard configuration. Unknown, with the
reason, so the row says it without the banner.

flash-attn is unknown on every card now, not just above sm_100. A build with no cubin or
PTX image for this architecture imports fine and fails its first launch, which is as true
of a source build or an older wheel as of a Blackwell card; flash-attn exposes no list of
the architectures it was compiled for, and this child never launches a kernel. A failed
import is still broken.

"device is currently in use by another process" is the driver saying the GPU is someone
else's right now. It matched none of the inconclusive markers, so a transient turned into
a process-wide fallback to SDPA on a wheel that was never tested.

The probe device honoured LOCAL_RANK and otherwise took device 0, ignoring a caller that
had already run torch.cuda.set_device(1). That can disable xformers over a card nothing
will touch, and creates a context on it to do so. LOCAL_RANK still wins when usable.

And sliding_window = 0 means "no local attention", the same as absent. Passing it through
made window_size (0, 0) for flash and, now that the dispatcher honours the window, an
all-false SDPA mask: the lower bound q_pos - (0 - 1) sits above the causal upper bound, so
the layer returned nothing at all. Normalised in Mistral and again in the dispatcher.

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

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

* Keep the xFormers kernel verdict unknown until a launch proves it

The op table admitting this GPU is not evidence the build ships a kernel image
for it: CUDA_MINIMUM/MAXIMUM_COMPUTE_CAPABILITY are class constants, and a source
build compiled for other architectures registers the same op and fails its first
launch with 'no kernel image is available'. The probe holds no CUDA context by
design, so it cannot establish coverage. The negative verdict is sound and stays;
every other exit is now unknown, matching probe_flash_attn.

The About row renders the reason on an unknown result too. Most unknowns are
deliberate and come with an explanation, and the row was showing 'Not checked'
and discarding it, so a skipped native extension looked like a probe that never
ran.

Also imports UNSLOTH_ENABLE_LOGGING explicitly in attention_dispatch: it is not
in _utils.__all__, so the newly reachable inconclusive-probe branch raised
NameError during import unsloth instead of keeping xformers on.

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

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

* Stop three xFormers diagnoses from stating more than they know

The no-metadata path (a source or editable 0.0.34+ build) fell back to the
recorded torch pin and called every later release a mismatch, contradicting the
stable-ABI rule the build-metadata branch two blocks up already applies. An
unrelated extension failure was therefore diagnosed as a torch-version problem
with reinstall instructions that fix nothing.

The breakage announcement claimed a fallback to SDPA and more memory even when
FlashAttention is installed, which select_attention_backend prefers over
xformers anyway. The consequence sentence now follows what actually picks up the
work; the breakage is still reported either way.

A numeric CUDA_VISIBLE_DEVICES entry is a CUDA ordinal in the current
CUDA_DEVICE_ORDER, and nvidia-smi's index is the PCI_BUS_ID ordering. The pin is
a setdefault, so a user who exported FASTEST_FIRST keeps it and the ordinal
cannot be inverted without initialising CUDA. That case now answers unknown
instead of probing the wrong card; UUID masks are unaffected.

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

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

* Four more honest answers from the accelerator report

An unresolvable device mask reached the probe child as an empty
UNSLOTH_PROBE_DEVICE_CC, which the child reads as no override at all and answers
from nvidia-smi over every physical GPU: the whole-box verdict the resolver
returned None to avoid. It now travels as an explicit unknown sentinel, and the
child refuses to fall back on it.

An xformers whose _cpp_lib raises a native load error left runs at None, so the
package stayed out of degraded and the About row read 'Not checked' with no
banner, on exactly the corrupt install this report is for. That is now broken; a
layout with no _cpp_lib at all stays unknown.

bitsandbytes is probed on ROCm. device_type.py imports it on every backend and
gates 4-bit and prequantized loading on native_kernels_ready, so a dead ROCm
wheel silently costs quantized loading while the report called the package 'not
used on this device'.

And the fix hint redacts the mirror URL. UNSLOTH_PYTORCH_MIRROR can carry
credentials or a signed-URL query, and that hint prints to stdout on the default
import path, into logs and shared notebooks.

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

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

* Find the bitsandbytes checker from the checkout too

find_spec is the right answer for an installed unsloth, but CI installs a
published wheel that predates bnb_availability.py, so the lookup landed on a
site-packages copy without the file and every bitsandbytes verdict came back
unknown. This file's own location settles it: studio/backend/utils/hardware to
the repo root.

* Stop three accelerator messages from overstating what is known

A transient probe failure is not a broken wheel. bitsandbytes keeps CUDA visible
on purpose, so opening Settings while a trainer has filled the GPU, or holds it
in EXCLUSIVE_PROCESS, fails at context creation on a healthy install -- and that
answer is cached for the life of the backend, so the banner sat there until
restart. Busy, out-of-memory and unavailable now read as not probed, with the
reason shown, using the same classification the in-process xformers probe makes.

The mirror redactor no longer returns its input when it cannot parse it. A
malformed authority is exactly the URL whose credentials or signed query this
was added to keep out of stdout, so it drops the index instead and the hint
omits --index-url.

And the Settings banner no longer promises a slower fallback. When xFormers is
the dead package and FlashAttention loaded, the dispatcher prefers FlashAttention
and there is no slower path; the banner now names what cannot load and points at
the list, in every locale.

* Pin two accelerator-report tests to a CUDA host

Both assert on the probe's classification, and on a CPU-only runner the
report never probes at all: every row comes back "not used on this device"
and degraded is empty, so the two assertions failed on CI while passing on
any machine with a GPU. The on_accelerator fixture the rest of the file
already uses is what makes the probe applicable.

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
…ubs first

Two holes in the prewarm, both found by review.

MiniMax H3 as a GGUF is the one video combination that never imports diffusers: VideoBackend
returns through _run_load_h3_native before its own `import diffusers`. The gate could not see
that, because the video backend has its own family type and detected_image_family has no answer
for a VideoFamily, so an H3-only install fell into the "unknown family" branch and paid 316 MB it
would never use. Ask the video backend's own detect_video_family and is_h3_native for video
picks. Everything else video still prewarms, including a repo id the detector cannot place.

core/inference/diffusion.py installs install_xformers_windows_rocm_stub,
install_torchao_windows_rocm_stub and install_torchao_int_mm_patch at module scope, above its own
lazy `import diffusers`, because on Windows ROCm diffusers imports xformers on sight and its
quantizers torchao, and both reach an absent distributed backend. This prewarm can be the first
importer in the process and was not paying that toll. Install the same three, in the same order,
in front of the import, and skip the prewarm entirely if they are unavailable, since importing
unprotected is the hazard.

Also purge on failure. A failed package import leaves its executed submodules in sys.modules and
the prewarm swallows the failure, so the retry is a user's image load, which would re-run
__init__ against that cache and come back missing attributes (unslothai#7580). purge_partial_import is
already in this module and already declines when a loaded C extension is involved.

Three tests added, each confirmed to fail with its fix reverted.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
`import diffusers` and `import diffusers.hooks` are two imports and either can be the one that
fails. When the parent succeeded and the subpackage did not, purging "diffusers" is a no-op by
design, since it is in sys.modules and belongs to nobody, so the hook submodules that already
executed stayed cached and the load path's own `from diffusers.hooks import ...` would rebuild an
incomplete package from them. That is the unslothai#7580 shape, one level down.

Purge the subpackage first, then the parent. purge_partial_import takes the subpackage's own
module lock and is a no-op when there is nothing of that shape to collect, so the healthy-parent
case is unaffected.

The lock test now asserts every purge call happened under the lock rather than expecting exactly
one. New test confirmed failing with the subtree purge removed.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…does not (#10989)

* Pre-import diffusers in the post-warm worker so the first image load does not

The first diffusion load in a fresh process pays about 5.3s of pure import before it touches
a weight: diffusers 1.6s, diffusers.hooks 2.4s and the pipeline classes 1.3s, for about
316 MB. None of it depends on which model was picked, so it is the same cost on every first
load and all of it can be paid earlier by a thread nobody is waiting on.

Measured end to end, the import work the load path does drops from 4.47s to 0.60s, at the
same peak RSS (818 MB vs 817 MB): the memory is paid either way, just earlier.

Gated on the install actually having a local image or video model, which is the point: a
chat-only or training-only user never pays the 316 MB for a page they do not open. The gate
is stdlib only, does not import torch or diffusers, and its index is cached and needed by the
Images page anyway, so building it here is work moved earlier rather than work added.

Runs from the POST-warm worker, after join_background_warm(), so it cannot delay a
coordinated warm stage or the socket bind, and last within that worker, because it is the
only item there that is latency work rather than correctness.

Concurrency was measured rather than assumed: 4 to 8 threads importing diffusers submodules
together failed 0 of 16 trials, with and without dynamo already imported. These are ordinary
package imports that CPython's per-module lock serialises, unlike the dynamo/inductor cycle
in #10350.

Also applies quiet_third_party_progress_bars() after the import, the same call the load path
makes: diffusers hard-codes _tqdm_active = True at import and honours no env var, so a
prewarm without it would draw progress bars onto the structlog stream.

Never fatal. Opt out with UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1.

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

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

* Ask the media index for the task identifiers it actually matches on

The gate passed "image" and "video". _build_index compares _local_model_task(info) == task
exactly, and the catalog's identifiers are "text-to-image" and "text-to-video", so both
indexes were permanently empty: available_media_model_ids returned nothing on every install
and the prewarm never ran. The change was a no-op.

The tests did not catch it because their stub was keyed on the same wrong strings the gate
passed, so the stub agreed with the bug.

Take the pair from the catalog's own _LOADABLE_MEDIA_GGUF_TASKS instead of spelling them
again, and add the two tests a stub cannot fake:

- one pinning our tuple against the catalog set, so a rename there fails here rather than
  silently disabling the prewarm;
- one driving the REAL index with a text-to-image model, asserting it is found under the
  identifier the gate passes and not found under "image".

Reintroducing the old strings fails 6 of the 12 tests, including both new ones.

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

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

* Prewarm only when a local model would actually load through diffusers

Presence was the wrong question. A CPU or MPS host with a runnable native binary, and any host
with UNSLOTH_DIFFUSION_ENGINE=sd_cpp, routes a supported GGUF to sd.cpp, which imports no
diffusers at all. Gating on "a media model exists" therefore added the measured 316 MB to
exactly the low-memory installs that can least afford it, and no later load ever reclaimed it.
That also falsified the claim in the description that the memory is paid either way: on those
hosts it is paid once and never used.

Ask predict_engine instead, which is the same predicate selection and the download planner
already use and is documented to activate nothing and install nothing, so asking at boot cannot
perturb a resident model. A non-GGUF pick short-circuits it, since only a GGUF can go native,
and an unrecognised family counts as diffusers because that is where such a load lands.

Keeps the speedup where it is real: a CUDA host, and a dense checkpoint even on a host that
prefers the native engine.

Three tests: an sd.cpp-routed host imports nothing, a non-GGUF model on that same host still
prewarms, and the gate asks the router rather than copying its policy.

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

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

* Resolve a pick's family the way the loader does, not from its id alone

detect_family(pick.model_id) cannot see a family that lives only in the .gguf filename, which
is a supported local layout: /models/custom/model.gguf holding z-image has an opaque directory
and an opaque id. The gate read that as an unknown family and prewarmed, so the sd.cpp memory
regression this gate exists to prevent survived for exactly that layout.

Use detected_image_family, the pick-aware resolver the listing and locality routes already
share. It tries the path before the id, which matters for the same reason it does there: the
path is the only needle the load route is handed and the only one that can carry a local
model_index.json, and asking the id first answers FLUX for a HiDream pipeline sitting in a
directory called flux.1.

Two tests: the filename-only pick resolves through the REAL resolver rather than a stub of it,
and the gate does not fall back to the id-only call.

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

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

* Do not prewarm for a native H3 video install, and install the ROCm stubs first

Two holes in the prewarm, both found by review.

MiniMax H3 as a GGUF is the one video combination that never imports diffusers: VideoBackend
returns through _run_load_h3_native before its own `import diffusers`. The gate could not see
that, because the video backend has its own family type and detected_image_family has no answer
for a VideoFamily, so an H3-only install fell into the "unknown family" branch and paid 316 MB it
would never use. Ask the video backend's own detect_video_family and is_h3_native for video
picks. Everything else video still prewarms, including a repo id the detector cannot place.

core/inference/diffusion.py installs install_xformers_windows_rocm_stub,
install_torchao_windows_rocm_stub and install_torchao_int_mm_patch at module scope, above its own
lazy `import diffusers`, because on Windows ROCm diffusers imports xformers on sight and its
quantizers torchao, and both reach an absent distributed backend. This prewarm can be the first
importer in the process and was not paying that toll. Install the same three, in the same order,
in front of the import, and skip the prewarm entirely if they are unavailable, since importing
unprotected is the hazard.

Also purge on failure. A failed package import leaves its executed submodules in sys.modules and
the prewarm swallows the failure, so the retry is a user's image load, which would re-run
__init__ against that cache and come back missing attributes (#7580). purge_partial_import is
already in this module and already declines when a loaded C extension is involved.

Three tests added, each confirmed to fail with its fix reverted.

* Match video.py's family detection: try the repo id, then the picked GGUF filename

The H3 skip only looked at the model path and the model id, so an H3 GGUF under an opaque
directory (`/models/custom/minimax_h3_fl2va-Q4.gguf`) was not recognised and still paid the
316 MB. video.py's own _detect_load_family tries `repo_id` first and then
`f"{repo_id}/{gguf_filename}"`, exactly because a local directory or a generically named repo
often carries the family token only in the checkpoint filename. Do the same, in the same order.

Not copied on purpose: _detect_load_family also reads general.architecture out of a renamed
GGUF's header. That is file IO on a boot thread to save memory, and guessing wrong in this
direction only costs the prewarm, so an unidentifiable GGUF falls through to the safe default and
prewarms.

Test uses Codex's own path. Confirmed failing with the filename needle removed.

* Hold the diffusers import lock across the failed import and its purge

Releasing between the two was the bug. CPython drops the `diffusers` module lock the moment
__init__ raises, so a request already blocked on that lock wakes up in the gap, re-imports
against the submodules the failed import left behind, and republishes the malformed parent. At
that point purge_partial_import deliberately declines, because the leftovers now belong to a live
importer, and the load path is left with the missing-attribute diffusers this PR was supposed to
prevent.

_held_import_lock already does exactly this for the bare warm stages; the prewarm now does the
same. _ModuleLockManager is reentrant per thread (verified), so the nested acquire inside
purge_partial_import is free.

Test asserts the lock is owned by this thread at the moment the purge runs, and fails with the
lock removed.

* Honour UNSLOTH_STUDIO_DISABLE_TORCH_WARM in the prewarm

start_background_warm() declines under that variable, but join_background_warm() reports True
when no worker ever ran, so the post-warm thread reached the prewarm regardless and imported
diffusers, which imports torch. That is exactly what the opt-out exists to prevent, and the
warm-window tests that assert no unsolicited torch import would have been defeated by this PR.
Checked inside the function so every caller gets it.

Also documents a scope limit rather than papering over it: the media index is keyed on
current_account_id() and this runs on a boot thread with no bound account, so on a multi-user
install where only a non-owner has an image model the gate says no and that user's first load
still pays the import. Building an index per configured account means a filesystem scan per
account on the boot thread, which is the cost this gate exists to avoid, and the failure mode is
only the absence of a speedup, exactly as today. Left as is, deliberately, and written down.

Test confirmed failing with the opt-out check removed.

* Purge the hooks subtree too when that is the import that failed

`import diffusers` and `import diffusers.hooks` are two imports and either can be the one that
fails. When the parent succeeded and the subpackage did not, purging "diffusers" is a no-op by
design, since it is in sys.modules and belongs to nobody, so the hook submodules that already
executed stayed cached and the load path's own `from diffusers.hooks import ...` would rebuild an
incomplete package from them. That is the #7580 shape, one level down.

Purge the subpackage first, then the parent. purge_partial_import takes the subpackage's own
module lock and is a no-op when there is nothing of that shape to collect, so the healthy-parent
case is unaffected.

The lock test now asserts every purge call happened under the lock rather than expecting exactly
one. New test confirmed failing with the subtree purge removed.

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

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

* Stop the purge tests leaking an evicted diffusers into the rest of the suite

Running the wider suite turned up test_diffusion_gguf_compile failing, and it was my own tests
that broke it, not the product code: the purge tests call the real purge_partial_import, which
evicts whatever diffusers submodules the session had already imported. monkeypatch cannot undo
that, since it restores only the keys it set itself, so the eviction leaked forward and a later
test rebuilt a partial diffusers and failed for reasons of its own that had nothing to do with it.

Snapshot and restore the whole diffusers subtree around the three tests that purge. Confirmed by
the minimal pair (prewarm tests then the compile test) and by the full selection: 8728 passed,
0 failures.

* Hold the hooks lock too, not just the parent's

Last round's lock only covered the parent, and the subpackage has the identical gap: these are
two imports with two locks, so `import diffusers.hooks` drops the hooks lock the moment it
raises, and with the healthy parent already published a waiting request can rebuild
diffusers.hooks from its stale submodules before purge_partial_import("diffusers.hooks")
reacquires it.

Hold both, parent then child, which is the order CPython's own import takes, so a concurrent
importer cannot invert it.

The lock assertion was also weaker than it read: it checked the parent's lock for every purge
call, including the one purging the hooks subtree, so it would have passed with the hooks lock
missing. It now reads the lock of the package actually being purged, and the hooks test carries
the same check. Both confirmed failing with the second lock removed.

* Take the two import locks sequentially, never nested

My last commit claimed parent-then-child was "the order CPython's own import takes". That is
backwards, and I checked the source this time instead of asserting it: _find_and_load takes
_ModuleLockManager(name) for the CHILD first, then _find_and_load_unlocked imports the parent
from inside that scope. So `import diffusers.hooks` goes child -> parent, and holding
parent-then-child here inverted it against any concurrent `from diffusers.hooks import ...`.

The resulting cycle surfaces as the _DeadlockError that _lock_unlock_module swallows, which
hands back a partially initialised module: precisely the failure #10350 and #10963 are about. So
the nesting risked causing the bug the prewarm is meant to help avoid.

Each package now gets its own scope, holding only its own lock across its own import and its own
cleanup. There is no cycle left: by the time the hooks scope runs the parent is published, so
importing the child acquires nothing else.

Two tests. One asserts the two locks are never owned simultaneously. The other runs a real
concurrent thread in CPython's order (hooks lock, then the parent) and requires both it and the
prewarm to finish. Both confirmed failing with the nested version restored, the second by
actually hanging until its timeout.

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

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

* Put the try inside each lock scope, not around it

A regression I introduced with the un-nesting fix one commit ago. Writing `try: with LM(...):`
releases the lock when the scope exits on the exception and reacquires it in the handler, which
reopens the exact release-before-cleanup gap closed two commits earlier: a request already
waiting takes the lock in that gap, re-imports against the submodules the failed import left
behind, and republishes the malformed package, after which purge_partial_import declines because
the leftovers now belong to a live importer.

Both scopes now hold their lock across their own import and their own cleanup, and the two scopes
stay sequential so CPython's child-then-parent order is not inverted.

The existing lock assertions did not catch this, because they check the lock is held at the
moment the purge runs and the handler had reacquired by then. The new test records the
enter/exit/purge timeline and fails on a release between the failed import and its purge, while
still tolerating the reentrant acquire purge_partial_import takes through its own decorator.
Confirmed failing against the previous arrangement.

Quieting the tqdm bars moves out of the locked scopes: it imports nothing under diffusers, and a
failure there no longer discards a prewarm whose imports already succeeded.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…does not (unslothai#10989)

* Pre-import diffusers in the post-warm worker so the first image load does not

The first diffusion load in a fresh process pays about 5.3s of pure import before it touches
a weight: diffusers 1.6s, diffusers.hooks 2.4s and the pipeline classes 1.3s, for about
316 MB. None of it depends on which model was picked, so it is the same cost on every first
load and all of it can be paid earlier by a thread nobody is waiting on.

Measured end to end, the import work the load path does drops from 4.47s to 0.60s, at the
same peak RSS (818 MB vs 817 MB): the memory is paid either way, just earlier.

Gated on the install actually having a local image or video model, which is the point: a
chat-only or training-only user never pays the 316 MB for a page they do not open. The gate
is stdlib only, does not import torch or diffusers, and its index is cached and needed by the
Images page anyway, so building it here is work moved earlier rather than work added.

Runs from the POST-warm worker, after join_background_warm(), so it cannot delay a
coordinated warm stage or the socket bind, and last within that worker, because it is the
only item there that is latency work rather than correctness.

Concurrency was measured rather than assumed: 4 to 8 threads importing diffusers submodules
together failed 0 of 16 trials, with and without dynamo already imported. These are ordinary
package imports that CPython's per-module lock serialises, unlike the dynamo/inductor cycle
in unslothai#10350.

Also applies quiet_third_party_progress_bars() after the import, the same call the load path
makes: diffusers hard-codes _tqdm_active = True at import and honours no env var, so a
prewarm without it would draw progress bars onto the structlog stream.

Never fatal. Opt out with UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1.

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

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

* Ask the media index for the task identifiers it actually matches on

The gate passed "image" and "video". _build_index compares _local_model_task(info) == task
exactly, and the catalog's identifiers are "text-to-image" and "text-to-video", so both
indexes were permanently empty: available_media_model_ids returned nothing on every install
and the prewarm never ran. The change was a no-op.

The tests did not catch it because their stub was keyed on the same wrong strings the gate
passed, so the stub agreed with the bug.

Take the pair from the catalog's own _LOADABLE_MEDIA_GGUF_TASKS instead of spelling them
again, and add the two tests a stub cannot fake:

- one pinning our tuple against the catalog set, so a rename there fails here rather than
  silently disabling the prewarm;
- one driving the REAL index with a text-to-image model, asserting it is found under the
  identifier the gate passes and not found under "image".

Reintroducing the old strings fails 6 of the 12 tests, including both new ones.

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

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

* Prewarm only when a local model would actually load through diffusers

Presence was the wrong question. A CPU or MPS host with a runnable native binary, and any host
with UNSLOTH_DIFFUSION_ENGINE=sd_cpp, routes a supported GGUF to sd.cpp, which imports no
diffusers at all. Gating on "a media model exists" therefore added the measured 316 MB to
exactly the low-memory installs that can least afford it, and no later load ever reclaimed it.
That also falsified the claim in the description that the memory is paid either way: on those
hosts it is paid once and never used.

Ask predict_engine instead, which is the same predicate selection and the download planner
already use and is documented to activate nothing and install nothing, so asking at boot cannot
perturb a resident model. A non-GGUF pick short-circuits it, since only a GGUF can go native,
and an unrecognised family counts as diffusers because that is where such a load lands.

Keeps the speedup where it is real: a CUDA host, and a dense checkpoint even on a host that
prefers the native engine.

Three tests: an sd.cpp-routed host imports nothing, a non-GGUF model on that same host still
prewarms, and the gate asks the router rather than copying its policy.

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

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

* Resolve a pick's family the way the loader does, not from its id alone

detect_family(pick.model_id) cannot see a family that lives only in the .gguf filename, which
is a supported local layout: /models/custom/model.gguf holding z-image has an opaque directory
and an opaque id. The gate read that as an unknown family and prewarmed, so the sd.cpp memory
regression this gate exists to prevent survived for exactly that layout.

Use detected_image_family, the pick-aware resolver the listing and locality routes already
share. It tries the path before the id, which matters for the same reason it does there: the
path is the only needle the load route is handed and the only one that can carry a local
model_index.json, and asking the id first answers FLUX for a HiDream pipeline sitting in a
directory called flux.1.

Two tests: the filename-only pick resolves through the REAL resolver rather than a stub of it,
and the gate does not fall back to the id-only call.

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

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

* Do not prewarm for a native H3 video install, and install the ROCm stubs first

Two holes in the prewarm, both found by review.

MiniMax H3 as a GGUF is the one video combination that never imports diffusers: VideoBackend
returns through _run_load_h3_native before its own `import diffusers`. The gate could not see
that, because the video backend has its own family type and detected_image_family has no answer
for a VideoFamily, so an H3-only install fell into the "unknown family" branch and paid 316 MB it
would never use. Ask the video backend's own detect_video_family and is_h3_native for video
picks. Everything else video still prewarms, including a repo id the detector cannot place.

core/inference/diffusion.py installs install_xformers_windows_rocm_stub,
install_torchao_windows_rocm_stub and install_torchao_int_mm_patch at module scope, above its own
lazy `import diffusers`, because on Windows ROCm diffusers imports xformers on sight and its
quantizers torchao, and both reach an absent distributed backend. This prewarm can be the first
importer in the process and was not paying that toll. Install the same three, in the same order,
in front of the import, and skip the prewarm entirely if they are unavailable, since importing
unprotected is the hazard.

Also purge on failure. A failed package import leaves its executed submodules in sys.modules and
the prewarm swallows the failure, so the retry is a user's image load, which would re-run
__init__ against that cache and come back missing attributes (unslothai#7580). purge_partial_import is
already in this module and already declines when a loaded C extension is involved.

Three tests added, each confirmed to fail with its fix reverted.

* Match video.py's family detection: try the repo id, then the picked GGUF filename

The H3 skip only looked at the model path and the model id, so an H3 GGUF under an opaque
directory (`/models/custom/minimax_h3_fl2va-Q4.gguf`) was not recognised and still paid the
316 MB. video.py's own _detect_load_family tries `repo_id` first and then
`f"{repo_id}/{gguf_filename}"`, exactly because a local directory or a generically named repo
often carries the family token only in the checkpoint filename. Do the same, in the same order.

Not copied on purpose: _detect_load_family also reads general.architecture out of a renamed
GGUF's header. That is file IO on a boot thread to save memory, and guessing wrong in this
direction only costs the prewarm, so an unidentifiable GGUF falls through to the safe default and
prewarms.

Test uses Codex's own path. Confirmed failing with the filename needle removed.

* Hold the diffusers import lock across the failed import and its purge

Releasing between the two was the bug. CPython drops the `diffusers` module lock the moment
__init__ raises, so a request already blocked on that lock wakes up in the gap, re-imports
against the submodules the failed import left behind, and republishes the malformed parent. At
that point purge_partial_import deliberately declines, because the leftovers now belong to a live
importer, and the load path is left with the missing-attribute diffusers this PR was supposed to
prevent.

_held_import_lock already does exactly this for the bare warm stages; the prewarm now does the
same. _ModuleLockManager is reentrant per thread (verified), so the nested acquire inside
purge_partial_import is free.

Test asserts the lock is owned by this thread at the moment the purge runs, and fails with the
lock removed.

* Honour UNSLOTH_STUDIO_DISABLE_TORCH_WARM in the prewarm

start_background_warm() declines under that variable, but join_background_warm() reports True
when no worker ever ran, so the post-warm thread reached the prewarm regardless and imported
diffusers, which imports torch. That is exactly what the opt-out exists to prevent, and the
warm-window tests that assert no unsolicited torch import would have been defeated by this PR.
Checked inside the function so every caller gets it.

Also documents a scope limit rather than papering over it: the media index is keyed on
current_account_id() and this runs on a boot thread with no bound account, so on a multi-user
install where only a non-owner has an image model the gate says no and that user's first load
still pays the import. Building an index per configured account means a filesystem scan per
account on the boot thread, which is the cost this gate exists to avoid, and the failure mode is
only the absence of a speedup, exactly as today. Left as is, deliberately, and written down.

Test confirmed failing with the opt-out check removed.

* Purge the hooks subtree too when that is the import that failed

`import diffusers` and `import diffusers.hooks` are two imports and either can be the one that
fails. When the parent succeeded and the subpackage did not, purging "diffusers" is a no-op by
design, since it is in sys.modules and belongs to nobody, so the hook submodules that already
executed stayed cached and the load path's own `from diffusers.hooks import ...` would rebuild an
incomplete package from them. That is the unslothai#7580 shape, one level down.

Purge the subpackage first, then the parent. purge_partial_import takes the subpackage's own
module lock and is a no-op when there is nothing of that shape to collect, so the healthy-parent
case is unaffected.

The lock test now asserts every purge call happened under the lock rather than expecting exactly
one. New test confirmed failing with the subtree purge removed.

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

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

* Stop the purge tests leaking an evicted diffusers into the rest of the suite

Running the wider suite turned up test_diffusion_gguf_compile failing, and it was my own tests
that broke it, not the product code: the purge tests call the real purge_partial_import, which
evicts whatever diffusers submodules the session had already imported. monkeypatch cannot undo
that, since it restores only the keys it set itself, so the eviction leaked forward and a later
test rebuilt a partial diffusers and failed for reasons of its own that had nothing to do with it.

Snapshot and restore the whole diffusers subtree around the three tests that purge. Confirmed by
the minimal pair (prewarm tests then the compile test) and by the full selection: 8728 passed,
0 failures.

* Hold the hooks lock too, not just the parent's

Last round's lock only covered the parent, and the subpackage has the identical gap: these are
two imports with two locks, so `import diffusers.hooks` drops the hooks lock the moment it
raises, and with the healthy parent already published a waiting request can rebuild
diffusers.hooks from its stale submodules before purge_partial_import("diffusers.hooks")
reacquires it.

Hold both, parent then child, which is the order CPython's own import takes, so a concurrent
importer cannot invert it.

The lock assertion was also weaker than it read: it checked the parent's lock for every purge
call, including the one purging the hooks subtree, so it would have passed with the hooks lock
missing. It now reads the lock of the package actually being purged, and the hooks test carries
the same check. Both confirmed failing with the second lock removed.

* Take the two import locks sequentially, never nested

My last commit claimed parent-then-child was "the order CPython's own import takes". That is
backwards, and I checked the source this time instead of asserting it: _find_and_load takes
_ModuleLockManager(name) for the CHILD first, then _find_and_load_unlocked imports the parent
from inside that scope. So `import diffusers.hooks` goes child -> parent, and holding
parent-then-child here inverted it against any concurrent `from diffusers.hooks import ...`.

The resulting cycle surfaces as the _DeadlockError that _lock_unlock_module swallows, which
hands back a partially initialised module: precisely the failure unslothai#10350 and unslothai#10963 are about. So
the nesting risked causing the bug the prewarm is meant to help avoid.

Each package now gets its own scope, holding only its own lock across its own import and its own
cleanup. There is no cycle left: by the time the hooks scope runs the parent is published, so
importing the child acquires nothing else.

Two tests. One asserts the two locks are never owned simultaneously. The other runs a real
concurrent thread in CPython's order (hooks lock, then the parent) and requires both it and the
prewarm to finish. Both confirmed failing with the nested version restored, the second by
actually hanging until its timeout.

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

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

* Put the try inside each lock scope, not around it

A regression I introduced with the un-nesting fix one commit ago. Writing `try: with LM(...):`
releases the lock when the scope exits on the exception and reacquires it in the handler, which
reopens the exact release-before-cleanup gap closed two commits earlier: a request already
waiting takes the lock in that gap, re-imports against the submodules the failed import left
behind, and republishes the malformed package, after which purge_partial_import declines because
the leftovers now belong to a live importer.

Both scopes now hold their lock across their own import and their own cleanup, and the two scopes
stay sequential so CPython's child-then-parent order is not inverted.

The existing lock assertions did not catch this, because they check the lock is held at the
moment the purge runs and the handler had reacquired by then. The new test records the
enter/exit/purge timeline and fails on a release between the failed import and its purge, while
still tolerating the reentrant acquire purge_partial_import takes through its own decorator.
Confirmed failing against the previous arrangement.

Quieting the tqdm bars moves out of the locked scopes: it imports nothing under diffusers, and a
failure there no longer discards a prewarm whose imports already succeeded.

---------

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.

1 participant