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: defer optional GPU startup work (#8564)

Wasim Yousef Said3c590a536458
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
index 91040f6868a..626fab772d9 100644
--- a/studio/backend/hub/utils/download_registry.py
+++ b/studio/backend/hub/utils/download_registry.py
@@ -104,12 +104,13 @@ def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTrans
auto_reason: Optional[str] = None
if xet_available:
try:
- from utils.hf_xet_fallback import xet_health
+ from utils.hf_xet_fallback import cached_xet_health, xet_health
- # Default probe = False: the UI polls this endpoint, so it answers from the cached
- # verdict and local signals. The download-start path opts in, since otherwise a host
- # with an unreachable CAS and no recorded failures yet would learn only by stalling.
- health = xet_health(probe = probe)
+ # Ordinary UI polls are read-only and must not load Zoo. `probe=True` is different:
+ # the frontend sends it only while resolving Auto for a download, then submits the
+ # concrete answer as xet/http, so this is the actual first-download decision.
+ health_fn = xet_health if probe else cached_xet_health
+ health = health_fn(probe = probe)
if health is not None:
auto_transport = TRANSPORT_XET if health.use_xet else TRANSPORT_HTTP
auto_reason = str(health.reason)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index c0eb2de8196..c5c5756dbf1 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -492,20 +492,6 @@ def _start_llama_cpp_probes_if_enabled(app: FastAPI) -> None:
).start()
-def _warm_rag_embedder() -> None:
- """Warm RAG embeddings without blocking backend readiness."""
- try:
- from storage import rag_db
-
- if not rag_db.RAG_AVAILABLE:
- return
- from core.rag import embeddings
-
- embeddings.warm()
- except Exception:
- pass
-
-
_post_warm_thread: Optional[threading.Thread] = None
_post_warm_lock = threading.Lock()
# Bumped by every start and stop. A worker captures the value it started with and stops once
@@ -555,9 +541,9 @@ def _stop_post_warm_thread() -> None:
def _post_warm_retired(generation: Optional[int]) -> bool:
"""True when this post-warm worker's lifespan has ended. Logs once when it has.
- A mismatch means the application that wanted this work has stopped. Everything the
- worker does imports or loads something, and the RAG warm can spawn a llama-server, so
- none of it may start for a stopped lifespan.
+ A mismatch means the application that wanted this work has stopped. The remaining
+ work imports optional platform or RAG scheduling modules, so none of it may start for
+ a stopped lifespan.
"""
if generation is None or _post_warm_current_generation() == generation:
return False
@@ -590,14 +576,11 @@ def _start_linked_folder_auto_sync(generation: Optional[int]) -> None:
def _post_warm_background_work(generation: Optional[int] = None) -> None:
- """Stack-dependent startup work, run after the coordinated warm.
-
- Both import the ML stack, and both used to do it their own way before the socket bound:
- the MLX check inline on the lifespan thread (a healthy Mac waited on mlx.core/mlx_lm/
- mlx_vlm before uvicorn could bind), the RAG embedder early enough to race the warm for
- the GIL and the import locks, outside its hardware-first order and purge-on-failure.
+ """Platform repair and linked-folder lifecycle work after the coordinated warm.
- Joining the warm first means the stack is imported once, in the intended order.
+ MLX repair used to probe the runtime before the socket bound. Joining first keeps that
+ optional probe out of the login-screen critical path. Linked-folder startup only loads
+ embeddings when a queued sync has real ingestion work; an idle scheduler stays cold.
"""
# No-op when the warm never started, so this is safe under the kill switch.
join_background_warm()
@@ -622,15 +605,6 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:
return
_start_linked_folder_auto_sync(generation)
- # Only the RAG warm is gated: it pulls sentence-transformers/transformers/torch. MLX
- # autorepair and linked-folder scheduling have their own lifecycles.
- if os.environ.get(DISABLE_ENV_VAR) == "1":
- return
-
- if _post_warm_retired(generation):
- return
- _warm_rag_embedder()
-
def clear_compiled_cache_unless_shared(app: FastAPI) -> None:
"""Clear the compiled cache unless a sibling backend of this install is live.
@@ -710,7 +684,7 @@ async def lifespan(app: FastAPI):
except Exception as exc:
_lifespan_log.warning("reconcile_orphaned_ingestion_jobs failed at startup: %s", exc)
- # The RAG embedder warm moved to _post_warm_background_work: here it raced for the GIL.
+ # Embeddings stay cold until ingestion or retrieval actually requests vectors.
_start_helper_precache_if_enabled()
from core.research_runs import ResearchSupervisor
@@ -766,6 +740,13 @@ async def lifespan(app: FastAPI):
# Before any shutdown await: a warm finishing during one would still read the lifespan as current.
_stop_post_warm_thread()
+ # Retire the coordinated warm at shutdown entry too. run_lifespan_shutdown() repeats
+ # this after cleanup, but its awaits would otherwise let startup imports continue for
+ # a lifespan that has already stopped.
+ _invalidate_detection = getattr(_hw_module, "invalidate_detection", None)
+ if _invalidate_detection is not None:
+ _invalidate_detection()
+
from core.inference.openai_codex_auth import shutdown_flows
await shutdown_flows()
@@ -775,13 +756,6 @@ async def lifespan(app: FastAPI):
except Exception as exc:
_lifespan_log.warning("linked-folder auto-sync failed at shutdown: %s", exc)
- # Same for the coordinated warm: retiring its epoch stops it at the next stage boundary.
- # run_lifespan_shutdown() also invalidates, but only after several awaits, through which the
- # warm keeps importing for a stopped lifespan. Retiring twice is harmless; getattr for tests.
- _invalidate_detection = getattr(_hw_module, "invalidate_detection", None)
- if _invalidate_detection is not None:
- _invalidate_detection()
-
_idle_task = getattr(app.state, "idle_unload_task", None)
if _idle_task is not None:
_idle_task.cancel()
@@ -1576,8 +1550,8 @@ def _torch_warm_in_progress() -> bool:
"""True while the coordinated warm thread is still working through its stages.
A separate field from ``hardware_detecting`` on purpose, rather than widening that one.
- Hardware detection is only ``_STAGES[0]``; inference_backend, transformers, datasets and
- unsloth_zoo import after it, and those C-extension imports are the ones that hold the GIL
+ Hardware detection is only ``_STAGES[0]``; inference_backend, transformers, and datasets
+ run after it, and those C-extension imports can hold the GIL
for seconds at a time. A launcher ending its startup grace on ``hardware_detecting``
alone ends it with the expensive half of the warm still ahead of it, which is the window
the grace exists for. But that marker also means "this hardware verdict is provisional,
@@ -1617,8 +1591,8 @@ async def liveness_check():
# are the point of the route: it probes liveness every 15s and holds its startup grace
# period open until a reply says the warm-up is over, because the warm thread's
# `import torch` holds the GIL and can stall the next probes on a healthy process.
- # The watchdog reads torch_warm_in_progress for that, not hardware_detecting: the GIL is
- # held just as hard by transformers and unsloth_zoo, which import after detection settles.
+ # The watchdog reads torch_warm_in_progress for that, not hardware_detecting: later
+ # transformers and datasets stages can also hold the GIL after detection settles.
# Both are non-blocking reads of module-level state, so unlike health this neither starts
# detection nor waits on it and the route stays cheap.
if _torch_warm_in_progress():
diff --git a/studio/backend/tests/test_hf_xet_fallback.py b/studio/backend/tests/test_hf_xet_fallback.py
index 8455faaf8a2..8ad7b15cb93 100644
--- a/studio/backend/tests/test_hf_xet_fallback.py
+++ b/studio/backend/tests/test_hf_xet_fallback.py
@@ -100,6 +100,9 @@ def test_shim_injects_studio_prepare_on_http_retry(monkeypatch):
_requires_shared()
for var in ("UNSLOTH_DISABLE_XET", "UNSLOTH_STABLE_DOWNLOADS", "HF_HUB_DISABLE_XET"):
monkeypatch.delenv(var, raising = False)
+ # This seam checks the Xet -> HTTP transition, not the independently configurable
+ # number of Xet retries (newer Zoo releases default to two).
+ monkeypatch.setenv("UNSLOTH_XET_ATTEMPTS", "1")
monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", lambda *a, **k: None)
seen_disable_xet = []
@@ -597,6 +600,28 @@ def test_importing_child_should_disable_xet_stays_light(monkeypatch):
assert "unsloth_zoo" not in sys.modules, "importing the shim must not import unsloth_zoo"
+def test_first_download_dispatch_loads_zoo_once(monkeypatch):
+ """Import stays light, but a real download dispatch activates the shared Zoo helper."""
+ import utils.hf_xet_fallback as shim
+
+ calls: list[str] = []
+
+ class _FakeShared:
+ @staticmethod
+ def hf_hub_download_with_xet_fallback(*args, **kwargs):
+ calls.append("download")
+ return "/cache/model.bin"
+
+ monkeypatch.setattr(shim, "_shared", _FakeShared, raising = False)
+ monkeypatch.setattr(shim, "_load_shared", lambda: calls.append("load") or True, raising = True)
+
+ assert (
+ shim.hf_hub_download_with_xet_fallback("org/model", "model.bin", None, cache_dir = "/cache")
+ == "/cache/model.bin"
+ )
+ assert calls == ["load", "download"]
+
+
def test_start_watchdog_drops_kwargs_the_installed_zoo_cannot_take(monkeypatch):
"""Version-skew adapter, and load-bearing: the floor's start_watchdog is keyword-only with no
**kwargs and no connect_timeout, so passing one raises TypeError into the caller's
diff --git a/studio/backend/tests/test_hub_download_transport_auto.py b/studio/backend/tests/test_hub_download_transport_auto.py
index cca1d05d2da..0df90595edc 100644
--- a/studio/backend/tests/test_hub_download_transport_auto.py
+++ b/studio/backend/tests/test_hub_download_transport_auto.py
@@ -356,10 +356,12 @@ def test_recording_a_failure_never_raises(monkeypatch):
def test_capabilities_report_what_auto_resolves_to(monkeypatch):
fake = _types.ModuleType("utils.hf_xet_fallback")
- fake.xet_health = lambda **kw: _types.SimpleNamespace(
+ fake.cached_xet_health = lambda **kw: _types.SimpleNamespace(
use_xet = False,
reason = "Xet failed 2 times in a row on this machine",
)
+
+ fake.xet_health = fake.cached_xet_health
monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)
caps = download_registry.get_download_transport_capabilities()
if not caps.xet.available:
@@ -374,6 +376,8 @@ def test_capabilities_stay_optimistic_when_health_raises(monkeypatch):
def _boom(**kw):
raise RuntimeError("no")
+ fake.cached_xet_health = _boom
+
fake.xet_health = _boom
monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)
caps = download_registry.get_download_transport_capabilities()
@@ -435,40 +439,62 @@ def test_optional_loader_returns_none_when_truly_absent(monkeypatch):
shim.record_xet_outcome(False, "x")
-def test_capabilities_probe_is_opt_in(monkeypatch):
- """The UI polls this endpoint on render, so it must stay cheap by default. The download-start
- path opts in: a host with an unreachable CAS and no recorded failure yet would otherwise learn
- by stalling."""
+def test_capabilities_read_does_not_load_zoo(monkeypatch):
+ """Opening Hub asks for capabilities; that read must not initialize optional GPU consumers."""
+ import utils.hf_xet_fallback as shim
+
+ monkeypatch.setattr(shim, "_optional_modules", {})
+
+ loaded: list[str] = []
+ monkeypatch.setattr(
+ shim,
+ "_load_optional",
+ lambda module_name: loaded.append(module_name),
+ )
+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", shim)
+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())
+
+ caps = download_registry.get_download_transport_capabilities()
+
+ assert caps.xet.available is True
+ assert caps.auto_resolves_to == download_registry.TRANSPORT_XET
+ assert loaded == [], "a read-only capability request imported Unsloth Zoo"
+
+
+def test_download_start_probe_loads_health_after_cached_browse(monkeypatch):
+ """Auto's probe resolves the submitted xet/http mode, so it must load fresh health."""
from hub.utils import download_registry
- seen: list[bool] = []
+ seen: list[tuple[str, bool]] = []
class _Health:
use_xet = False
reason = "probed: CAS unreachable"
- def _fake_health(*, probe = True):
- seen.append(probe)
+ def _cached_health(*, probe = True):
+ seen.append(("cached", probe))
+ return None
+
+ def _loading_health(*, probe = True):
+ seen.append(("loading", probe))
return _Health()
- # Patch the sys.modules entry, not an imported alias: the endpoint does a local
- # `from utils.hf_xet_fallback import xet_health`, and test_hf_xet_fallback.py swaps that
- # sys.modules entry in and out, so an alias captured here can be a different module object.
+ # Patch sys.modules because the endpoint imports both helpers locally.
import sys
import types
stub = types.ModuleType("utils.hf_xet_fallback")
- stub.xet_health = _fake_health
+ stub.cached_xet_health = _cached_health
+ stub.xet_health = _loading_health
monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", stub)
+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())
- caps = download_registry.get_download_transport_capabilities()
- if not caps.xet.available:
- # The health lookup sits behind an hf_xet availability check, so with no hf_xet installed
- # neither call reaches it.
- pytest.skip("hf_xet is not installed in this environment")
- download_registry.get_download_transport_capabilities(probe = True)
+ browse = download_registry.get_download_transport_capabilities()
+ download = download_registry.get_download_transport_capabilities(probe = True)
- assert seen == [False, True]
+ assert browse.auto_resolves_to == download_registry.TRANSPORT_XET
+ assert download.auto_resolves_to == download_registry.TRANSPORT_HTTP
+ assert seen == [("cached", False), ("loading", True)]
def test_gpu_init_override_is_serialized(monkeypatch):
diff --git a/studio/backend/tests/test_rag_embeddings.py b/studio/backend/tests/test_rag_embeddings.py
index 197ae4c4959..fddb4d9be48 100644
--- a/studio/backend/tests/test_rag_embeddings.py
+++ b/studio/backend/tests/test_rag_embeddings.py
@@ -79,6 +79,27 @@ def _hammer(fn, n = 8):
return errors
+def test_first_encode_builds_the_selected_backend_once(monkeypatch):
+ """Importing the facade is inert; the first real vector operation owns construction."""
+ builds: list[str] = []
+
+ class _Backend:
+ def encode(self, texts, **_kwargs):
+ return np.zeros((len(texts), 4), dtype = np.float32)
+
+ def _build():
+ builds.append("backend")
+ return _Backend()
+
+ monkeypatch.setattr(embeddings, "_build_st_backend_or_fallback", _build)
+
+ assert embeddings._backend is None
+ embeddings.encode(["first"])
+ embeddings.encode(["second"])
+
+ assert builds == ["backend"]
+
+
def test_encode_is_serialized(monkeypatch):
probe = _ConcurrencyProbe()
monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _FakeModel(probe))
diff --git a/studio/backend/tests/test_startup_defers_stack_dependent_work.py b/studio/backend/tests/test_startup_defers_stack_dependent_work.py
index d23d583bcaf..dfc94821505 100644
--- a/studio/backend/tests/test_startup_defers_stack_dependent_work.py
+++ b/studio/backend/tests/test_startup_defers_stack_dependent_work.py
@@ -1,13 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Stack-dependent startup work must not run before the socket binds.
+"""Optional GPU consumers must stay cold through normal backend startup.
-Two pieces of work import the ML stack: the MLX availability probe (the MLX runtime) and
-the RAG embedder warm (sentence-transformers/transformers/torch). Uvicorn binds only once
-the lifespan yields, so doing either on the lifespan thread, or on a thread early enough to
-race the warm for the GIL and the import locks, puts that import back in front of the login
-screen. Both now run on the post-warm thread, which joins the warm first.
+MLX repair remains deferred until after the coordinated warm, and linked-folder lifecycle
+management remains active. The RAG embedder is different: startup must never warm it. A linked
+folder sync with real queued ingestion may activate embeddings through the ordinary operation.
"""
from __future__ import annotations
@@ -59,20 +57,16 @@ def test_lifespan_does_not_probe_mlx_before_yielding():
)
-def test_lifespan_does_not_start_the_rag_warm_before_yielding():
- referenced = _names_called(_lifespan_body())
- assert "_warm_rag_embedder" not in referenced, (
- "the RAG embedder warm is started from the lifespan again; it imports "
- "sentence-transformers/transformers/torch and races the coordinated warm"
- )
+def test_no_startup_worker_warms_the_rag_embedder():
+ referenced = _names_called(_lifespan_body()) | _names_called(_post_warm_body())
+ assert "_warm_rag_embedder" not in referenced
+ assert (
+ "warm" not in referenced
+ ), "startup calls an eager warm method; embeddings must load only from a real RAG operation"
-def test_post_warm_thread_joins_the_warm_before_doing_stack_work():
+def test_post_warm_thread_joins_before_platform_repair_and_folder_scheduling():
body = _post_warm_body()
- statements = [n for n in body.body if not isinstance(n, ast.Expr) or True]
-
- # The join has to come first, or these imports race the warm instead of
- # building on it.
join_line = None
work_lines = []
for sub in ast.walk(body):
@@ -80,50 +74,25 @@ def test_post_warm_thread_joins_the_warm_before_doing_stack_work():
join_line = sub.lineno if join_line is None else min(join_line, sub.lineno)
if isinstance(sub, ast.Name) and sub.id in {
"start_mlx_autorepair_if_needed",
- "_warm_rag_embedder",
+ "_start_linked_folder_auto_sync",
}:
work_lines.append(sub.lineno)
assert join_line is not None, "_post_warm_background_work must join the warm"
- assert work_lines, "_post_warm_background_work must do the deferred work"
- assert join_line < min(work_lines), (
- "join_background_warm() must precede the stack-dependent work, "
- f"got join at {join_line} and work at {sorted(work_lines)}"
- )
- assert statements, "body must not be empty"
-
+ assert work_lines, "post-warm lifecycle work was dropped"
+ assert join_line < min(work_lines)
-def test_post_warm_work_honours_the_coordinated_warm_kill_switch():
- """The switch must gate the torch-dependent work, and only that.
- It used to be the first statement, which also skipped MLX autorepair. That one is not
- torch, has its own UNSLOTH_DISABLE_MLX_AUTOREPAIR opt-out, and ran unconditionally
- before the deferral, so skipping it left a broken-MLX Mac chat-only for good. Ordering
- against autorepair is pinned in test_warm_window_review_fixes.py."""
+def test_post_warm_work_has_no_rag_warm_kill_switch_branch():
+ """With no eager torch/RAG work, the post-warm worker needs no torch kill-switch gate."""
body = _post_warm_body()
guards = [
node
for node in body.body
if isinstance(node, ast.If) and "DISABLE_ENV_VAR" in ast.unparse(node.test)
]
- assert guards, "the kill-switch guard is gone; the RAG warm would import torch anyway"
- guard = guards[0]
- condition = ast.unparse(guard.test)
- assert "os.environ" in condition
- assert any(isinstance(node, ast.Return) for node in guard.body)
-
- # Everything after the guard is what the switch actually disables.
- after = body.body[body.body.index(guard) + 1 :]
- protected = {
- sub.func.id
- for stmt in after
- for sub in ast.walk(stmt)
- if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)
- }
- assert "_warm_rag_embedder" in protected, (
- "the RAG warm is no longer behind the kill switch, so a --no-torch host "
- "still pulls sentence-transformers and torch at startup"
- )
+ assert guards == []
+ assert "_warm_rag_embedder" not in _names_called(body)
def test_post_warm_thread_is_started_by_the_lifespan():
@@ -134,8 +103,8 @@ def test_post_warm_thread_is_started_by_the_lifespan():
assert "_start_post_warm_thread" in referenced or (
"_post_warm_background_work" in referenced
), (
- "nothing starts the post-warm thread, so the MLX autorepair and the RAG "
- "warm would never run"
+ "nothing starts the post-warm thread, so MLX autorepair and linked-folder "
+ "lifecycle management would never run"
)
# ...and the helper must target the real work, or a do-nothing thread passes.
@@ -148,10 +117,7 @@ def test_post_warm_thread_is_started_by_the_lifespan():
assert "_post_warm_background_work" in _names_called(starter)
-def test_post_warm_actually_runs_both_pieces_of_work(monkeypatch):
- """Deferring must not become dropping. The lexical tests above would still pass if the
- deferred work never ran at all, silently ending MLX self-healing and leaving the RAG
- embedder cold."""
+def test_post_warm_runs_repair_and_linked_folder_lifecycle(monkeypatch):
import main as main_mod
import utils.mlx_repair as mlx_mod
@@ -160,19 +126,18 @@ def test_post_warm_actually_runs_both_pieces_of_work(monkeypatch):
monkeypatch.setattr(
mlx_mod, "start_mlx_autorepair_if_needed", lambda: order.append("mlx") or False
)
- monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: order.append("rag"))
+ monkeypatch.setattr(
+ main_mod,
+ "_start_linked_folder_auto_sync",
+ lambda generation: order.append("folder-sync"),
+ )
main_mod._post_warm_background_work()
- assert order == [
- "join",
- "mlx",
- "rag",
- ], f"post-warm work did not run in the intended order, got {order}"
+ assert order == ["join", "mlx", "folder-sync"]
-def test_a_failing_mlx_probe_does_not_strand_the_rag_warm(monkeypatch):
- """One deferred stage failing must not take the other down with it."""
+def test_a_failing_mlx_probe_does_not_strand_linked_folder_startup(monkeypatch):
import main as main_mod
import utils.mlx_repair as mlx_mod
@@ -183,8 +148,10 @@ def test_a_failing_mlx_probe_does_not_strand_the_rag_warm(monkeypatch):
raise RuntimeError("mlx probe exploded")
monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", _boom)
- monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))
+ monkeypatch.setattr(
+ main_mod, "_start_linked_folder_auto_sync", lambda generation: ran.append("folder-sync")
+ )
main_mod._post_warm_background_work()
- assert ran == ["rag"], "a failing MLX probe must not skip the RAG warm"
+ assert ran == ["folder-sync"]
diff --git a/studio/backend/tests/test_startup_defers_torch.py b/studio/backend/tests/test_startup_defers_torch.py
index eeb7ade0c6b..c222ec4ca68 100644
--- a/studio/backend/tests/test_startup_defers_torch.py
+++ b/studio/backend/tests/test_startup_defers_torch.py
@@ -79,6 +79,8 @@ def test_import_main_does_not_import_torch():
"utils.datasets.raw_text",
"core.inference.orchestrator",
"routes.models",
+ "utils.hf_xet_fallback",
+ "core.rag.embeddings",
],
)
def test_module_import_does_not_pull_torch(module_path: str):
@@ -202,60 +204,22 @@ def test_warm_starts_once_and_honours_the_kill_switch(monkeypatch):
assert status["stages"]["noop"]["ok"] is True
-def test_the_warm_covers_every_package_import_main_used_to_pull():
- """Deferring an import only moves its cost if something still pays it. One stage per
- package `import main` used to leave in sys.modules; dropping one fails no other test,
- it silently moves that import onto the first request."""
+def test_the_warm_keeps_optional_gpu_consumers_cold():
+ """Startup prepares hardware and metadata, but first-use integrations stay lazy."""
from utils import torch_warmup
- assert [name for name, _ in torch_warmup._STAGES] == [
+
+ stage_names = [name for name, _ in torch_warmup._STAGES]
+ assert stage_names == [
"hardware", # torch, via utils.hardware
- # Not a package import: builds the orchestrator singleton, whose constructor
- # waits on the detection a first request would otherwise pay for. Right after
- # hardware so it reuses this thread's.
+ # Builds the metadata-only orchestrator after hardware detection.
"inference_backend",
- "transformers", # via model_config's registry read
- "datasets", # via utils/datasets/raw_text.py
- "unsloth_zoo", # via orchestrator's utils.hf_xet_fallback import
+ "transformers", # model_config registry read
+ "datasets", # raw-text dataset helpers
]
-
-
-def test_the_unsloth_zoo_stage_goes_through_the_shim(monkeypatch):
- """The warm must reproduce the eager import, not just import the package. The edge it
- replaces was orchestrator.py's ``from utils.hf_xet_fallback import DownloadStallError``,
- and the shim retries under UNSLOTH_ZOO_DISABLE_GPU_INIT=1 when unsloth_zoo's GPU init
- raises. A bare ``import unsloth_zoo`` skips that retry and fails where startup
- succeeded."""
- import builtins
- import importlib
-
- from utils import torch_warmup
-
- # Through sys.modules: another test re-imports the shim and leaves the package
- # attribute pointing elsewhere. import_module resolves it the way the code does.
- hf_xet_fallback = importlib.import_module("utils.hf_xet_fallback")
-
- monkeypatch.setattr(torch_warmup, "_torch_installed", lambda: True)
- calls = []
- monkeypatch.setattr(hf_xet_fallback, "_load_shared", lambda: (calls.append(1), True)[1])
-
- real_import = builtins.__import__
-
- def no_bare_zoo(name, *args, **kwargs):
- assert name != "unsloth_zoo", (
- "the warm imported unsloth_zoo directly; it must go through "
- "utils.hf_xet_fallback so the UNSLOTH_ZOO_DISABLE_GPU_INIT retry runs"
- )
- return real_import(name, *args, **kwargs)
-
- monkeypatch.setattr(builtins, "__import__", no_bare_zoo)
- torch_warmup._warm_unsloth_zoo()
- assert calls == [1]
-
- # A shim that could not load leaves the watchdog degraded; that has to surface as a
- # failed stage rather than a silent success.
- monkeypatch.setattr(hf_xet_fallback, "_load_shared", lambda: False)
- with pytest.raises(RuntimeError, match = "unsloth_zoo unavailable"):
- torch_warmup._warm_unsloth_zoo()
+ assert "unsloth_zoo" not in stage_names
+ assert not hasattr(
+ torch_warmup, "_warm_unsloth_zoo"
+ ), "the optional Hub/Xet integration must be loaded by a real download, not startup"
def test_a_failing_warm_stage_is_reported_not_swallowed(monkeypatch, capsys, caplog):
diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.py
index 94ed3f103f3..4f57e070cb9 100644
--- a/studio/backend/tests/test_warm_window_review_fixes.py
+++ b/studio/backend/tests/test_warm_window_review_fixes.py
@@ -345,10 +345,8 @@ def test_the_model_config_capability_block_runs_off_loop():
# ------------------------------------------------------------- kill switch
-def test_the_torch_kill_switch_leaves_mlx_selfheal_running():
- """The switch is about torch; MLX autorepair has its own opt-out. Gating autorepair on it
- left an Apple Silicon host with a broken MLX stack chat-only for good, where before it
- ran in the lifespan no matter what."""
+def test_post_warm_order_keeps_mlx_selfheal_and_linked_folder_startup():
+ """Removing the RAG warm must not drop either remaining lifecycle action."""
tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))
fn = next(
node
@@ -364,18 +362,11 @@ def test_the_torch_kill_switch_leaves_mlx_selfheal_running():
return -1
mlx_at = _index_of(lambda d: "start_mlx_autorepair_if_needed" in d)
- gate_at = _index_of(lambda d: "DISABLE_ENV_VAR" in d and "Return" in d)
- rag_at = _index_of(lambda d: "_warm_rag_embedder" in d)
+ folders_at = _index_of(lambda d: "_start_linked_folder_auto_sync" in d)
- assert mlx_at >= 0 and gate_at >= 0 and rag_at >= 0
- assert mlx_at < gate_at, (
- "the kill-switch return precedes MLX autorepair, so setting "
- "UNSLOTH_STUDIO_DISABLE_TORCH_WARM leaves a broken MLX host chat-only"
- )
- assert gate_at < rag_at, (
- "the RAG warm is no longer gated; it pulls sentence-transformers and "
- "torch, which is what the kill switch exists to prevent"
- )
+ assert mlx_at >= 0 and folders_at >= 0
+ assert mlx_at < folders_at
+ assert "_warm_rag_embedder" not in ast.dump(fn)
def test_the_torch_kill_switch_leaves_linked_folder_sync_running(monkeypatch):
@@ -478,15 +469,16 @@ def test_threading_import_is_present_for_the_lazy_fetch():
def test_shutdown_stands_the_post_warm_thread_down(monkeypatch):
"""Work must not start for an application that has already stopped. The worker is parked
- in join_background_warm(), so a shutdown before the warm finishes reaches it no other
- way: it wakes later and loads the embedder, which can spawn a llama-server."""
+ in join_background_warm(), so a shutdown before the warm finishes reaches it no other way."""
import main as main_mod
ran: list[str] = []
released = threading.Event()
monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: released.wait(30))
- monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))
+ monkeypatch.setattr(
+ main_mod, "_start_linked_folder_auto_sync", lambda generation: ran.append("folders")
+ )
import utils.mlx_repair as mlx_mod
monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))
@@ -500,10 +492,7 @@ def test_shutdown_stands_the_post_warm_thread_down(monkeypatch):
released.set()
worker.join(30)
- assert ran == [], (
- f"post-warm work ran after shutdown: {ran}. The RAG warm can load an "
- f"embedder or start a llama-server for a stopped application."
- )
+ assert ran == [], f"post-warm work ran after shutdown: {ran}"
def test_the_post_warm_thread_still_works_without_a_shutdown(monkeypatch):
@@ -514,11 +503,13 @@ def test_the_post_warm_thread_still_works_without_a_shutdown(monkeypatch):
ran: list[str] = []
monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: None)
monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))
- monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))
+ monkeypatch.setattr(
+ main_mod, "_start_linked_folder_auto_sync", lambda generation: ran.append("folders")
+ )
assert main_mod._start_post_warm_thread() is True
main_mod._post_warm_thread.join(30)
- assert ran == ["mlx", "rag"]
+ assert ran == ["mlx", "folders"]
def test_a_restart_gets_its_own_worker_while_the_old_one_is_parked(monkeypatch):
@@ -539,7 +530,9 @@ def test_a_restart_gets_its_own_worker_while_the_old_one_is_parked(monkeypatch):
monkeypatch.setattr(main_mod, "join_background_warm", _join)
monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))
- monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))
+ monkeypatch.setattr(
+ main_mod, "_start_linked_folder_auto_sync", lambda generation: ran.append("folders")
+ )
# Lifespan 1 starts a worker, then shuts down while it is still parked.
assert main_mod._start_post_warm_thread() is True
@@ -558,7 +551,7 @@ def test_a_restart_gets_its_own_worker_while_the_old_one_is_parked(monkeypatch):
release_new.set()
new.join(30)
- assert ran == ["mlx", "rag"], f"the restarted lifespan did not get its deferred work: {ran}"
+ assert ran == ["mlx", "folders"], f"the restarted lifespan did not get its deferred work: {ran}"
def test_only_the_current_generation_does_the_work(monkeypatch):
@@ -570,7 +563,9 @@ def test_only_the_current_generation_does_the_work(monkeypatch):
gate = threading.Event()
monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: gate.wait(30))
monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))
- monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))
+ monkeypatch.setattr(
+ main_mod, "_start_linked_folder_auto_sync", lambda generation: ran.append("folders")
+ )
main_mod._start_post_warm_thread()
first = main_mod._post_warm_thread
@@ -581,7 +576,7 @@ def test_only_the_current_generation_does_the_work(monkeypatch):
first.join(30)
second.join(30)
- assert ran == ["mlx", "rag"], f"expected one worker to do the work once, got {ran}"
+ assert ran == ["mlx", "folders"], f"expected one worker to do the work once, got {ran}"
def test_shutdown_does_not_wait_for_the_post_warm_thread():
@@ -1049,9 +1044,8 @@ async def _run_shutdown(shutdown_mod, hw_mod) -> None:
# ------------------------------------------- the post-warm worker rechecks
def test_the_post_warm_worker_rechecks_before_each_action():
- """One check after the join leaves a window shutdown can land in. The MLX autorepair and
- the RAG warm each take their own time, and the RAG warm can spawn a llama-server, so a
- generation read before each action is what keeps a stopped lifespan from starting one."""
+ """One check after the join leaves a shutdown window around each remaining action.
+ A generation read before MLX repair and linked-folder startup keeps a stopped lifespan cold."""
tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))
fn = next(
node
@@ -1067,8 +1061,8 @@ def test_the_post_warm_worker_rechecks_before_each_action():
]
assert len(checks) >= 3, (
"the post-warm worker checks retirement fewer than once per action; a "
- "shutdown landing after the join can still start MLX autorepair or a "
- "llama-server for a lifespan that has stopped"
+ "shutdown landing after the join can still start MLX autorepair or linked-folder "
+ "startup for a lifespan that has stopped"
)
diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.py
index 77364ae05b3..cb6fc4ca85a 100644
--- a/studio/backend/utils/hf_xet_fallback.py
+++ b/studio/backend/utils/hf_xet_fallback.py
@@ -217,12 +217,7 @@ def _load_optional(module_name: str) -> Any:
return module
-def xet_health(**kwargs: Any) -> Any:
- """The machine's Xet verdict, or ``None`` when unsloth_zoo cannot answer.
-
- ``None`` means "no opinion": callers keep their default (Xet), they do not downgrade.
- """
- module = _load_optional("unsloth_zoo.hf_xet_health")
+def _xet_health_from(module: Any, **kwargs: Any) -> Any:
if module is None:
return None
try:
@@ -233,6 +228,27 @@ def xet_health(**kwargs: Any) -> Any:
return None
+def cached_xet_health(**kwargs: Any) -> Any:
+ """Return Zoo's Xet verdict only when its health module is already loaded.
+
+ Capability reads use this path so opening Hub cannot initialize Unsloth Zoo. A real
+ download calls :func:`xet_health`, which loads the optional module and populates this cache.
+ """
+ with _load_lock:
+ module = _optional_modules.get("unsloth_zoo.hf_xet_health", _UNTRIED)
+ return None if module is _UNTRIED else _xet_health_from(module, **kwargs)
+
+
+def xet_health(**kwargs: Any) -> Any:
+ """Load and query Zoo's Xet verdict for an actual download decision.
+
+ ``None`` means "no opinion": callers keep their default (Xet), they do not downgrade.
+ Read-only capability requests use :func:`cached_xet_health` instead.
+ """
+ module = _load_optional("unsloth_zoo.hf_xet_health")
+ return _xet_health_from(module, **kwargs)
+
+
def record_xet_outcome(ok: bool, reason: str = "") -> None:
"""Record a finished Xet attempt so a repeatedly-failing machine stops starting on Xet."""
module = _load_optional("unsloth_zoo.hf_xet_health")
@@ -543,6 +559,7 @@ __all__ = [
"DEFAULT_XET_ATTEMPTS",
"DownloadStallError",
"child_should_disable_xet",
+ "cached_xet_health",
"is_data_phase_stall",
"xet_attempts",
"get_hf_download_state",
diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.py
index 333e22083fe..4aba5e84046 100644
--- a/studio/backend/utils/torch_warmup.py
+++ b/studio/backend/utils/torch_warmup.py
@@ -15,10 +15,10 @@ Contract:
* idempotent -- one thread per process, repeat calls are no-ops
* never fatal -- a failed stage is logged and left cold, retried by whoever needs it
* no half-initialised state -- stages delegate to the module owning the cache
- (utils.hardware, model_config, hf_xet_fallback), which caches under a lock and
- only on success, so a racing request waits rather than sees a partial
- * same end state -- same imports, order and call sites as `import main`. A stage
- shortcutting to a bare `import x` can behave differently; see _warm_unsloth_zoo.
+ (utils.hardware, model_config), which caches under a lock and only on success,
+ so a racing request waits rather than sees a partial
+ * optional GPU consumers stay cold -- Hub downloads load the Xet/Unsloth Zoo
+ integration on demand, and RAG operations load their embedding backend on demand
This does NOT make torch-dependent endpoints cheap while it runs: anything reaching
get_device() blocks until the hardware stage finishes, so `async def` handlers on
@@ -29,7 +29,6 @@ from __future__ import annotations
import importlib
import importlib.machinery
-import importlib.util
import os
import sys
import threading
@@ -51,15 +50,6 @@ _thread_epoch: Optional[int] = None
_status: dict = {"started": False, "finished": False, "stages": {}}
-def _torch_installed() -> bool:
- """True if torch is importable without importing it, so torch-requiring stages are
- skipped on a --no-torch install rather than logging an error for a missing-on-purpose dep."""
- try:
- return importlib.util.find_spec("torch") is not None
- except (ImportError, ValueError):
- return False
-
-
def _is_extension_module(name: str) -> bool:
"""True if sys.modules[name] is a compiled extension, not Python source."""
module = sys.modules.get(name)
@@ -141,7 +131,6 @@ _STAGE_PACKAGE = {
"hardware": "torch",
"transformers": "transformers",
"datasets": "datasets",
- "unsloth_zoo": "unsloth_zoo",
}
@@ -172,7 +161,6 @@ def _warm_hardware(epoch: Optional[int] = None) -> None:
def _warm_transformers() -> None:
- # Ahead of unsloth_zoo: that is the eager order, and unsloth_zoo patches it on import.
from utils.models.model_config import _detection_sets
_detection_sets()
@@ -182,35 +170,8 @@ def _warm_datasets() -> None:
importlib.import_module("datasets")
-def _warm_unsloth_zoo() -> None:
- """Prime the download stall watchdog, the way the eager import primed it.
-
- Through utils.hf_xet_fallback, not a bare ``import unsloth_zoo``: the edge this
- replaces was orchestrator.py's ``from utils.hf_xet_fallback import
- DownloadStallError``, and the shim does more. When unsloth_zoo's GPU init raises it
- retries under UNSLOTH_ZOO_DISABLE_GPU_INIT=1 and injects triton/bitsandbytes stubs;
- a bare import skips that retry, so a host whose bitsandbytes cannot find libcudart
- would fail a stage startup used to complete.
-
- Skipped without torch: unsloth_zoo hard-requires it and the shim degrades to stubs.
- """
- if not _torch_installed():
- return
- # Private deliberately: the exact function the eager import drove. The public names
- # reach it only via an attribute whose degraded fallback looks like success.
- from utils.hf_xet_fallback import _load_shared
-
- if not _load_shared():
- # Downloads still work on the degraded stubs, but the stage is cold and
- # warm_status() must say so. Purge so the next importer re-runs __init__ clean;
- # the shim's negative cache stays pinned, as the raise site and `except` must
- # resolve to one DownloadStallError class or the stall handler is bypassed.
- purge_partial_import("unsloth_zoo")
- raise RuntimeError("unsloth_zoo unavailable; the download stall watchdog stays degraded")
-
-
-# _STAGES follows the eager import order: transformers before unsloth_zoo (which patches
-# it on import), datasets between them because that is where `import main` reached it.
+# Keep metadata and framework registries ready without importing optional GPU consumers.
+# Unsloth Zoo is loaded by utils.hf_xet_fallback only when a Hub operation needs it.
def _warm_inference_backend() -> None:
# Its constructor reaches hw.get_device(), so whoever builds it first pays for detection
# -- lazily that is some request, and sync helpers call the getter inline from async
@@ -224,7 +185,6 @@ _STAGES = (
("inference_backend", _warm_inference_backend),
("transformers", _warm_transformers),
("datasets", _warm_datasets),
- ("unsloth_zoo", _warm_unsloth_zoo),
)