Skip to content

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

Merged
danielhanchen merged 19 commits into
mainfrom
perf/prewarm-diffusers-post-warm
Sep 15, 2026
Merged

danielhanchen merged 19 commits into
mainfrom
perf/prewarm-diffusers-post-warm

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

What this costs today

The first diffusion load in a fresh process pays this before it touches a single weight:

import seconds RSS
diffusers 1.63 169.8 MB
diffusers.hooks 2.38 104.5 MB
pipeline classes (StableDiffusionPipeline, AutoPipelineForText2Image) 1.26 42.0 MB
total 5.26 316.3 MB

None of it depends on which model was picked, so it is the same cost on every first load in a fresh process, and all of it can be paid earlier by a thread nobody is waiting on. Diffusers is currently imported lazily at roughly a dozen call sites and never pre-imported at boot.

After

Measured end to end, the import work the load path itself does:

first-load import work peak RSS
today 4.47s 818.1 MB
with this change 0.60s 816.9 MB

A 3.87s saving on the first image generation, at the same peak memory on a host whose image path uses diffusers.

The "paid either way" claim is only true on such a host, which is why the gate below asks the router rather than counting models: a CPU or MPS host with a runnable native binary, and any host with UNSLOTH_DIFFUSION_ENGINE=sd_cpp, serves a supported GGUF through sd.cpp and imports no diffusers at all. Prewarming there would add 316 MB that nothing ever reclaims.

Why it does not cost chat-only users anything

Gated on whether any local model would actually load through diffusers on this host, not on whether one exists. A chat-only or training-only user never pays the 316 MB for a page they do not open, and neither does a CPU or MPS host whose image path is native.

The gate is worth describing because it is the whole justification:

  • The task identifiers come from the catalog's own _LOADABLE_MEDIA_GGUF_TASKS. Spelling them again is how the first revision shipped a permanently empty index and a prewarm that never ran.
  • Routing is answered by predict_engine, the same predicate selection and the download planner use, 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.
  • The index itself is stdlib only, imports neither torch nor diffusers, is cached, and the Images page needs it anyway, so building it here is work moved earlier rather than work added.
  • Not latched on the negative answer, so a model downloaded later lets the next lifespan reconsider.

Where it runs

From _post_warm_background_work, 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: MLX autorepair and linked-folder sync keep their place in the queue.

Deliberately not a fifth _STAGES entry. Those four are on the path to a usable backend, and pulling diffusers into one of them would delay every boot including chat-only ones. There is a test pinning that the warm stages do not import diffusers.

Safety

Concurrency was measured, not assumed. A background pre-import can race a user-triggered load importing the same package, which is the shape of the bug in #10350. Tested: 4 to 8 threads importing diffusers submodules together, 0 failures in 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, which is a cross-package cycle.

The tqdm side effect is handled. diffusers hard-codes _tqdm_active = True at import and honours no env var, so a prewarm that skipped quiet_third_party_progress_bars() would let "Loading pipeline components..." draw straight onto the structlog stream, mid-record. The prewarm calls the same idempotent helper the load path calls.

Every failure mode degrades to skip, never to an exception. The post-warm worker also carries MLX repair and linked-folder sync, so a broken model index or an unimportable diffusers must not take it down. Both paths are tested.

Opt out with UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1.

Tests

15 new tests, covering the gate (no models means no import at all), an sd.cpp-routed host importing nothing, a non-GGUF model still prewarming on that same host, the real index answering the catalog's identifiers, the video-only install, the kill switch, latching, single-flight under 10 threads, a gate that raises, a diffusers that cannot import, the post-warm placement and ordering, and the guard that no coordinated warm stage imports diffusers.

The behavioural ones fail on main; the warm-stage guard correctly passes on both.

Warm, lifespan, liveness, diffusion-warmup and media-keepwarm suites: 200 passed.

Scope

Backend Python only, no frontend, TypeScript or Tauri file touched. No new hardware path and nothing branches on platform or accelerator, so there is no old path to regress.

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-15T13:21:24.561470Z b0122d0 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits September 15, 2026 07:07
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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 15, 2026 08:44
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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 15, 2026 10:11
…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 (#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
wasimysaid pushed a commit to wasimysaid/unsloth that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…GUF 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.
wasimysaid pushed a commit to wasimysaid/unsloth that referenced this pull request Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

`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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: fa0166f4a5

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

pre-commit-ci Bot and others added 2 commits September 15, 2026 12:01
…e 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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits September 15, 2026 13:02
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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 76c86659b2

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread studio/backend/utils/torch_warmup.py Outdated
Comment on lines +554 to +556
except Exception as exc: # noqa: BLE001 -- the load path imports it again and reports
logger.debug("diffusers prewarm skipped: %r", exc)
with _ModuleLockManager("diffusers"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the import lock held through failure cleanup

When the background import fails while an image request is waiting to import diffusers, exiting the first with releases the module lock before the exception handler reacquires it. The waiting request can therefore publish a package using the failed import's stale submodules, causing purge_partial_import() to decline cleanup and leaving the request with a malformed package. Move the try/except inside one _ModuleLockManager scope; the same release/reacquire gap also exists for diffusers.hooks below.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it was a regression I introduced one commit earlier: un-nesting the locks, I wrote try: around the with instead of inside it, which reopened the exact release-before-cleanup gap I had closed two commits before that. Both scopes now hold their lock across their own import and their own cleanup, and the scopes stay sequential so CPython child-then-parent order is not inverted.

The part worth calling out is that my existing lock assertions did not catch it. They check the lock is held at the moment the purge runs, and the handler had reacquired by then, so they passed against the broken arrangement. 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. It fails against the previous arrangement.

Also moved the tqdm quieting out of the locked scopes. It imports nothing under diffusers, and a failure there should not discard a prewarm whose imports already succeeded. b0122d0.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b0122d0deb

ℹ️ About Codex in GitHub

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

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

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

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

@danielhanchen
danielhanchen merged commit 405b2a5 into main Sep 15, 2026
50 of 52 checks passed
@danielhanchen
danielhanchen deleted the perf/prewarm-diffusers-post-warm branch September 15, 2026 13:31
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 15, 2026
…ain (unslothai#11019)

main is not formatted the way its own pre-commit hook formats. Running
scripts/run_ruff_format.py with the pinned ruff 0.6.9 over every file the hook
selects changes three files on 52fb7b0:

    studio/backend/tests/test_diffusers_prewarm.py   (unslothai#10989)
    studio/backend/utils/torch_warmup.py             (unslothai#10989)
    tests/python/test_amd_extras_contract.py         (unslothai#7536)

Both of those PRs merged in the last hour with `pre-commit.ci - pr` in ERROR.

That is not only a tidiness problem, because it takes pre-commit.ci's autofix
down for every OTHER pull request. The hook runs against the PR merged with
main, so every PR's tree now contains these three files needing reformatting;
the autofix patch is computed over them and then cannot be applied to a head
that does not carry main's copy. Three PRs are red on exactly that, each with a
one-or-two-line formatting delta it cannot self-heal, all reporting:

    a conflict occurred when applying fixes to the pr.
    try pulling the upstream branch

So this is self-sustaining: unformatted code on main disables the autofix, and
PRs then merge red because nothing can push the fix for them.

The formatter, not the code, is the thing to trust here: it is pinned in
.pre-commit-config.yaml, and it is idempotent. Running it again over these files
changes nothing on the second or third pass, so this is a fixed point rather
than one step of a moving target. One hunk expands a short signature, which
looks wrong until you see why: the hook rewrites `path=None` to `path = None`
first, and the longer line then no longer fits.

Nothing but whitespace: comment_tools.py check --strict-ext reports 3/3 OK, so
every AST is unchanged. test_diffusers_prewarm.py 28 passed,
test_amd_extras_contract.py 10 passed. Re-running the hook over the whole tree
afterwards touches these three files and nothing else.
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>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…ain (unslothai#11019)

main is not formatted the way its own pre-commit hook formats. Running
scripts/run_ruff_format.py with the pinned ruff 0.6.9 over every file the hook
selects changes three files on 52fb7b0:

    studio/backend/tests/test_diffusers_prewarm.py   (unslothai#10989)
    studio/backend/utils/torch_warmup.py             (unslothai#10989)
    tests/python/test_amd_extras_contract.py         (unslothai#7536)

Both of those PRs merged in the last hour with `pre-commit.ci - pr` in ERROR.

That is not only a tidiness problem, because it takes pre-commit.ci's autofix
down for every OTHER pull request. The hook runs against the PR merged with
main, so every PR's tree now contains these three files needing reformatting;
the autofix patch is computed over them and then cannot be applied to a head
that does not carry main's copy. Three PRs are red on exactly that, each with a
one-or-two-line formatting delta it cannot self-heal, all reporting:

    a conflict occurred when applying fixes to the pr.
    try pulling the upstream branch

So this is self-sustaining: unformatted code on main disables the autofix, and
PRs then merge red because nothing can push the fix for them.

The formatter, not the code, is the thing to trust here: it is pinned in
.pre-commit-config.yaml, and it is idempotent. Running it again over these files
changes nothing on the second or third pass, so this is a fixed point rather
than one step of a moving target. One hunk expands a short signature, which
looks wrong until you see why: the hook rewrites `path=None` to `path = None`
first, and the longer line then no longer fits.

Nothing but whitespace: comment_tools.py check --strict-ext reports 3/3 OK, so
every AST is unchanged. test_diffusers_prewarm.py 28 passed,
test_amd_extras_contract.py 10 passed. Re-running the hook over the whole tree
afterwards touches these three files and nothing else.
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.

2 participants