Skip to content

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.

Studio: keep a load's diffusers / peft import off the post-warm import (#12572)

Daniel Han132af56b5a73
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 54f615a1007..06963b79c6d 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -384,6 +384,7 @@ import utils.hardware.hardware as _hw_module
from utils.torch_warmup import (
DISABLE_ENV_VAR,
+ background_media_import,
join_background_warm,
prewarm_diffusers_if_image_models_exist,
reset_background_warm,
@@ -655,18 +656,23 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:
# _dense_quant_supported). Gated on torch being up rather than assumed, since
# UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 exists precisely to keep the ML stack cold.
if "torch" in sys.modules:
- try:
- _refresh_dense_quant_capability()
- except Exception as _dq_exc: # noqa: BLE001 -- a picker label must never break the warm
- import structlog as _structlog
- _structlog.get_logger(__name__).debug("dense quant capability skipped: %s", _dq_exc)
- try:
- _refresh_quantised_streaming_capability()
- except Exception as _qs_exc: # noqa: BLE001 -- a picker tier must never break the warm
- import structlog as _structlog
- _structlog.get_logger(__name__).debug(
- "quantised streaming capability skipped: %s", _qs_exc
- )
+ # Inside the media import window: skipped once a load claimed it; /api/system resolves both later.
+ with background_media_import() as _window_open:
+ if _window_open:
+ try:
+ _refresh_dense_quant_capability()
+ except Exception as _dq_exc: # noqa: BLE001 -- a picker label must never break the warm
+ import structlog as _structlog
+ _structlog.get_logger(__name__).debug(
+ "dense quant capability skipped: %s", _dq_exc
+ )
+ try:
+ _refresh_quantised_streaming_capability()
+ except Exception as _qs_exc: # noqa: BLE001 -- a picker tier must never break the warm
+ import structlog as _structlog
+ _structlog.get_logger(__name__).debug(
+ "quantised streaming capability skipped: %s", _qs_exc
+ )
if _post_warm_retired(generation):
return
@@ -2451,9 +2457,18 @@ def _probe_quantised_streaming(supported: Any) -> bool:
def _quantised_streaming() -> bool:
"""The streaming bit for ``/api/system``. Resolved here only once a load has already loaded every
- module it reads, since a cold warm (UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1) never resolves it."""
+ module it reads, since a cold warm (UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1) never resolves it.
+ Needs each module initialised (probing mid-load races the load), not core.inference.video (image loads skip it)."""
if _quantised_streaming_capability is None and all(
- name in sys.modules for name in ("torch", "diffusers", "torchao", "core.inference.video")
+ (module := sys.modules.get(name)) is not None
+ and not getattr(getattr(module, "__spec__", None), "_initializing", False)
+ for name in (
+ "torch",
+ "torchao",
+ "diffusers",
+ "diffusers.hooks",
+ "diffusers.hooks.group_offloading",
+ )
):
try:
return _refresh_quantised_streaming_capability()
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 6e27ffa6cc1..3908109a1f4 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -189,6 +189,15 @@ def _reset_gpu_query_cache():
_reset()
[email protected](autouse = True)
+def _reset_media_import_window(monkeypatch):
+ # A load path claims the window for the process; later prewarm tests would skip.
+ warm = sys.modules.get("utils.torch_warmup")
+ if warm is not None and hasattr(warm, "_media_import_claimed"):
+ monkeypatch.setattr(warm, "_media_import_claimed", False)
+ monkeypatch.setattr(warm, "_media_import_owner", None)
+
+
@pytest.fixture(autouse = True)
def _isolate_studio_home(_studio_home_root, monkeypatch):
home = _studio_home_root / f"home-{next(_studio_home_counter)}"
diff --git a/studio/backend/tests/test_media_import_window.py b/studio/backend/tests/test_media_import_window.py
new file mode 100644
index 00000000000..d9ba226dabe
--- /dev/null
+++ b/studio/backend/tests/test_media_import_window.py
@@ -0,0 +1,182 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A load must not race the post-warm worker's diffusers / peft import (half-built modules:
+"cannot import name 'LoraLayer' from partially initialized module 'peft.tuners.lora'")."""
+
+from __future__ import annotations
+
+import ast
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+
+
+class _Log:
+ def __init__(self):
+ self.lines = []
+
+ def info(self, msg, *args):
+ self.lines.append(msg % args if args else msg)
+
+ warning = info
+ debug = info
+
+
+def warm(monkeypatch):
+ """``utils.torch_warmup`` with the dynamo latch set and the media window unclaimed."""
+ from utils import torch_warmup
+
+ monkeypatch.setattr(torch_warmup, "_dynamo_done", True)
+ monkeypatch.setattr(torch_warmup, "_media_import_claimed", False)
+ monkeypatch.setattr(torch_warmup, "_diffusers_prewarmed", False)
+ monkeypatch.delenv(torch_warmup.DIFFUSERS_PREWARM_DISABLE_ENV_VAR, raising = False)
+ monkeypatch.delenv(torch_warmup.DISABLE_ENV_VAR, raising = False)
+ return torch_warmup
+
+
+def test_the_load_waits_for_a_background_import_in_flight(warm):
+ """The reported race: the load blocks in close_dynamo_import_window until the import ends."""
+ in_window = threading.Event()
+ release = threading.Event()
+
+ def _background():
+ with warm.background_media_import() as window_open:
+ assert window_open
+ in_window.set()
+ release.wait(10)
+
+ bg = threading.Thread(target = _background)
+ bg.start()
+ assert in_window.wait(10)
+
+ log = _Log()
+ done = threading.Event()
+ load = threading.Thread(target = lambda: (warm.close_dynamo_import_window(log), done.set()))
+ load.start()
+ try:
+ # Still importing in the background: the load has not passed the gate.
+ assert not done.wait(0.5), "the load entered diffusers while a background import ran"
+ finally:
+ release.set()
+ bg.join(10)
+ assert done.wait(10)
+ load.join(10)
+ assert any("waiting for the background diffusers import" in line for line in log.lines)
+ assert warm._media_import_claimed is True
+
+
+def test_background_work_stands_down_once_a_load_claimed_the_window(warm):
+ """The other order: the load got there first, so the background must not import at all."""
+ assert warm.close_dynamo_import_window(_Log()) is True
+ with warm.background_media_import() as window_open:
+ assert window_open is False
+
+
+def test_background_work_runs_while_no_load_has_claimed_it(warm):
+ with warm.background_media_import() as window_open:
+ assert window_open is True
+
+
+def test_a_load_path_reached_from_background_work_does_not_wait_on_itself(warm):
+ """The window lock is not reentrant: a background probe reaching a load helper passes through."""
+ result = []
+
+ def _background():
+ with warm.background_media_import() as window_open:
+ assert window_open
+ result.append(warm.close_dynamo_import_window(_Log()))
+
+ t = threading.Thread(target = _background, daemon = True)
+ t.start()
+ t.join(5)
+ assert not t.is_alive(), "background work deadlocked on its own window"
+ assert result == [True]
+ # The background thread does not claim the window for loads.
+ assert warm._media_import_claimed is False
+
+
+def test_claiming_is_idempotent_and_cheap_once_claimed(warm):
+ assert warm.claim_media_import_window() is True
+ started = time.perf_counter()
+ for _ in range(1000):
+ assert warm.claim_media_import_window() is True
+ assert time.perf_counter() - started < 1.0
+
+
+def test_the_prewarm_skips_once_a_load_claimed_the_window(warm, monkeypatch):
+ """After a load claimed the window the prewarm must not even consult its gate."""
+ called = []
+ monkeypatch.setattr(
+ warm, "_a_local_model_would_load_through_diffusers", lambda: called.append(1) or True
+ )
+ warm.claim_media_import_window()
+ assert warm.prewarm_diffusers_if_image_models_exist() is False
+ assert called == []
+ # Not latched: a later lifespan may still prewarm.
+ assert warm._diffusers_prewarmed is False
+
+
+def test_the_prewarm_imports_inside_the_window(warm, monkeypatch):
+ """A load arriving mid-prewarm must wait: the prewarm holds the window while it imports."""
+ seen = {}
+
+ def _gate():
+ seen["locked"] = warm._media_import_lock.locked()
+ return False # stop before any real import
+
+ monkeypatch.setattr(warm, "_a_local_model_would_load_through_diffusers", _gate)
+ assert warm.prewarm_diffusers_if_image_models_exist() is False
+ assert seen == {"locked": True}
+ assert not warm._media_import_lock.locked()
+
+
+def _function(name: str) -> ast.FunctionDef:
+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ return node
+ raise AssertionError(f"{name} not found in main.py")
+
+
+def _calls_inside_window(fn: ast.FunctionDef) -> set:
+ names = set()
+ for node in ast.walk(fn):
+ if not isinstance(node, ast.With):
+ continue
+ if not any(
+ isinstance(item.context_expr, ast.Call)
+ and getattr(item.context_expr.func, "id", None) == "background_media_import"
+ for item in node.items
+ ):
+ continue
+ for inner in ast.walk(node):
+ if isinstance(inner, ast.Call) and isinstance(inner.func, ast.Name):
+ names.add(inner.func.id)
+ return names
+
+
+def test_the_post_warm_probes_import_inside_the_window():
+ inside = _calls_inside_window(_function("_post_warm_background_work"))
+ assert "_refresh_quantised_streaming_capability" in inside
+ assert "_refresh_dense_quant_capability" in inside
+
+
+def test_close_dynamo_import_window_claims_the_media_window():
+ """Every media load path calls it first (pinned by test_dynamo_import_window.py)."""
+ src = ast.get_source_segment(
+ (_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8"),
+ next(
+ node
+ for node in ast.parse(
+ (_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8")
+ ).body
+ if isinstance(node, ast.FunctionDef) and node.name == "close_dynamo_import_window"
+ ),
+ )
+ assert "claim_media_import_window(" in src
diff --git a/studio/backend/tests/test_quantised_streaming_capability.py b/studio/backend/tests/test_quantised_streaming_capability.py
index d261d773123..8153bdb453c 100644
--- a/studio/backend/tests/test_quantised_streaming_capability.py
+++ b/studio/backend/tests/test_quantised_streaming_capability.py
@@ -78,8 +78,7 @@ def test_the_refresh_caches_the_prequant_verdict(monkeypatch, supported):
@pytest.mark.parametrize("loaded", [True, False])
def test_a_cold_warm_resolves_it_once_a_load_has_loaded_the_stack(monkeypatch, loaded):
"""UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 skips the warm refresh; a later load must still publish the bit."""
- names = ("torch", "diffusers", "torchao", "core.inference.video")
- for name in names:
+ for name in _STREAMING_MODULES:
if loaded:
monkeypatch.setitem(sys.modules, name, types.ModuleType(name))
else:
@@ -92,6 +91,46 @@ def test_a_cold_warm_resolves_it_once_a_load_has_loaded_the_stack(monkeypatch, l
assert calls == ([1] if loaded else [])
+def test_an_image_load_alone_resolves_it(monkeypatch):
+ """An early image load makes the post-warm probe stand down and never loads core.inference.video,
+ so requiring it kept the streamed tier hidden for the rest of the process."""
+ for name in _STREAMING_MODULES:
+ monkeypatch.setitem(sys.modules, name, types.ModuleType(name))
+ monkeypatch.delitem(sys.modules, "core.inference.video", raising = False)
+ namespace: dict = {"_quantised_streaming_capability": None, "sys": sys}
+ exec(_src("_quantised_streaming"), namespace) # noqa: S102
+ namespace["_refresh_quantised_streaming_capability"] = lambda: True
+ assert namespace["_quantised_streaming"]() is True
+
+
+_STREAMING_MODULES = (
+ "torch",
+ "torchao",
+ "diffusers",
+ "diffusers.hooks",
+ "diffusers.hooks.group_offloading",
+)
+
+
[email protected]("half_built", _STREAMING_MODULES)
+def test_the_poll_waits_until_a_loads_import_has_finished(monkeypatch, half_built):
+ """Probing while a load still imports diffusers failed that load ("Failed to import
+ diffusers.loaders.peft"), so a module still initialising defers the refresh."""
+ for name in _STREAMING_MODULES:
+ module = types.ModuleType(name)
+ module.__spec__ = types.SimpleNamespace(_initializing = name == half_built)
+ monkeypatch.setitem(sys.modules, name, module)
+ calls: list = []
+ namespace: dict = {"_quantised_streaming_capability": None, "sys": sys}
+ exec(_src("_quantised_streaming"), namespace) # noqa: S102
+ namespace["_refresh_quantised_streaming_capability"] = lambda: calls.append(1) or True
+ assert namespace["_quantised_streaming"]() is False
+ assert calls == []
+ sys.modules[half_built].__spec__._initializing = False
+ assert namespace["_quantised_streaming"]() is True
+ assert calls == [1]
+
+
def test_a_mixed_host_offers_the_tier_only_when_every_card_qualifies(monkeypatch):
"""A load can be pinned to any card; one resolving to float16 would keep the bf16 denoiser."""
namespace = _exec_refresh(monkeypatch, lambda target = None: target != 1, device_count = 2)
diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.py
index f69646a6b00..6c7c8994739 100644
--- a/studio/backend/utils/torch_warmup.py
+++ b/studio/backend/utils/torch_warmup.py
@@ -340,7 +340,10 @@ def close_dynamo_import_window(log) -> bool:
`import diffusers` is itself a dynamo importer, so every media load path owes this call in
front of its first one. A warning, not a retry: a process that lost the race does not
recover. Wrap the IMPORT of this module too, since it reaches a private CPython name."""
- if ensure_dynamo_imported(log = log, reason = "diffusers import"):
+ imported = ensure_dynamo_imported(log = log, reason = "diffusers import")
+ # Not nested in the dynamo gate: the background import it waits on reaches torch._dynamo.
+ claim_media_import_window(log)
+ if imported:
return True
log.warning(
"torch._dynamo is not importable in this process; "
@@ -349,6 +352,52 @@ def close_dynamo_import_window(log) -> bool:
return False
+# diffusers and peft are circular graphs: a load and the post-warm worker importing them from
+# different entry points get a half-built module ("partially initialized module 'peft.tuners.lora'").
+_media_import_lock = threading.Lock()
+_media_import_claimed = False
+_media_import_owner: Optional[int] = None
+
+
+@contextmanager
+def background_media_import():
+ """Hold the window for background work; yields False once a load has claimed it (skip then)."""
+ global _media_import_owner
+ with _media_import_lock:
+ _media_import_owner = threading.get_ident()
+ try:
+ yield not _media_import_claimed
+ finally:
+ _media_import_owner = None
+
+
+def claim_media_import_window(log = None) -> bool:
+ """Wait out a background media import in flight, then keep later ones off. False on timeout."""
+ global _media_import_claimed
+ if _media_import_claimed or _media_import_owner == threading.get_ident():
+ return True
+ if not _media_import_lock.acquire(blocking = False):
+ waited = time.perf_counter()
+ if log is not None:
+ log.info("diffusers import: waiting for the background diffusers import to finish")
+ if not _media_import_lock.acquire(timeout = _dynamo_gate_timeout()):
+ (log or logger).warning(
+ "diffusers import: gave up waiting for the background diffusers import after %.0fs",
+ time.perf_counter() - waited,
+ )
+ return False
+ if log is not None:
+ log.info(
+ "diffusers import: background import finished after waiting %.1fs",
+ time.perf_counter() - waited,
+ )
+ try:
+ _media_import_claimed = True
+ return True
+ finally:
+ _media_import_lock.release()
+
+
_STAGES = (
("hardware", _warm_hardware),
("inference_backend", _warm_inference_backend),
@@ -572,8 +621,8 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
training-only user never pays it. The gate itself is stdlib only.
Called from the POST-warm worker, after ``join_background_warm()``, so it cannot delay a
- warm stage or the socket bind. Concurrent submodule imports are safe here, unlike the
- dynamo cycle in #10350: CPython's per-module lock serialises ordinary imports.
+ warm stage or the socket bind. Imports inside the media import window; skips once a load
+ has claimed it.
Never fatal, and opt out with ``UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1``."""
global _diffusers_prewarmed
@@ -585,9 +634,12 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
# here even under DISABLE_ENV_VAR, and diffusers imports torch.
if os.environ.get(DISABLE_ENV_VAR) == "1":
return False
- with _diffusers_prewarm_lock:
+ with _diffusers_prewarm_lock, background_media_import() as window_open:
if _diffusers_prewarmed:
return False
+ if not window_open:
+ logger.debug("diffusers prewarm skipped: a load is importing diffusers")
+ return False
try:
if not _a_local_model_would_load_through_diffusers():
# Not latched: a model downloaded later lets the next lifespan reconsider.
@@ -670,8 +722,9 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
"diffusers prewarmed in %.0fms; the first image load skips that import",
(time.perf_counter() - started) * 1000,
)
- _prewarm_quant_probe()
- return True
+ # Outside the window: a child-process probe, not an import.
+ _prewarm_quant_probe()
+ return True
def warm_status() -> dict: