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
Studio: start the torch warm-up stages after the first response is sent (#15732)
Daniel Han6b9b6c271a1f
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 7d401118dd0..fc432a8416a 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -611,6 +611,10 @@ def _start_llama_cpp_probes_if_enabled(app: FastAPI) -> None:).start()+# Torch warm start gate: set by the first response, and at shutdown so a parked warm reaches its epoch check.+_first_response_sent = threading.Event()++_post_warm_thread: Optional[threading.Thread] = None_post_warm_lock = threading.Lock()# Bumped every start/stop so a worker parked in join_background_warm() cannot act after shutdown.@@ -1013,8 +1017,9 @@ async def lifespan(app: FastAPI):+ "\n")- # Last, so it never contends for the GIL before the socket binds.- start_background_warm()+ # Last, so it never contends for the GIL before the socket binds; its stages wait for the first response.+ _first_response_sent.clear()+ start_background_warm(gate = _first_response_sent)_start_post_warm_thread()_lifespan_log.info(@@ -1048,6 +1053,7 @@ async def lifespan(app: FastAPI):_invalidate_detection = getattr(_hw_module, "invalidate_detection", None)if _invalidate_detection is not None:_invalidate_detection()+ _first_response_sent.set()await asyncio.to_thread(_release_api_usage_writer, _api_usage_writer_lease)@@ -1152,6 +1158,10 @@ logger = LogConfig.setup_logging(app.add_middleware(LoggingMiddleware)+from utils.first_response_gate import FirstResponseGateMiddleware # noqa: E402++app.add_middleware(FirstResponseGateMiddleware, event = _first_response_sent)+if os.environ.get("UNSLOTH_STUDIO_MCP_TOKEN", "").strip():logger.warning("UNSLOTH_STUDIO_MCP_TOKEN is no longer used and /mcp refuses it. "diff --git a/studio/backend/tests/test_warm_start_gate.py b/studio/backend/tests/test_warm_start_gate.pynew file mode 100644index 00000000000..a149dc04724--- /dev/null+++ b/studio/backend/tests/test_warm_start_gate.py@@ -0,0 +1,235 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The torch warm's GIL-heavy stages start only after the first HTTP response has gone out.++import torch and the CUDA probe hold the GIL for whole C calls, so a liveness or desktop-login probe that lands+during one waits it out and the desktop's 2 s port probe can miss. The warm thread still starts in the+lifespan (torch_warm_in_progress reads as before); only its stages wait for the gate."""++from __future__ import annotations++import ast+import threading+import time+import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import utils.torch_warmup as warmup # noqa: E402+++def _gate_middleware(app, event):+ from utils.first_response_gate import FirstResponseGateMiddleware+ return FirstResponseGateMiddleware(app, event = event)+++def recorded(monkeypatch):+ """A fresh warm latch with one stage that records when it ran."""+ monkeypatch.setattr(warmup, "_thread", None, raising = False)+ monkeypatch.setattr(warmup, "_thread_epoch", None, raising = False)+ monkeypatch.setattr(+ warmup, "_status", {"started": False, "finished": False, "stages": {}}, raising = False+ )+ runs: list[float] = []+ monkeypatch.setattr(warmup, "_STAGES", (("probe", lambda: runs.append(time.monotonic())),))+ yield runs+ warmup.join_background_warm(30)+++def test_a_gated_warm_is_in_progress_but_runs_no_stage_until_the_gate_opens(recorded, monkeypatch):+ monkeypatch.setattr(warmup, "START_GATE_MAX_WAIT_S", 60.0)+ gate = threading.Event()+ assert warmup.start_background_warm(gate = gate) is True++ # The marker the desktop watchdog keys its startup grace on is up from the start, as before.+ status = warmup.warm_status()+ assert status["started"] and status["alive"] and not status["finished"]+ time.sleep(0.3)+ assert recorded == [], "a warm stage ran before the first response was sent"++ opened = time.monotonic()+ gate.set()+ assert warmup.join_background_warm(30) is True+ assert len(recorded) == 1 and recorded[0] >= opened+ assert warmup.warm_status()["finished"] is True+++def test_the_warm_starts_anyway_when_no_request_arrives(recorded, monkeypatch, caplog):+ monkeypatch.setattr(warmup, "START_GATE_MAX_WAIT_S", 0.05)+ assert warmup.start_background_warm(gate = threading.Event()) is True+ assert warmup.join_background_warm(30) is True+ assert len(recorded) == 1, "a launch nobody connects to never warmed"+++def test_an_ungated_warm_starts_at_once(recorded, monkeypatch):+ """Control: callers that pass no gate (and the code before the gate existed) warm immediately."""+ monkeypatch.setattr(warmup, "START_GATE_MAX_WAIT_S", 60.0, raising = False)+ assert warmup.start_background_warm() is True+ assert warmup.join_background_warm(30) is True+ assert len(recorded) == 1+++def test_a_shutdown_while_parked_runs_no_stage(recorded, monkeypatch):+ from utils.hardware import hardware as hw++ monkeypatch.setattr(warmup, "START_GATE_MAX_WAIT_S", 60.0)+ gate = threading.Event()+ assert warmup.start_background_warm(gate = gate) is True+ hw.invalidate_detection()+ gate.set()+ assert warmup.join_background_warm(30) is True+ assert recorded == [], "a warm parked at the gate ran after its lifespan ended"+++def _http_scope(path: str = "/api/liveness") -> dict:+ return {"type": "http", "method": "GET", "path": path, "headers": []}+++async def _receive():+ return {"type": "http.request", "body": b"", "more_body": False}+++def _run(coro):+ import asyncio+ return asyncio.run(coro)+++def test_the_gate_opens_only_once_the_last_body_chunk_is_sent():+ event = threading.Event()+ seen: list[tuple[str, bool]] = []++ async def app(scope, receive, send):+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b"a", "more_body": True})+ await send({"type": "http.response.body", "body": b"b", "more_body": False})++ async def send(message):+ seen.append((message["type"], event.is_set()))++ _run(_gate_middleware(app, event)(_http_scope(), _receive, send))+ assert seen == [+ ("http.response.start", False),+ ("http.response.body", False),+ ("http.response.body", False),+ ]+ assert event.is_set()+++def test_a_failed_first_request_still_opens_the_gate():+ event = threading.Event()++ async def app(scope, receive, send):+ raise RuntimeError("boom")++ async def send(message):+ pass++ with pytest.raises(RuntimeError):+ _run(_gate_middleware(app, event)(_http_scope(), _receive, send))+ assert event.is_set()+++def test_lifespan_and_websocket_scopes_do_not_open_the_gate():+ event = threading.Event()+ calls: list[str] = []++ async def app(scope, receive, send):+ calls.append(scope["type"])++ async def send(message):+ pass++ middleware = _gate_middleware(app, event)+ _run(middleware({"type": "lifespan"}, _receive, send))+ _run(middleware({"type": "websocket", "path": "/ws", "headers": []}, _receive, send))+ assert calls == ["lifespan", "websocket"]+ assert not event.is_set()+++def test_a_real_request_reaches_the_client_before_the_warm_stage_runs(recorded, monkeypatch):+ """End to end over Starlette: the stage's start time is after the client already has the reply."""+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from utils.first_response_gate import FirstResponseGateMiddleware++ monkeypatch.setattr(warmup, "START_GATE_MAX_WAIT_S", 60.0)+ gate = threading.Event()+ app = FastAPI()++ @app.get("/api/liveness")+ async def liveness():+ return {"status": "alive"}++ app.add_middleware(FirstResponseGateMiddleware, event = gate)+ assert warmup.start_background_warm(gate = gate) is True+ with TestClient(app) as client:+ time.sleep(0.2)+ assert recorded == []+ assert client.get("/api/liveness").json() == {"status": "alive"}+ answered = time.monotonic()+ assert warmup.join_background_warm(30) is True+ assert len(recorded) == 1+ # The stage starts once the body is sent; the client may read it a hair later, so allow scheduling slack.+ assert recorded[0] >= answered - 0.5+++def _lifespan_node() -> ast.AsyncFunctionDef:+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "lifespan":+ return node+ raise AssertionError("lifespan not found in main.py")+++def test_the_lifespan_gates_the_warm_on_the_first_response():+ calls = [+ sub+ for sub in ast.walk(_lifespan_node())+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "start_background_warm"+ ]+ assert len(calls) == 1+ gates = [kw.value for kw in calls[0].keywords if kw.arg == "gate"]+ assert (+ gates and isinstance(gates[0], ast.Name) and gates[0].id == "_first_response_sent"+ ), "the lifespan starts the warm ungated, so its first GIL-holding import races the first probe"+++def test_shutdown_opens_the_gate_after_retiring_the_epoch():+ source = ast.unparse(_lifespan_node())+ head, _, shutdown = source.partition("yield")+ assert "_first_response_sent.clear()" in head+ assert "_first_response_sent.set()" in shutdown+ assert shutdown.index("_invalidate_detection()") < shutdown.index(+ "_first_response_sent.set()"+ ), "opening the gate before the epoch is retired lets a parked warm run after shutdown"+++def test_the_app_registers_the_gate_middleware_on_the_same_event():+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ found = False+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "add_middleware"+ and node.args+ and isinstance(node.args[0], ast.Name)+ and node.args[0].id == "FirstResponseGateMiddleware"+ ):+ event = [kw.value for kw in node.keywords if kw.arg == "event"]+ found = (+ bool(event)+ and isinstance(event[0], ast.Name)+ and event[0].id == "_first_response_sent"+ )+ assert founddiff --git a/studio/backend/utils/first_response_gate.py b/studio/backend/utils/first_response_gate.pynew file mode 100644index 00000000000..340e3f24280--- /dev/null+++ b/studio/backend/utils/first_response_gate.py@@ -0,0 +1,34 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Start gate for the torch warm: its import torch / CUDA probe hold the GIL for whole C calls, so the desktop's+first 2 s port probe must be answered before they begin."""++from __future__ import annotations++import threading+++class FirstResponseGateMiddleware:+ """Pure ASGI: sets ``event`` once the first HTTP response body is complete, then passes through."""++ def __init__(self, app, event: threading.Event) -> None:+ self.app = app+ self.event = event++ async def __call__(self, scope, receive, send) -> None:+ event = self.event+ if event.is_set() or scope["type"] != "http":+ await self.app(scope, receive, send)+ return++ async def send_and_mark(message) -> None:+ await send(message)+ if message["type"] == "http.response.body" and not message.get("more_body", False):+ event.set()++ try:+ await self.app(scope, receive, send_and_mark)+ finally:+ # Client gone or error: still answered.+ event.set()diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.pyindex 06c0837d96f..e52e4b7930c 100644--- a/studio/backend/utils/torch_warmup.py+++ b/studio/backend/utils/torch_warmup.py@@ -437,7 +437,23 @@ _STAGES = ()-def _warm(epoch: Optional[int] = None) -> None:+START_GATE_MAX_WAIT_S = 2.0+++def _wait_for_start_gate(gate: Optional[threading.Event]) -> None:+ if gate is None:+ return+ waited = time.perf_counter()+ opened = gate.wait(START_GATE_MAX_WAIT_S)+ logger.info(+ "torch warm leaving its start gate after %.0fms (%s)",+ (time.perf_counter() - waited) * 1000,+ "first response sent" if opened else "no request yet",+ )+++def _warm(epoch: Optional[int] = None, gate: Optional[threading.Event] = None) -> None:+ _wait_for_start_gate(gate)started = time.perf_counter()if epoch is None:epoch = _detection_epoch()@@ -484,14 +500,20 @@ def _detection_epoch() -> Optional[int]:return None-def _warm_after(previous: threading.Thread, epoch: Optional[int]) -> None:+def _warm_after(+ previous: threading.Thread,+ epoch: Optional[int],+ gate: Optional[threading.Event] = None,+) -> None:"""Wait out a retired warm, then warm for ``epoch``. One importer at a time."""previous.join()- _warm(epoch)+ _warm(epoch, gate)++def start_background_warm(gate: Optional[threading.Event] = None) -> bool:+ """A finished thread from an earlier lifespan does not count; shutdown cleared the state it warmed.-def start_background_warm() -> bool:- """A finished thread from an earlier lifespan does not count; shutdown cleared the state it warmed."""+ ``gate``: reports started now, runs stages once set or after START_GATE_MAX_WAIT_S (utils/first_response_gate.py)."""global _threadif os.environ.get(DISABLE_ENV_VAR) == "1":return False@@ -499,13 +521,13 @@ def start_background_warm() -> bool:# Epoch read before start(): reading it in the child would adopt the post-shutdown one.epoch = _detection_epoch()with _start_lock:- target, args = _warm, (epoch,)+ target, args = _warm, (epoch, gate)if _thread is not None:if _thread_epoch is not None and epoch == _thread_epoch:return Falseif _thread.is_alive():# Stale but mid-stage: hand off to a successor that joins it first, keeping one importer.- target, args = _warm_after, (_thread, epoch)+ target, args = _warm_after, (_thread, epoch, gate)else:_clear_finished_warm_locked()_thread = threading.Thread(