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: idle auto-unload for the image and video backends (#8672)

Daniel Han32c2627ae4f7
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index cd338acc628..4b82f249410 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -7,6 +7,9 @@ Off by default (idle seconds = 0). When enabled, a background loop unloads the
loaded GGUF once it has been idle for the configured TTL, freeing VRAM. A
pure-ASGI middleware tracks in-flight inference requests so a long stream that
outlives the TTL is never unloaded mid-response.
+
+The same loop and the same middleware drive the image/video side (media_keepwarm),
+so Studio has one idle mechanism rather than one per backend.
"""
from __future__ import annotations
@@ -276,6 +279,34 @@ def sweep_slot_save_dir() -> None:
pass
+def _as_bytes(value) -> bytes:
+ return value if isinstance(value, bytes) else str(value).encode("utf-8", "replace")
+
+
+def _carries_bearer_credentials(scope) -> bool:
+ """Whether this request carries the ``Authorization: Bearer`` its route demands.
+
+ Every tracked media route depends on ``get_current_subject`` (HTTPBearer), so a request
+ without one is refused before any handler runs. Counting it anyway would still pin the
+ pipeline: the count is taken here, ahead of FastAPI parsing the body, and a client that
+ opens the POST and then withholds its body produces no response status either, so the
+ 401/403 exclusion below never gets to run. One such connection, replaced as it times
+ out, would keep a multi-GB pipeline resident for good. Real clients always send the
+ header, so requiring it costs a legitimate generation nothing.
+ """
+ headers = scope.get("headers")
+ if headers is None:
+ # A real ASGI server always populates headers; a caller that does not is not a
+ # client to second-guess, so keep the protection.
+ return True
+ for name, value in headers:
+ if _as_bytes(name).lower() != b"authorization":
+ continue
+ scheme, _, token = _as_bytes(value).partition(b" ")
+ return scheme.lower() == b"bearer" and bool(token.strip())
+ return False
+
+
class LlamaKeepWarmMiddleware:
"""Pure ASGI: count in-flight inference requests and stamp activity on completion."""
@@ -285,11 +316,25 @@ class LlamaKeepWarmMiddleware:
async def __call__(self, scope, receive, send):
# Inference endpoints are all POST; skipping non-POST avoids counting CORS
# preflight (OPTIONS). ``or ""`` guards an explicit None path.
- if (
- scope.get("type") != "http"
- or scope.get("method") != "POST"
- or not _is_inference_path(scope.get("path") or "")
- ):
+ path = scope.get("path") or ""
+ if scope.get("type") != "http" or scope.get("method") != "POST":
+ await self.app(scope, receive, send)
+ return
+ # An image/video generation gets the same bookkeeping against ITS backend, so the
+ # media idle unload cannot free the pipeline this request is about to generate on
+ # -- or the load it is about to start. The media load routes are tracked HERE only:
+ # they do not use the chat GGUF, so they must not stamp chat activity nor count
+ # towards other_inference_request_count().
+ from core.inference import media_keepwarm
+
+ media_owner = media_keepwarm.owner_for_path(path)
+ if media_owner is not None and not _carries_bearer_credentials(scope):
+ # Cannot reach the backend, so it must not hold it warm (see the helper). The
+ # chat count keeps its own rule: /p/{run}/v1/chat/completions is public by
+ # design, so a missing bearer there is not proof of anything.
+ media_owner = None
+ chat_tracked = _is_inference_path(path)
+ if not chat_tracked and media_owner is None:
await self.app(scope, receive, send)
return
# Always track in-flight on inference paths, even when the feature is off,
@@ -298,15 +343,28 @@ class LlamaKeepWarmMiddleware:
# cheap and invisible to clients (the response is proxied unchanged).
# Mark pending before the gate so the idle loop (which holds the gate while
# unloading) can't free the model while this request is waiting to start.
- _note_pending()
- started = False
- try:
- async with _unload_gate():
- _note_start()
- started = True
- finally:
- if not started:
- _note_unpending()
+ if chat_tracked:
+ _note_pending()
+ started = False
+ try:
+ async with _unload_gate():
+ _note_start()
+ started = True
+ finally:
+ if not started:
+ _note_unpending()
+ if media_owner is not None:
+ try:
+ await media_keepwarm.begin_request(media_owner)
+ except BaseException:
+ # The generate routes are tracked on both sides, and this gate can be held
+ # for the length of a teardown. A client that disconnects while waiting on
+ # it never reaches the _finish below, so balance the chat count here or it
+ # stays positive for the life of the process: chat idle unload would never
+ # fire again and every training start would see an inference request.
+ if chat_tracked:
+ _note_untracked_end()
+ raise
ended = {"done": False}
status = {"code": None}
@@ -315,7 +373,11 @@ class LlamaKeepWarmMiddleware:
if ended["done"]:
return
ended["done"] = True
- if scope.get(_UNTRACKED_SCOPE_KEY):
+ # Before the untracked early return below: that marks a request as not using the
+ # local GGUF, which says nothing about the media backend it was counted against.
+ if media_owner is not None:
+ media_keepwarm.end_request(media_owner, counted = status["code"] not in (401, 403))
+ if not chat_tracked or scope.get(_UNTRACKED_SCOPE_KEY):
return
# This middleware runs before FastAPI auth, so a 401/403 reaches here
# without ever touching llama.cpp. Decrement the in-flight count (to
@@ -386,6 +448,13 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:
seen_model = None
while True:
await asyncio.sleep(poll_seconds)
+ # The image/video half of the tick, in its own guard so neither side can cost the
+ # other an iteration. Inert unless the media TTL is set.
+ try:
+ from core.inference.media_keepwarm import idle_unload_step
+ await idle_unload_step()
+ except Exception as exc:
+ logger.debug("media idle_unload_step failed: %s", exc)
try:
ttl = get_auto_unload_idle_seconds()
if ttl <= 0:
diff --git a/studio/backend/core/inference/media_keepwarm.py b/studio/backend/core/inference/media_keepwarm.py
new file mode 100644
index 00000000000..f23a6fdb6c0
--- /dev/null
+++ b/studio/backend/core/inference/media_keepwarm.py
@@ -0,0 +1,301 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Opt-in idle auto-unload for the diffusion image and video backends.
+
+The image and video pipelines are the largest thing Studio holds in VRAM, and until now only
+the chat GGUF was freed when the user walked away: one generation and a navigate-away left
+several GB resident forever. This is the same mechanism rather than a second one -- the same
+in-flight bookkeeping (``LlamaKeepWarmMiddleware`` already tracks the generate routes) and one
+step per tick of ``llama_keepwarm.idle_unload_loop``. The TTL is its own setting, off by
+default, so nothing here runs until the user asks for it: the tick returns before it resolves
+a backend, which is also what keeps torch out of a Studio that never opened these pages.
+
+Each backend owns its teardown barrier, so this decides only WHEN: it calls the same
+``unload()`` the arbiter's evictor calls, resolved through ``get_active_diffusion_engine()``
+so a native sd.cpp selection stops the sd-server instead of a diffusers pipeline that was
+never loaded. Device-agnostic on purpose: CUDA, ROCm, XPU and MPS free VRAM, and a CPU load
+frees the host RAM the same weights occupy there, which is just as much the user's.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import sys
+import threading
+import time
+from typing import Any, Optional
+
+from core.inference.gpu_arbiter import DIFFUSION, VIDEO, release_if
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+
+class _Tracker:
+ """Per-owner twin of llama_keepwarm's module-level in-flight bookkeeping."""
+
+ def __init__(self, owner: str) -> None:
+ self.owner = owner
+ self._lock = threading.Lock()
+ # Held across the idle check AND the unload, so a request cannot start in between.
+ self.gate = threading.Lock()
+ self._inflight = 0
+ # Requests blocked on the gate but not yet counted in _inflight (see llama_keepwarm).
+ self._pending = 0
+ self._last_active = time.monotonic()
+ # The model identity the last tick saw, so a fresh load counts as activity.
+ self.seen: Any = None
+ # Whether the last tick found work in flight, so the tick that sees it end can
+ # start the TTL there rather than at the last busy poll.
+ self.was_busy = False
+ # The terminal record of the last finished background job this tracker has seen, so
+ # a job no poll ever sampled as busy still dates the TTL from its completion.
+ self.completed: Any = None
+
+ def note_pending(self) -> None:
+ with self._lock:
+ self._pending += 1
+
+ def note_unpending(self) -> None:
+ with self._lock:
+ self._pending = max(0, self._pending - 1)
+
+ def note_start(self) -> None:
+ with self._lock:
+ self._pending = max(0, self._pending - 1)
+ self._inflight += 1
+
+ def note_end(self, *, counted: bool = True) -> None:
+ with self._lock:
+ self._inflight = max(0, self._inflight - 1)
+ if counted:
+ self._last_active = time.monotonic()
+
+ def note_activity(self) -> None:
+ with self._lock:
+ self._last_active = time.monotonic()
+
+ def is_idle(self, ttl_seconds: float) -> bool:
+ with self._lock:
+ return (
+ self._inflight == 0
+ and self._pending == 0
+ and (time.monotonic() - self._last_active) >= ttl_seconds
+ )
+
+
+_TRACKERS = {DIFFUSION: _Tracker(DIFFUSION), VIDEO: _Tracker(VIDEO)}
+
+# The concrete mounted paths, not any path that ends in one of them: FastAPI answers
+# /v1/anything/images/generations with a 404 without ever running an endpoint, and stamping
+# that as activity would let unauthenticated 404s keep a pipeline resident past every TTL.
+# Only the generate and load routes: */generate-progress and */generate/cancel are polled
+# while the user watches, so they must not count as activity.
+#
+# The load routes are here because a load registers with the backend only part way through
+# its POST, so sampling loading_repo_ids() cannot see one that has been accepted but not yet
+# started. Holding the gate for the whole request closes that window rather than narrowing it.
+#
+# test_media_keepwarm asserts every one of these is a real route on the routers main.py
+# mounts, so a rename cannot silently drop the protection an in-flight generation rides on.
+_TRACKED_PATHS = {
+ # studio_router, mounted at /api/inference only.
+ "/api/inference/images/generate": DIFFUSION,
+ "/api/inference/images/load": DIFFUSION,
+ # video_router, likewise.
+ "/api/inference/video/generate": VIDEO,
+ "/api/inference/video/load": VIDEO,
+ # The OpenAI-compatible route is on inference_router, mounted at both prefixes.
+ "/api/inference/images/generations": DIFFUSION,
+ "/v1/images/generations": DIFFUSION,
+}
+
+
+def owner_for_path(path: str) -> Optional[str]:
+ """Which media backend a tracked inference path generates or loads on, if any."""
+ return _TRACKED_PATHS.get(path)
+
+
+async def _gate(tracker: _Tracker):
+ # Polled non-blocking acquire, exactly like llama_keepwarm's: it keeps the wait off this
+ # loop AND cancellation-safe, since a cancel lands during the sleep with the gate free.
+ while not tracker.gate.acquire(blocking = False):
+ await asyncio.sleep(0.02)
+ try:
+ yield
+ finally:
+ tracker.gate.release()
+
+
+async def begin_request(owner: str) -> None:
+ """Count a generation request in, holding the gate off the idle unload."""
+ tracker = _TRACKERS[owner]
+ tracker.note_pending()
+ started = False
+ try:
+ async with _gate(tracker):
+ tracker.note_start()
+ started = True
+ finally:
+ if not started:
+ tracker.note_unpending()
+
+
+def end_request(owner: str, *, counted: bool = True) -> None:
+ """Count a generation request out. ``counted`` False drops it without stamping
+ activity, for a request rejected before it ever reached the backend."""
+ _TRACKERS[owner].note_end(counted = counted)
+
+
+def _diffusion_engine() -> Any:
+ # Through the router: a native sd.cpp selection must unload the sd-server, not the
+ # diffusers pipeline. Nothing can be resident before either module is imported, and
+ # importing them here just to find that out would drag torch into every idle tick.
+ if not {"core.inference.diffusion", "core.inference.sd_cpp_backend"} & set(sys.modules):
+ return None
+ from core.inference.diffusion_engine_router import get_active_diffusion_engine
+ return get_active_diffusion_engine()
+
+
+def _video_engine() -> Any:
+ if "core.inference.video" not in sys.modules:
+ return None
+ from core.inference.video import get_video_backend
+ return get_video_backend()
+
+
+_ENGINES = {DIFFUSION: _diffusion_engine, VIDEO: _video_engine}
+
+
+def _completed_token(progress: dict[str, Any]) -> Optional[tuple[Any, ...]]:
+ """Identity of the last FINISHED job, for a backend that publishes a terminal record.
+
+ The video backend runs its generation as a job that outlives the POST and holds the
+ terminal record until the next job starts, so a job that begins and ends between two
+ 15s polls is never sampled as busy: without this the TTL would still date from the POST
+ that started it, and the model could be freed a poll interval short of the window the
+ user configured. The image backend generates inside its request (which the middleware
+ covers end to end) and publishes no terminal record, so this is None there.
+ """
+ phase = progress.get("phase")
+ if progress.get("active") or phase not in ("completed", "failed"):
+ return None
+ video = progress.get("video")
+ return (
+ phase,
+ (video or {}).get("id") if isinstance(video, dict) else None,
+ progress.get("error"),
+ )
+
+
+def _probe(backend: Any) -> tuple[bool, Optional[tuple[Any, ...]]]:
+ """One off-loop read of the state both backends publish: whether a load or generation
+ is in flight, plus the terminal record of the last finished job.
+
+ Both publish progress BEFORE the slow pre-generate setup and keep it active until the
+ work is done, so this covers a video job that outlives its POST as well as a denoise.
+ One read of generate_progress(), so the two answers cannot come from different jobs."""
+ loading = bool(backend.loading_repo_ids())
+ progress = backend.generate_progress() or {}
+ return loading or bool(progress.get("active")), _completed_token(progress)
+
+
+# What makes one resident build different from another. The repo id is not enough:
+# MiniMax-H3 stages a different denoiser per h3_task, so a cached fl2va -> ref2va reload
+# is a new build under the same id, and the quants are picked per load too. Only fields
+# fixed at load time, so nothing that moves under a resident model (a Speed=Auto compile
+# flips speed_optims mid-life) can be mistaken for a reload and keep it warm forever.
+_IDENTITY_FIELDS = (
+ "repo_id",
+ "base_repo",
+ "model_kind",
+ "gguf_variant",
+ "h3_task",
+ "transformer_quant",
+ "text_encoder_quant",
+)
+
+
+def _identity(status: dict[str, Any]) -> Optional[tuple[Any, ...]]:
+ if not status.get("loaded"):
+ return None
+ return tuple(status.get(field) for field in _IDENTITY_FIELDS)
+
+
+async def _tick(tracker: _Tracker, ttl: float) -> None:
+ backend = _ENGINES[tracker.owner]()
+ if backend is None:
+ return
+ async with _gate(tracker):
+ status = await asyncio.to_thread(backend.status)
+ identity = _identity(status)
+ busy, completed = await asyncio.to_thread(_probe, backend)
+ # A job whose whole life fell between two polls is only ever visible as a terminal
+ # record this tracker has not seen before. The first tick to see any record spends
+ # one TTL on work that may be older, which is the direction that keeps the model.
+ finished = completed is not None and completed != tracker.completed
+ tracker.completed = completed
+ if busy:
+ # A load or generation in flight is activity: the TTL restarts from the end of
+ # the work, and the backend is never torn down under it.
+ tracker.note_activity()
+ tracker.seen = identity
+ tracker.was_busy = True
+ return
+ if tracker.was_busy or finished:
+ # The work ended between two ticks. A video generation outlives its POST, so the
+ # only activity it stamps after that is the busy polls, and dating the TTL from
+ # the last of those spends up to one poll interval of the keep-warm window the
+ # user configured before the model was even free. Start it here instead.
+ tracker.was_busy = False
+ tracker.seen = identity
+ tracker.note_activity()
+ return
+ if identity != tracker.seen:
+ # A (re)loaded model counts as activity so it survives at least one TTL before
+ # its first generation: loads never pass through the request middleware.
+ tracker.seen = identity
+ if identity is not None:
+ tracker.note_activity()
+ return
+ if identity is None or not tracker.is_idle(ttl):
+ return
+ # Re-read the effective setting immediately before the teardown. One step covers both
+ # backends and an unload frees several GB, so a residency veto applied while it runs
+ # (Model Memory, API-only, or the TTL itself moved) would otherwise be ignored by
+ # every teardown left in the step, freeing a model the settings page now calls pinned.
+ ttl = _effective_ttl()
+ if ttl <= 0 or not tracker.is_idle(ttl):
+ return
+ await asyncio.to_thread(backend.unload)
+ # Drop ownership only if nothing came back meanwhile, and check it under the arbiter
+ # lock so a same-owner load that re-registered keeps it. Mirrors /images/unload.
+ await asyncio.to_thread(
+ release_if,
+ tracker.owner,
+ lambda: not backend.loading_repo_ids() and not backend.status().get("loaded"),
+ )
+ tracker.seen = None
+ logger.info("Idle auto-unload: freed the %s model after %ss idle", tracker.owner, ttl)
+
+
+def _effective_ttl() -> float:
+ """The media TTL with the residency vetoes applied: 0 means nothing is unloaded."""
+ from utils.openai_auto_switch_settings import get_media_auto_unload_idle_seconds
+ return float(get_media_auto_unload_idle_seconds())
+
+
+async def idle_unload_step() -> None:
+ """The media half of one idle_unload_loop tick. Inert when the TTL is off."""
+ ttl = _effective_ttl()
+ if ttl <= 0:
+ return
+ for tracker in _TRACKERS.values():
+ try:
+ await _tick(tracker, ttl)
+ except Exception as exc:
+ # One backend failing to tear down must not stop the other, nor the chat unload.
+ logger.debug("idle media unload (%s) failed: %s", tracker.owner, exc)
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index eb204db3e71..ec184207422 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -66,6 +66,7 @@ from utils.openai_auto_switch_settings import (
BATCH_SIZE_MIN,
DEFAULT_AUTO_UNLOAD_API_ONLY,
DEFAULT_AUTO_UNLOAD_KEEP_KV,
+ DEFAULT_MEDIA_AUTO_UNLOAD_IDLE_SECONDS,
DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED,
DEFAULT_OPENAI_AUTO_SWITCH_ENABLED,
MAX_GPU_ID,
@@ -75,11 +76,13 @@ from utils.openai_auto_switch_settings import (
get_auto_unload_api_only,
get_auto_unload_idle_seconds,
get_auto_unload_keep_kv,
+ get_media_auto_unload_idle_seconds,
get_model_overrides,
get_openai_auto_switch_enabled,
resolve_model_override_key,
resolve_model_override_keys,
get_stored_auto_unload_idle_seconds,
+ get_stored_media_auto_unload_idle_seconds,
get_stored_openai_auto_download_enabled,
idle_unload_is_configured,
set_model_override,
@@ -620,6 +623,8 @@ class OpenAIAutoSwitchPayload(BaseModel):
auto_unload_keep_kv: Optional[bool] = None
auto_download_model: Optional[bool] = None
auto_unload_api_only: Optional[bool] = None
+ # The image/video TTL is its own setting, not a share of the chat one.
+ media_auto_unload_idle_seconds: Optional[int] = Field(default = None, ge = 0)
class OpenAIAutoSwitchResponse(BaseModel):
@@ -635,6 +640,10 @@ class OpenAIAutoSwitchResponse(BaseModel):
auto_download_model: bool = DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED
# When true, the idle unload spares models loaded from the UI, not just via the API.
auto_unload_api_only: bool = DEFAULT_AUTO_UNLOAD_API_ONLY
+ # Stored, then effective: the UI shows the saved seconds and flags when a veto
+ # (residency, or API-loaded only) is holding the image/video unload off.
+ media_auto_unload_idle_seconds: int = DEFAULT_MEDIA_AUTO_UNLOAD_IDLE_SECONDS
+ media_idle_unload_active: bool = False
# A quant suffix, as modelOverrideKey builds it. Matched against the loader's quant pattern,
@@ -1010,6 +1019,8 @@ def get_openai_auto_switch(
auto_unload_keep_kv = get_auto_unload_keep_kv(),
auto_download_model = get_stored_openai_auto_download_enabled(),
auto_unload_api_only = get_auto_unload_api_only(),
+ media_auto_unload_idle_seconds = get_stored_media_auto_unload_idle_seconds(),
+ media_idle_unload_active = get_media_auto_unload_idle_seconds() > 0,
)
@@ -1018,12 +1029,20 @@ def update_openai_auto_switch(
payload: OpenAIAutoSwitchPayload, current_subject: str = Depends(get_current_subject)
) -> OpenAIAutoSwitchResponse:
try:
- enabled, idle_seconds, keep_kv, auto_download, api_only = set_openai_auto_switch(
+ (
+ enabled,
+ idle_seconds,
+ keep_kv,
+ auto_download,
+ api_only,
+ media_idle_seconds,
+ ) = set_openai_auto_switch(
payload.enabled,
payload.auto_unload_idle_seconds,
payload.auto_unload_keep_kv,
payload.auto_download_model,
payload.auto_unload_api_only,
+ payload.media_auto_unload_idle_seconds,
)
except ValueError as exc:
raise log_and_http_error(
@@ -1046,6 +1065,8 @@ def update_openai_auto_switch(
auto_unload_keep_kv = keep_kv,
auto_download_model = auto_download,
auto_unload_api_only = api_only,
+ media_auto_unload_idle_seconds = media_idle_seconds,
+ media_idle_unload_active = get_media_auto_unload_idle_seconds() > 0,
)
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index dbf6e3e158b..fa867cd3b49 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -369,6 +369,37 @@ def test_unload_keeps_ownership_when_a_model_is_still_resident(client, monkeypat
assert gpu_arbiter.current_owner() is None
+def test_idle_unload_frees_the_pipeline_and_the_user_can_reload(client, monkeypatch):
+ # The idle tick frees a model loaded through the route, and the user who comes back
+ # gets a working reload: it drops the pipeline the same way /images/unload does and
+ # stashes nothing, so the load path afterwards is the ordinary one.
+ import asyncio
+ import time
+
+ import core.inference.media_keepwarm as media_keepwarm
+ import utils.openai_auto_switch_settings as auto_switch_settings
+
+ monkeypatch.setattr(auto_switch_settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ tracker = media_keepwarm._TRACKERS[gpu_arbiter.DIFFUSION]
+ monkeypatch.setattr(tracker, "seen", None)
+ monkeypatch.setattr(tracker, "_inflight", 0)
+ monkeypatch.setattr(tracker, "_pending", 0)
+ load = {"model_path": "x/z-image", "gguf_filename": "q.gguf"}
+
+ assert client.post("/api/inference/images/load", json = load).json()["loaded"] is True
+ asyncio.run(media_keepwarm.idle_unload_step()) # the fresh load survives this tick
+ assert client.get("/api/inference/images/status").json()["loaded"] is True
+
+ tracker._last_active = time.monotonic() - 3600
+ asyncio.run(media_keepwarm.idle_unload_step())
+ assert client.get("/api/inference/images/status").json()["loaded"] is False
+ assert gpu_arbiter.current_owner() is None
+
+ assert client.post("/api/inference/images/load", json = load).json()["loaded"] is True
+ gen = client.post("/api/inference/images/generate", json = {"prompt": "a sloth", "seed": 7})
+ assert gen.status_code == 200 and gen.json()["images"][0]["seed"] == 7
+
+
def test_unload_keeps_ownership_when_a_load_is_in_flight(client, monkeypatch):
# A concurrent /images/load re-acquires DIFFUSION but is not is_loaded yet, so ownership must be kept on the in-flight state alone.
backend = diffusion_module.get_diffusion_backend()
diff --git a/studio/backend/tests/test_media_keepwarm.py b/studio/backend/tests/test_media_keepwarm.py
new file mode 100644
index 00000000000..c92d634d8f9
--- /dev/null
+++ b/studio/backend/tests/test_media_keepwarm.py
@@ -0,0 +1,731 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the idle auto-unload of the image and video backends.
+
+The real backends are replaced with fakes that publish the same status /
+loading_repo_ids / generate_progress surface, so these verify only the idle
+decision -- no torch, GPU, or model download.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import time
+
+import pytest
+
+import core.inference.gpu_arbiter as arb
+import core.inference.media_keepwarm as mk
+import utils.openai_auto_switch_settings as settings
+
+
+class _FakeEngine:
+ """Minimal stand-in for the diffusers / sd.cpp / video backends."""
+
+ def __init__(
+ self,
+ repo_id = "unsloth/FLUX.1-dev",
+ loaded = True,
+ **build,
+ ):
+ self.repo_id = repo_id
+ self.loaded = loaded
+ self.loading: tuple[str, ...] = ()
+ self.active = False
+ self.unloads = 0
+ # The terminal record the video backend holds after a job (None on the image side).
+ self.terminal: dict | None = None
+ # The rest of the build identity the real backends publish (H3 task, quants).
+ self.build = dict(build)
+
+ def status(self):
+ rest = self.build if self.loaded else dict.fromkeys(self.build)
+ return {
+ "loaded": self.loaded,
+ "repo_id": self.repo_id if self.loaded else None,
+ "gguf_variant": None,
+ **rest,
+ }
+
+ def loading_repo_ids(self):
+ return self.loading
+
+ def generate_progress(self):
+ if self.active:
+ return {"active": True}
+ return {"active": False, **(self.terminal or {})}
+
+ def unload(self):
+ self.unloads += 1
+ self.loaded = False
+ return self.status()
+
+
+def media(monkeypatch):
+ """Both trackers reset, both engines faked, the arbiter left unowned."""
+ monkeypatch.setattr(arb, "_owner", None)
+ engines = {arb.DIFFUSION: _FakeEngine(), arb.VIDEO: _FakeEngine("unsloth/Wan2.2")}
+ for owner, engine in engines.items():
+ monkeypatch.setitem(mk._ENGINES, owner, lambda e = engine: e)
+ # The real evictors tear down live backends; ownership sequencing is all these need.
+ monkeypatch.setitem(arb._EVICTORS, owner, lambda: None)
+ tracker = mk._TRACKERS[owner]
+ monkeypatch.setattr(tracker, "_inflight", 0)
+ monkeypatch.setattr(tracker, "_pending", 0)
+ monkeypatch.setattr(tracker, "_last_active", time.monotonic())
+ monkeypatch.setattr(tracker, "seen", None)
+ monkeypatch.setattr(tracker, "was_busy", False, raising = False)
+ monkeypatch.setattr(tracker, "completed", None, raising = False)
+ return engines
+
+
+_BOTH = (arb.DIFFUSION, arb.VIDEO)
+
+
+def _idle(*owners):
+ """Backdate the trackers as if nothing had touched these backends for an hour."""
+ for owner in owners:
+ mk._TRACKERS[owner]._last_active = time.monotonic() - 3600.0
+
+
+def _step(*idle_owners):
+ """One idle tick, with the named backends backdated past the TTL first."""
+ _idle(*idle_owners)
+ asyncio.run(mk.idle_unload_step())
+
+
+# ── the TTL setting ─────────────────────────────────────────────────
+
+
+def store(monkeypatch):
+ """The app settings map in memory, read back through the real stored readers."""
+ values: dict = {}
+ monkeypatch.setattr(
+ settings, "_cached_setting", lambda key, default = None: values.get(key, default)
+ )
+ for var in (settings.MODEL_IDLE_TTL_ENV_VAR, settings.MEDIA_IDLE_TTL_ENV_VAR):
+ monkeypatch.delenv(var, raising = False)
+ return values
+
+
+def test_the_chat_ttl_alone_does_not_unload_media(store):
+ # The consent line. "Model auto-switch (OpenAI API)" never mentions Images or Video,
+ # so a user who turned that on gets nothing new here on upgrade: the media TTL is its
+ # own setting and its default is off.
+ store[settings.OPENAI_AUTO_SWITCH_SETTING_KEY] = True
+ store[settings.AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ assert settings.get_auto_unload_idle_seconds() == 600
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+
+
+def test_the_media_ttl_unloads_media_without_touching_chat(store):
+ # The other direction: a whole setting, not a modifier on the chat one, so it works
+ # with auto-switch and the chat TTL both off.
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ assert settings.get_media_auto_unload_idle_seconds() == 600
+ assert settings.get_auto_unload_idle_seconds() == 0
+ # Floored like the chat one, for a value persisted before the minimum existed.
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 5
+ assert settings.get_media_auto_unload_idle_seconds() == settings.MIN_AUTO_UNLOAD_IDLE_SECONDS
+ # And it is not gated on auto-switch: that flag is about serving /v1 requests.
+ store[settings.OPENAI_AUTO_SWITCH_SETTING_KEY] = False
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ assert settings.get_media_auto_unload_idle_seconds() == 600
+
+
+def test_media_ttl_env_behaves_like_the_chat_env(store, monkeypatch):
+ # UNSLOTH_MEDIA_IDLE_TTL stands in the same relationship to the media setting that
+ # UNSLOTH_MODEL_IDLE_TTL has to the chat one: the startup default while nothing is
+ # stored, floored the same way, and outranked by an explicit value.
+ monkeypatch.setenv(settings.MEDIA_IDLE_TTL_ENV_VAR, "900")
+ assert settings.get_media_auto_unload_idle_seconds() == 900
+ assert settings.get_stored_media_auto_unload_idle_seconds() == 900
+ monkeypatch.setenv(settings.MEDIA_IDLE_TTL_ENV_VAR, "5")
+ assert settings.get_media_auto_unload_idle_seconds() == settings.MIN_AUTO_UNLOAD_IDLE_SECONDS
+ monkeypatch.setenv(settings.MEDIA_IDLE_TTL_ENV_VAR, "900")
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 0
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ assert settings.get_media_auto_unload_idle_seconds() == 600
+ # The chat env var is not the media one.
+ del store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY]
+ monkeypatch.delenv(settings.MEDIA_IDLE_TTL_ENV_VAR)
+ monkeypatch.setenv(settings.MODEL_IDLE_TTL_ENV_VAR, "900")
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+
+
+def test_api_only_disables_the_media_ttl(store, monkeypatch):
+ # "Only unload models loaded by the API" promises a model the user loaded from
+ # Studio stays resident, and nothing but the user ever loads an image or video
+ # model: /images/load and /video/load are the only entry points, and
+ # /v1/images/generations 503s rather than loading one. So with the setting on
+ # there is nothing here the idle unload is allowed to free.
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ store[settings.AUTO_UNLOAD_API_ONLY_SETTING_KEY] = True
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ # The env-backed TTL is vetoed too, exactly as residency vetoes it.
+ del store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY]
+ monkeypatch.setenv(settings.MEDIA_IDLE_TTL_ENV_VAR, "900")
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ # The stored seconds survive it, so turning the veto off brings them back.
+ store[settings.AUTO_UNLOAD_API_ONLY_SETTING_KEY] = False
+ assert settings.get_media_auto_unload_idle_seconds() == 900
+
+
+def test_residency_vetoes_the_media_ttl(store, monkeypatch):
+ monkeypatch.setattr(settings, "_residency_vetoes_unload", lambda: True)
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 900
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ assert settings.get_stored_media_auto_unload_idle_seconds() == 900
+ del store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY]
+ monkeypatch.setenv(settings.MEDIA_IDLE_TTL_ENV_VAR, "900")
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ monkeypatch.setattr(settings, "_residency_vetoes_unload", lambda: False)
+ assert settings.get_media_auto_unload_idle_seconds() == 900
+
+
+# ── the idle decision ───────────────────────────────────────────────
+
+
+def test_idle_load_is_unloaded_after_the_ttl(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ arb.acquire_for(arb.DIFFUSION)
+ _step() # the loop has now seen both models, so only the TTL is left
+ _step(*_BOTH)
+ assert media[arb.DIFFUSION].unloads == 1
+ assert media[arb.VIDEO].unloads == 1
+ # The arbiter claim went with it, so a later chat load has nothing to evict.
+ assert arb.current_owner() is None
+ # Freed once, not once per tick.
+ _step(*_BOTH)
+ assert media[arb.DIFFUSION].unloads == 1
+
+
+def test_an_in_flight_generation_is_not_unloaded(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ for owner in _BOTH:
+ media[owner].active = True
+ _step()
+ _step(*_BOTH)
+ assert media[arb.DIFFUSION].unloads == 0
+ assert media[arb.VIDEO].unloads == 0
+ # The generation counted as activity, so the TTL restarts from its end rather than
+ # freeing the pipeline the moment the last step lands.
+ for owner in _BOTH:
+ media[owner].active = False
+ _step()
+ assert media[arb.DIFFUSION].unloads == 0
+ assert media[arb.VIDEO].unloads == 0
+
+
+def test_an_in_flight_load_is_not_unloaded(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ engine = media[arb.DIFFUSION]
+ _step()
+ # A superseding load in flight over the resident model.
+ engine.loading = ("unsloth/FLUX.1-schnell",)
+ _step(arb.DIFFUSION)
+ assert engine.unloads == 0
+ # Once it lands, the same state IS collectable: the load was what spared it. One tick
+ # later, though -- the tick that finds the load done starts the TTL from there, since a
+ # load that outlives its POST stamps no activity of its own when it finishes.
+ engine.loading = ()
+ _step(arb.DIFFUSION)
+ assert engine.unloads == 0
+ _step(arb.DIFFUSION)
+ assert engine.unloads == 1
+
+
+def test_a_request_in_flight_is_not_unloaded(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step()
+
+ async def _drive():
+ await mk.begin_request(arb.DIFFUSION)
+ _idle(arb.DIFFUSION)
+ await mk.idle_unload_step()
+ assert media[arb.DIFFUSION].unloads == 0
+ mk.end_request(arb.DIFFUSION)
+
+ asyncio.run(_drive())
+ # The completed request stamped activity, so the next tick still spares it.
+ _step()
+ assert media[arb.DIFFUSION].unloads == 0
+
+
+def test_a_load_that_just_finished_survives_one_ttl(media, monkeypatch):
+ # The server has been idle far longer than the TTL and a model then lands: the
+ # first tick that sees it stamps activity, so it is not freed out from under the
+ # user who just loaded it.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step(*_BOTH)
+ _step()
+ assert media[arb.DIFFUSION].unloads == 0
+ assert media[arb.VIDEO].unloads == 0
+
+
+def test_reload_after_an_idle_unload_works(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ engine = media[arb.DIFFUSION]
+ _step()
+ _step(arb.DIFFUSION)
+ assert engine.unloads == 1 and not engine.status()["loaded"]
+ # The user comes back and loads again: the reload sticks, and the tick that finds it
+ # treats the load as activity instead of freeing it straight back off the stale stamp.
+ engine.loaded = True
+ _step()
+ _step()
+ assert engine.unloads == 1 and engine.status()["loaded"]
+
+
+def test_the_ttl_starts_when_the_background_work_ends(media, monkeypatch):
+ # A video generation outlives its POST: the response is sent at once and the job runs on
+ # in a worker, so after that only the busy polls stamp activity. Dating the TTL from the
+ # last of those spends up to a whole poll interval of the keep-warm window the user
+ # configured before the model was even free. The tick that finds the work done starts it.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ engine = media[arb.VIDEO]
+ engine.active = True
+ _step()
+ # The job ends just after that tick, so the newest stamp is already a poll old -- here,
+ # far older than the TTL, which is the same thing with the clock wound on.
+ _idle(arb.VIDEO)
+ engine.active = False
+ _step()
+ assert engine.unloads == 0
+ # A restart, not a one-tick reprieve: the whole TTL runs from the end of the work.
+ _step()
+ assert engine.unloads == 0
+ _step(arb.VIDEO)
+ assert engine.unloads == 1
+
+
+def test_a_job_that_lives_between_two_polls_still_gets_the_full_ttl(media, monkeypatch):
+ # A video job can start and finish inside one 15s poll interval, so no tick ever samples
+ # it as busy. Its POST returned near the START of the generation, and that response is
+ # the only activity it stamps, so the TTL was spent while the job was still running: a
+ # 74s TTL could free the model after about 60s of real idleness. The terminal record the
+ # backend publishes is the only proof the job ran, so the tick that first sees it starts
+ # the TTL there.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ engine = media[arb.VIDEO]
+ _step()
+ engine.terminal = {"phase": "completed", "video": {"id": "clip-1"}}
+ _idle(arb.VIDEO) # the POST's stamp is already older than the TTL
+ _step()
+ assert engine.unloads == 0
+ # A restart, not a one-tick reprieve.
+ _step()
+ assert engine.unloads == 0
+ # The record itself keeps nothing warm: it is still published on that last tick, and
+ # only a record this tracker has not seen before counts as work having finished.
+ _step(arb.VIDEO)
+ assert engine.unloads == 1
+
+
+def test_a_veto_applied_during_the_step_stops_the_next_teardown(media, monkeypatch):
+ # One step tears down both backends and freeing several GB takes seconds. Reading the
+ # effective TTL once for the whole step let a residency veto turned on during the
+ # diffusion unload be ignored by the video one, so Studio freed a model its own settings
+ # response already reported as pinned.
+ ttl = {"value": 60}
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: ttl["value"])
+ diffusion, video = media[arb.DIFFUSION], media[arb.VIDEO]
+ real_unload = diffusion.unload
+
+ def _slow_unload():
+ # Model Memory residency (or API-only, or a TTL of 0) applied mid-teardown.
+ ttl["value"] = 0
+ return real_unload()
+
+ diffusion.unload = _slow_unload
+ _step()
+ _step(*_BOTH)
+ assert diffusion.unloads == 1
+ assert video.unloads == 0
+
+
+def test_a_ttl_raised_during_the_step_spares_the_next_teardown(media, monkeypatch):
+ # The same window, with the setting moved rather than vetoed: a TTL the backend is no
+ # longer past must be honoured by the teardown that has not happened yet.
+ ttl = {"value": 60}
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: ttl["value"])
+ diffusion, video = media[arb.DIFFUSION], media[arb.VIDEO]
+ real_unload = diffusion.unload
+
+ def _slow_unload():
+ ttl["value"] = 7200 # further out than the hour _idle backdates by
+ return real_unload()
+
+ diffusion.unload = _slow_unload
+ _step()
+ _step(*_BOTH)
+ assert diffusion.unloads == 1
+ assert video.unloads == 0
+
+
+def test_a_different_model_restarts_the_ttl(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ engine = media[arb.DIFFUSION]
+ _step()
+ engine.repo_id = "unsloth/FLUX.1-schnell"
+ _step(arb.DIFFUSION)
+ assert engine.unloads == 0
+
+
+def test_api_only_spares_a_model_the_user_loaded(media, store):
+ # The whole feature is off while the setting is on, and off means today's behaviour:
+ # nothing resolved, nothing unloaded.
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 60
+ store[settings.AUTO_UNLOAD_API_ONLY_SETTING_KEY] = True
+ _step()
+ _step(*_BOTH)
+ assert media[arb.DIFFUSION].unloads == 0
+ assert media[arb.VIDEO].unloads == 0
+ # Turned off again, the same idle models are collectable: the setting was the only
+ # thing sparing them, so this does not cost the feature anything else.
+ store[settings.AUTO_UNLOAD_API_ONLY_SETTING_KEY] = False
+ _step()
+ _step(*_BOTH)
+ assert media[arb.DIFFUSION].unloads == 1
+ assert media[arb.VIDEO].unloads == 1
+
+
+def test_a_cached_reload_of_another_h3_partition_is_not_unloaded(media, monkeypatch):
+ # MiniMax-H3 keeps its identity in more than the repo id: fl2va and ref2va are
+ # different denoiser partitions, and the quants are part of the build too. A cached
+ # reload between two ticks lands with the old timestamp already expired, so an
+ # identity that cannot tell the partitions apart frees it the moment it arrives.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ engine = media[arb.VIDEO]
+ engine.repo_id = "MiniMaxAI/MiniMax-H3"
+ engine.build = {"h3_task": "fl2va", "transformer_quant": "fp8", "text_encoder_quant": None}
+ _step()
+ engine.build["h3_task"] = "ref2va"
+ _step(arb.VIDEO)
+ assert engine.unloads == 0
+ # A quant swap is a rebuild as well.
+ engine.build["transformer_quant"] = None
+ _step(arb.VIDEO)
+ assert engine.unloads == 0
+ # Unchanged and idle, it is still collectable.
+ _step(arb.VIDEO)
+ assert engine.unloads == 1
+
+
+def test_disabled_ttl_never_touches_the_backends(media, monkeypatch):
+ # Today's behaviour, and the default: nothing is resolved, nothing is unloaded.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 0)
+ resolved = []
+ for owner in _BOTH:
+ monkeypatch.setitem(mk._ENGINES, owner, lambda o = owner: resolved.append(o))
+ arb.acquire_for(arb.VIDEO)
+ _step(*_BOTH)
+ _step(*_BOTH)
+ assert resolved == []
+ assert media[arb.DIFFUSION].unloads == 0
+ assert arb.current_owner() == arb.VIDEO
+
+
+def test_a_chat_ttl_alone_leaves_the_media_backends_alone(media, store, monkeypatch):
+ # Same consent line as the settings test, one level down: an install that had chat
+ # idle-unload on before this landed must tick exactly as it did before.
+ store[settings.OPENAI_AUTO_SWITCH_SETTING_KEY] = True
+ store[settings.AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ resolved = []
+ for owner in _BOTH:
+ monkeypatch.setitem(mk._ENGINES, owner, lambda o = owner: resolved.append(o))
+ _step(*_BOTH)
+ _step(*_BOTH)
+ assert resolved == []
+ assert media[arb.DIFFUSION].unloads == 0
+ assert media[arb.VIDEO].unloads == 0
+ # Turning the media TTL on is what starts it, and only that.
+ store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = 60
+ _step(*_BOTH)
+ assert resolved == list(_BOTH)
+
+
+def test_the_off_tick_does_not_import_the_media_modules(store, monkeypatch):
+ # Off is the default and has to stay free: the tick runs every 15s from startup, so
+ # importing diffusion or video to find out there is nothing loaded would drag torch
+ # into a Studio that never opened either page. No engine fakes here on purpose --
+ # this is the real resolution path.
+ store[settings.OPENAI_AUTO_SWITCH_SETTING_KEY] = True
+ store[settings.AUTO_UNLOAD_IDLE_SETTING_KEY] = 600
+ media_modules = {
+ "core.inference.diffusion",
+ "core.inference.sd_cpp_backend",
+ "core.inference.video",
+ }
+ for module in media_modules:
+ monkeypatch.delitem(sys.modules, module, raising = False)
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ asyncio.run(mk.idle_unload_step())
+ asyncio.run(mk.idle_unload_step())
+ assert not media_modules & set(sys.modules)
+
+
+def test_a_failing_unload_does_not_stop_the_other_backend(media, monkeypatch):
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+
+ def _boom():
+ raise RuntimeError("cuda teardown failed")
+
+ media[arb.DIFFUSION].unload = _boom
+ _step()
+ _step(*_BOTH)
+ assert media[arb.VIDEO].unloads == 1
+
+
+def test_an_unimported_backend_is_not_imported_to_check_it(monkeypatch):
+ # The tick runs every 15s from startup; resolving the engines would drag torch in
+ # on a Studio that has never opened the Image or Video page.
+ for module in ("core.inference.diffusion", "core.inference.sd_cpp_backend"):
+ monkeypatch.delitem(sys.modules, module, raising = False)
+ monkeypatch.delitem(sys.modules, "core.inference.video", raising = False)
+ assert mk._diffusion_engine() is None
+ assert mk._video_engine() is None
+
+
+# ── the request middleware ──────────────────────────────────────────
+
+
+def test_generate_routes_map_to_their_backend():
+ assert mk.owner_for_path("/api/inference/images/generate") == arb.DIFFUSION
+ assert mk.owner_for_path("/v1/images/generations") == arb.DIFFUSION
+ assert mk.owner_for_path("/api/inference/video/generate") == arb.VIDEO
+ # Progress polling while the user watches is not activity, and neither is chat.
+ assert mk.owner_for_path("/api/inference/images/generate-progress") is None
+ assert mk.owner_for_path("/api/inference/images/generate/cancel") is None
+ assert mk.owner_for_path("/v1/chat/completions") is None
+
+
+def test_a_path_that_is_not_a_mounted_route_is_not_tracked():
+ # A recognised prefix and a recognised tail is not a route. FastAPI answers these with a
+ # 404 without running an endpoint, and _finish() excludes only 401/403 from stamping
+ # activity, so an unauthenticated caller could hold a multi-GB pipeline resident forever
+ # by repeating one below the TTL.
+ assert mk.owner_for_path("/v1/not-a-route/images/generations") is None
+ assert mk.owner_for_path("/api/inference/nope/video/generate") is None
+ # The Studio routes are mounted under /api/inference only; /v1 carries the OpenAI shape.
+ assert mk.owner_for_path("/v1/images/generate") is None
+ assert mk.owner_for_path("/v1/video/load") is None
+
+
+def test_every_tracked_path_is_a_route_that_is_actually_mounted():
+ # Exact matching costs this: a renamed route would silently stop being tracked, and an
+ # untracked generate is one an idle tick can tear the pipeline down under. So pin the
+ # list to the routers main.py mounts, in both directions.
+ from routes.inference import router as inference_router
+ from routes.inference import studio_router
+ from routes.video import router as video_router
+
+ mounted = {
+ prefix + route.path
+ for router, prefixes in (
+ (inference_router, ("/api/inference", "/v1")),
+ (studio_router, ("/api/inference",)),
+ (video_router, ("/api/inference",)),
+ )
+ for route in router.routes
+ for prefix in prefixes
+ }
+ assert not set(mk._TRACKED_PATHS) - mounted
+ for path in mounted:
+ if ("/images/" in path or "/video/" in path) and path.rsplit("/", 1)[-1] in (
+ "generate",
+ "generations",
+ "load",
+ ):
+ assert mk.owner_for_path(path) is not None, path
+
+
+def test_load_routes_map_to_their_backend():
+ # A load registers with the backend only PART WAY through its POST, so the route has
+ # to hold the gate for the whole of it: sampling loading_repo_ids() cannot see a load
+ # the route has been accepted for but not yet started.
+ assert mk.owner_for_path("/api/inference/images/load") == arb.DIFFUSION
+ assert mk.owner_for_path("/api/inference/video/load") == arb.VIDEO
+ # Progress polling is not a load, and neither is planning a download.
+ assert mk.owner_for_path("/api/inference/images/load-progress") is None
+ assert mk.owner_for_path("/api/inference/video/load-progress") is None
+ assert mk.owner_for_path("/api/inference/images/download-plan") is None
+
+
+def test_a_load_that_has_not_registered_yet_is_not_unloaded(media, monkeypatch):
+ # The check/start race. The tick reads the backend as idle with no load in flight, the
+ # user's load is accepted a moment later, and the unload that tick issues bumps the load
+ # token and signals the fresh cancel event: the worker exits without publishing an error
+ # and the page silently rolls the pick back. The window has to be closed, not narrowed,
+ # so the tick is pinned to the exact moment the route has started and the backend still
+ # reports nothing loading.
+ from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware
+
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step()
+ engine = media[arb.VIDEO]
+ seen = {}
+
+ async def _app(scope, receive, send):
+ # Inside the load route, before begin_load has registered anything.
+ assert engine.loading == ()
+ _idle(arb.VIDEO)
+ await mk.idle_unload_step()
+ seen["unloads"] = engine.unloads
+ # begin_load registers only now; from here loading_repo_ids() covers it.
+ engine.loading = ("MiniMaxAI/MiniMax-H3",)
+ await send({"type": "http.response.start", "status": 200})
+ await send({"type": "http.response.body", "body": b"{}", "more_body": False})
+
+ scope = {"type": "http", "method": "POST", "path": "/api/inference/video/load"}
+ asyncio.run(LlamaKeepWarmMiddleware(_app)(scope, None, lambda message: _noop()))
+ assert seen["unloads"] == 0
+ assert engine.unloads == 0
+ assert mk._TRACKERS[arb.VIDEO]._inflight == 0
+ # The accepted load kept it: once the load is in flight the existing guard has it.
+ _step(arb.VIDEO)
+ assert engine.unloads == 0
+
+
+def test_the_middleware_counts_a_generation_against_its_backend(media, monkeypatch):
+ from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware
+
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step()
+ _idle(arb.DIFFUSION)
+ seen = {}
+
+ async def _app(scope, receive, send):
+ # Mid-request: the idle tick must see this backend as busy and spare it.
+ await mk.idle_unload_step()
+ seen["unloads"] = media[arb.DIFFUSION].unloads
+ await send({"type": "http.response.start", "status": 200})
+ await send({"type": "http.response.body", "body": b"{}", "more_body": False})
+
+ scope = {"type": "http", "method": "POST", "path": "/api/inference/images/generate"}
+ asyncio.run(LlamaKeepWarmMiddleware(_app)(scope, None, lambda message: _noop()))
+ assert seen["unloads"] == 0
+ assert mk._TRACKERS[arb.DIFFUSION]._inflight == 0
+
+
+async def _noop():
+ return None
+
+
+def test_a_cancelled_wait_on_the_media_gate_leaves_no_chat_request_behind(media, monkeypatch):
+ # The generate routes are counted on BOTH sides, and the media gate is held for the
+ # length of a teardown. A client that disconnects while waiting on it used to leave the
+ # process-wide chat count positive for good: chat idle unload would never fire again and
+ # every training start would go on being told an inference request was running.
+ import core.inference.llama_keepwarm as lk
+ from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware
+
+ monkeypatch.setattr(lk, "_inflight", 0)
+ monkeypatch.setattr(lk, "_pending", 0)
+ tracker = mk._TRACKERS[arb.DIFFUSION]
+
+ async def _app(scope, receive, send):
+ raise AssertionError("the request was cancelled before it could reach the app")
+
+ async def _run():
+ # Stand in for the tick: the gate is taken for the whole check-and-unload.
+ tracker.gate.acquire()
+ try:
+ scope = {
+ "type": "http",
+ "method": "POST",
+ "path": "/api/inference/images/generate",
+ }
+ task = asyncio.ensure_future(
+ LlamaKeepWarmMiddleware(_app)(scope, None, lambda message: _noop())
+ )
+ await asyncio.sleep(0.1)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ tracker.gate.release()
+
+ asyncio.run(_run())
+ assert lk._inflight == 0
+ assert lk._pending == 0
+ assert tracker._inflight == 0
+ assert tracker._pending == 0
+
+
+def test_an_unauthenticated_probe_does_not_keep_the_pipeline_warm(media, monkeypatch):
+ from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware
+
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step()
+ _idle(arb.DIFFUSION)
+
+ async def _app(scope, receive, send):
+ await send({"type": "http.response.start", "status": 401})
+ await send({"type": "http.response.body", "body": b"", "more_body": False})
+
+ scope = {"type": "http", "method": "POST", "path": "/v1/images/generations"}
+ asyncio.run(LlamaKeepWarmMiddleware(_app)(scope, None, lambda message: _noop()))
+ # The 401 never reached the backend, so the model is still idle and gets freed.
+ _step(arb.DIFFUSION)
+ assert media[arb.DIFFUSION].unloads == 1
+
+
+_BEARER = [(b"authorization", b"Bearer sk-unsloth-test")]
+
+
+def _stalled_media_request(path, headers):
+ """Open a tracked media POST that never sends a body, tick, and cancel it.
+
+ Stands in for a client that opens the connection and drips: the count is taken in the
+ middleware, ahead of the body parsing every one of these routes does before its auth
+ dependency runs, so nothing downstream ever produces a status for it."""
+
+ async def _run():
+ from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware
+
+ started = asyncio.Event()
+
+ async def _app(scope, receive, send):
+ started.set()
+ await asyncio.sleep(3600) # the body never arrives
+
+ scope = {"type": "http", "method": "POST", "path": path, "headers": headers}
+ task = asyncio.ensure_future(
+ LlamaKeepWarmMiddleware(_app)(scope, None, lambda message: _noop())
+ )
+ await started.wait()
+ _idle(arb.DIFFUSION)
+ await mk.idle_unload_step()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ asyncio.run(_run())
+
+
+def test_an_unauthenticated_stalled_request_cannot_pin_the_pipeline(media, monkeypatch):
+ # An exposed server: a client opens a POST to a tracked media route and withholds its
+ # body. It is counted before FastAPI authenticates or parses anything, and it produces
+ # no status, so the 401/403 exclusion never runs -- one held connection kept a multi-GB
+ # pipeline resident for the life of the process, which is the whole feature denied.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step()
+ _stalled_media_request("/api/inference/images/generate", [])
+ assert media[arb.DIFFUSION].unloads == 1
+ assert mk._TRACKERS[arb.DIFFUSION]._inflight == 0
+ assert mk._TRACKERS[arb.DIFFUSION]._pending == 0
+
+
+def test_an_authenticated_request_is_still_counted_before_its_body(media, monkeypatch):
+ # The other direction, which matters more: a real client's generation is protected from
+ # the moment its request arrives, body or no body.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+ _step()
+ _stalled_media_request("/api/inference/images/generate", _BEARER)
+ assert media[arb.DIFFUSION].unloads == 0
diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.py
index c48c2e2711a..40eee26d735 100644
--- a/studio/backend/tests/test_openai_auto_download.py
+++ b/studio/backend/tests/test_openai_auto_download.py
@@ -1172,7 +1172,7 @@ def test_setter_round_trips_auto_download_in_one_transaction(monkeypatch):
monkeypatch.setattr(settings, "_cached_setting", lambda k, d = None: store.get(k, d))
result = settings.set_openai_auto_switch(True, 120, None, True)
- assert result == (True, 120, True, True, False)
+ assert result == (True, 120, True, True, False, 0)
assert len(calls) == 1
assert calls[0][settings.OPENAI_AUTO_DOWNLOAD_SETTING_KEY] is True
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 1b2529df7da..c8e423fc781 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -788,7 +788,7 @@ def test_disabling_idle_unload_purges_saved_kv(monkeypatch, tmp_path):
"slots": [{"id": 0, "filename": saved.name}],
}
monkeypatch.setattr(
- settings_route, "set_openai_auto_switch", lambda *a: (False, 300, True, False, False)
+ settings_route, "set_openai_auto_switch", lambda *a: (False, 300, True, False, False, 0)
)
monkeypatch.setattr(settings_route, "get_auto_unload_idle_seconds", lambda: 0)
@@ -813,7 +813,7 @@ def test_residency_does_not_purge_saved_kv(monkeypatch, tmp_path):
}
kw._kv_resume = manifest
monkeypatch.setattr(
- settings_route, "set_openai_auto_switch", lambda *a: (True, 300, True, False, False)
+ settings_route, "set_openai_auto_switch", lambda *a: (True, 300, True, False, False, 0)
)
monkeypatch.setattr(settings_route, "get_auto_unload_idle_seconds", lambda: 0)
monkeypatch.setattr(settings_route, "idle_unload_is_configured", lambda: True)
@@ -5450,11 +5450,21 @@ def test_keep_kv_only_update_leaves_env_idle_ttl_active(monkeypatch):
monkeypatch.setenv(settings.MODEL_IDLE_TTL_ENV_VAR, "600")
assert settings_route.OpenAIAutoSwitchPayload(enabled = False).auto_unload_idle_seconds is None
- enabled, idle, keep_kv, auto_dl, api_only = settings.set_openai_auto_switch(False, None, False)
+ enabled, idle, keep_kv, auto_dl, api_only, media_idle = settings.set_openai_auto_switch(
+ False, None, False
+ )
assert settings.AUTO_UNLOAD_IDLE_SETTING_KEY not in store # idle untouched
assert settings.OPENAI_AUTO_DOWNLOAD_SETTING_KEY not in store # nor auto-download
+ assert settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY not in store # nor the media TTL
assert settings.get_auto_unload_idle_seconds() == 600 # env TTL still active
- assert (enabled, idle, keep_kv, auto_dl, api_only) == (False, 600, False, False, False)
+ assert (enabled, idle, keep_kv, auto_dl, api_only, media_idle) == (
+ False,
+ 600,
+ False,
+ False,
+ False,
+ 0,
+ )
def test_load_impl_notes_loaded_with_backend_off_loop():
@@ -5504,6 +5514,61 @@ def test_setter_rejects_idle_below_floor(monkeypatch):
assert settings.set_openai_auto_switch(True, 3600)[1] == 3600
+def test_media_idle_setting_roundtrip_and_default(monkeypatch):
+ # The image/video TTL is persisted on its own key, in the same write as the rest
+ # of the section, and starts off: a chat TTL alone must not evict a pipeline.
+ import storage.studio_db as db
+
+ store = {}
+ monkeypatch.setattr(db, "upsert_app_settings", lambda m: store.update(m))
+ monkeypatch.setattr(settings, "_cached_setting", lambda k, d = None: store.get(k, d))
+ monkeypatch.delenv(settings.MEDIA_IDLE_TTL_ENV_VAR, raising = False)
+
+ assert settings.set_openai_auto_switch(True, 300)[5] == 0
+ assert settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY not in store
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+ assert settings.get_auto_unload_idle_seconds() == 300
+
+ assert settings.set_openai_auto_switch(True, 300, None, None, None, 600)[5] == 600
+ assert store[settings.MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] == 600
+ assert settings.get_media_auto_unload_idle_seconds() == 600
+ assert settings.get_stored_media_auto_unload_idle_seconds() == 600
+ # None leaves the stored value untouched, and the floor is the chat one.
+ assert settings.set_openai_auto_switch(False, None)[5] == 600
+ with pytest.raises(ValueError, match = "at least 60"):
+ settings.set_openai_auto_switch(True, None, None, None, None, 30)
+ assert settings.set_openai_auto_switch(True, None, None, None, None, 0)[5] == 0
+ assert settings.get_media_auto_unload_idle_seconds() == 0
+
+
+def test_settings_route_reports_the_media_idle_ttl(monkeypatch):
+ import routes.settings as settings_route
+
+ monkeypatch.setattr(settings_route, "get_stored_media_auto_unload_idle_seconds", lambda: 600)
+ monkeypatch.setattr(settings_route, "get_media_auto_unload_idle_seconds", lambda: 600)
+ resp = settings_route.get_openai_auto_switch("tester")
+ assert resp.media_auto_unload_idle_seconds == 600
+ assert resp.media_idle_unload_active is True
+ # Vetoed (residency, or API-loaded only): the saved number stays, the flag drops,
+ # so the UI can say the unload is paused rather than silently doing nothing.
+ monkeypatch.setattr(settings_route, "get_media_auto_unload_idle_seconds", lambda: 0)
+ resp = settings_route.get_openai_auto_switch("tester")
+ assert resp.media_auto_unload_idle_seconds == 600
+ assert resp.media_idle_unload_active is False
+
+
+def test_put_route_rejects_media_idle_below_floor():
+ import routes.settings as settings_route
+ from fastapi import HTTPException
+
+ payload = settings_route.OpenAIAutoSwitchPayload(
+ enabled = True, media_auto_unload_idle_seconds = 30
+ )
+ with pytest.raises(HTTPException) as excinfo:
+ settings_route.update_openai_auto_switch(payload, "tester")
+ assert excinfo.value.status_code == 400
+
+
def test_put_route_rejects_idle_below_floor():
import routes.settings as settings_route
from fastapi import HTTPException
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index 1df89321eec..72db44dacdf 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -14,11 +14,17 @@ All off by default so existing API behavior is unchanged:
unloaded after this many idle seconds to free VRAM. Enabled values have a
60s floor (0 stays "off"): a tiny TTL tears the model down between turns of
an active chat, forcing a full weight reload + prompt re-prefill per turn.
-
-The idle TTL can also be set at startup via the ``UNSLOTH_MODEL_IDLE_TTL`` env
-var. Unlike the stored setting (which stays gated on auto-switch), the env value
-is a standalone default that enables idle-unload even with auto-switch off, for
-headless/container deploys; an explicit UI/API value still overrides it.
+- ``media_auto_unload_idle_seconds``: the same for the image and video
+ pipelines. Its own setting, not a share of the chat one: this section is
+ about the OpenAI API and nothing here says it frees a model the user loaded
+ on the Image or Video page, so turning that one on must not start evicting
+ these.
+
+Either idle TTL can also be set at startup via ``UNSLOTH_MODEL_IDLE_TTL`` /
+``UNSLOTH_MEDIA_IDLE_TTL``. Unlike the stored setting (which stays gated on
+auto-switch), the env value is a standalone default that enables idle-unload
+even with auto-switch off, for headless/container deploys; an explicit UI/API
+value still overrides it.
Reads are cached for a short window because these are consulted on the
per-request hot path; writes invalidate the cache.
@@ -35,14 +41,17 @@ from typing import Any, Optional
OPENAI_AUTO_SWITCH_SETTING_KEY = "openai_api_auto_switch_model"
OPENAI_AUTO_DOWNLOAD_SETTING_KEY = "openai_api_auto_download_model"
AUTO_UNLOAD_IDLE_SETTING_KEY = "openai_api_auto_unload_idle_seconds"
+MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY = "media_auto_unload_idle_seconds"
AUTO_UNLOAD_KEEP_KV_SETTING_KEY = "openai_api_auto_unload_keep_kv"
AUTO_UNLOAD_API_ONLY_SETTING_KEY = "openai_api_auto_unload_api_only"
MODEL_OVERRIDES_SETTING_KEY = "openai_api_auto_switch_overrides"
MODEL_IDLE_TTL_ENV_VAR = "UNSLOTH_MODEL_IDLE_TTL"
+MEDIA_IDLE_TTL_ENV_VAR = "UNSLOTH_MEDIA_IDLE_TTL"
DEFAULT_OPENAI_AUTO_SWITCH_ENABLED = False
DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED = False
DEFAULT_AUTO_UNLOAD_IDLE_SECONDS = 0
+DEFAULT_MEDIA_AUTO_UNLOAD_IDLE_SECONDS = 0
DEFAULT_AUTO_UNLOAD_KEEP_KV = True
DEFAULT_AUTO_UNLOAD_API_ONLY = False
MIN_AUTO_UNLOAD_IDLE_SECONDS = 60
@@ -124,36 +133,47 @@ def _stored_idle_seconds() -> Optional[int]:
return _coerce_int(_cached_setting(AUTO_UNLOAD_IDLE_SETTING_KEY, None))
-_env_floor_warned = False
+def _stored_media_idle_seconds() -> Optional[int]:
+ """The persisted image/video idle TTL as an int, or None when never set."""
+ return _coerce_int(_cached_setting(MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY, None))
-def _env_idle_seconds() -> Optional[int]:
- """UNSLOTH_MODEL_IDLE_TTL as a non-negative seconds value, or None if unset/invalid.
+_env_floor_warned: set[str] = set()
+
+
+def _env_ttl(var: str) -> Optional[int]:
+ """``var`` as a non-negative seconds value, or None if unset/invalid.
Floored to MIN_AUTO_UNLOAD_IDLE_SECONDS here (with a one-time warning) since
headless/container deploys have no UI to surface a validation error."""
- raw = os.environ.get(MODEL_IDLE_TTL_ENV_VAR)
+ raw = os.environ.get(var)
if raw is None or not raw.strip():
return None
parsed = _coerce_int(raw)
if parsed is None:
return None
floored = _apply_idle_floor(parsed)
- if floored != parsed:
- global _env_floor_warned
- if not _env_floor_warned:
- _env_floor_warned = True
- from loggers import get_logger
- get_logger(__name__).warning(
- "%s=%s is below the %ss minimum; using %ss",
- MODEL_IDLE_TTL_ENV_VAR,
- parsed,
- MIN_AUTO_UNLOAD_IDLE_SECONDS,
- floored,
- )
+ if floored != parsed and var not in _env_floor_warned:
+ _env_floor_warned.add(var)
+ from loggers import get_logger
+ get_logger(__name__).warning(
+ "%s=%s is below the %ss minimum; using %ss",
+ var,
+ parsed,
+ MIN_AUTO_UNLOAD_IDLE_SECONDS,
+ floored,
+ )
return floored
+def _env_idle_seconds() -> Optional[int]:
+ return _env_ttl(MODEL_IDLE_TTL_ENV_VAR)
+
+
+def _env_media_idle_seconds() -> Optional[int]:
+ return _env_ttl(MEDIA_IDLE_TTL_ENV_VAR)
+
+
def get_stored_auto_unload_idle_seconds() -> int:
"""The persisted idle-unload TTL, independent of whether auto-switch is on.
@@ -170,16 +190,35 @@ def get_stored_auto_unload_idle_seconds() -> int:
return env if env is not None else DEFAULT_AUTO_UNLOAD_IDLE_SECONDS
+def get_stored_media_auto_unload_idle_seconds() -> int:
+ """The persisted image/video idle TTL, before any veto.
+
+ The settings UI reads this so it can display and round-trip the saved value.
+ Falls back to the env override so the UI shows the startup default. The idle
+ loop uses the gated reader below.
+ """
+ stored = _stored_media_idle_seconds()
+ if stored is not None:
+ return _apply_idle_floor(stored)
+ env = _env_media_idle_seconds()
+ return env if env is not None else DEFAULT_MEDIA_AUTO_UNLOAD_IDLE_SECONDS
+
+
+def _residency_vetoes_unload() -> bool:
+ """Model Memory residency pins the weights, so no idle TTL applies."""
+ try:
+ from utils.model_memory_settings import get_keep_resident
+ return bool(get_keep_resident())
+ except Exception:
+ return False
+
+
def get_auto_unload_idle_seconds() -> int:
"""Effective idle TTL the idle loop runs on (0 = never unload)."""
# Model Memory residency vetoes the TTL. Effective reader only, so the stored
# reader keeps the number the user typed and it returns when they turn it off.
- try:
- from utils.model_memory_settings import get_keep_resident
- if get_keep_resident():
- return 0
- except Exception:
- pass
+ if _residency_vetoes_unload():
+ return 0
stored = _stored_idle_seconds()
if stored is not None:
# An explicit UI/API value stays gated on auto-switch: off reports 0 so the
@@ -192,6 +231,27 @@ def get_auto_unload_idle_seconds() -> int:
return env if env is not None else 0
+def get_media_auto_unload_idle_seconds() -> int:
+ """Effective idle TTL for the image and video backends (0 = never unload).
+
+ Its own setting, off by default: the chat TTL lives under "Model auto-switch
+ (OpenAI API)" and says nothing about image or video, so inheriting it would
+ start evicting pipelines on upgrade for everyone who had turned that on.
+ UNSLOTH_MEDIA_IDLE_TTL is the startup default when nothing is stored, exactly
+ as UNSLOTH_MODEL_IDLE_TTL is for chat.
+
+ Residency vetoes it like the chat reader, and so does "only unload models
+ loaded by the API": /images/load and /video/load are the only way a pipeline
+ is ever loaded (the OpenAI images route 503s instead of loading one), so every
+ resident image or video model is one the user loaded from Studio and the
+ setting promises to leave it alone. Chat can tell its two origins apart per
+ model and still frees the API-loaded ones; here there is nothing to free.
+ """
+ if get_auto_unload_api_only() or _residency_vetoes_unload():
+ return 0
+ return get_stored_media_auto_unload_idle_seconds()
+
+
def idle_unload_is_configured() -> bool:
"""The user's idle-unload setting, ignoring the residency veto.
@@ -223,7 +283,8 @@ def set_openai_auto_switch(
keep_kv: Any = None,
auto_download: Any = None,
api_only: Any = None,
-) -> tuple[bool, int, bool, bool, bool]:
+ media_idle_seconds: Any = None,
+) -> tuple[bool, int, bool, bool, bool, int]:
"""One-transaction write; ``None`` leaves a stored value untouched."""
parsed_enabled = _coerce_bool(enabled)
if parsed_enabled is None:
@@ -238,6 +299,16 @@ def set_openai_auto_switch(
f"Auto-unload idle seconds must be 0 (off) or at least "
f"{MIN_AUTO_UNLOAD_IDLE_SECONDS}."
)
+ parsed_media_idle = None
+ if media_idle_seconds is not None:
+ parsed_media_idle = _coerce_int(media_idle_seconds)
+ if parsed_media_idle is None:
+ raise ValueError("Media auto-unload idle seconds must be a non-negative integer.")
+ if 0 < parsed_media_idle < MIN_AUTO_UNLOAD_IDLE_SECONDS:
+ raise ValueError(
+ f"Media auto-unload idle seconds must be 0 (off) or at least "
+ f"{MIN_AUTO_UNLOAD_IDLE_SECONDS}."
+ )
parsed_keep_kv = None
if keep_kv is not None:
parsed_keep_kv = _coerce_bool(keep_kv)
@@ -258,6 +329,8 @@ def set_openai_auto_switch(
updates: dict[str, Any] = {OPENAI_AUTO_SWITCH_SETTING_KEY: parsed_enabled}
if parsed_idle is not None:
updates[AUTO_UNLOAD_IDLE_SETTING_KEY] = parsed_idle
+ if parsed_media_idle is not None:
+ updates[MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY] = parsed_media_idle
if parsed_keep_kv is not None:
updates[AUTO_UNLOAD_KEEP_KV_SETTING_KEY] = parsed_keep_kv
if parsed_auto_download is not None:
@@ -268,6 +341,8 @@ def set_openai_auto_switch(
_invalidate(OPENAI_AUTO_SWITCH_SETTING_KEY)
if parsed_idle is not None:
_invalidate(AUTO_UNLOAD_IDLE_SETTING_KEY)
+ if parsed_media_idle is not None:
+ _invalidate(MEDIA_AUTO_UNLOAD_IDLE_SETTING_KEY)
if parsed_keep_kv is not None:
_invalidate(AUTO_UNLOAD_KEEP_KV_SETTING_KEY)
if parsed_auto_download is not None:
@@ -284,6 +359,11 @@ def set_openai_auto_switch(
else get_stored_openai_auto_download_enabled()
),
parsed_api_only if parsed_api_only is not None else get_auto_unload_api_only(),
+ (
+ parsed_media_idle
+ if parsed_media_idle is not None
+ else get_stored_media_auto_unload_idle_seconds()
+ ),
)
diff --git a/studio/frontend/src/features/settings/api/openai-auto-switch.ts b/studio/frontend/src/features/settings/api/openai-auto-switch.ts
index 7b191a64853..2ef71b93c51 100644
--- a/studio/frontend/src/features/settings/api/openai-auto-switch.ts
+++ b/studio/frontend/src/features/settings/api/openai-auto-switch.ts
@@ -17,6 +17,12 @@ export type OpenAIAutoSwitchSettings = {
autoDownloadModel: boolean;
// Spare models loaded from the UI on idle unload; only free API-loaded ones.
autoUnloadApiOnly: boolean;
+ // Idle TTL for the image and video pipelines. Its own setting, off by default:
+ // the chat TTL above is about the OpenAI API and never implied these.
+ mediaAutoUnloadIdleSeconds: number;
+ // True when the media idle unload will actually run, so the UI can say a veto
+ // (residency, or API-loaded only) is holding a saved TTL off.
+ mediaIdleUnloadActive: boolean;
};
type ApiOpenAIAutoSwitchSettings = {
@@ -33,6 +39,10 @@ type ApiOpenAIAutoSwitchSettings = {
auto_download_model?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
auto_unload_api_only?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_auto_unload_idle_seconds?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_idle_unload_active?: boolean;
};
let cachedSettings: OpenAIAutoSwitchSettings | null = null;
@@ -53,6 +63,8 @@ function fromApi(
autoUnloadKeepKv: settings.auto_unload_keep_kv ?? true,
autoDownloadModel: settings.auto_download_model ?? false,
autoUnloadApiOnly: settings.auto_unload_api_only ?? false,
+ mediaAutoUnloadIdleSeconds: settings.media_auto_unload_idle_seconds ?? 0,
+ mediaIdleUnloadActive: settings.media_idle_unload_active ?? false,
};
}
@@ -131,6 +143,7 @@ export async function updateOpenAIAutoSwitchSettings(
autoUnloadKeepKv?: boolean,
autoDownloadModel?: boolean,
autoUnloadApiOnly?: boolean,
+ mediaAutoUnloadIdleSeconds?: number,
): Promise<OpenAIAutoSwitchSettings> {
// Read BEFORE the request: idleUnloadActive depends on the Model Memory
// setting, so a residency write landing mid-flight makes this response stale
@@ -158,6 +171,10 @@ export async function updateOpenAIAutoSwitchSettings(
? {}
: // biome-ignore lint/style/useNamingConvention: API schema
{ auto_unload_api_only: autoUnloadApiOnly }),
+ ...(mediaAutoUnloadIdleSeconds === undefined
+ ? {}
+ : // biome-ignore lint/style/useNamingConvention: API schema
+ { media_auto_unload_idle_seconds: mediaAutoUnloadIdleSeconds }),
}),
});
if (!res.ok) {
diff --git a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx
index 6d4ba81429f..d68a1ad39ab 100644
--- a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx
+++ b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx
@@ -17,13 +17,88 @@ import { SettingsSection } from "./settings-section";
// Mirrors MIN_AUTO_UNLOAD_IDLE_SECONDS in the backend settings store.
const MIN_IDLE_SECONDS = 60;
+// Its own row so the section keeps one job per control: this TTL has no enable
+// toggle in front of it, unlike the chat one above.
+function MediaIdleUnloadRow({
+ draftSeconds,
+ onDraftChange,
+ onSave,
+ settings,
+ isSaving,
+ error,
+}: {
+ draftSeconds: string;
+ onDraftChange: (value: string) => void;
+ onSave: () => void;
+ settings: OpenAIAutoSwitchSettings | null;
+ isSaving: boolean;
+ error: string | null;
+}) {
+ const t = useT();
+ const disabled = !settings || isSaving;
+ // A saved TTL that cannot run: residency or "only unload models loaded by the
+ // API" is vetoing it, and the number alone would not say so.
+ const paused =
+ settings !== null &&
+ settings.mediaAutoUnloadIdleSeconds > 0 &&
+ !settings.mediaIdleUnloadActive;
+ return (
+ <SettingsRow
+ label={t("settings.general.modelAutoSwitch.mediaIdleUnload")}
+ description={t(
+ "settings.general.modelAutoSwitch.mediaIdleUnloadDescription",
+ )}
+ >
+ <div className="flex flex-col items-end gap-1">
+ <div className="flex items-center gap-2">
+ <div className="flex items-center gap-1.5">
+ <Input
+ type="number"
+ min={0}
+ step={1}
+ value={draftSeconds}
+ aria-label={t(
+ "settings.general.modelAutoSwitch.mediaIdleSecondsAriaLabel",
+ )}
+ disabled={disabled}
+ onChange={(event) => onDraftChange(event.target.value)}
+ className="h-8 w-24"
+ />
+ <span className="text-xs font-medium text-muted-foreground">s</span>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={onSave}
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ </div>
+ {error ? (
+ <span className="max-w-[260px] text-right text-xs text-destructive">
+ {error}
+ </span>
+ ) : paused ? (
+ <span className="max-w-[260px] text-right text-xs text-muted-foreground">
+ {t("settings.general.modelAutoSwitch.mediaIdlePaused")}
+ </span>
+ ) : null}
+ </div>
+ </SettingsRow>
+ );
+}
+
export function ModelAutoSwitchSection() {
const t = useT();
const [settings, setSettings] = useState<OpenAIAutoSwitchSettings | null>(
null,
);
const [draftIdleSeconds, setDraftIdleSeconds] = useState("0");
+ const [draftMediaIdleSeconds, setDraftMediaIdleSeconds] = useState("0");
const [error, setError] = useState<string | null>(null);
+ // The media row validates its own input, so its message belongs beside it.
+ const [mediaError, setMediaError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
useEffect(() => {
@@ -33,6 +108,7 @@ export function ModelAutoSwitchSection() {
if (cancelled) return;
setSettings(loaded);
setDraftIdleSeconds(String(loaded.autoUnloadIdleSeconds));
+ setDraftMediaIdleSeconds(String(loaded.mediaAutoUnloadIdleSeconds));
setError(null);
})
.catch((loadError) => {
@@ -48,12 +124,12 @@ export function ModelAutoSwitchSection() {
};
}, [t]);
- // Parse the idle-seconds draft: 0 (off) or >= MIN_IDLE_SECONDS; else null.
- const parseIdleSeconds = (): number | null => {
- if (!draftIdleSeconds.trim()) {
+ // Parse an idle-seconds draft: 0 (off) or >= MIN_IDLE_SECONDS; else null.
+ const parseIdleSeconds = (draft: string): number | null => {
+ if (!draft.trim()) {
return null;
}
- const parsed = Number(draftIdleSeconds);
+ const parsed = Number(draft);
if (!Number.isInteger(parsed)) {
return null;
}
@@ -67,6 +143,7 @@ export function ModelAutoSwitchSection() {
keepKv?: boolean,
autoDownload?: boolean,
apiOnly?: boolean,
+ mediaIdleSeconds?: number,
) => {
setIsSaving(true);
setError(null);
@@ -77,8 +154,12 @@ export function ModelAutoSwitchSection() {
keepKv,
autoDownload,
apiOnly,
+ mediaIdleSeconds,
);
setSettings(saved);
+ if (mediaIdleSeconds !== undefined) {
+ setDraftMediaIdleSeconds(String(saved.mediaAutoUnloadIdleSeconds));
+ }
if (syncDraft) {
setDraftIdleSeconds(String(saved.autoUnloadIdleSeconds));
}
@@ -104,11 +185,11 @@ export function ModelAutoSwitchSection() {
void persist(false, savedIdleSeconds, false);
return;
}
- void persist(true, parseIdleSeconds() ?? savedIdleSeconds);
+ void persist(true, parseIdleSeconds(draftIdleSeconds) ?? savedIdleSeconds);
};
const handleSaveIdle = () => {
- const idleSeconds = parseIdleSeconds();
+ const idleSeconds = parseIdleSeconds(draftIdleSeconds);
if (idleSeconds === null) {
setError(t("settings.general.modelAutoSwitch.idleError"));
return;
@@ -116,6 +197,28 @@ export function ModelAutoSwitchSection() {
void persist(true, idleSeconds);
};
+ // The image/video TTL is its own setting, so it saves on its own: no enable
+ // toggle gates it, and the chat seconds are left untouched.
+ const handleSaveMediaIdle = () => {
+ if (!settings) return;
+ const mediaIdleSeconds = parseIdleSeconds(draftMediaIdleSeconds);
+ setMediaError(
+ mediaIdleSeconds === null
+ ? t("settings.general.modelAutoSwitch.idleError")
+ : null,
+ );
+ if (mediaIdleSeconds === null) return;
+ void persist(
+ settings.enabled,
+ undefined,
+ false,
+ undefined,
+ undefined,
+ undefined,
+ mediaIdleSeconds,
+ );
+ };
+
const handleKeepKvToggle = (keepKv: boolean) => {
if (!settings) return;
void persist(settings.enabled, undefined, false, keepKv);
@@ -211,33 +314,41 @@ export function ModelAutoSwitchSection() {
) : null}
</div>
</SettingsRow>
+ <MediaIdleUnloadRow
+ draftSeconds={draftMediaIdleSeconds}
+ onDraftChange={setDraftMediaIdleSeconds}
+ onSave={handleSaveMediaIdle}
+ settings={settings}
+ isSaving={isSaving}
+ error={mediaError}
+ />
{settings?.idleUnloadActive ? (
- <>
- <SettingsRow
- label={t("settings.general.modelAutoSwitch.keepKv")}
- description={t(
- "settings.general.modelAutoSwitch.keepKvDescription",
- )}
- >
- <Switch
- checked={settings.autoUnloadKeepKv}
- disabled={isSaving}
- onCheckedChange={handleKeepKvToggle}
- />
- </SettingsRow>
- <SettingsRow
- label={t("settings.general.modelAutoSwitch.apiOnly")}
- description={t(
- "settings.general.modelAutoSwitch.apiOnlyDescription",
- )}
- >
- <Switch
- checked={settings.autoUnloadApiOnly}
- disabled={isSaving}
- onCheckedChange={handleApiOnlyToggle}
- />
- </SettingsRow>
- </>
+ <SettingsRow
+ label={t("settings.general.modelAutoSwitch.keepKv")}
+ description={t("settings.general.modelAutoSwitch.keepKvDescription")}
+ >
+ <Switch
+ checked={settings.autoUnloadKeepKv}
+ disabled={isSaving}
+ onCheckedChange={handleKeepKvToggle}
+ />
+ </SettingsRow>
+ ) : null}
+ {/* Also whenever a media TTL is saved: this switch vetoes that TTL, and hiding it
+ behind the chat one leaves the media row stuck on "paused" with the only way out
+ being to re-enable chat unloading first. */}
+ {settings &&
+ (settings.idleUnloadActive || settings.mediaAutoUnloadIdleSeconds > 0) ? (
+ <SettingsRow
+ label={t("settings.general.modelAutoSwitch.apiOnly")}
+ description={t("settings.general.modelAutoSwitch.apiOnlyDescription")}
+ >
+ <Switch
+ checked={settings.autoUnloadApiOnly}
+ disabled={isSaving}
+ onCheckedChange={handleApiOnlyToggle}
+ />
+ </SettingsRow>
) : null}
</SettingsSection>
);
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 94f49f0c2f1..0fbd60125a8 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -1860,15 +1860,40 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
[],
);
- const refreshStatus = useCallback(async () => {
+ // Answers with what it wrote, or null when the read failed or a newer one superseded it,
+ // so a caller can act on what the server now says.
+ const refreshStatus = useCallback(async (): Promise<VideoStatus | null> => {
const ticket = ++statusTicket.current;
try {
- setStatusIfNewest(ticket, await getVideoStatus());
+ const next = await getVideoStatus();
+ setStatusIfNewest(ticket, next);
+ return ticket === statusTicket.current ? next : null;
} catch {
// Status is best-effort; a failed poll shouldn't surface an error toast.
+ return null;
}
}, [setStatusIfNewest]);
+ // A generation can be refused because the runtime went away under the page: an idle
+ // auto-unload frees it server-side and the browser hears nothing, since the eject event
+ // is raised by whoever clicked eject. Without a re-read here Generate stays enabled off
+ // the stale flag and every retry 409s again, so the refusal is the news that the model
+ // is gone. Also clears the state that only means anything while one is resident (the
+ // Reapply target, a replacement load's tracking), as the indicator eject does.
+ const resyncAfterGenerateRefusal = useCallback(async () => {
+ // A model picked while this read is in flight makes the answer stale rather than wrong:
+ // /video/status reports committed state, so it says loaded: false for the load that has
+ // just started. Acting on it would dismiss that load's toast and poll, and -- while its
+ // start request is still out -- the cancel it counts as sends the compensating unload
+ // that tears it down. The load counter is the fence handleLoad already bumps.
+ const startLoad = loadSeq.current;
+ const next = await refreshStatus();
+ if (!isMounted.current || next === null || next.loaded) return;
+ if (startLoad !== loadSeq.current) return;
+ dropResidentState();
+ setQuant(null);
+ }, [refreshStatus, dropResidentState]);
+
// Track mount so a long generate stops issuing GPU work when the page is truly unmounted.
useEffect(() => {
isMounted.current = true;
@@ -3003,6 +3028,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
toast.error(err instanceof Error ? err.message : "Video generation failed");
setBusy(null);
setGenStep(null);
+ // The refusal can be "No video model is loaded": re-read rather than leave Generate
+ // enabled against a runtime that is already free.
+ void resyncAfterGenerateRefusal();
return;
}
// Track live progress + the terminal outcome via the shared poll loop (also used by the mount-time resume).
@@ -3033,6 +3061,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
defaultAudioFlowShift,
canPickAudioFlowShift,
startGenPoll,
+ resyncAfterGenerateRefusal,
]);
// The Advanced (load-time) tuning controls, rendered in the right-docked panel below.
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index e62784fcabe..8222e282b8e 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -369,6 +369,13 @@ export const ar = {
"حرّر ذاكرة VRAM بعد هذا العدد من ثواني الخمول. تُبقي القيمة 0 النموذج محمّلًا، والحد الأدنى 60 ثانية.",
idleSecondsAriaLabel:
"عدد الثواني قبل التفريغ التلقائي عند الخمول",
+ mediaIdleUnload: "التفريغ التلقائي عند الخمول للصور والفيديو",
+ mediaIdleUnloadDescription:
+ "حرّر ذاكرة VRAM بتفريغ نموذجَي الصور والفيديو بعد هذا العدد من ثواني الخمول. إنه إعداد مستقل: الإعداد أعلاه يخصّ نموذج المحادثة فقط. تُبقي القيمة 0 النموذجين محمَّلين، والحد الأدنى 60 ثانية.",
+ mediaIdleSecondsAriaLabel:
+ "عدد الثواني قبل التفريغ التلقائي عند الخمول للصور والفيديو",
+ mediaIdlePaused:
+ "متوقف مؤقتًا ما دام «إبقاء النموذج في ذاكرة كرت الرسوميات» أو «تفريغ النماذج التي حمّلتها واجهة API فقط» مفعّلًا.",
idleNeedsEnable: "فعّل «تبديل النموذج حسب الطلب» أولًا.",
idleActiveViaEnv:
"التفريغ التلقائي عند الخمول مُفعَّل عبر متغير البيئة UNSLOTH_MODEL_IDLE_TTL.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 676b7b6d087..fdf18db3cc1 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -382,6 +382,14 @@ export const de = {
"Gibt VRAM nach der angegebenen Anzahl von Sekunden ohne Aktivität frei. Bei 0 bleibt das Modell geladen; der Mindestwert ist 60.",
idleSecondsAriaLabel:
"Inaktivitätsdauer bis zum automatischen Entladen in Sekunden",
+ mediaIdleUnload:
+ "Automatisches Entladen bei Inaktivität für Bild und Video",
+ mediaIdleUnloadDescription:
+ "Gibt VRAM frei, indem die Bild- und Videomodelle nach der angegebenen Anzahl von Sekunden ohne Aktivität entladen werden. Eine eigene Einstellung: Die Einstellung darüber gilt nur für das Chat-Modell. Bei 0 bleiben sie geladen; der Mindestwert ist 60.",
+ mediaIdleSecondsAriaLabel:
+ "Inaktivitätsdauer bis zum automatischen Entladen von Bild und Video in Sekunden",
+ mediaIdlePaused:
+ "Pausiert, solange „Modell im GPU-Speicher behalten“ oder „Nur über die API geladene Modelle entladen“ aktiv ist.",
idleNeedsEnable: "Aktivieren Sie zuerst „Modell je Anfrage wechseln“.",
idleActiveViaEnv:
"Automatisches Entladen bei Inaktivität ist über die Umgebungsvariable UNSLOTH_MODEL_IDLE_TTL aktiv.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e40ccdd5a3d..8bc2ed0f9cd 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -367,6 +367,12 @@ export const en = {
idleUnloadDescription:
"Free VRAM after this many idle seconds. 0 keeps it loaded, minimum 60.",
idleSecondsAriaLabel: "Idle auto-unload seconds",
+ mediaIdleUnload: "Idle auto-unload for image and video",
+ mediaIdleUnloadDescription:
+ "Free VRAM by unloading the image and video models after this many idle seconds. Its own setting: the one above covers the chat model only. 0 keeps them loaded, minimum 60.",
+ mediaIdleSecondsAriaLabel: "Image and video idle auto-unload seconds",
+ mediaIdlePaused:
+ "Paused while Keep model in GPU memory or Only unload models loaded by the API is on.",
idleNeedsEnable: "Turn on Switch model by request first.",
idleActiveViaEnv: "Active via UNSLOTH_MODEL_IDLE_TTL.",
loadError: "Failed to load model auto-switch settings.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index d5464a718da..38056302c97 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -378,6 +378,14 @@ export const es = {
"Libera la VRAM después de este número de segundos de inactividad. El valor 0 mantiene el modelo cargado; el mínimo es 60.",
idleSecondsAriaLabel:
"Segundos de inactividad antes de liberar el modelo",
+ mediaIdleUnload:
+ "Liberar imagen y vídeo automáticamente por inactividad",
+ mediaIdleUnloadDescription:
+ "Libera la VRAM descargando los modelos de imagen y vídeo después de este número de segundos de inactividad. Es una configuración independiente: la de arriba solo afecta al modelo de chat. El valor 0 los mantiene cargados; el mínimo es 60.",
+ mediaIdleSecondsAriaLabel:
+ "Segundos de inactividad antes de liberar los modelos de imagen y vídeo",
+ mediaIdlePaused:
+ "En pausa mientras «Mantener el modelo en la memoria de la GPU» o «Liberar solo los modelos cargados por la API» esté activado.",
idleNeedsEnable: "Activa primero «Cambiar de modelo según la solicitud».",
idleActiveViaEnv:
"La descarga automática por inactividad está activa mediante la variable de entorno UNSLOTH_MODEL_IDLE_TTL.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 9628b47979b..f23d133152d 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -380,6 +380,14 @@ export const fr = {
"Libérer la VRAM après ce nombre de secondes d’inactivité. 0 maintient le modèle chargé ; le minimum est 60.",
idleSecondsAriaLabel:
"Délai d’inactivité avant le déchargement automatique, en secondes",
+ mediaIdleUnload:
+ "Déchargement automatique en cas d’inactivité pour l’image et la vidéo",
+ mediaIdleUnloadDescription:
+ "Libérer la VRAM en déchargeant les modèles d’image et de vidéo après ce nombre de secondes d’inactivité. Réglage distinct : celui du dessus ne concerne que le modèle de discussion. 0 les maintient chargés ; le minimum est 60.",
+ mediaIdleSecondsAriaLabel:
+ "Délai d’inactivité avant le déchargement automatique de l’image et de la vidéo, en secondes",
+ mediaIdlePaused:
+ "En pause tant que « Conserver le modèle dans la mémoire du GPU » ou « Décharger uniquement les modèles chargés par l'API » est activé.",
idleNeedsEnable:
"Activez d’abord « Changer de modèle par requête ».",
idleActiveViaEnv: "Actif via UNSLOTH_MODEL_IDLE_TTL.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index d4dce2e825c..f65bfc68f9b 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -372,6 +372,13 @@ export const hi = {
idleUnloadDescription:
"इतने सेकंड तक निष्क्रिय रहने के बाद VRAM खाली करें। 0 पर मॉडल लोड रहता है; न्यूनतम 60 सेकंड।",
idleSecondsAriaLabel: "निष्क्रिय ऑटो-अनलोड की अवधि (सेकंड में)",
+ mediaIdleUnload: "इमेज और वीडियो के लिए निष्क्रिय ऑटो-अनलोड",
+ mediaIdleUnloadDescription:
+ "इतने सेकंड तक निष्क्रिय रहने के बाद इमेज और वीडियो मॉडल अनलोड करके VRAM खाली करें। यह अपनी अलग सेटिंग है: ऊपर वाली सेटिंग केवल चैट मॉडल पर लागू होती है। 0 पर वे लोड रहते हैं; न्यूनतम 60 सेकंड।",
+ mediaIdleSecondsAriaLabel:
+ "इमेज और वीडियो के निष्क्रिय ऑटो-अनलोड की अवधि (सेकंड में)",
+ mediaIdlePaused:
+ "‘मॉडल को GPU मेमोरी में रखें’ या ‘केवल API द्वारा लोड किए गए मॉडल अनलोड करें’ चालू रहने तक रुका हुआ है।",
idleNeedsEnable: "पहले ‘अनुरोध के अनुसार मॉडल बदलें’ चालू करें।",
idleActiveViaEnv:
"निष्क्रिय ऑटो-अनलोड UNSLOTH_MODEL_IDLE_TTL एनवायरनमेंट वेरिएबल के माध्यम से सक्रिय है।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index caca3916ee5..a9b2b81f19e 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -348,6 +348,14 @@ export const it = {
"Libera la VRAM dopo il numero indicato di secondi di inattività. 0 mantiene il modello in memoria; il minimo è 60.",
idleSecondsAriaLabel:
"Secondi di inattività prima dello scaricamento automatico",
+ mediaIdleUnload:
+ "Scaricamento automatico dalla memoria per inattività di immagini e video",
+ mediaIdleUnloadDescription:
+ "Libera la VRAM scaricando i modelli di immagini e video dopo il numero indicato di secondi di inattività. È un'impostazione a sé: quella qui sopra riguarda solo il modello di chat. 0 li mantiene in memoria; il minimo è 60.",
+ mediaIdleSecondsAriaLabel:
+ "Secondi di inattività prima dello scaricamento automatico di immagini e video",
+ mediaIdlePaused:
+ "In pausa finché «Mantieni il modello nella memoria della GPU» o «Scarica solo i modelli caricati dall'API» è attivo.",
idleNeedsEnable:
"Attiva prima «Cambia modello in base alla richiesta».",
idleActiveViaEnv: "Attivo tramite UNSLOTH_MODEL_IDLE_TTL.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index a64d058236c..6302772ba12 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -363,6 +363,13 @@ export const ja = {
idleUnloadDescription:
"指定した秒数だけアイドル状態が続くと、モデルをアンロードして VRAM を解放します。0 にすると読み込んだままになります。最小値は 60 秒です。",
idleSecondsAriaLabel: "アイドル時の自動アンロードまでの秒数",
+ mediaIdleUnload: "画像と動画のアイドル時の自動アンロード",
+ mediaIdleUnloadDescription:
+ "指定した秒数だけアイドル状態が続くと、画像モデルと動画モデルをアンロードして VRAM を解放します。これは独立した設定です。上の設定はチャットモデルのみが対象です。0 にすると読み込んだままになります。最小値は 60 秒です。",
+ mediaIdleSecondsAriaLabel:
+ "画像と動画のアイドル時の自動アンロードまでの秒数",
+ mediaIdlePaused:
+ "「モデルを GPU メモリに保持」または「API が読み込んだモデルのみアンロード」がオンの間は一時停止します。",
idleNeedsEnable: "アンロードされたモデルが次回使用時に再読み込みされるように、「リクエストごとにモデルを切り替え」をオンにしてください。",
idleActiveViaEnv: "アイドル時の自動アンロードは UNSLOTH_MODEL_IDLE_TTL 環境変数によって有効になっています。",
loadError: "モデル自動切り替え設定の読み込みに失敗しました。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index f3574a476f1..e6e783a3565 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -366,6 +366,13 @@ export const ko = {
idleUnloadDescription:
"지정한 유휴 시간(초)이 지나면 모델을 해제하여 VRAM을 확보합니다. 다음 요청 시 다시 불러옵니다. 0으로 설정하면 계속 로드된 상태로 유지됩니다. 최소 60초입니다.",
idleSecondsAriaLabel: "유휴 시 자동 해제까지의 시간(초)",
+ mediaIdleUnload: "이미지와 동영상의 유휴 시 자동 해제",
+ mediaIdleUnloadDescription:
+ "지정한 유휴 시간(초)이 지나면 이미지와 동영상 모델을 해제하여 VRAM을 확보합니다. 별도의 설정입니다. 위 설정은 채팅 모델에만 적용됩니다. 0으로 설정하면 계속 로드된 상태로 유지됩니다. 최소 60초입니다.",
+ mediaIdleSecondsAriaLabel:
+ "이미지와 동영상의 유휴 시 자동 해제까지의 시간(초)",
+ mediaIdlePaused:
+ "‘모델을 GPU 메모리에 유지’ 또는 ‘API가 불러온 모델만 해제’가 켜져 있는 동안 일시 중지됩니다.",
idleNeedsEnable: "먼저 ‘요청에 따라 모델 전환’을 켜세요.",
idleActiveViaEnv:
"유휴 시 자동 해제가 UNSLOTH_MODEL_IDLE_TTL 환경 변수를 통해 활성화되어 있습니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 8d50a5888f9..6018586bd2e 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -374,6 +374,14 @@ export const ptBR = {
"Libera a VRAM após esta quantidade de segundos de inatividade. 0 mantém o modelo carregado; o mínimo é 60.",
idleSecondsAriaLabel:
"Segundos até o descarregamento automático por inatividade",
+ mediaIdleUnload:
+ "Descarregamento automático por inatividade de imagem e vídeo",
+ mediaIdleUnloadDescription:
+ "Libera a VRAM descarregando os modelos de imagem e vídeo após esta quantidade de segundos de inatividade. É uma configuração própria: a de cima cobre apenas o modelo de chat. 0 os mantém carregados; o mínimo é 60.",
+ mediaIdleSecondsAriaLabel:
+ "Segundos até o descarregamento automático por inatividade de imagem e vídeo",
+ mediaIdlePaused:
+ "Pausado enquanto Manter o modelo na memória da GPU ou Descarregar apenas modelos carregados pela API estiver ativado.",
idleNeedsEnable: "Primeiro, ative Trocar de modelo por requisição.",
idleActiveViaEnv: "Ativo por meio de UNSLOTH_MODEL_IDLE_TTL.",
loadError: "Falha ao carregar as configurações de troca automática de modelo.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 22299fb8bd4..3d8b1cd2b00 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -372,6 +372,13 @@ export const ru = {
idleUnloadDescription:
"Освобождать VRAM после указанного числа секунд простоя. 0 оставляет модель загруженной; минимальное значение: 60.",
idleSecondsAriaLabel: "Число секунд до автовыгрузки при простое",
+ mediaIdleUnload: "Автовыгрузка при простое для изображений и видео",
+ mediaIdleUnloadDescription:
+ "Освобождать VRAM, выгружая модели изображений и видео после указанного числа секунд простоя. Это отдельная настройка: та, что выше, относится только к модели чата. 0 оставляет их загруженными; минимальное значение: 60.",
+ mediaIdleSecondsAriaLabel:
+ "Число секунд до автовыгрузки при простое для изображений и видео",
+ mediaIdlePaused:
+ "Приостановлено, пока включено «Держать модель в памяти GPU» или «Выгружать только модели, загруженные через API».",
idleNeedsEnable: "Сначала включите «Переключать модель по запросу».",
idleActiveViaEnv: "Активно через UNSLOTH_MODEL_IDLE_TTL.",
loadError: "Не удалось загрузить настройки автопереключения модели.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 0914b559bf4..0f3d50e778f 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -354,6 +354,12 @@ export const zhCN = {
idleUnloadDescription:
"空闲达到该秒数后释放 VRAM。设为 0 则保持加载,最小值为 60 秒。",
idleSecondsAriaLabel: "空闲自动卸载秒数",
+ mediaIdleUnload: "图像和视频的空闲自动卸载",
+ mediaIdleUnloadDescription:
+ "空闲达到该秒数后卸载图像和视频模型以释放 VRAM。这是独立的设置:上面那项仅适用于聊天模型。设为 0 则保持加载,最小值为 60 秒。",
+ mediaIdleSecondsAriaLabel: "图像和视频空闲自动卸载秒数",
+ mediaIdlePaused:
+ "当“将模型保留在显存中”或“仅卸载由 API 加载的模型”开启时暂停。",
idleNeedsEnable: "请先开启“按请求切换模型”。",
idleActiveViaEnv: "已通过 UNSLOTH_MODEL_IDLE_TTL 启用。",
loadError: "加载模型自动切换设置失败。",
diff --git a/studio/frontend/tests/media-idle-unload-api-only.test.ts b/studio/frontend/tests/media-idle-unload-api-only.test.ts
new file mode 100644
index 00000000000..f1a218cd3a5
--- /dev/null
+++ b/studio/frontend/tests/media-idle-unload-api-only.test.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// "Only unload models loaded by the API" vetoes the media TTL outright: every resident image
+// or video model is one the user loaded from Studio, so there is nothing the setting would
+// let go of. The switch that lifts the veto used to render only while the CHAT idle unload
+// was active, so a user who had turned that off after enabling the option saw the media row
+// go straight to "paused" with no control anywhere to explain it or undo it -- the feature
+// was unusable without re-enabling chat unloading first.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const SECTION = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/settings/components/model-auto-switch-section.tsx",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+);
+
+// The JSX guard the given row is rendered under: the nearest conditional above it at the
+// section's own indentation, so a `{settings.foo}` prop inside a neighbouring row is not
+// mistaken for one.
+const GUARD = "\n {settings";
+
+function guardFor(labelKey: string): string {
+ const upTo = SECTION.slice(0, SECTION.indexOf(`modelAutoSwitch.${labelKey}"`));
+ return upTo.slice(upTo.lastIndexOf(GUARD));
+}
+
+test("the API-only switch is reachable whenever a media TTL is saved", () => {
+ assert.match(guardFor("apiOnly"), /mediaAutoUnloadIdleSeconds > 0/);
+});
+
+test("it is still reachable from the chat TTL alone", () => {
+ // The media TTL is off by default, so this stays the ordinary way in.
+ assert.match(guardFor("apiOnly"), /idleUnloadActive/);
+});
+
+test("the KV-save option stays with the chat TTL it belongs to", () => {
+ // It persists llama.cpp slot KV; there is no media equivalent, so widening the API-only
+ // row must not drag it along.
+ const guard = guardFor("keepKv");
+ assert.match(guard, /idleUnloadActive/);
+ assert.doesNotMatch(guard, /mediaAutoUnloadIdleSeconds/);
+});
+
+test("the media row still says when a veto is holding its TTL", () => {
+ assert.match(
+ SECTION,
+ /settings\.mediaAutoUnloadIdleSeconds > 0 &&\s*!settings\.mediaIdleUnloadActive/,
+ );
+});
diff --git a/studio/frontend/tests/media-idle-unload-setting.test.ts b/studio/frontend/tests/media-idle-unload-setting.test.ts
new file mode 100644
index 00000000000..98cb91b4fe4
--- /dev/null
+++ b/studio/frontend/tests/media-idle-unload-setting.test.ts
@@ -0,0 +1,120 @@
+// 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 image/video idle TTL rides the shared auto-switch PUT but is its own
+// setting: saving it must not carry the chat seconds along, and a backend that
+// predates the field must read as off rather than inheriting the chat TTL.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+// The settings API modules reach authFetch through the auth barrel, which
+// re-exports login-page.tsx. See helpers/auth-stub.mjs.
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+installLocalStorageFake();
+
+const API = {
+ enabled: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_unload_idle_seconds: 300,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_enabled: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ idle_unload_active: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_unload_keep_kv: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_download_model: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_unload_api_only: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_auto_unload_idle_seconds: 0,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_idle_unload_active: false,
+};
+
+let nextBody: Record<string, unknown> = { ...API };
+const bodies: string[] = [];
+
+globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.body) bodies.push(String(init.body));
+ return new Response(JSON.stringify(nextBody), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}) as typeof fetch;
+
+const {
+ invalidateOpenAIAutoSwitchSettings,
+ loadOpenAIAutoSwitchSettings,
+ updateOpenAIAutoSwitchSettings,
+} = await import("../src/features/settings/api/openai-auto-switch.ts");
+
+test("a backend without the field reads as off, not as the chat TTL", async () => {
+ invalidateOpenAIAutoSwitchSettings();
+ const {
+ media_auto_unload_idle_seconds: _seconds,
+ media_idle_unload_active: _active,
+ ...older
+ } = API;
+ nextBody = older;
+ const settings = await loadOpenAIAutoSwitchSettings();
+ assert.equal(settings.autoUnloadIdleSeconds, 300);
+ assert.equal(settings.mediaAutoUnloadIdleSeconds, 0);
+ assert.equal(settings.mediaIdleUnloadActive, false);
+ nextBody = { ...API };
+});
+
+test("the seconds round-trip", async () => {
+ invalidateOpenAIAutoSwitchSettings();
+ nextBody = {
+ ...API,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_auto_unload_idle_seconds: 600,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_idle_unload_active: true,
+ };
+ const saved = await updateOpenAIAutoSwitchSettings(
+ true,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ 600,
+ );
+ assert.equal(saved.mediaAutoUnloadIdleSeconds, 600);
+ assert.equal(saved.mediaIdleUnloadActive, true);
+ nextBody = { ...API };
+});
+
+test("saving it alone leaves the chat TTL untouched", async () => {
+ invalidateOpenAIAutoSwitchSettings();
+ bodies.length = 0;
+ await updateOpenAIAutoSwitchSettings(
+ true,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ 600,
+ );
+ assert.deepEqual(JSON.parse(bodies[0] ?? "{}"), {
+ enabled: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ media_auto_unload_idle_seconds: 600,
+ });
+});
+
+test("saving the chat TTL does not send a media TTL", async () => {
+ invalidateOpenAIAutoSwitchSettings();
+ bodies.length = 0;
+ await updateOpenAIAutoSwitchSettings(true, 300);
+ assert.deepEqual(JSON.parse(bodies[0] ?? "{}"), {
+ enabled: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ auto_unload_idle_seconds: 300,
+ });
+});
diff --git a/studio/frontend/tests/video-generate-refusal-resync.test.ts b/studio/frontend/tests/video-generate-refusal-resync.test.ts
new file mode 100644
index 00000000000..6991f580236
--- /dev/null
+++ b/studio/frontend/tests/video-generate-refusal-resync.test.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// An idle auto-unload frees the video runtime on the server. Nothing tells the browser:
+// the eject event is raised by whoever clicked eject, and this page re-reads its status
+// when the route becomes active, not while it stays active. So status.loaded is still
+// true, Generate is still enabled, the POST 409s with "No video model is loaded." and the
+// catch only toasted -- every retry repeated it until the user changed tabs.
+//
+// The refusal is the page's only news that the model is gone, so it has to act on it.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const VIDEO = readFileSync(
+ fileURLToPath(new URL("../src/features/video/video-page.tsx", import.meta.url)),
+ "utf8",
+);
+
+const RESYNC = VIDEO.slice(
+ VIDEO.indexOf("const resyncAfterGenerateRefusal = useCallback("),
+ VIDEO.indexOf("// Track mount so a long generate"),
+);
+
+test("a refused generation re-reads the model status", () => {
+ const generateCatch = VIDEO.slice(
+ VIDEO.indexOf('toast.error(err instanceof Error ? err.message : "Video generation failed")'),
+ ).slice(0, 400);
+ assert.match(generateCatch, /void resyncAfterGenerateRefusal\(\);/);
+});
+
+test("the re-read is the page's own ticketed refresh", () => {
+ // Not a second reader: a read of its own would be one more writer racing the
+ // activation read, which is the thing statusTicket exists to stop.
+ assert.match(RESYNC, /const next = await refreshStatus\(\);/);
+ assert.match(
+ VIDEO,
+ /return ticket === statusTicket\.current \? next : null;/,
+ "refreshStatus answers with what it wrote, and null when superseded",
+ );
+});
+
+test("a status that comes back unloaded clears the resident-only state", () => {
+ // Same correction the indicator eject makes: Reapply must not point at a model that is
+ // no longer resident, and the quant pick belongs to the load that is gone.
+ assert.match(RESYNC, /dropResidentState\(\);\s*setQuant\(null\);/);
+});
+
+test("a failed or superseded re-read changes nothing", () => {
+ // Status is best-effort everywhere else on this page; a network blip must not look
+ // like an unload and tear the page's state down, and neither must a stale answer.
+ assert.match(RESYNC, /if \(!isMounted\.current \|\| next === null \|\| next\.loaded\) return;/);
+});
+
+test("a load started while the re-read was in flight is left alone", () => {
+ // /video/status reports committed state, so it answers loaded: false for a load that has
+ // just started -- a true answer that means the opposite of what this continuation reads
+ // into it. Acting on it dismisses the new load's toast and stops its progress poll, and
+ // while its start request is still out the cancel it counts as sends the compensating
+ // unload that tears the whole multi-gigabyte load down. handleLoad already bumps the
+ // counter that says so, so the fence is to snapshot it across the await.
+ assert.match(RESYNC, /const startLoad = loadSeq\.current;\s*const next = await refreshStatus\(\);/);
+ assert.match(RESYNC, /if \(startLoad !== loadSeq\.current\) return;/);
+ // And the fence has to come before the teardown, not after it.
+ assert.ok(
+ RESYNC.indexOf("if (startLoad !== loadSeq.current) return;") <
+ RESYNC.indexOf("dropResidentState();"),
+ );
+});
+
+test("the images page already corrects itself on every generate exit", () => {
+ // It has the same dead-button shape, but its finally re-reads status on success,
+ // failure and cancel alike, so there is nothing to fix there.
+ const images = readFileSync(
+ fileURLToPath(new URL("../src/features/images/images-page.tsx", import.meta.url)),
+ "utf8",
+ );
+ const finallyBlock = images.slice(images.indexOf(" cancelRequested.current = false;"));
+ assert.match(finallyBlock.slice(0, 1200), /if \(isMounted\.current\) await refreshStatus\(\);/);
+});