Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Pre-import diffusers in the post-warm worker so the first image load does not (#10989)
Daniel Han405b2a54e95b
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 6c9946d7bed..2861de646ca 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -348,6 +348,7 @@ import utils.hardware.hardware as _hw_modulefrom utils.torch_warmup import (DISABLE_ENV_VAR,join_background_warm,+ prewarm_diffusers_if_image_models_exist,reset_background_warm,start_background_warm,warm_status,@@ -609,6 +610,18 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:return_start_linked_folder_auto_sync(generation)+ # Last, and deliberately so: it is the only item here that is pure latency work rather than+ # correctness, so everything above keeps its place in the queue. Roughly 5.3s of diffusers+ # import that the first image load would otherwise pay, moved onto this thread, and only on+ # installs that actually have an image or video model. Self-guarded and never fatal.+ if _post_warm_retired(generation):+ return+ try:+ prewarm_diffusers_if_image_models_exist()+ except Exception as _prewarm_exc: # noqa: BLE001 -- latency work must never end the worker+ import structlog as _structlog+ _structlog.get_logger(__name__).debug("diffusers prewarm skipped: %s", _prewarm_exc)+def clear_compiled_cache_unless_shared(app: FastAPI) -> None:"""Clear the compiled cache unless a sibling backend of this install is live. The decision lives indiff --git a/studio/backend/tests/test_diffusers_prewarm.py b/studio/backend/tests/test_diffusers_prewarm.pynew file mode 100644index 00000000000..cb4920ebdbb--- /dev/null+++ b/studio/backend/tests/test_diffusers_prewarm.py@@ -0,0 +1,793 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Pre-importing diffusers off the first image load.++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, the pipeline classes 1.3s). None of it+depends on which model was picked, so it can be paid earlier on a thread nobody waits on.+Measured end to end, the load path's own import work drops from 4.47s to 0.60s, at the same+peak RSS: the memory is paid either way, just earlier.++The tests below pin the properties that make that safe to ship rather than the speedup itself:++ 1. A chat-only or training-only install pays NOTHING. The gate must not import diffusers when+ there is no local image or video model, which is the whole reason the gate exists.+ 2. Every failure mode degrades to "skip", never to an exception: the post-warm worker also+ carries MLX repair and linked-folder sync.+ 3. It runs from the POST-warm worker, after the coordinated warm, so it cannot delay a warm+ stage or the socket bind.+ 4. The tqdm quieting that diffusers forces at import is applied here too, or the prewarm would+ write progress bars onto the structlog stream.++None of these import the real diffusers, which is the point of stubbing it.+"""++from __future__ import annotations++import ast+import builtins+import sys+import threading+import types+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+++def restore_diffusers_modules():+ """Put back every ``diffusers*`` entry this test disturbs.++ The purge tests call the real ``purge_partial_import``, which evicts whatever ``diffusers``+ submodules the session had already imported. monkeypatch cannot undo that: it only restores+ keys it set itself, so the eviction leaks into later tests, which then rebuild a partial+ diffusers and fail for reasons that have nothing to do with them.+ """+ saved = {name: mod for name, mod in sys.modules.items() if name.split(".")[0] == "diffusers"}+ try:+ yield+ finally:+ for name in [n for n in sys.modules if n.split(".")[0] == "diffusers"]:+ del sys.modules[name]+ sys.modules.update(saved)+++def warm(monkeypatch):+ """``utils.torch_warmup`` with the prewarm latch reset, so each test starts cold."""+ from utils import torch_warmup++ monkeypatch.setattr(torch_warmup, "_diffusers_prewarmed", False, raising = False)+ monkeypatch.delenv(torch_warmup.DIFFUSERS_PREWARM_DISABLE_ENV_VAR, raising = False)+ return torch_warmup+++def _stub_gate(+ monkeypatch,+ ids_by_task,+ *,+ raises = False,+ engine = "diffusers",+):+ """Stand in for the media index and the engine router.++ ``engine`` is what a load of these models would select. It is not decoration: a CPU or MPS+ host routes a supported GGUF to sd.cpp, which imports no diffusers, so "a model exists" and+ "diffusers would be used" are different questions and only the second one may prewarm.+ """+ idx = types.ModuleType("core.inference.media_model_index")++ def _available(task):+ if raises:+ raise RuntimeError("index unavailable")+ return list(ids_by_task.get(task, []))++ idx.available_media_model_ids = _available+ idx.resolve_local_media_model = lambda model_id, task: types.SimpleNamespace(+ model_id = model_id,+ model_path = "/nonexistent",+ gguf_filename = "m.gguf",+ model_kind = "gguf",+ ambiguous = False,+ )+ monkeypatch.setitem(sys.modules, "core.inference.media_model_index", idx)++ router = types.ModuleType("core.inference.diffusion_engine_router")+ router.ENGINE_DIFFUSERS = "diffusers"+ router.predict_engine = lambda fam, model_kind = None: engine+ monkeypatch.setitem(sys.modules, "core.inference.diffusion_engine_router", router)++ loc = types.ModuleType("core.inference.media_locality")+ loc.detected_image_family = lambda pick: object()+ monkeypatch.setitem(sys.modules, "core.inference.media_locality", loc)+++def _stub_diffusers(monkeypatch, *, raises = False):+ """A diffusers that records whether it was imported, without importing the real one."""+ seen = {"imported": False, "quieted": False}+ if raises:+ monkeypatch.setitem(sys.modules, "diffusers", None) # import -> ImportError+ return seen+ d = types.ModuleType("diffusers")+ hooks = types.ModuleType("diffusers.hooks")+ d.hooks = hooks+ seen["imported"] = False++ class _Marking(types.ModuleType):+ pass++ monkeypatch.setitem(sys.modules, "diffusers", d)+ monkeypatch.setitem(sys.modules, "diffusers.hooks", hooks)+ seen["imported"] = True++ cfg = sys.modules.get("loggers.config")+ if cfg is not None:+ monkeypatch.setattr(+ cfg,+ "quiet_third_party_progress_bars",+ lambda: seen.__setitem__("quieted", True),+ raising = False,+ )+ return seen+++def test_an_install_with_no_image_models_pays_nothing(warm, monkeypatch):+ """The gate is the entire justification for doing this at boot. A chat-only or+ training-only user must not pay diffusers' 316 MB for a page they never open."""+ _stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": []})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ assert "diffusers" not in sys.modules, "the prewarm imported diffusers with nothing to load"+++def test_it_prewarms_when_an_image_model_is_present(warm, monkeypatch):+ _stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"], "text-to-video": []})+ seen = _stub_diffusers(monkeypatch)++ assert warm.prewarm_diffusers_if_image_models_exist() is True+ assert seen["imported"] is True+++def test_a_video_only_install_also_prewarms(warm, monkeypatch):+ """Both media backends go through the same diffusers import."""+ _stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["some/video-model"]})+ _stub_diffusers(monkeypatch)++ assert warm.prewarm_diffusers_if_image_models_exist() is True+++def test_a_video_only_install_of_an_h3_gguf_pays_nothing(warm, monkeypatch):+ """MiniMax H3 as a GGUF is the one video combination that never imports diffusers.++ ``VideoBackend.load_pipeline`` asks ``is_h3_native(fam, kind)`` and returns through+ ``_run_load_h3_native`` before its own ``import diffusers``. The image resolver cannot see+ this: ``detected_image_family`` has no answer for a ``VideoFamily``, so the "unknown family"+ branch would call it diffusers and charge an H3-only install 316 MB it never uses. Uses the+ real family detector and the real predicate, so a rename on either side fails here.+ """+ _stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["unsloth/MiniMax-H3-GGUF"]})+ seen = _stub_diffusers(monkeypatch)+ seen["imported"] = False++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ # And not latched, so an image model downloaded later still gets a prewarm next boot.+ assert warm._diffusers_prewarmed is False+++def test_an_h3_gguf_named_only_by_its_filename_pays_nothing(warm, monkeypatch):+ """The supported layout the repo id alone cannot answer for.++ A local directory or a generically named repo often carries the family token only in the+ checkpoint filename, which is why video.py's own ``_detect_load_family`` tries the repo id+ and then ``f"{repo_id}/{gguf_filename}"``. Looking at the id alone leaves this install+ prewarming 316 MB for a load that returns through ``_run_load_h3_native``.+ """+ _stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["custom-video"]})+ sys.modules["core.inference.media_model_index"].resolve_local_media_model = (+ lambda model_id, task: types.SimpleNamespace(+ model_id = "custom-video", # names no family+ model_path = "/models/custom", # nor does the directory+ gguf_filename = "minimax_h3_fl2va-Q4.gguf", # only the checkpoint does+ model_kind = "gguf",+ ambiguous = False,+ )+ )+ _stub_diffusers(monkeypatch)++ assert warm.prewarm_diffusers_if_image_models_exist() is False+++def test_a_video_family_we_cannot_identify_still_prewarms(warm, monkeypatch):+ """The H3 skip is an exception carved out of the default, not a new default.++ Every other video load reaches video.py's ``import diffusers``, so anything the detector+ cannot place must keep prewarming. Getting this backwards would silently drop the feature+ for every video user whose repo id is not in the family table.+ """+ _stub_gate(monkeypatch, {"text-to-image": [], "text-to-video": ["someone/private-repack"]})+ _stub_diffusers(monkeypatch)++ assert warm.prewarm_diffusers_if_image_models_exist() is True+++def test_the_torch_warm_opt_out_also_disables_the_prewarm(warm, monkeypatch):+ """UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 means no unsolicited torch import, and importing+ diffusers imports torch. start_background_warm() declines under that variable, but+ join_background_warm() reports True when no worker ever ran, so the post-warm thread reaches+ the prewarm anyway. Without this check the opt-out would be defeated by the new code."""+ monkeypatch.setenv(warm.DISABLE_ENV_VAR, "1")+ _stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ assert "diffusers" not in sys.modules, "the torch-warm opt-out did not stop the prewarm"+++def test_the_kill_switch_is_honoured(warm, monkeypatch):+ monkeypatch.setenv(warm.DIFFUSERS_PREWARM_DISABLE_ENV_VAR, "1")+ _stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ assert "diffusers" not in sys.modules+++def test_it_latches_so_a_second_call_is_free(warm, monkeypatch):+ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ _stub_diffusers(monkeypatch)++ assert warm.prewarm_diffusers_if_image_models_exist() is True+ assert warm.prewarm_diffusers_if_image_models_exist() is False+++def test_concurrent_callers_prewarm_once(warm, monkeypatch):+ """Single-flight, asserted on how many callers did the work rather than on lock entries,+ which would be a race against thread scheduling."""+ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ _stub_diffusers(monkeypatch)++ did = []+ threads = [+ threading.Thread(target = lambda: did.append(warm.prewarm_diffusers_if_image_models_exist()))+ for _ in range(10)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert sum(1 for d in did if d) == 1, f"the import ran more than once: {did}"+++def test_a_gate_that_raises_means_skip_not_crash(warm, monkeypatch):+ """A broken or absent model index must not take the post-warm worker down with it."""+ _stub_gate(monkeypatch, {}, raises = True)+ assert warm.prewarm_diffusers_if_image_models_exist() is False+++def test_a_diffusers_that_cannot_import_means_skip_not_crash(warm, monkeypatch):+ """A --no-torch host, or a broken diffusers, reports False. The load path imports it again+ and is the one that reports the failure to the user."""+ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ _stub_diffusers(monkeypatch, raises = True)+ assert warm.prewarm_diffusers_if_image_models_exist() is False+++def test_the_windows_rocm_stubs_are_installed_before_the_import(warm, monkeypatch):+ """core/inference/diffusion.py installs these three at module scope, above its own lazy+ `import diffusers`, because on Windows ROCm diffusers imports xformers on sight and its+ quantizers torchao, and both land on an absent distributed backend. This prewarm can be the+ first importer in the process, so it owes the same three installs, in front of the import."""+ from core import _torchao_stub+ from core.inference import diffusion_torchao_patches++ order = []+ for mod, name in (+ (_torchao_stub, "install_xformers_windows_rocm_stub"),+ (_torchao_stub, "install_torchao_windows_rocm_stub"),+ (diffusion_torchao_patches, "install_torchao_int_mm_patch"),+ ):+ monkeypatch.setattr(mod, name, (lambda n: lambda: order.append(n))(name))++ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)++ real_import = builtins.__import__++ def _record_import(name, *args, **kwargs):+ if name.startswith("diffusers"):+ order.append("import")+ return types.ModuleType(name)+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _record_import)++ warm.prewarm_diffusers_if_image_models_exist()+ monkeypatch.undo()++ assert order[:3] == [+ "install_xformers_windows_rocm_stub",+ "install_torchao_windows_rocm_stub",+ "install_torchao_int_mm_patch",+ ], f"stubs did not run first, in the loader's order: {order}"+ assert "import" in order and order.index("import") > 2+++def test_a_failed_prewarm_leaves_no_half_imported_diffusers(+ warm, monkeypatch, restore_diffusers_modules+):+ """The failure this prewarm adds that the loader did not have.++ When ``diffusers/__init__.py`` raises, CPython evicts only the parent and keeps every+ submodule it already executed. The prewarm swallows that failure, so the next importer is a+ user's image load, and it would re-run ``__init__`` with each ``from .x import y`` served+ from that cache and attributes never rebound: diffusers imports "successfully" while missing+ pieces. Hand the load path a clean slate instead.+ """+ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ leftover = types.ModuleType("diffusers.pipelines")+ monkeypatch.setitem(sys.modules, "diffusers.pipelines", leftover)++ class _Boom:+ def find_module(self, *a, **k):+ return None++ def find_spec(+ self,+ name,+ path = None,+ target = None,+ ):+ if name == "diffusers":+ raise ImportError("simulated half-built diffusers")+ return None++ monkeypatch.setattr(sys, "meta_path", [_Boom(), *sys.meta_path])++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ assert (+ "diffusers.pipelines" not in sys.modules+ ), "a failed prewarm left submodules behind for the load path to trip over"+++def test_the_diffusers_import_lock_is_held_across_the_failure_cleanup(+ warm, monkeypatch, restore_diffusers_modules+):+ """Releasing between the failed import and the purge is the whole bug.++ CPython drops the ``diffusers`` module lock the moment ``__init__`` raises. A request already+ blocked on that lock would wake up in the gap, re-import against the submodules the failed+ import left behind, and republish the malformed parent, at which point+ ``purge_partial_import`` deliberately declines because those leftovers now belong to a live+ importer. The bare warm stages already hold the lock across import and cleanup+ (``_held_import_lock``); this asserts the prewarm does the same.+ """+ from importlib._bootstrap import _get_module_lock++ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.setitem(sys.modules, "diffusers.pipelines", types.ModuleType("diffusers.pipelines"))++ held_during_purge = []+ real_purge = warm.purge_partial_import++ def _checking_purge(package):+ # The lock of the package being purged, not always the parent: the hooks subtree has its+ # own lock and the same release-before-cleanup gap. Reading .owner does not disturb the+ # lock the way acquiring it would.+ lock = _get_module_lock(package)+ held_during_purge.append(getattr(lock, "owner", None) == threading.get_ident())+ return real_purge(package)++ monkeypatch.setattr(warm, "purge_partial_import", _checking_purge)++ class _Boom:+ def find_spec(+ self,+ name,+ path = None,+ target = None,+ ):+ if name == "diffusers":+ raise ImportError("simulated half-built diffusers")+ return None++ monkeypatch.setattr(sys, "meta_path", [_Boom(), *sys.meta_path])++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ # One entry per purge call (the hooks subtree and the parent); every one must be under lock.+ assert held_during_purge and all(held_during_purge), (+ "the diffusers import lock was released before the purge ran, so a waiting importer "+ f"could take it in the gap (observed: {held_during_purge})"+ )+++def test_a_hooks_failure_after_a_good_parent_still_purges_the_hook_subtree(+ warm, monkeypatch, restore_diffusers_modules+):+ """The half of the failure the parent purge cannot reach.++ ``import diffusers`` and ``import diffusers.hooks`` are two imports and either can fail. When+ the parent succeeded and the subpackage did not, purging "diffusers" is a no-op by design (it+ is in sys.modules and belongs to nobody), so the hook submodules that already executed stay+ cached and the load path's own ``from diffusers.hooks import ...`` rebuilds an incomplete+ package from them. That is the #7580 shape, one level down.+ """+ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ parent = types.ModuleType("diffusers")+ monkeypatch.setitem(sys.modules, "diffusers", parent)+ monkeypatch.setitem(+ sys.modules,+ "diffusers.hooks.group_offloading",+ types.ModuleType("diffusers.hooks.group_offloading"),+ )+ monkeypatch.delitem(sys.modules, "diffusers.hooks", raising = False)++ from importlib._bootstrap import _get_module_lock++ held = []+ real_purge = warm.purge_partial_import++ def _checking_purge(package):+ lock = _get_module_lock(package)+ held.append((package, getattr(lock, "owner", None) == threading.get_ident()))+ return real_purge(package)++ monkeypatch.setattr(warm, "purge_partial_import", _checking_purge)++ class _Boom:+ def find_spec(+ self,+ name,+ path = None,+ target = None,+ ):+ if name == "diffusers.hooks":+ raise ImportError("simulated half-built diffusers.hooks")+ return None++ monkeypatch.setattr(sys, "meta_path", [_Boom(), *sys.meta_path])++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ # The subpackage has its own lock and the same gap: `import diffusers.hooks` drops it when it+ # raises, and with the healthy parent already published a waiting request could rebuild the+ # hooks package from these stale submodules before the purge reacquires it.+ assert held and all(+ ok for _, ok in held+ ), f"a purge ran without holding that package's own import lock (observed: {held})"+ assert (+ "diffusers.hooks.group_offloading" not in sys.modules+ ), "the executed hook submodules survived, so the load path can rebuild a partial package"+ assert (+ sys.modules.get("diffusers") is parent+ ), "the healthy parent was evicted; only the failed subtree should go"+++def test_the_parent_and_child_import_locks_are_never_held_together(warm, monkeypatch, restore_diffusers_modules):+ """Holding both would invert CPython's own lock order and deadlock a concurrent import.++ ``import diffusers.hooks`` makes CPython take the CHILD lock first and import the parent from+ inside it (``_find_and_load`` -> ``_ModuleLockManager(name)`` -> ``_find_and_load_unlocked``+ -> import parent). A prewarm holding parent-then-child inverts that against any concurrent+ ``from diffusers.hooks import ...``, and the resulting cycle surfaces as the ``_DeadlockError``+ that ``_lock_unlock_module`` swallows, which is the partially initialised module this whole+ change exists to prevent.+ """+ from importlib._bootstrap import _get_module_lock++ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.delitem(sys.modules, "diffusers.hooks", raising = False)++ me = threading.get_ident()+ both_held = []++ def _owned(name):+ return getattr(_get_module_lock(name), "owner", None) == me++ real_import = builtins.__import__++ def _watching_import(name, *args, **kwargs):+ if name.startswith("diffusers"):+ both_held.append((name, _owned("diffusers"), _owned("diffusers.hooks")))+ return types.ModuleType(name)+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _watching_import)++ warm.prewarm_diffusers_if_image_models_exist()+ monkeypatch.undo()++ assert both_held, "the prewarm imported nothing; this test would be vacuous"+ offenders = [(n, p, c) for n, p, c in both_held if p and c]+ assert not offenders, (+ f"parent and child import locks held at the same time: {offenders}"+ )+++def test_a_concurrent_submodule_import_does_not_deadlock_the_prewarm(warm, monkeypatch, restore_diffusers_modules):+ """The failure mode from the other side, with two real threads and the real locks.++ One thread takes the hooks lock and then reaches for the parent, which is the order CPython+ uses for ``from diffusers.hooks import ...``. The prewarm runs concurrently. With sequential+ scopes both finish; with the locks nested this is the cycle.+ """+ from importlib._bootstrap import _ModuleLockManager as LM++ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.delitem(sys.modules, "diffusers.hooks", raising = False)+ _stub_diffusers(monkeypatch)++ started = threading.Event()+ release = threading.Event()+ finished = threading.Event()++ def _importer():+ # CPython's order for a submodule import: child lock, then the parent.+ with LM("diffusers.hooks"):+ started.set()+ release.wait(10)+ with LM("diffusers"):+ pass+ finished.set()++ t = threading.Thread(target = _importer, daemon = True)+ t.start()+ assert started.wait(10), "the helper thread never took the hooks lock"++ done = threading.Event()++ def _prewarm():+ try:+ warm.prewarm_diffusers_if_image_models_exist()+ finally:+ done.set()++ p = threading.Thread(target = _prewarm, daemon = True)+ p.start()+ # The prewarm must not be blocked behind a lock the other thread is holding while that+ # thread waits on one the prewarm holds.+ release.set()+ assert done.wait(20), "the prewarm deadlocked against a concurrent submodule import"+ assert finished.wait(20), "the concurrent submodule import deadlocked against the prewarm"+ t.join(5)+ p.join(5)+++def test_the_lock_is_never_released_between_a_failed_import_and_its_purge(warm, monkeypatch, restore_diffusers_modules):+ """Held CONTINUOUSLY, not merely held again by the time the purge runs.++ Writing the try around the ``with`` instead of inside it releases the lock when the scope+ exits on the exception and reacquires it in the handler. A request already waiting wakes up+ in that gap, re-imports against the submodules the failed import left behind, and republishes+ the malformed package, at which point ``purge_partial_import`` declines because the leftovers+ now belong to a live importer. Asserting the purge ran under the lock does not catch this,+ because the handler has reacquired by then; only the timeline does.+ """+ _stub_gate(monkeypatch, {"text-to-image": ["m"]})+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.setitem(sys.modules, "diffusers.pipelines", types.ModuleType("diffusers.pipelines"))++ real_lm = warm._ModuleLockManager+ real_purge = warm.purge_partial_import+ timeline = []++ class _RecordingLockManager:+ def __init__(self, name):+ self._name = name+ self._inner = real_lm(name)++ def __enter__(self):+ timeline.append(("enter", self._name))+ return self._inner.__enter__()++ def __exit__(self, *exc):+ timeline.append(("exit", self._name))+ return self._inner.__exit__(*exc)++ def _recording_purge(package):+ timeline.append(("purge", package))+ return real_purge(package)++ monkeypatch.setattr(warm, "_ModuleLockManager", _RecordingLockManager)+ monkeypatch.setattr(warm, "purge_partial_import", _recording_purge)++ class _Boom:+ def find_spec(self, name, path = None, target = None):+ if name == "diffusers":+ raise ImportError("simulated half-built diffusers")+ return None++ monkeypatch.setattr(sys, "meta_path", [_Boom(), *sys.meta_path])++ assert warm.prewarm_diffusers_if_image_models_exist() is False++ purge_at = next(+ i for i, (what, name) in enumerate(timeline)+ if what == "purge" and name == "diffusers"+ )+ # Everything before the purge, from the first acquisition onwards, must be acquisitions:+ # a matching release in there is the gap. Reentrant acquires (purge_partial_import takes the+ # same lock through its own decorator) are fine and expected.+ enter_at = next(+ i for i, (what, name) in enumerate(timeline)+ if what == "enter" and name == "diffusers"+ )+ released_early = [+ i for i, (what, name) in enumerate(timeline)+ if what == "exit" and name == "diffusers" and enter_at < i < purge_at+ ]+ assert not released_early, (+ "the diffusers lock was released between the failed import and the purge, so a waiting "+ f"importer could take it in the gap (timeline: {timeline})"+ )+++def test_a_host_that_routes_to_sd_cpp_pays_nothing(warm, monkeypatch):+ """The case presence alone gets wrong. A CPU or MPS host with a runnable native binary, or+ UNSLOTH_DIFFUSION_ENGINE=sd_cpp, serves a supported GGUF through sd.cpp and imports no+ diffusers, so prewarming would add ~316 MB to a low-memory install that never reclaims it+ with a load."""+ _stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"]}, engine = "sd_cpp")+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)++ assert warm.prewarm_diffusers_if_image_models_exist() is False+ assert "diffusers" not in sys.modules, "prewarmed on a host whose image path is native"+++def test_a_non_gguf_model_still_prewarms_on_a_native_host(warm, monkeypatch):+ """Only a GGUF can go native, so a dense checkpoint lands on diffusers even where sd.cpp is+ the preferred engine. Gating the whole host off would lose the speedup for it."""+ _stub_gate(monkeypatch, {"text-to-image": ["some/dense-sdxl"]}, engine = "sd_cpp")+ idx = sys.modules["core.inference.media_model_index"]+ monkeypatch.setattr(+ idx,+ "resolve_local_media_model",+ lambda model_id, task: types.SimpleNamespace(+ model_id = model_id,+ model_path = "/nonexistent",+ gguf_filename = None,+ model_kind = None,+ ambiguous = False,+ ),+ )+ _stub_diffusers(monkeypatch)++ assert warm.prewarm_diffusers_if_image_models_exist() is True+++def test_a_gguf_whose_family_is_only_in_its_filename_is_still_recognised():+ """The layout `detect_family` cannot see: an opaque directory whose family keyword lives+ only in the .gguf filename. Treating it as unknown would prewarm on exactly the sd.cpp host+ this gate exists to spare, so the gate must use the same pick-aware resolver the listing and+ the loader use. Driven through the REAL resolver, since a stub of it could not show this."""+ from core.inference.media_locality import detected_image_family++ opaque = types.SimpleNamespace(+ model_id = "local/custom",+ model_path = "/models/custom",+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",+ model_kind = "gguf",+ ambiguous = False,+ )+ assert (+ detected_image_family(opaque) is not None+ ), "the filename-only family went unrecognised; the gate would prewarm on an sd.cpp host"+++def test_the_gate_uses_the_pick_aware_family_resolver():+ """Not `detect_family(pick.model_id)`: that misses the filename-only layout above."""+ import inspect+ from utils import torch_warmup++ body = inspect.getsource(torch_warmup._a_local_model_would_load_through_diffusers)+ assert "detected_image_family" in body+ assert "detect_family(" not in body, "the id-only resolver misses filename-only families"+++def test_the_gate_uses_the_routers_own_prediction():+ """Not a reimplementation of the routing policy: predict_engine is what selection and the+ download planner use, and it is documented to activate nothing and install nothing."""+ import inspect+ from utils import torch_warmup++ body = inspect.getsource(torch_warmup._a_local_model_would_load_through_diffusers)+ assert "predict_engine" in body, "the gate no longer asks the router"+ assert "policy_eligible" not in body, "the routing policy must not be copied here"+++def test_the_gate_asks_for_the_catalogs_real_task_identifiers():+ """``_build_index`` matches ``_local_model_task(info) == task`` exactly, so a friendly+ ``"image"``/``"video"`` builds a permanently EMPTY index and the gate refuses forever: the+ prewarm would be dead code that every stubbed test still passes. Pinned against the+ catalog's own set so a rename there fails here instead of silently disabling the prewarm."""+ from hub.services.models.catalog_classification import _LOADABLE_MEDIA_GGUF_TASKS+ from utils import torch_warmup++ assert set(torch_warmup._MEDIA_PREWARM_TASKS) == set(_LOADABLE_MEDIA_GGUF_TASKS)+++def test_the_real_index_answers_our_task_strings_and_not_the_friendly_ones(monkeypatch):+ """The same check driven through the REAL index rather than a stub of it.++ This is the one a stub cannot make: feed the catalog one text-to-image model and confirm+ ``available_media_model_ids`` finds it under the identifier the gate passes, and finds+ nothing under ``"image"``. Without it, keying the stub on the gate's own strings makes a+ wrong identifier look correct, which is exactly how this shipped the first time."""+ from core.inference import media_model_index as idx+ from utils import torch_warmup++ fake = types.SimpleNamespace(+ id = "unsloth/Z-Image-GGUF",+ model_id = "unsloth/Z-Image-GGUF",+ display_name = "Z-Image-GGUF",+ path = "/nonexistent/z-image",+ model_format = None,+ partial = False,+ )+ routes_models = sys.modules.setdefault("routes.models", types.ModuleType("routes.models"))+ monkeypatch.setattr(routes_models, "collect_local_models", lambda _root: [fake], raising = False)+ monkeypatch.setattr(+ routes_models, "_local_model_task", lambda _info: "text-to-image", raising = False+ )+ # _name_keys and the on-disk checks would reject a path that does not exist, so stand in+ # for the registration step; the task comparison above it is what is under test.+ monkeypatch.setattr(idx, "_name_keys", lambda _info: ("z-image-gguf",), raising = False)+ monkeypatch.setattr(idx, "_resolve_load_dir", lambda p: p, raising = False)+ monkeypatch.setattr(+ idx, "_add_gguf_picks", lambda index, info, keys, on_disk, load_dir: False, raising = False+ )+ monkeypatch.setattr(idx, "_loadable_directory", lambda _d: True, raising = False)+ idx.invalidate_index()++ found = {+ task: idx.available_media_model_ids(task)+ for task in (*torch_warmup._MEDIA_PREWARM_TASKS, "image", "video")+ }+ idx.invalidate_index()++ assert found["text-to-image"], "the gate's identifier finds nothing in the real index"+ assert not found["image"], "the friendly identifier unexpectedly matched"+ assert not found["video"]+++def _post_warm_source() -> str:+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_post_warm_background_work"+ )+ return ast.unparse(fn)+++def test_it_runs_from_the_post_warm_worker_and_last():+ """POST-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 repair and linked-folder sync keep their place in the queue."""+ src = _post_warm_source()+ assert (+ "prewarm_diffusers_if_image_models_exist" in src+ ), "the prewarm is no longer wired into the post-warm worker"+ assert "join_background_warm" in src+ assert src.index("join_background_warm") < src.index("prewarm_diffusers_if_image_models_exist")+ assert src.index("_start_linked_folder_auto_sync") < src.index(+ "prewarm_diffusers_if_image_models_exist"+ ), "latency work must not jump ahead of the correctness work in this worker"+++def test_the_coordinated_warm_stages_do_not_import_diffusers():+ """The four warm stages are on the path to a usable backend. Pulling diffusers into one of+ them would delay every boot, including chat-only ones, which is what the post-warm worker+ exists to avoid."""+ from utils import torch_warmup+ import inspect++ for name, fn in torch_warmup._STAGES:+ body = inspect.getsource(fn)+ assert "diffusers" not in body, f"warm stage {name!r} imports diffusers"diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.pyindex 573615b3c80..66c94491ead 100644--- a/studio/backend/utils/torch_warmup.py+++ b/studio/backend/utils/torch_warmup.py@@ -446,6 +446,245 @@ def _clear_finished_warm_locked() -> None:_status.pop("seconds", None)+DIFFUSERS_PREWARM_DISABLE_ENV_VAR = "UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM"++# The catalog's own task identifiers, which _build_index compares with ==. Anything else+# (a friendly "image"/"video") silently builds an empty index and reads as "no models here",+# so the gate would refuse forever. Pinned against the catalog by test_diffusers_prewarm.py.+_VIDEO_TASK = "text-to-video"+_MEDIA_PREWARM_TASKS = ("text-to-image", _VIDEO_TASK)++_diffusers_prewarm_lock = threading.Lock()+_diffusers_prewarmed = False+++def _a_local_model_would_load_through_diffusers() -> bool:+ """Whether any indexed media model would actually load through DIFFUSERS on this host.++ Presence alone is the wrong question. A CPU or MPS host with a runnable native binary, or+ any host with ``UNSLOTH_DIFFUSION_ENGINE=sd_cpp``, routes a supported GGUF to sd.cpp, which+ imports no diffusers at all -- so prewarming there would add ~316 MB to exactly the+ low-memory installs that can least afford it, and it would never be reclaimed by a load.++ ``predict_engine`` is the same predicate selection and the download planner use, and it is+ documented to activate nothing and install nothing, so asking it here cannot perturb a+ resident model. A non-GGUF pick short-circuits it: only a GGUF can go native.++ The family comes from ``detected_image_family``, the resolver the listing and locality+ routes already share, rather than ``detect_family`` on the id: a local GGUF can carry its+ family only in the FILENAME (``/models/custom/model.gguf`` holding ``z-image``), which+ ``detect_family`` cannot see, and treating that as unknown would prewarm on exactly the+ sd.cpp host this gate exists to spare."""+ from core.inference.diffusion_engine_router import ( # noqa: PLC0415+ ENGINE_DIFFUSERS,+ predict_engine,+ )+ from core.inference.media_locality import detected_image_family # noqa: PLC0415+ from core.inference.media_model_index import ( # noqa: PLC0415+ available_media_model_ids,+ resolve_local_media_model,+ )++ # Scope limit, deliberate: the media index is keyed on current_account_id(), and this runs on+ # a boot thread with no bound account, so it answers for the owner. 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. Not worth fixing here: 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.+ for task in _MEDIA_PREWARM_TASKS:+ for model_id in available_media_model_ids(task):+ pick = resolve_local_media_model(model_id, task = task)+ if pick is None:+ continue+ kind = pick.model_kind or ("gguf" if pick.gguf_filename else None)+ if kind != "gguf":+ return True # only a GGUF can go native, by either backend+ if task == _VIDEO_TASK:+ # The video backend has its own native path and its own family type, so the+ # image resolver and the image router cannot answer for it: an H3 GGUF returns+ # from _run_load_h3_native before video.py's own `import diffusers`, while every+ # other video load reaches it.+ if _is_native_video_pick(pick):+ continue+ return True+ family = detected_image_family(pick)+ if family is None:+ return True # unknown family: diffusers is where the load would land+ if predict_engine(family, model_kind = "gguf") == ENGINE_DIFFUSERS:+ return True+ return False+++def _is_native_video_pick(pick) -> bool:+ """Whether *pick* is the one video combination that never imports diffusers.++ ``VideoBackend.load_pipeline`` asks ``is_h3_native(fam, kind)`` and returns through+ ``_run_load_h3_native`` before its own ``import diffusers``; everything else falls through+ to it. Asking the video backend's own predicate keeps this from drifting away from it."""+ from core.inference.video_families import detect_video_family # noqa: PLC0415+ from core.inference.video_minimax_h3 import is_h3_native # noqa: PLC0415++ gguf = getattr(pick, "gguf_filename", None)+ for base in (pick.model_path, pick.model_id):+ if not base:+ continue+ # Repo id first, then repo id + picked filename, which is the order and the pair+ # video.py's own _detect_load_family uses: a local directory or a generically named repo+ # often carries the family token only in the checkpoint filename.+ for needle in (base, f"{base}/{gguf}" if gguf else None):+ if not needle:+ continue+ try:+ family = detect_video_family(needle)+ except Exception: # noqa: BLE001 -- a probe failure must not decide "native"+ continue+ if family is not None:+ return bool(is_h3_native(family, "gguf"))+ # Not covered 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.+ return False+++def prewarm_diffusers_if_image_models_exist() -> bool:+ """Import diffusers off the first image load. True iff this call did the import.++ Measured on this stack, the first diffusion load pays roughly 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 every+ first load in a fresh process, and all of it can be paid earlier by a thread nobody is+ waiting on.++ Gated on the install actually having a local image or video model, which is the whole point:+ a chat-only or training-only user never pays the 316 MB. The gate itself is stdlib only (it+ 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.++ Called from the POST-warm worker, after ``join_background_warm()``, so it cannot delay any+ coordinated warm stage or the socket bind. 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, because these are ordinary package imports that CPython's per module+ lock serialises, unlike the dynamo/inductor cycle in #10350.++ Never fatal, and opt out with ``UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1``."""+ global _diffusers_prewarmed+ if _diffusers_prewarmed:+ return False+ if os.environ.get(DIFFUSERS_PREWARM_DISABLE_ENV_VAR) == "1":+ return False+ # The torch opt-out covers this too. start_background_warm() declines under DISABLE_ENV_VAR,+ # but join_background_warm() reports True when no worker ever ran, so the post-warm thread+ # arrives here regardless; importing diffusers imports torch, which is precisely what that+ # variable exists to prevent. Checked here rather than at the call site so every caller gets+ # it, and so the warm-window tests that assert no unsolicited torch import keep holding.+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return False+ with _diffusers_prewarm_lock:+ if _diffusers_prewarmed:+ return False+ try:+ if not _a_local_model_would_load_through_diffusers():+ # Nothing diffusers would serve, so the import is pure cost. Not latched: a+ # model downloaded later should let the next lifespan reconsider.+ logger.debug("diffusers prewarm skipped: no local model routes to diffusers")+ return False+ except Exception as exc: # noqa: BLE001 -- a gate that cannot answer means skip, not crash+ logger.debug("diffusers prewarm gate unavailable: %r", exc)+ return False++ try:+ # core.inference.diffusion installs these at module scope, above its own lazy+ # `import diffusers`, because on Windows ROCm diffusers reaches xformers and torchao+ # and both land on an absent distributed backend. This prewarm can be the first+ # importer in the process, so it owes the same three installs; they are idempotent.+ from core._torchao_stub import ( # noqa: PLC0415+ install_torchao_windows_rocm_stub,+ install_xformers_windows_rocm_stub,+ )+ from core.inference.diffusion_torchao_patches import ( # noqa: PLC0415+ install_torchao_int_mm_patch,+ )++ install_xformers_windows_rocm_stub()+ install_torchao_windows_rocm_stub()+ install_torchao_int_mm_patch()+ except Exception as exc: # noqa: BLE001 -- importing unprotected is the hazard; skip+ logger.debug("diffusers prewarm skipped: stubs unavailable: %r", exc)+ return False++ started = time.perf_counter()+ # One lock at a time, never both. Each scope holds that package's own lock across its+ # import AND its cleanup, the way _held_import_lock does for the bare warm stages,+ # because releasing between the two is the bug: CPython drops the lock the moment the+ # import raises, so a request already waiting on it wakes up, re-imports against the+ # submodules that import left behind, and republishes the malformed package -- at which+ # point purge_partial_import declines, since those leftovers now belong to a live+ # importer. Reentrant per thread, so the nested acquire inside the purge is free.+ #+ # NOT nested, which is the part that is easy to get backwards. `import diffusers.hooks`+ # makes CPython take the CHILD lock first and import the parent from inside it+ # (_find_and_load -> _ModuleLockManager(name) -> _find_and_load_unlocked -> import+ # parent). Holding parent-then-child here would invert that against any concurrent+ # `from diffusers.hooks import ...` and produce a lock cycle, which surfaces as the+ # _DeadlockError that _lock_unlock_module swallows -- i.e. exactly the partially+ # initialised module this whole change exists to prevent. Sequential scopes have no+ # cycle: by the time the hooks scope runs, the parent is published, so importing the+ # child acquires nothing else.+ # The try INSIDE each with, not around it: exiting the scope on the exception would+ # release the lock and the handler would reacquire it, and that gap is the whole bug.+ # A request already waiting on the lock wakes up in it, re-imports against the submodules+ # the failed import left behind, and republishes the malformed package -- at which point+ # purge_partial_import declines, because those leftovers now belong to a live importer.+ # Reentrant per thread, so the nested acquire inside the purge is free.+ with _ModuleLockManager("diffusers"):+ try:+ import diffusers # noqa: F401, PLC0415+ except Exception as exc: # noqa: BLE001 -- the load path imports it again and reports+ logger.debug("diffusers prewarm skipped: %r", exc)+ purge_partial_import("diffusers")+ return False++ # A separate scope, never nested inside the one above. `import diffusers.hooks` makes+ # CPython take the CHILD lock first and import the parent from inside it (_find_and_load+ # -> _ModuleLockManager(name) -> _find_and_load_unlocked -> import parent). Holding+ # parent-then-child here would invert that against a concurrent `from diffusers.hooks+ # import ...` and produce a lock cycle, which surfaces as the _DeadlockError that+ # _lock_unlock_module swallows: exactly the partially initialised module this change+ # exists to prevent. Sequentially there is no cycle, because the parent is already+ # published by the time this runs, so importing the child acquires nothing else.+ with _ModuleLockManager("diffusers.hooks"):+ try:+ import diffusers.hooks # noqa: F401, PLC0415+ except Exception as exc: # noqa: BLE001 -- the load path imports it again and reports+ logger.debug("diffusers prewarm skipped: %r", exc)+ # The parent stays: it imported cleanly, and purging it would be a no-op anyway+ # since it is in sys.modules and belongs to nobody. What has to go is the hook+ # submodules that did execute, or the load path's own `from diffusers.hooks+ # import ...` rebuilds an incomplete package from them (#7580, one level down).+ purge_partial_import("diffusers.hooks")+ return False++ # Outside both locks: it imports nothing under diffusers. diffusers hard-codes+ # _tqdm_active = True at import and honours no env var, so a prewarm that skipped this+ # would let "Loading pipeline components..." draw straight onto the structlog stream,+ # mid-record. Not fatal to the prewarm: the imports above already succeeded, which is the+ # work this exists to do, and the load path calls the same idempotent helper anyway.+ try:+ from loggers.config import quiet_third_party_progress_bars # noqa: PLC0415++ quiet_third_party_progress_bars()+ except Exception as exc: # noqa: BLE001 -- cosmetic only+ logger.debug("quieting third-party progress bars failed: %r", exc)++ _diffusers_prewarmed = True+ logger.info(+ "diffusers prewarmed in %.0fms; the first image load skips that import",+ (time.perf_counter() - started) * 1000,+ )+ return True++def warm_status() -> dict:"""Snapshot of the warm for diagnostics and tests."""return {