Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add an Always choice to Keep multiple models loaded, track every model on the GPU, and report every model a load unloads (#14088)
Etherl9edc7318c9fb
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.pyindex 06b64905740..49cfe982218 100644--- a/studio/backend/core/inference/diffusion_engine_router.py+++ b/studio/backend/core/inference/diffusion_engine_router.py@@ -36,6 +36,7 @@ import reimport platformimport sysimport threading+from contextvars import ContextVarfrom dataclasses import dataclassfrom typing import Any, Callable, Optional@@ -356,6 +357,10 @@ _lock = threading.Lock()_transition_lock = threading.Lock()_active_engine_name: str = ENGINE_DIFFUSERS_fallback_reason: Optional[str] = None+# Runs under _transition_lock just before a switch unloads the active engine, and may raise to refuse it.+before_engine_switch: ContextVar[Optional[Callable[[], None]]] = ContextVar(+ "before_engine_switch", default = None+)_mlx_fallback_reason: Optional[str] = None_MLX_MIN_MACOS = (14, 0)@@ -544,6 +549,9 @@ def _activate(name: str, reason: Optional[str]) -> Any:old_name = _active_engine_nameelse:_fallback_reason = reason if name == ENGINE_DIFFUSERS else None+ check = before_engine_switch.get() if engine_to_unload is not None else None+ if check is not None:+ check()if engine_to_unload is not None:# Publish the new engine only AFTER the old one unloads: the evictor unloads# get_active_diffusion_engine(), so flipping the name first would let a concurrent acquire_for evict thediff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.pyindex 6fc7d184af2..500167fc9ea 100644--- a/studio/backend/core/inference/gpu_arbiter.py+++ b/studio/backend/core/inference/gpu_arbiter.py@@ -1,19 +1,26 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Single-GPU arbiter for Unsloth's heavy GPU consumers.--The chat backends, diffusion, and video share one GPU. Before taking it each calls-``acquire_for(owner)``, which evicts the current other owner so two large models never sit in VRAM-at once. The arbiter only sequences ownership (freeing is each backend's teardown); eviction runs-under the lock, so a transfer is atomic vs other acquires.+"""GPU arbiter for Unsloth's heavy GPU consumers.++The chat backends, diffusion, and video share the GPUs. Before taking them each calls+``acquire_for(owner)``. Under the default policy that evicts every other resident, so two large+models never sit in VRAM at once. Under "always" (Keep multiple models loaded set to Always) it+refuses instead of evicting a chat, image or video model. The arbiter only sequences residency+(freeing is each backend's teardown); eviction runs under the lock, so a transfer is atomic vs+other acquires.++Residents are tracked in ``_residents`` with the physical GPU ids each one uses (None when not+known). ``_owner`` stays the last claimant, and tests may still set it directly: while it+disagrees with ``_residents``, ``_owner`` wins."""from __future__ import annotationsimport sysimport threading-from typing import Any, Callable, Optional+from contextvars import ContextVar+from typing import Any, Callable, Iterable, Optionalfrom loggers import get_logger@@ -25,18 +32,96 @@ VIDEO = "video"# A Decision API llama.cpp server on the GPU (the PyTorch Clef worker is not arbitrated).DECISIONS = "decisions"+# What each kind is called in refusals and eviction reports.+KIND_LABELS = {CHAT: "chat", DIFFUSION: "image", VIDEO: "video", DECISIONS: "decisions"}+# Residents that "always" protects; a Decision API server is still evicted as before.+_KEPT_UNDER_ALWAYS = frozenset({CHAT, DIFFUSION, VIDEO})+_lock = threading.Lock()_owner: Optional[str] = None_owner_epoch = 0# Account whose load put the current owner on the GPU, so routes can refuse to evict it._owner_account: Optional[str] = None_prior_account: Optional[str] = None+# Every resident and the physical GPU ids it uses (None = unknown, treat as every GPU).+_residents: dict[str, Optional[frozenset[int]]] = {}+# (account, prior account) for residents other than ``_owner``, whose pair lives in the globals above.+_accounts: dict[str, tuple[Optional[str], Optional[str]]] = {}++# Phrases the refusal copy always contains, for readers that lose the X-Unsloth-Refusal header.+MULTI_MODEL_REFUSAL_MARKERS = ("is set to Always", "is set to keep loaded")+MULTI_MODEL_REFUSAL_HEADERS = {"X-Unsloth-Refusal": "multi-model-always"}class OwnerChangedError(RuntimeError):"""The outgoing GPU owner changed after a pre-handoff capacity snapshot."""+class MultiModelAlwaysRefusal(RuntimeError):+ """A load would unload another model while Keep multiple models loaded is set to Always.++ Not a ``GpuMemoryShortError``: the chat load loop answers that by evicting. Waiting does not+ help, so routes answer 409 without Retry-After, with ``MULTI_MODEL_REFUSAL_HEADERS``.+ """++ def __init__(+ self,+ message: str,+ *,+ kind: Optional[str] = None,+ model: Optional[str] = None,+ ):+ self.kind = kind+ self.model = model+ super().__init__(message)++ def as_http_exception(self, path: Optional[str] = None):+ from fastapi import HTTPException+ from utils.api_errors import error_body_for_path++ message = str(self)+ detail = (+ error_body_for_path(path, message, status = 409, code = "multi_model_always", param = "model")+ if path and path.startswith("/v1/")+ else message+ )+ return HTTPException(+ status_code = 409, detail = detail, headers = dict(MULTI_MODEL_REFUSAL_HEADERS)+ )+++def always_refusal_message(+ kind: str,+ model: Optional[str] = None,+ *,+ is_owner: Optional[bool] = None,+) -> str:+ """The Always refusal copy. ``kind`` is chat, audio, image or video."""+ if is_owner is None:+ from utils.account_context import is_owner_context+ is_owner = is_owner_context()+ what = f"the {kind} model {model}" if model else f"the {kind} model"+ if is_owner:+ return (+ f"Loading this model would unload {what}, and Keep multiple models loaded is set to Always. "+ "Unload that model first, or choose When they fit."+ )+ return (+ f"Loading this model would unload {what}, which Unsloth Studio is set to keep loaded. "+ "Unload that model first, or ask the Unsloth Studio owner."+ )+++def refusal_for(+ slots: Iterable[dict[str, Any]], fallback_kind: str = "chat"+) -> MultiModelAlwaysRefusal:+ """Build the refusal naming the first model a load would have unloaded (hidden from other accounts)."""+ shown = public_slots(slots)+ first = shown[0] if shown else {"kind": fallback_kind, "model": ""}+ kind, model = first.get("kind") or fallback_kind, first.get("model") or None+ return MultiModelAlwaysRefusal(always_refusal_message(kind, model), kind = kind, model = model)++def _evict_chat() -> None:import time@@ -113,7 +198,7 @@ def _evict_decisions() -> None:evict_for_gpu()-# Patchable in tests via monkeypatch.setitem. Ownership is exclusive, so acquire_for's evict-the-current-owner+# Patchable in tests via monkeypatch.setitem. Under the default policy acquire_for evicts every other resident, so this# generalises to any number of owners._EVICTORS = {CHAT: _evict_chat,@@ -123,6 +208,265 @@ _EVICTORS = {}+def _chat_slots() -> list[dict[str, str]]:+ from routes.inference import chat_eviction_reports+ return chat_eviction_reports()+++def _media_backend(owner: str) -> Any:+ if owner == DIFFUSION:+ from core.inference.diffusion_engine_router import get_active_diffusion_engine+ return get_active_diffusion_engine()+ from core.inference.video import get_video_backend+ return get_video_backend()+++def _media_loading(owner: str) -> bool:+ """Whether an image or video load is in flight; lock-safe under ``_lock``."""+ return bool(_media_backend(owner).loading_repo_ids())+++def _chat_occupied() -> bool:+ """Whether a chat load is in flight, a kept slot failed to stop, or the primary cannot be read;+ unreadable counts as yes, so Always never evicts it blind."""+ try:+ from core.inference import model_slots+ from core.inference.llama_cpp import chat_load_active+ from routes.inference import _primary_chat_reports, get_llama_cpp_backend++ if chat_load_active() or model_slots.any_loading() or model_slots.stuck:+ return True+ model_slots.in_slot(None, _primary_chat_reports)+ # A llama-server mid-respawn is active but not loaded, so no report lists it.+ return bool(+ model_slots.in_slot(None, lambda: get_llama_cpp_backend().is_active)+ or any(slot.llama.is_active for slot in list(model_slots.slots))+ )+ except Exception: # noqa: BLE001+ return True+++def _media_occupied(owner: str) -> bool:+ """Whether an image or video model is loaded or loading. One that cannot be read counts as+ loaded, so Always never evicts it blind."""+ try:+ return _media_status(owner) is not None or _media_loading(owner)+ except Exception: # noqa: BLE001+ return True+++def _media_status(owner: str) -> Optional[dict]:+ """The loaded image or video model's status, or None when none is loaded."""+ backend = _media_backend(owner)+ status = backend.status() if hasattr(backend, "status") else None+ return status if isinstance(status, dict) and status.get("loaded") else None+++def _diffusion_slots() -> list[dict[str, str]]:+ return _media_slot("image", DIFFUSION, _media_status(DIFFUSION))+++def _video_slots() -> list[dict[str, str]]:+ return _media_slot("video", VIDEO, _media_status(VIDEO))+++def refuse_replacing_media(+ owner: str, policy: str, requested: Iterable[Optional[str]]+) -> list[dict[str, Any]]:+ """The image or video model of its own kind a load of ``requested`` would replace. Under Always+ that is refused instead, as is replacing a load of another repo still in flight. Another file or+ setting of the same repo is allowed, as for chat. ``requested`` are the model paths the load+ reads, never a caller's display label, which nothing checks against the path. Safe under+ ``_lock``."""+ if owner not in (DIFFUSION, VIDEO):+ return []+ from core.inference.model_ids import hf_cache_repo_id++ # Only an HF cache snapshot path names its repo; any other local path is its own identity.+ def aliases(name: Optional[str]) -> set:+ return {alias for alias in (name, hf_cache_repo_id(name) if name else None) if alias}++ names = {alias for name in requested for alias in aliases(name)}+ try:+ status = _media_status(owner)+ loading = () if status is not None else _media_backend(owner).loading_repo_ids()+ except Exception: # noqa: BLE001 - unreadable: Always keeps it, Off replaces it as before+ if policy == "always":+ raise refusal_for([], KIND_LABELS[owner])+ return []+ if status is not None:+ repo = status.get("repo_id")+ loaded = aliases(repo)+ if not loaded.isdisjoint(names):+ return []+ slots = resident_slots(owner)+ if policy == "always":+ raise refusal_for(slots, KIND_LABELS[owner])+ return slots+ # The in-flight load's own repo comes first; the rest are companions it reads, not its identity.+ if policy == "always" and loading and names.isdisjoint(aliases(loading[0])):+ raise refusal_for([], KIND_LABELS[owner])+ return []+++def guarded_media_begin(+ owner: str, policy: str, requested: Iterable[Optional[str]], begin: Callable[[], Any]+) -> Callable[[], Any]:+ """``begin`` re-checked against a load that registered meanwhile, for use as an acquire's+ ``register`` (which runs under ``_lock``). Off and fit begin as before."""+ if policy != "always":+ return begin+ names = tuple(requested)++ def register() -> Any:+ refuse_replacing_media(owner, policy, names)+ return begin()++ return register+++def begin_media_load(+ owner: str, policy: str, requested: Iterable[Optional[str]], begin: Callable[[], Any]+) -> Any:+ """``guarded_media_begin`` for a load that takes no GPU claim, under ``_lock`` all the same."""+ register = guarded_media_begin(owner, policy, requested, begin)+ if register is begin:+ return begin()+ with _lock:+ return register()+++def _media_slot(kind: str, owner: str, status: Optional[dict]) -> list[dict[str, str]]:+ if status is None:+ return []+ from core.inference.model_ids import public_model_id+ from hub.services.models.account_access import _resident_loader++ # display_repo_id is what the page shows; a bare repo_id can be a local path.+ model = status.get("display_repo_id") or public_model_id(status.get("repo_id")) or kind+ return [{"kind": kind, "model": str(model), "account": _resident_loader(owner)}]+++# What an owner's eviction unloads, as {kind, model} with the public model id, plus the loading account under+# "account". Patchable like _EVICTORS. Read before the evictor runs, under _lock, so a reporter must never call back+# into the arbiter's locking functions. One that fails reports nothing rather than blocking the acquire.+_SLOT_REPORTERS: dict[str, Callable[[], list[dict[str, Any]]]] = {+ CHAT: _chat_slots,+ DIFFUSION: _diffusion_slots,+ VIDEO: _video_slots,+}++# Where an acquire without an explicit ``evicted`` list reports, so a route can collect what a nested load evicted.+eviction_sink: ContextVar[Optional[list]] = ContextVar("gpu_eviction_sink", default = None)+++def resident_slots(owner: str) -> list[dict[str, Any]]:+ reporter = _SLOT_REPORTERS.get(owner)+ if reporter is None:+ return []+ try:+ return [dict(slot) for slot in reporter() or ()]+ except Exception as exc: # noqa: BLE001 - a report must never block an acquire+ logger.warning("gpu_arbiter: could not list the %s models: %s", owner, exc)+ return []+++def public_slots(slots: Iterable[dict[str, Any]]) -> list[dict[str, str]]:+ """``{kind, model}`` for a caller: a managed account never sees what another account loaded."""+ try:+ from hub.services.models.account_access import managed_account+ from utils.account_context import current_account_id+ hide, me = managed_account(), current_account_id()+ except Exception: # noqa: BLE001+ hide, me = False, None+ out = []+ for slot in slots:+ account = slot.get("account")+ model = (+ "" if hide and account is not None and account != me else str(slot.get("model") or "")+ )+ out.append({"kind": str(slot.get("kind") or "chat"), "model": model})+ return out+++def note_evictions(slots: Iterable[dict[str, Any]], evicted: Optional[list] = None) -> None:+ """Report models a route unloaded itself, to ``evicted`` or the current eviction sink."""+ sink = evicted if evicted is not None else eviction_sink.get()+ if sink is not None:+ sink.extend(public_slots(slots))+++def policy_kwargs(policy: str) -> dict[str, str]:+ """``acquire_for`` kwargs for a mode: none for "off", so callers and fakes see today's call."""+ return {} if policy == "off" else {"policy": policy}+++def physical_gpu_ids(visible: Optional[Iterable[int]]) -> Optional[frozenset[int]]:+ """Map visible device ordinals to physical GPU ids (CUDA_VISIBLE_DEVICES=2,3 makes ordinal 0 GPU 2)."""+ if visible is None:+ return None+ ordinals = [int(i) for i in visible]+ try:+ from utils.hardware.hardware import get_parent_visible_gpu_ids+ parent = get_parent_visible_gpu_ids()+ except Exception: # noqa: BLE001+ parent = []+ if not parent:+ return frozenset(ordinals)+ return frozenset(parent[i] if 0 <= i < len(parent) else i for i in ordinals)+++def _view(owner: Any = ...) -> dict[str, Optional[frozenset[int]]]:+ """Residents, trusting ``_owner`` when a caller or test set it without going through the arbiter."""+ if owner is ...:+ owner = _owner+ if owner is None:+ return {}+ if owner not in _residents:+ return {owner: None}+ return dict(_residents)+++def _sync_from_view() -> None:+ """Bring ``_residents`` and ``_accounts`` in line with ``_owner`` before a mutation. Caller holds ``_lock``."""+ global _residents+ view = _view()+ if view != _residents:+ _residents = view+ for stale in [name for name in _accounts if name not in view or name == _owner]:+ _accounts.pop(stale, None)+++def _drop_resident(owner: str) -> None:+ """Remove ``owner`` and recompute ``_owner`` from the residents left. Caller holds ``_lock``."""+ global _owner, _owner_epoch, _owner_account, _prior_account+ _sync_from_view()+ if owner not in _residents:+ return+ del _residents[owner]+ if owner == _owner:+ if _residents:+ _owner = next(reversed(_residents))+ _owner_account, _prior_account = _accounts.pop(_owner, (None, None))+ else:+ _owner = None+ _owner_account = None+ _prior_account = None+ else:+ _accounts.pop(owner, None)+ _owner_epoch += 1+++def holds(owner: str) -> bool:+ """Whether ``owner`` has a model resident on a GPU. Lock-free, so register callbacks may call it."""+ return owner in _view(current_owner())+++def residents() -> dict[str, Optional[frozenset[int]]]:+ """Every resident owner and its physical GPU ids (None when unknown). Lock-free like ``holds``."""+ return _view(current_owner())++class GpuOwnerBusyError(RuntimeError):"""Raised when an ownership transfer is configured to refuse eviction."""@@ -208,11 +552,20 @@ def acquire_for(account_id: Optional[str] = None,replacing: bool = False,alongside: bool = False,+ policy: str = "off",+ evicted: Optional[list] = None,+ gpu_ids: Optional[Iterable[int]] = None,) -> Any:- """Make ``owner`` the sole GPU owner, evicting the other if it holds it.+ """Make ``owner`` resident, evicting every other resident under the default policy.- ``register`` runs under the arbiter lock as ownership transfers, so a competing acquire cannot+ ``register`` runs under the arbiter lock as residency transfers, so a competing acquire cannotevict this owner and let both loaders allocate VRAM at once.++ ``policy`` is the Keep multiple models loaded mode, read by the caller outside the lock. "off"+ and "fit" evict as before; "always" raises ``MultiModelAlwaysRefusal`` instead of evicting a+ chat, image or video model. ``alongside`` is unrelated: it only decides whether the owner+ account is re-claimed. ``evicted`` collects ``{kind, model}`` for each model an evictor+ unloads. ``gpu_ids`` are the visible device ordinals the owner will use, when known."""global _owner, _owner_epoch, _owner_account, _prior_accountif owner not in _EVICTORS:@@ -225,21 +578,51 @@ def acquire_for(raise OwnerChangedError("The resident GPU model changed; retry the load.")if register is not None or replacing:raise_if_other_accounts_active(acting)- if _owner is not None and _owner != owner:+ _sync_from_view()+ prev_owner, prev_pair = _owner, (_owner_account, _prior_account)+ others = [name for name in _residents if name != owner]+ if others:if not allow_evict:- raise GpuOwnerBusyError(_owner)+ raise GpuOwnerBusyError(others[-1])+ if policy == "always" and owner in _KEPT_UNDER_ALWAYS:+ kept = [name for name in others if name in _KEPT_UNDER_ALWAYS]+ slots = [slot for name in kept for slot in resident_slots(name)]+ # A claim whose load failed holds nothing: evicting it unloads nothing.+ if slots or any(+ _chat_occupied() if name == CHAT else _media_occupied(name) for name in kept+ ):+ raise refusal_for(slots, KIND_LABELS[kept[0]])# Never evict an account mid-generation; the caller retries after its stream ends.busy = other_accounts_active(acting)if busy:- raise GpuBusyForAnotherAccountError(_owner, busy)- logger.info("gpu_arbiter: evicting %s for %s", _owner, owner)- _EVICTORS[_owner]()+ raise GpuBusyForAnotherAccountError(others[-1], busy)+ sink = evicted if evicted is not None else eviction_sink.get()+ for name in others:+ logger.info("gpu_arbiter: evicting %s for %s", name, owner)+ unloading = resident_slots(name) if sink is not None else []+ _EVICTORS[name]()+ note_evictions(unloading, sink)+ _drop_resident(name)if owner != VIDEO:# A resident H3 sd-server sits outside every owner's teardown._release_idle_video_servers(f"GPU acquired for {owner}")# Records who LOADED the model; a plain re-assert must not hand it to whoever asked last.- claims = _owner != owner or ((register is not None or replacing) and not alongside)+ claims = prev_owner != owner or ((register is not None or replacing) and not alongside)+ if owner != _owner:+ if _owner is not None:+ # Another resident stays loaded; park its accounts while ``owner`` is the last claimant.+ _accounts[_owner] = (_owner_account, _prior_account)+ if owner in _accounts:+ _owner_account, _prior_account = _accounts.pop(owner)+ elif prev_owner is None or prev_owner not in _residents:+ # The evicted owner's accounts carry over, as they did with a single owner.+ _owner_account, _prior_account = prev_pair+ else:+ _owner_account, _prior_account = None, None_owner = owner+ _residents.pop(owner, None)+ known = physical_gpu_ids(gpu_ids)+ _residents[owner] = known_owner_epoch += 1result = register() if register is not None else None# A raising registration loaded nothing and must not take residency.@@ -255,51 +638,52 @@ def restore_owner_account(owner: str, account_id: Optional[str] = None) -> bool:with _lock:acting = account_id or current_account_id()- if _owner != owner or _owner_account != acting or _prior_account is None:+ if owner == _owner:+ if _owner_account != acting or _prior_account is None:+ return False+ _owner_account, _prior_account = _prior_account, None+ return True+ account, prior = _accounts.get(owner, (None, None))+ if owner not in _view() or account != acting or prior is None:return False- _owner_account, _prior_account = _prior_account, None+ _accounts[owner] = (prior, None)return Truedef release(owner: str) -> None:- """Drop ``owner``'s claim (no-op if it isn't the current owner)."""- global _owner, _owner_epoch, _owner_account, _prior_account+ """Drop ``owner``'s residency (no-op if it isn't resident)."""with _lock:- if _owner == owner:- if owner == DIFFUSION:- _stop_prompt_upsampler()- _owner = None- _owner_account = None- _prior_account = None- _owner_epoch += 1+ if owner == DIFFUSION and owner in _view():+ _stop_prompt_upsampler()+ _drop_resident(owner)def release_if(owner: str, predicate: Callable[[], bool]) -> bool:- """Drop ``owner``'s claim only if it still holds it AND ``predicate()`` is true, atomically.+ """Drop ``owner``'s residency only if it still holds it AND ``predicate()`` is true, atomically.A slow unload's idle check and its ``release`` must not straddle a concurrent same-owner loadwhose ``acquire_for(register=...)`` re-registers ownership under this lock; evaluating thepredicate under the lock keeps them atomic so ``release`` never clears the newer claim.``predicate`` must be quick and not re-enter the arbiter. Returns True iff ownership was dropped."""- global _owner, _owner_epoch, _owner_account, _prior_accountwith _lock:- if _owner != owner or not predicate():+ if owner not in _view() or not predicate():return Falseif owner == DIFFUSION:_stop_prompt_upsampler()- _owner = None- _owner_account = None- _prior_account = None- _owner_epoch += 1+ _drop_resident(owner)return Truedef current_owner() -> Optional[str]:+ """The last claimant. Prefer ``holds()`` / ``residents()``: other models may be resident too."""return _owner-def owner_account() -> Optional[str]:- return _owner_account+def owner_account(owner: Optional[str] = None) -> Optional[str]:+ """Account whose load put ``owner`` (default: the last claimant) on the GPU."""+ if owner is None or owner == _owner:+ return _owner_account+ return _accounts.get(owner, (None, None))[0]def owner_snapshot() -> tuple[Optional[str], int]:diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4ba8089d0e2..e3c2dfcd47e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -585,9 +585,19 @@ def _gpu_short_message()if capped_only:return message + f"It fits with a {fitting_ctx} context."+ try:+ from utils.multi_model_settings import get_multi_model_mode+ always = get_multi_model_mode() == "always"+ except Exception: # noqa: BLE001 - the copy must never fail the load+ always = False+ if always:+ return message + (+ "Unload one of them or lower the context length. Keep multiple models loaded "+ "is set to Always, so nothing is unloaded to make room."+ )return message + (- "Unload one of them, lower the context length, or turn off "- '"Keep other models loaded" to replace the current model.'+ "Unload one of them, lower the context length, or set Keep multiple models loaded "+ "to Off to replace the current model.")diff --git a/studio/backend/core/inference/media_auto_switch.py b/studio/backend/core/inference/media_auto_switch.pyindex 292089967b5..28c50593361 100644--- a/studio/backend/core/inference/media_auto_switch.py+++ b/studio/backend/core/inference/media_auto_switch.py@@ -34,7 +34,7 @@ import functoolsimport timefrom typing import Any, Callable, Optional-from core.inference.gpu_arbiter import DIFFUSION, VIDEO+from core.inference.gpu_arbiter import DIFFUSION, MULTI_MODEL_REFUSAL_HEADERS, VIDEOfrom core.inference import media_localityfrom core.inference.media_locality import is_edit_only, missing_download_bytesfrom core.inference.media_model_index import (@@ -388,6 +388,20 @@ async def _gated_start_load(openai_errors,retry_after = int(exc.detail["retry_after"]),) from exc+ headers = {k.lower(): v for k, v in (exc.headers or {}).items()}+ if (+ headers.get("x-unsloth-refusal")+ == MULTI_MODEL_REFUSAL_HEADERS["X-Unsloth-Refusal"]+ ):+ # Keep multiple models loaded is set to Always: waiting does not help, so no Retry-After.+ refusal = refuse(+ exc.detail if isinstance(exc.detail, str) else str(exc.detail),+ status_code = 409,+ openai_errors = openai_errors,+ code = "multi_model_always",+ )+ refusal.headers = dict(MULTI_MODEL_REFUSAL_HEADERS)+ raise refusal from excraisereturn Falsefinally:diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.pyindex 50e761a427f..976d69a0338 100644--- a/studio/backend/core/systemone/laya_runtime.py+++ b/studio/backend/core/systemone/laya_runtime.py@@ -563,17 +563,21 @@ def _select_gguf(checkpoint: Checkpoint, questions, preference: str) -> Checkpoireturn checkpoint+def _gpu_taken() -> bool:+ """A chat, image or video model is resident on the GPU (a decision server does not count)."""+ from core.inference import gpu_arbiter+ return any(owner != gpu_arbiter.DECISIONS for owner in gpu_arbiter.residents())++def _auto_keeps_pytorch(checkpoint: Checkpoint, native: Checkpoint) -> str | None:"""Why Auto answers text on PyTorch although llama.cpp could: as before llama.cpp existed here."""- from core.inference.gpu_arbiter import DECISIONS, current_owner-from .catalog import clef_unsupported_reasonif _loaded == native and _agent is not None:return Noneif clef_unsupported_reason(wait = False) is not None:return None- if _native_gpu() and current_owner() not in (None, DECISIONS):+ if _native_gpu() and _gpu_taken():return "Another model is using the GPU."if not native.is_local and not is_cached(native) and is_cached(checkpoint):return "The GGUF is not downloaded; the cached PyTorch checkpoint serves."@@ -1560,8 +1564,7 @@ def _ensure_loading(checkpoint: Checkpoint, unloads: int | None = None) -> threaif _loaded == checkpoint and _agent is not None and not misplaced:return Noneif _wants_gpu(checkpoint):- from core.inference.gpu_arbiter import DECISIONS, current_owner- if current_owner() not in (None, DECISIONS):+ if _gpu_taken():busy = _GPU_BUSY.format(checkpoint.name if _is_mlx(checkpoint) else "a decision model through llama.cpp")@@ -2423,11 +2426,9 @@ def unload(reload_after_training: bool = False) -> bool:def _clef_preempted() -> bool:global _reload_stopped_by- from core.inference.gpu_arbiter import current_owner-if _training_active():reason = "training"- elif _reloading is not None and current_owner() is not None:+ elif _reloading is not None and _gpu_taken():# A reload nobody asked for yields to a chat, image or video model that claims the GPU meanwhile.reason = "gpu"else:@@ -2439,18 +2440,11 @@ def _clef_preempted() -> bool:def _reload_after_training(checkpoint: Checkpoint, unloads: int) -> None:global _reloading, _reload_stopped_by, _failure- from core.inference.gpu_arbiter import current_owner-while True:while _training_active():time.sleep(TRAINING_POLL_S)with _state_lock:- if (- _unloads != unloads- or _agent is not None- or _loading is not None- or current_owner() is not None- ):+ if _unloads != unloads or _agent is not None or _loading is not None or _gpu_taken():return_reloading = checkpoint_reload_stopped_by = None@@ -2464,7 +2458,7 @@ def _reload_after_training(checkpoint: Checkpoint, unloads: int) -> None:with _state_lock:_reloading = Nonetraining = _reload_stopped_by == "training" or _training_active()- if training or _reload_stopped_by == "gpu" or current_owner() is not None:+ if training or _reload_stopped_by == "gpu" or _gpu_taken():# Another run, or a chat, image or video model, took the GPU while this loaded: not a failure to report.with _state_lock:if _failure is not None and _failure[0] == checkpoint:@@ -2477,7 +2471,7 @@ def _reload_after_training(checkpoint: Checkpoint, unloads: int) -> None:# The first decision builds the GPU kernels; done now, a request does not wait for it.try:- if current_owner() is None:+ if not _gpu_taken():agent.decide("ready", {"ready": {"type": "noul"}})except ClefWorkerError:logger.info(@@ -2487,7 +2481,7 @@ def _reload_after_training(checkpoint: Checkpoint, unloads: int) -> None:returnexcept Exception:logger.debug("Could not warm up %s", checkpoint.name, exc_info = True)- if current_owner() is not None:+ if _gpu_taken():logger.info("Retiring %s: another model took the GPU as it reloaded", checkpoint.name)_evict_agent(agent)diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex 5344985a910..ccf9657e537 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -284,7 +284,7 @@ def _resident_loader(modality: str) -> str | None:return recorded[0]from core.inference import gpu_arbiter- return gpu_arbiter.owner_account() if gpu_arbiter.current_owner() == modality else None+ return gpu_arbiter.owner_account(modality) if gpu_arbiter.holds(modality) else Nonedef release_shared_resident(modality: str) -> bool:@@ -386,9 +386,14 @@ def resident_hidden(modality: str | None = None, reference: str | None = None) -return Falsefrom core.inference import gpu_arbiter- owner = gpu_arbiter.current_owner()- if owner is not None and (modality is None or owner == modality):- return gpu_arbiter.owner_account() != current_account_id()+ if modality is None:+ resident = gpu_arbiter.residents()+ if resident:+ return any(+ gpu_arbiter.owner_account(owner) != current_account_id() for owner in resident+ )+ elif gpu_arbiter.holds(modality):+ return gpu_arbiter.owner_account(modality) != current_account_id()if reference:account, references = _resident_accounts.get(modality, (OWNER.account_id, frozenset()))if reference not in references:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 72e8d4ec0cc..6d374d74b9b 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2001,6 +2001,15 @@ class _InferenceRuntimeFields(BaseModel):)+class EvictedSlot(BaseModel):+ """A model a load unloaded to make room."""++ kind: Literal["chat", "audio", "image", "video"] = Field(+ ..., description = "chat, audio (a native or audio.cpp audio model), image or video"+ )+ model: str = Field(..., description = "Public model id, as /api/inference/status prints it")++class LoadResponse(_InferenceRuntimeFields):"""Response after loading a model"""@@ -2033,7 +2042,12 @@ class LoadResponse(_InferenceRuntimeFields):)evicted: list[str] = Field(default_factory = list,- description = "Models loaded alongside that were unloaded to make room for this one.",+ description = "Models unloaded to make room for this one: chat models loaded alongside, "+ "the replaced chat model, and any image or video model this load freed.",+ )+ evicted_slots: list[EvictedSlot] = Field(+ default_factory = list,+ description = "The same models as evicted, each with its kind and public model id.",)@@ -2159,6 +2173,10 @@ class InferenceStatusResponse(_InferenceRuntimeFields):)loading: List[str] = Field(default_factory = list, description = "Models currently being loaded")loaded: List[str] = Field(default_factory = list, description = "Models currently loaded")+ multi_model_mode: Optional[Literal["off", "fit", "always"]] = Field(+ None,+ description = "Keep multiple models loaded: off, fit (When they fit) or always.",+ )serving: List[str] = Field(default_factory = list,description = "Models answering requests: the active one and each kept alongside. "@@ -5428,6 +5446,14 @@ class DiffusionStatusResponse(BaseModel):"""Current diffusion backend state."""loaded: bool = Field(False, description = "Whether a diffusion model is loaded")+ evicted: List[str] = Field(+ default_factory = list,+ description = "Models this load unloaded to make room. Filled only on the load answer.",+ )+ evicted_slots: List[EvictedSlot] = Field(+ default_factory = list,+ description = "The same models as evicted, each with its kind and public model id.",+ )repo_id: Optional[str] = Field(None, description = "Loaded repo id or local path")display_repo_id: Optional[str] = Field(None, description = "Logical Hub id of a local snapshot")family: Optional[str] = Field(None, description = "Detected diffusion family")@@ -6941,6 +6967,14 @@ class VideoStatusResponse(BaseModel):"""Current video backend state."""loaded: bool = Field(False, description = "Whether a video model is loaded")+ evicted: List[str] = Field(+ default_factory = list,+ description = "Models this load unloaded to make room. Filled only on the load answer.",+ )+ evicted_slots: List[EvictedSlot] = Field(+ default_factory = list,+ description = "The same models as evicted, each with its kind and public model id.",+ )repo_id: Optional[str] = Field(None, description = "Loaded repo id or local path")display_repo_id: Optional[str] = Field(None, description = "Logical Hub id of a local snapshot")family: Optional[str] = Field(None, description = "Detected video family")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 2a14d6a4878..1d7f67b04ea 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3297,8 +3297,23 @@ _TUNNEL_KEEPALIVE_EVERY_S = 20.0_DEFERRED_ERROR_KEY = "_deferred_error"-def _deferred_error_body(status_code: int, detail) -> bytes:+# Headers a padded error keeps in its body: the status line and headers were already sent.+_DEFERRED_ERROR_HEADERS = ("x-unsloth-refusal", "retry-after")+++def _deferred_error_body(+ status_code: int,+ detail,+ headers: Optional[dict] = None,+) -> bytes:body = {_DEFERRED_ERROR_KEY: {"status_code": status_code, "detail": detail}}+ kept = {+ name.lower(): value+ for name, value in (headers or {}).items()+ if name.lower() in _DEFERRED_ERROR_HEADERS+ }+ if kept:+ body[_DEFERRED_ERROR_KEY]["headers"] = keptreturn json.dumps(body).encode()@@ -3354,7 +3369,9 @@ async def _tunnel_safe_json(coro, *, label: str):payload = task.result()except HTTPException as exc:logger.info(f"{label} failed with {exc.status_code} after the response committed")- yield _deferred_error_body(exc.status_code, restore_inventory_handles(exc.detail))+ yield _deferred_error_body(+ exc.status_code, restore_inventory_handles(exc.detail), exc.headers+ )except Exception as exc:logger.exception(f"{label} failed after the response was committed")# A filesystem failure quotes the path it failed on, never shown to a caller@@ -11400,7 +11417,7 @@ async def _auto_switch_npu_model(The caller has checked auto-switch is on. Same lock, gates, waiter count, cancellation anddeferred claim as a GGUF switch."""- from core.inference.gpu_arbiter import require_no_foreign_generations+ from core.inference.gpu_arbiter import MultiModelAlwaysRefusal, require_no_foreign_generationsfrom core.inference.llama_keepwarm import inference_lifecycle_gate, model_load_gatefrom utils.openai_auto_switch_settings import get_model_override, resolve_fit_max_seq_length@@ -11444,6 +11461,8 @@ async def _auto_switch_npu_model()loaded_ok = True_raise_if_cancelled()+ except MultiModelAlwaysRefusal as exc:+ raise exc.as_http_exception(switch_path) from excfinally:if not claim_resident:# Preview-owned until the route's 2xx claims it, so a later rejection@@ -12259,8 +12278,14 @@ async def _maybe_auto_switch_model(if waiter_noted:_note_switch_waiter(key, -1)+ from core.inference.gpu_arbiter import MultiModelAlwaysRefusal+try:await _resolve_and_switch()+ except MultiModelAlwaysRefusal as exc:+ raise exc.as_http_exception(+ getattr(getattr(fastapi_request, "url", None), "path", None)+ ) from excexcept HTTPException as exc:path = getattr(getattr(fastapi_request, "url", None), "path", None)if (@@ -12459,8 +12484,8 @@ def release_chat_after_kept_models() -> bool:def reap_dead_managed_engine(backend) -> None:"""A crashed engine leaves nothing resident, so its claim and sharers go with it."""- from core.inference.gpu_arbiter import CHAT, current_owner- if backend.reap_dead_managed_engine() and (release_chat_gpu_claim() or current_owner() != CHAT):+ from core.inference.gpu_arbiter import CHAT, holds+ if backend.reap_dead_managed_engine() and (release_chat_gpu_claim() or not holds(CHAT)):account_access.clear_resident("chat")@@ -12613,10 +12638,11 @@ async def load_model_for_preview(DIFFUSION,VIDEO,GpuOwnerBusyError,- current_owner,+ MultiModelAlwaysRefusal,+ holds,)- if current_owner() in (DIFFUSION, VIDEO):+ if holds(DIFFUSION) or holds(VIDEO):untrack_current_request(scope)raise HTTPException(status_code = 503,@@ -12654,7 +12680,7 @@ async def load_model_for_preview(allow_gpu_owner_eviction = False,)loaded_ok = True- except GpuOwnerBusyError as exc:+ except (GpuOwnerBusyError, MultiModelAlwaysRefusal) as exc:untrack_current_request(scope)raise HTTPException(status_code = 503,@@ -18479,11 +18505,30 @@ async def load_model_gated(# then gets unloaded by the pre-swap teardown. Rechecked under the gate: an# install can reserve while this request queues on the gate, so the pre-gate# check alone is only a fast path.+ from core.inference.gpu_arbiter import (+ MultiModelAlwaysRefusal,+ eviction_sink,+ note_evictions,+ refusal_for,+ )from core.inference.llama_cpp import GpuMemoryShortErrorfrom core.inference.llama_keepwarm import inference_lifecycle_gate, model_load_gateextra = Noneevicted: list[str] = []+ # Every model this load unloads, as {kind, model}: kept slots dropped here and anything the arbiter evicts.+ evicted_slots: list[dict] = []+ replaced_slots: list[dict] = []+ replaced_token = None+ # Indices of evicted_slots that already have a legacy ``_model_key`` entry in ``evicted``.+ keyed: set[int] = set()++ def note_keyed(reports) -> None:+ start = len(evicted_slots)+ note_evictions(reports)+ keyed.update(range(start, len(evicted_slots)))++ sink_token = Noneattempt = _begin_load_attempt(request, current_subject)with _scoped_load_attempts_lock:_pending_load_attempts[attempt.token] = attempt@@ -18499,6 +18544,8 @@ async def load_model_gated(# model mid-load. Auto-switch calls the tracked impl directly since it already# holds this gate.async with model_load_gate():+ sink_token = eviction_sink.set(evicted_slots)+ replaced_token = _replaced_primary_sink.set(replaced_slots)# Chosen under the gate, so two loads cannot both claim an empty primary.extra = await _select_load_slot(request)new_slot = extra is not None and extra not in model_slots.slots@@ -18540,17 +18587,42 @@ async def load_model_gated()breakexcept (GpuMemoryShortError, HTTPException) as exc:- if not isinstance(exc, GpuMemoryShortError):+ measured = isinstance(exc, GpuMemoryShortError)+ if not measured:# A non-GGUF load reports no fit up front: its out-of-memory failure# makes room the same way, one idle kept model at a time.if extra is None or not _ran_out_of_memory(exc):raise- exc = GpuMemoryShortError(str(exc.detail))+ detail = exc.detail+ exc = GpuMemoryShortError(+ str(detail.get("message") or detail)+ if isinstance(detail, dict)+ else str(detail)+ )+ from utils.multi_model_settings import get_multi_model_mode++ if await asyncio.to_thread(get_multi_model_mode) == "always":+ # Always unloads nothing: try once more beside the others, else refuse.+ if exc.capped and not request.force_alongside:+ request = request.model_copy(update = {"force_alongside": True})+ continue+ if measured and not account_access.managed_account():+ # Its Always copy already says nothing is unloaded to make room.+ raise MultiModelAlwaysRefusal(str(exc), kind = "chat") from exc+ raise refusal_for(+ await asyncio.to_thread(chat_eviction_reports)+ ) from exc# No chat may start on a victim between its pick and teardown.async with inference_lifecycle_gate() if new_slot else nullcontext():- dropped = await asyncio.to_thread(- model_slots.evict, extra, exc.short_mib, exc.gpu_indices+ victims = await asyncio.to_thread(+ model_slots.eviction_victims, extra, exc.short_mib, exc.gpu_indices)+ # Named before the drop, while their public ids are still live.+ reports = await asyncio.to_thread(+ lambda: {slot: _kept_slot_reports(slot) for slot in victims}+ )+ dropped = await asyncio.to_thread(model_slots.evict_these, victims)+ note_keyed([r for slot in dropped for r in reports.get(slot, ())])if not dropped:if exc.capped:request = request.model_copy(update = {"force_alongside": True})@@ -18566,6 +18638,9 @@ async def load_model_gated(await asyncio.to_thread(model_slots.drop, extra)model_slots.loading, extra = None, Nonereplaced = _primary_model_label()+ replaced_reports = await asyncio.to_thread(+ model_slots.in_slot, None, _primary_chat_reports+ )request = request.model_copy(update = {"alongside": False, "force_alongside": False})@@ -18576,6 +18651,7 @@ async def load_model_gated(# As a pick does before a switch: the active model goes first, so# the new one is placed on a GPU it no longer shares.await asyncio.to_thread(_unload_primary)+ note_keyed(replaced_reports)response = await _run_tracked_load_model_impl(request,fastapi_request,@@ -18606,10 +18682,32 @@ async def load_model_gated(# it is a plain attribute write and holding the gate for it would only widen# the window that blocks unload.get_llama_cpp_backend()._loaded_by_user_action = user_initiated- if evicted and isinstance(response, LoadResponse):- response.evicted = evicted+ # Every other model this load unloaded is listed too, under its model id: idle kept models,+ # kept models a vLLM/SGLang load retired and media a chat load freed.+ evicted += [+ slot["model"]+ for index, slot in enumerate(evicted_slots)+ if slot.get("model") and index not in keyed+ ]+ if isinstance(response, LoadResponse):+ if evicted:+ response.evicted = evicted+ # A retried attempt can name the same model twice.+ response.evicted_slots = [+ dict(pair)+ for pair in dict.fromkeys(+ tuple(slot.items()) for slot in [*evicted_slots, *replaced_slots]+ )+ ]return response+ except MultiModelAlwaysRefusal as exc:+ path = getattr(getattr(fastapi_request, "url", None), "path", None)+ raise exc.as_http_exception(path) from excfinally:+ if sink_token is not None:+ eviction_sink.reset(sink_token)+ if replaced_token is not None:+ _replaced_primary_sink.reset(replaced_token)try:if extra is not None:model_slots.loading = None@@ -18640,8 +18738,17 @@ def _gate_kept_models(request: LoadRequest, cancel: bool = True) -> None:async def _retire_kept_models(request: LoadRequest) -> None:"""vLLM and SGLang reserve the GPU, so a load of either takes the kept models down too: gatedbefore any chat is cancelled, torn down once nothing can still reject the load."""+ from core.inference.gpu_arbiter import note_evictions+_gate_kept_models(request)+ # Named before the teardown, while their public ids are still live.+ kept = await asyncio.to_thread(+ lambda: {slot: _kept_slot_reports(slot) for slot in list(model_slots.slots)}+ )await asyncio.to_thread(model_slots.unload_extra_models, strict = True)+ note_evictions(+ [r for slot, found in kept.items() if slot not in model_slots.slots for r in found]+ )def _unload_primary() -> None:@@ -18661,6 +18768,153 @@ def _primary_model_label() -> Optional[str]:return getattr(_peek_inference_backend(), "active_model_name", None)+def _orchestrator_chat_report(backend, account) -> Optional[dict]:+ from core.inference.native_audio import NATIVE_AUDIO_TYPES++ name = getattr(backend, "active_model_name", None)+ if not name:+ return None+ entry = (getattr(backend, "models", None) or {}).get(name) or {}+ kind = "audio" if entry.get("audio_type") in NATIVE_AUDIO_TYPES else "chat"+ return {"kind": kind, "model": _orchestrator_public_model_id(backend) or "", "account": account}+++def _primary_chat_reports() -> list[dict]:+ """Reports for the loaded primary chat model; call through ``model_slots.in_slot(None, ...)``."""+ from core.inference.npu_backend import peek_npu_backend+ from hub.services.models.account_access import _resident_loader++ account = _resident_loader("chat")+ found = []+ llama = get_llama_cpp_backend()+ if getattr(llama, "is_loaded", False):+ found.append(+ {"kind": "chat", "model": _llama_status_model_ids(llama)[0] or "", "account": account}+ )+ report = _orchestrator_chat_report(_peek_inference_backend(), account)+ if report is not None:+ found.append(report)+ npu = peek_npu_backend()+ npu_model = npu.loaded_model if npu is not None else None+ if npu_model is not None:+ found.append({"kind": "chat", "model": npu_model.id or "", "account": account})+ return found+++def _kept_slot_reports(slot) -> list[dict]:+ """Reports for one kept slot, evaluated in the slot as the status code does."""++ def collect() -> list[dict]:+ found = []+ if getattr(slot.llama, "is_loaded", False):+ model = _llama_public_model_id(slot.llama) or ""+ found.append({"kind": "chat", "model": model, "account": slot.account})+ report = _orchestrator_chat_report(slot.orchestrator, slot.account)+ if report is not None:+ found.append(report)+ return found++ try:+ return model_slots.in_slot(slot, collect)+ except Exception as exc: # noqa: BLE001 - a report never blocks an eviction+ logger.warning("Could not list a model kept alongside: %s", exc)+ return []+++def chat_eviction_reports() -> list[dict]:+ """``{kind, model, account}`` for every loaded chat model, read before an eviction tears it down.++ The GPU arbiter calls this under its lock, so it never calls back into the arbiter, never+ takes ``model_slots.lock`` and never raises. Models still loading and stuck slots are skipped.+ """+ reports: list[dict] = []+ try:+ reports += model_slots.in_slot(None, _primary_chat_reports)+ except Exception as exc: # noqa: BLE001 - a report never blocks an eviction+ logger.warning("Could not list the active chat model: %s", exc)+ try:+ filling = model_slots.loading[0] if model_slots.loading else None+ for slot in list(model_slots.slots):+ if slot is not filling:+ reports += _kept_slot_reports(slot)+ except Exception as exc: # noqa: BLE001+ logger.warning("Could not list the models kept alongside: %s", exc)+ return reports+++# The serving primary an ordinary load replaces, reported in ``evicted_slots`` only: the legacy+# ``evicted`` list drives the "to make room" toast, which an ordinary switch must not show.+_replaced_primary_sink: contextvars.ContextVar[Optional[list]] = contextvars.ContextVar(+ "replaced_primary_sink", default = None+)+++async def _guard_primary_replacement(request: LoadRequest, names) -> None:+ """Before any teardown: under Always, refuse a load that would replace the serving primary with+ another repo, or whose vLLM/SGLang engine would retire a kept model. Otherwise report the+ primary such a load replaces."""+ from core.inference.gpu_arbiter import public_slots, refusal_for+ from core.inference.openai_auto_download import split_model_ref+ from utils.multi_model_settings import get_multi_model_mode++ always = await asyncio.to_thread(get_multi_model_mode) == "always"+ sink = _replaced_primary_sink.get()+ if not always and sink is None:+ return+ if always and request.engine != "auto":+ for slot in list(model_slots.slots):+ if model_slots.in_use(slot):+ raise refusal_for(await asyncio.to_thread(_kept_slot_reports, slot))+ # A slot that failed to stop still holds its model, and the retire retries its unload.+ stuck = list(model_slots.stuck)+ if stuck:+ raise refusal_for(await asyncio.to_thread(_kept_slot_reports, stuck[0]), "chat")+ try:+ reports = await asyncio.to_thread(model_slots.in_slot, None, _primary_chat_reports)+ except Exception: # noqa: BLE001 - unreadable: Always keeps it, as for media+ if always:+ raise refusal_for([], "chat")+ reports = []+ if not reports:+ # A primary restarting after a crash reports no row yet, but Always still keeps it.+ if not (always and await asyncio.to_thread(model_slots.in_slot, None, _primary_respawning)):+ return+ # The bare repo id, so another quant of the same repo is allowed; the full name for an NPU id.+ candidates = dict.fromkeys(+ ref for name in names if name for ref in (split_model_ref(name)[0], name) if ref+ )+ for ref in candidates:+ if await asyncio.to_thread(+ model_slots.in_slot, None, functools.partial(_loaded_satisfies, ref)+ ):+ return+ if always:+ raise refusal_for(reports)+ sink.extend(public_slots(reports))+++def _primary_respawning() -> bool:+ llama_backend = get_llama_cpp_backend()+ return bool(getattr(llama_backend, "is_active", False)) and not getattr(+ llama_backend, "is_loaded", False+ )+++def _reassert_chat_claim(policy: str) -> None:+ """Re-assert CHAT for a chat model already loaded. Under Always a refusal is ignored: the+ model stays usable and nothing is unloaded."""+ from core.inference.gpu_arbiter import (+ CHAT,+ MultiModelAlwaysRefusal,+ acquire_for_request,+ policy_kwargs,+ )+ try:+ acquire_for_request(CHAT, **policy_kwargs(policy))+ except MultiModelAlwaysRefusal:+ pass++async def _select_load_slot(request: LoadRequest) -> Optional[_ExtraSlot]:"""The extra slot already serving the model, or a new one for ``alongside``. None is the primary."""from core.inference.npu_backend import is_npu_model_path@@ -18685,7 +18939,15 @@ async def _select_load_slot(request: LoadRequest) -> Optional[_ExtraSlot]:# at the first load after it is idle.if not await asyncio.to_thread(get_multi_model_enabled):if model_slots.slots:+ from core.inference.gpu_arbiter import note_evictions++ kept = await asyncio.to_thread(+ lambda: {slot: _kept_slot_reports(slot) for slot in list(model_slots.slots)}+ )await asyncio.to_thread(model_slots.unload_idle)+ note_evictions(+ [r for slot, found in kept.items() if slot not in model_slots.slots for r in found]+ )return Noneif not request.alongside:return None@@ -18918,6 +19180,10 @@ async def _load_npu_model(await asyncio.to_thread(npu.loadable_model, model_id)except NpuError as exc:raise HTTPException(status_code = 400, detail = str(exc)) from None+ # The NPU model replaces the primary: under Always only the one already serving may reload.+ # After the checks above, so a request that can only fail never asks to unload a model.+ if routed_slot.get() is None:+ await _guard_primary_replacement(request, (request.model_path,))llama_backend = get_llama_cpp_backend()unsloth_backend = _peek_inference_backend()serving = bool(@@ -19039,6 +19305,7 @@ async def _load_model_impl(_cache_footprint_before = _hub_cache_footprint(request.model_path)_lora_base_before_this_load = _lora_base_already_in_the_hub_cache(request.model_path)from core.inference.llama_cpp import GpuMemoryShortError, LlamaServerNotFoundError+ from core.inference.gpu_arbiter import MultiModelAlwaysRefusaldef _raise_if_scoped_load_cancelled() -> None:if load_cancel_event is not None and load_cancel_event.is_set():@@ -19212,7 +19479,8 @@ async def _load_model_impl(# already-loaded fast paths below re-assert CHAT themselves. Deferred past validation so a doomed load evicts nothing.from core.inference.gpu_arbiter import (acquire_for_request,- current_owner,+ holds,+ policy_kwargs,CHAT,DIFFUSION,VIDEO,@@ -19227,6 +19495,27 @@ async def _load_model_impl(or getattr(backend, "active_model_name", None)or (replacing and _resident_npu_model() is not None))+ # Under Always, a load that would unload the serving primary or a kept model is refused+ # here, before any teardown; another quant, context or engine of the same repo is not.+ if replacing and (+ serving or (request.engine != "auto" and (model_slots.slots or model_slots.stuck))+ ):+ # A native lease's model_path is only its display label; the granted path is the identity.+ await _guard_primary_replacement(+ request,+ (model_identifier,)+ if native_grant_backed+ else (+ _model_key(request),+ request.model_path,+ _requested_model_id,+ scan_folder_public_id,+ model_identifier,+ ),+ )+ from utils.multi_model_settings import get_multi_model_mode++ multi_model_mode = await asyncio.to_thread(get_multi_model_mode)# Resolve once so dedupe, admission and launch use the same slot count._n_parallel = _resolve_parallel_slots(request, fastapi_request)@@ -19306,7 +19595,7 @@ async def _load_model_impl(# held) to correct a drifted owner. Unless the resident server is a confirmed# zero-VRAM one, which coexists with an image/video pipeline.if not llama_backend.holds_no_vram:- await asyncio.to_thread(acquire_for_request, CHAT)+ await asyncio.to_thread(_reassert_chat_claim, multi_model_mode)return reusedif not (request.gguf_variant or is_direct_gguf_request):_inherit_resident_load_in_4bit(backend, request, model_identifier)@@ -19349,7 +19638,7 @@ async def _load_model_impl(# Requested chat model already resident: assert CHAT ownership (no-op when held) to correct a drifted owner.# Owns no GPU, so the arbiter would cancel a generation for nothing.if not _resident_audio_holds_no_gpu(backend):- await asyncio.to_thread(acquire_for_request, CHAT)+ await asyncio.to_thread(_reassert_chat_claim, multi_model_mode)if replacing:account_access.join_resident("chat")if request._advertised_id:@@ -19767,6 +20056,7 @@ async def _load_model_impl(handoff_kwargs["allow_evict"] = Falseif not replacing:handoff_kwargs["alongside"] = True+ handoff_kwargs.update(policy_kwargs(multi_model_mode))await asyncio.to_thread(acquire_for_request,CHAT,@@ -19778,7 +20068,12 @@ async def _load_model_impl(if isinstance(exc, OwnerChangedError):raise HTTPException(status_code = 409, detail = str(exc)) from excraise- if post_media_handoff_gpu is not None and post_media_handoff_needed_gb is not None:+ # Wait for the freed VRAM only when the media model was actually evicted.+ if (+ post_media_handoff_gpu is not None+ and post_media_handoff_needed_gb is not None+ and not holds(expected_native_owner[0])+ ):settled = await asyncio.to_thread(_wait_for_native_audio_gpu_free_gb,post_media_handoff_gpu,@@ -19943,7 +20238,7 @@ async def _load_model_impl(# Recovery may turn an automatic GPU request into a zero-VRAM load.if llama_backend.holds_no_vram:chat_load_needs_gpu = False- if chat_load_needs_gpu and current_owner() != CHAT:+ if chat_load_needs_gpu and not holds(CHAT):await asyncio.to_thread(llama_backend.unload_model)raise HTTPException(status_code = 409,@@ -20156,7 +20451,7 @@ async def _load_model_impl(# Same guard the GGUF branch runs above: an Images/Video acquire can land between this load's cancellation and its publish, so this load undoes itself.# On a clean server the owner is None, so ungated this unloads what it loaded.- if chat_load_needs_gpu and current_owner() != CHAT:+ if chat_load_needs_gpu and not holds(CHAT):await asyncio.to_thread(backend.unload_model, config.identifier)# The worker's base CUDA context outlives the model unload, so kill it too.await asyncio.to_thread(backend._shutdown_subprocess, 5.0)@@ -20334,6 +20629,8 @@ async def _load_model_impl(raise HTTPException(status_code = 400, detail = redacted_msg)except GpuMemoryShortError:raise # load_model_gated makes room and retries+ except MultiModelAlwaysRefusal:+ raise # the route answers 409 with the refusal headerexcept LlamaServerNotFoundError as e:# Missing GGUF runtime: 400 with the install message, not a generic 500.logger.warning("GGUF runtime missing while loading '%s': %s", model_log_label, e)@@ -22842,6 +23139,9 @@ async def get_status(current_subject: str, model: Optional[str] = None):slot = await _route_to_extra_slot(model)response = await _slot_status(current_subject)if isinstance(response, InferenceStatusResponse):+ from utils.multi_model_settings import get_multi_model_mode++ response.multi_model_mode = await asyncio.to_thread(get_multi_model_mode)active = response.active_modelresponse.serving = [active] if active else []response.serving_checkpoints = [response.model_identifier or active] if active else []@@ -49813,9 +50113,9 @@ def _training_is_active() -> bool:return _diffusion_training_active()-def _unload_native_video_sharing_the_sd_cpp_tree() -> None:+def _unload_native_video_sharing_the_sd_cpp_tree(policy: str = "off", evicted = None) -> None:"""An off-torch image load skips the arbiter, a native H3 model's only evictor, yet may reinstall- the managed sd.cpp tree that model runs from."""+ the managed sd.cpp tree that model runs from. Under Always that is refused instead."""from core.inference import gpu_arbiterfrom core.inference.video import get_video_backend@@ -49830,9 +50130,24 @@ def _unload_native_video_sharing_the_sd_cpp_tree() -> None:and H3_GGUF_REPO in (getattr(loading, "asset_repos", None) or ()))if h3_loading or video.status().get("engine") == "sd_cpp":+ slots = gpu_arbiter.resident_slots(gpu_arbiter.VIDEO) or [{"kind": "video", "model": ""}]+ if policy == "always":+ raise gpu_arbiter.refusal_for(slots, "video")logger.info("Unloading the native video model: the Images load replaces its sd.cpp build")video.unload()gpu_arbiter.release(gpu_arbiter.VIDEO)+ gpu_arbiter.note_evictions(slots, evicted)+++def _activate_checked(check, activate):+ """``activate()`` with ``check`` run before an engine switch unloads the active engine."""+ from core.inference.diffusion_engine_router import before_engine_switch++ token = before_engine_switch.set(check)+ try:+ return activate()+ finally:+ before_engine_switch.reset(token)def _guard_diffusion_load_against_training() -> None:@@ -50281,6 +50596,13 @@ async def load_diffusion_model_gated()from core.inference.gpu_arbiter import (acquire_for_request,+ eviction_sink,+ MultiModelAlwaysRefusal,+ begin_media_load,+ guarded_media_begin,+ note_evictions,+ policy_kwargs,+ refuse_replacing_media,require_no_foreign_generations,release,DIFFUSION,@@ -50469,12 +50791,31 @@ async def load_diffusion_model_gated(preflighted = engine_for(pending_name)await asyncio.to_thread(_preflight, preflighted)+ from utils.multi_model_settings import get_multi_model_mode++ # Read outside the arbiter lock.+ multi_model_mode = await asyncio.to_thread(get_multi_model_mode)+ media_names = (request.model_path,)+ # Before the engine switch below: on any device the load replaces the loaded image model.+ replaced_media = await asyncio.to_thread(+ refuse_replacing_media, DIFFUSION, multi_model_mode, media_names+ )+ # Every model this load unloads, as {kind, model}.+ evicted_slots: list[dict] = []+ note_evictions(replaced_media, evicted_slots)# begin_load signals whatever generation is running, so guard on every device, not just GPU.require_no_foreign_generations()if off_torch is not None and pending_name == ENGINE_SD_CPP:- await asyncio.to_thread(_unload_native_video_sharing_the_sd_cpp_tree)+ await asyncio.to_thread(+ _unload_native_video_sharing_the_sd_cpp_tree, multi_model_mode, evicted_slots+ )# Pick the engine for this host (diffusers on GPU, native sd.cpp otherwise), installing sd-cli if needed, BEFORE evicting chat.+ # Under Always the switch re-checks under the router's transition lock: another load may have landed meanwhile.engine = await asyncio.to_thread(+ _activate_checked,+ functools.partial(refuse_replacing_media, DIFFUSION, multi_model_mode, media_names)+ if multi_model_mode == "always"+ else None,functools.partial(select_and_activate_engine,fam,@@ -50488,7 +50829,7 @@ async def load_diffusion_model_gated(),# Only the opt-in MLX engine reads it (to judge the GGUF quant).gguf_filename = request.gguf_filename,- )+ ),)# predict_engine is selection's read-only twin: it never installs, so a host whose sd-cli# install then fails lands on the OTHER engine. Re-ask the engine actually activated when@@ -50607,14 +50948,26 @@ async def load_diffusion_model_gated(# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts DIFFUSION before# the load is marked, finds nothing to cancel, and both allocate at once. The training admission wraps the same span.def _acquire_and_begin():- with _diffusion_training_admission():- return acquire_for_request(DIFFUSION, _begin_load)+ sink_token = eviction_sink.set(evicted_slots)+ try:+ with _diffusion_training_admission():+ return acquire_for_request(+ DIFFUSION,+ guarded_media_begin(+ DIFFUSION, multi_model_mode, media_names, _begin_load+ ),+ **policy_kwargs(multi_model_mode),+ )+ finally:+ eviction_sink.reset(sink_token)status_dict = await asyncio.to_thread(_acquire_and_begin)else:# A CPU-only native load never touches the GPU, but switching FROM a previous GPU load leaves DIFFUSION marked as owner, so release (owner-guarded).await asyncio.to_thread(release, DIFFUSION)- status_dict = await asyncio.to_thread(_begin_load)+ status_dict = await asyncio.to_thread(+ begin_media_load, DIFFUSION, multi_model_mode, media_names, _begin_load+ )# Keyed to the target: this load can still fail with the previous model resident, and# its origin must not be read off that model.note_media_load_origin(@@ -50631,11 +50984,18 @@ async def load_diffusion_model_gated(*(r for r in account_access.media_component_file_references(request) if r),)reset_media_load_progress("image")+ status_dict = {+ **status_dict,+ "evicted": [slot["model"] for slot in evicted_slots if slot.get("model")],+ "evicted_slots": evicted_slots,+ }return DiffusionStatusResponse(**(await asyncio.to_thread(annotate_status, status_dict)))except (ValueError, FileNotFoundError) as exc:raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))except account_access.GpuBusyForAnotherAccountError as exc:raise account_access.gpu_busy_error() from exc+ except MultiModelAlwaysRefusal as exc:+ raise exc.as_http_exception() from excexcept RuntimeError as exc:# A load is already in progress.raise HTTPException(status_code = 409, detail = str(exc))diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 6639c678eb8..4de2f7fdd76 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -108,8 +108,9 @@ from utils.reasoning_budget import validate_reasoning_budget_messagefrom utils.coding_agents import CODING_AGENTS, detect_installed_coding_agentsfrom utils.multi_model_settings import (DEFAULT_MULTI_MODEL_ENABLED,- get_multi_model_enabled,- set_multi_model_enabled,+ DEFAULT_MULTI_MODEL_MODE,+ get_multi_model_mode,+ set_multi_model_mode,)from utils.model_memory_settings import (DEFAULT_KEEP_RESIDENT,@@ -567,12 +568,26 @@ def delete_custom_generation_preset(class MultiModelPayload(BaseModel):- enabled: StrictBool+ # ``mode`` is the current shape; a bare ``enabled`` comes from an older client.+ enabled: Optional[StrictBool] = None+ mode: Optional[Literal["off", "fit", "always"]] = None++ @model_validator(mode = "after")+ def exactly_one(self):+ if (self.enabled is None) == (self.mode is None):+ raise ValueError("Send exactly one of mode or enabled.")+ return selfclass MultiModelResponse(BaseModel):enabled: booldefault_enabled: bool = DEFAULT_MULTI_MODEL_ENABLED+ mode: Literal["off", "fit", "always"] = DEFAULT_MULTI_MODEL_MODE+ default_mode: Literal["off", "fit", "always"] = DEFAULT_MULTI_MODEL_MODE+++def _multi_model_response(mode: str) -> MultiModelResponse:+ return MultiModelResponse(enabled = mode != "off", mode = mode)class UploadLimitPayload(BaseModel):@@ -1449,7 +1464,7 @@ def update_llama_cpp_path(@_shared_settings_router.get("/multi-model", response_model = MultiModelResponse)def get_multi_model(current_subject: str = Depends(get_current_subject)) -> MultiModelResponse:- return MultiModelResponse(enabled = get_multi_model_enabled())+ return _multi_model_response(get_multi_model_mode())@_owner_settings_router.put("/multi-model", response_model = MultiModelResponse)@@ -1458,9 +1473,14 @@ def update_multi_model(background_tasks: BackgroundTasks,current_subject: str = Depends(get_current_subject),) -> MultiModelResponse:- """Keep the loaded models when another loads. Takes effect on the next load."""+ """Off, When they fit or Always. Takes effect on the next load."""try:- enabled = set_multi_model_enabled(payload.enabled)+ mode = payload.mode+ if mode is None:+ # A legacy "on" never downgrades Always to When they fit.+ current = get_multi_model_mode()+ mode = (current if current != "off" else "fit") if payload.enabled else "off"+ set_multi_model_mode(mode)except Exception as exc:raise log_and_http_error(exc,@@ -1469,12 +1489,12 @@ def update_multi_model(event = "settings.update_multi_model_failed",log = logger,) from exc- logger.info("settings.multi_model_updated subject=%s enabled=%s", current_subject, enabled)- if not enabled:+ logger.info("settings.multi_model_updated subject=%s mode=%s", current_subject, mode)+ if mode == "off":# Back to one model: the idle kept ones go after the reply (a teardown can take minutes),# a busy one once it is ejected. One that fails to unload stays tracked as stuck.background_tasks.add_task(_unload_idle_models)- return MultiModelResponse(enabled = enabled)+ return _multi_model_response(mode)def _unload_idle_models() -> None:diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 6dc2d0b6f20..7b9ad7347f3 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -337,10 +337,20 @@ async def load_video_model_gated(resolve_selected_cuda_ordinal,)from core.inference.gpu_arbiter import (+ DIFFUSION,VIDEO,+ MultiModelAlwaysRefusal,acquire_for_request,+ eviction_sink,+ note_evictions,+ policy_kwargs,+ begin_media_load,+ guarded_media_begin,+ refusal_for,+ refuse_replacing_media,release,require_no_foreign_generations,+ resident_slots,)from core.inference.media_keepwarm import note_load_originfrom hub.utils.gguf import extract_quant_token@@ -462,12 +472,29 @@ async def load_video_model_gated(require_no_foreign_generations()from core.inference.sd_cpp_args import forces_cpu_backendfrom core.inference.video_minimax_h3 import is_h3_native+ from utils.multi_model_settings import get_multi_model_mode++ multi_model_mode = await asyncio.to_thread(get_multi_model_mode)+ media_names = (request.model_path,)+ # On any device: the load would replace the loaded video model, which no acquire evicts.+ replaced_media = await asyncio.to_thread(+ refuse_replacing_media, VIDEO, multi_model_mode, media_names+ )+ evicted: list = []+ note_evictions(replaced_media, evicted)++ def begin():+ return begin_media_load(VIDEO, multi_model_mode, media_names, _begin_load)if is_h3_native(fam, kind):from core.inference.diffusion_engine_router import get_active_diffusion_engineimages = get_active_diffusion_engine()if getattr(images, "runs_off_torch_device", False) is True:# No arbiter owner evicts it, yet it holds the one managed sd.cpp tree H3 installs into.+ image_slots = resident_slots(DIFFUSION) or [{"kind": "image", "model": ""}]+ if multi_model_mode == "always":+ raise refusal_for(image_slots, "image")+ note_evictions(image_slots, evicted)await asyncio.to_thread(images.unload)# sd.cpp runs a paravirtual Mac GPU on the CPU backend: take no VIDEO claim, but keep any existing one until the# worker tears the old model down and releases it.@@ -477,20 +504,28 @@ async def load_video_model_gated(and await asyncio.to_thread(forces_cpu_backend, device))if forced_cpu:- status_dict = await asyncio.to_thread(_begin_load)+ status_dict = await asyncio.to_thread(begin)elif device != "cpu":# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts VIDEO# before the load is marked, finds nothing to cancel, and both allocate at once. The training admission wraps# the same span.from routes.inference import _diffusion_training_admissiondef _acquire_and_begin():- with _diffusion_training_admission():- return acquire_for_request(VIDEO, _begin_load)+ token = eviction_sink.set(evicted)+ try:+ with _diffusion_training_admission():+ return acquire_for_request(+ VIDEO,+ guarded_media_begin(VIDEO, multi_model_mode, media_names, _begin_load),+ **policy_kwargs(multi_model_mode),+ )+ finally:+ eviction_sink.reset(token)status_dict = await asyncio.to_thread(_acquire_and_begin)else:await asyncio.to_thread(release, VIDEO)- status_dict = await asyncio.to_thread(_begin_load)+ status_dict = await asyncio.to_thread(begin)# Keyed to the target: this load can still fail with the previous model residentnote_load_origin(VIDEO,@@ -507,11 +542,18 @@ async def load_video_model_gated(*account_access.media_adapter_references(request),)reset_media_load_progress("video")+ status_dict = {+ **status_dict,+ "evicted": [slot["model"] for slot in evicted if slot.get("model")],+ "evicted_slots": evicted,+ }return VideoStatusResponse(**status_dict)except (ValueError, FileNotFoundError) as exc:raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))except account_access.GpuBusyForAnotherAccountError as exc:raise account_access.gpu_busy_error() from exc+ except MultiModelAlwaysRefusal as exc:+ raise exc.as_http_exception() from excexcept RuntimeError as exc:# A video load is already in progress.raise HTTPException(status_code = 409, detail = str(exc))diff --git a/studio/backend/studio_mcp/outputs.py b/studio/backend/studio_mcp/outputs.pyindex c7085b5aab6..2d4f1953ad8 100644--- a/studio/backend/studio_mcp/outputs.py+++ b/studio/backend/studio_mcp/outputs.py@@ -121,6 +121,8 @@ class ChatModel(ToolOutput):class ChatSlot(ToolOutput):loaded: list[ChatModel] = []loading: list[RouteText] = []+ # Keep multiple models loaded: off, fit or always. None from a server that predates it.+ multi_model_mode: Optional[RouteText] = Noneclass ImageSlot(ToolOutput):diff --git a/studio/backend/studio_mcp/tools/status.py b/studio/backend/studio_mcp/tools/status.pyindex 595237a28d7..97bce1c37d0 100644--- a/studio/backend/studio_mcp/tools/status.py+++ b/studio/backend/studio_mcp/tools/status.py@@ -62,7 +62,9 @@ def _chat(payload: dict) -> ChatSlot:if isinstance(model_id, str)]loading = [model for model in payload.get("loading") or [] if isinstance(model, str)]- return ChatSlot(loaded = loaded, loading = loading)+ return ChatSlot(+ loaded = loaded, loading = loading, multi_model_mode = opt_text(payload.get("multi_model_mode"))+ )def _media(slot: type, payload: dict) -> Any:diff --git a/studio/backend/tests/multi_account/test_multi_model_owner_mode.py b/studio/backend/tests/multi_account/test_multi_model_owner_mode.pynew file mode 100644index 00000000000..0b2313d4c5a--- /dev/null+++ b/studio/backend/tests/multi_account/test_multi_model_owner_mode.py@@ -0,0 +1,79 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's load reads the owner's Keep multiple models loaded mode, not its own DB."""++import asyncio++import pytest++import core.inference.model_slots as model_slots+import core.inference.orchestrator as orchestrator+import routes.inference as inf+from models.inference import LoadRequest+from utils import multi_model_settings+from utils.account_context import AccountContext, bind_account, reset_account, run_as+++class FakeLlama:+ holds_no_vram = False++ def __init__(+ self,+ identifier = None,+ variant = None,+ ):+ self.model_identifier, self.hf_variant = identifier, variant+ self.is_loaded = self.is_active = identifier is not None+ self.is_vision, self.context_length = False, 4096++ def unload_model(self):+ self.is_loaded = self.is_active = False++ def _cleanup(self):+ pass+++class FakeOrch:+ def __init__(self):+ self.active_model_name, self.models = None, {}++ def unload_model(self, name):+ self.active_model_name = None++ def _cleanup(self):+ pass+++def fresh_mode_cache():+ multi_model_settings.invalidate_multi_model_cache()+ yield+ multi_model_settings.invalidate_multi_model_cache()++[email protected]("mode, keeps", [("fit", True), ("always", True), ("off", False)])+def test_a_managed_load_reads_the_owners_mode_and_keeps_its_idle_models(+ accounts, monkeypatch, fresh_mode_cache, mode, keeps+):+ alice = accounts["alice"]+ ctx = AccountContext(alice.account_id, alice.username, alice.role)+ multi_model_settings.set_multi_model_mode(+ mode+ ) # isolated_auth binds OWNER; alice's DB never stores it+ extra = model_slots.ExtraSlot(FakeLlama("org/B-GGUF", "Q8_0"), FakeOrch(), "owner")+ monkeypatch.setattr(inf, "_llama_cpp_backend", FakeLlama("org/A-GGUF", "Q4_K_M"))+ monkeypatch.setattr(orchestrator, "_inference_backend", FakeOrch())+ monkeypatch.setattr(model_slots, "slots", [extra])+ monkeypatch.setattr(model_slots, "stuck", [])+ unloads: list[int] = []+ monkeypatch.setattr(model_slots, "unload_idle", lambda: unloads.append(1) or 0)+ assert run_as(ctx, multi_model_settings.get_multi_model_mode) == mode+ multi_model_settings.invalidate_multi_model_cache() # make the load itself read the DB as alice+ token = bind_account(ctx)+ try:+ asyncio.run(inf._select_load_slot(LoadRequest(model_path = "org/C-GGUF")))+ finally:+ reset_account(token)+ assert unloads == ([] if keeps else [1])+ assert model_slots.slots == [extra]diff --git a/studio/backend/tests/test_account_video_cancel_handoff.py b/studio/backend/tests/test_account_video_cancel_handoff.pyindex 888295802f7..0c3056eef04 100644--- a/studio/backend/tests/test_account_video_cancel_handoff.py+++ b/studio/backend/tests/test_account_video_cancel_handoff.py@@ -77,7 +77,7 @@ def isolated(monkeypatch, tmp_path):monkeypatch.setattr(auth_storage, "_bootstrap_password", None)monkeypatch.setattr(video, "_generation_account", None, raising = False)monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)- monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda *_a, **_k: ALICE.account_id)monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)yielddiff --git a/studio/backend/tests/test_account_video_generation_owner.py b/studio/backend/tests/test_account_video_generation_owner.pyindex 80a07a0cd5d..78fafd8cbe3 100644--- a/studio/backend/tests/test_account_video_generation_owner.py+++ b/studio/backend/tests/test_account_video_generation_owner.py@@ -83,7 +83,7 @@ def isolated(monkeypatch, tmp_path):)connection.close()monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)- monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda *_a, **_k: ALICE.account_id)monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)yieldpolicy.invalidate_account_cache()diff --git a/studio/backend/tests/test_account_video_generation_reservation.py b/studio/backend/tests/test_account_video_generation_reservation.pyindex dda98defc8a..8b9a2821373 100644--- a/studio/backend/tests/test_account_video_generation_reservation.py+++ b/studio/backend/tests/test_account_video_generation_reservation.py@@ -87,7 +87,7 @@ def isolated(monkeypatch, tmp_path):monkeypatch.setattr(auth_storage, "_bootstrap_password", None)monkeypatch.setattr(video, "_generation_account", None, raising = False)monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)- monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda *_a, **_k: ALICE.account_id)monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)yielddiff --git a/studio/backend/tests/test_account_video_idle_cancel.py b/studio/backend/tests/test_account_video_idle_cancel.pyindex 8d2123dd653..98a40af7001 100644--- a/studio/backend/tests/test_account_video_idle_cancel.py+++ b/studio/backend/tests/test_account_video_idle_cancel.py@@ -65,7 +65,7 @@ def isolated(monkeypatch, tmp_path):monkeypatch.setattr(auth_storage, "_bootstrap_password", None)monkeypatch.setattr(video, "_generation_account", None, raising = False)monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)- monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda *_a, **_k: ALICE.account_id)monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)yield@@ -119,7 +119,7 @@ def test_idle_cancel_still_stops_the_callers_own_render_started_in_the_gap(monkedef test_single_user_cancel_still_works_and_is_a_no_op_when_idle(monkeypatch):monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)- monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: OWNER.account_id)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda *_a, **_k: OWNER.account_id)backend = VideoBackend()_install(monkeypatch, backend)diff --git a/studio/backend/tests/test_account_video_progress_handoff.py b/studio/backend/tests/test_account_video_progress_handoff.pyindex 1a1bacdf488..f5910155a0d 100644--- a/studio/backend/tests/test_account_video_progress_handoff.py+++ b/studio/backend/tests/test_account_video_progress_handoff.py@@ -112,7 +112,7 @@ def isolated(monkeypatch, tmp_path):monkeypatch.setattr(auth_storage, "_bootstrap_password", None)monkeypatch.setattr(video, "_generation_account", None, raising = False)monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)- monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda *_a, **_k: ALICE.account_id)monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)yielddiff --git a/studio/backend/tests/test_audio_device_guards.py b/studio/backend/tests/test_audio_device_guards.pyindex 91b07fc3ef1..7df08e7decf 100644--- a/studio/backend/tests/test_audio_device_guards.py+++ b/studio/backend/tests/test_audio_device_guards.py@@ -304,8 +304,9 @@ def test_the_post_load_ownership_check_is_gated_like_the_gguf_one():"""Ungated, it unloads the CPU audio model it just loaded and returns 409:the load skips acquire_for, so on a clean server the owner is None."""src = _inference_source()- assert "if chat_load_needs_gpu and current_owner() != CHAT:" in src- assert "\n if current_owner() != CHAT:" not in src+ assert "if chat_load_needs_gpu and not holds(CHAT):" in src+ assert "\n if not holds(CHAT):" not in src+ assert "chat_load_needs_gpu and current_owner() != CHAT" not in srcdef test_a_cpu_audio_worker_hides_cuda_and_hip():diff --git a/studio/backend/tests/test_diffusion_compat_preflight.py b/studio/backend/tests/test_diffusion_compat_preflight.pyindex 941c42aed03..a5201d96817 100644--- a/studio/backend/tests/test_diffusion_compat_preflight.py+++ b/studio/backend/tests/test_diffusion_compat_preflight.py@@ -17,6 +17,7 @@ and a stubbed ``hf_hub_download`` fails the test if anything tries to fetch a whfrom __future__ import annotationsimport inspect+import reimport threadingimport timeimport types@@ -1434,18 +1435,20 @@ def test_both_media_routes_refuse_a_speech_pick_before_taking_the_gpu():for source, acquire, label in ((inspect.getsource(video_route.load_video_model_gated),- "acquire_for_request(VIDEO",+ r"acquire_for_request\(\s*VIDEO\b","video",),(inspect.getsource(inference_route.load_diffusion_model_gated),- "acquire_for_request(DIFFUSION",+ r"acquire_for_request\(\s*DIFFUSION\b","images",),):assert "assert_pick_is_not_speech" in source, label- assert acquire in source, label- assert source.index("assert_pick_is_not_speech") < source.index(acquire), label+ # The call may wrap its arguments over several lines (e.g. with policy_kwargs).+ call = re.search(acquire, source)+ assert call is not None, label+ assert source.index("assert_pick_is_not_speech") < call.start(), labeldef test_an_automatic_image_load_keeps_the_pre_eviction_preflight_offline():diff --git a/studio/backend/tests/test_gpu_arbiter.py b/studio/backend/tests/test_gpu_arbiter.pyindex 7fc7515c723..84b51914744 100644--- a/studio/backend/tests/test_gpu_arbiter.py+++ b/studio/backend/tests/test_gpu_arbiter.py@@ -9,6 +9,8 @@ these verify only the ownership/eviction sequencing — no torch, GPU, or subprofrom __future__ import annotations+import types+import pytestimport core.inference.gpu_arbiter as arb@@ -346,7 +348,7 @@ def test_the_safetensors_load_yields_a_gpu_it_lost_while_loading():# Gated on chat_load_needs_gpu like the GGUF branch: a load that never took the# arbiter has no ownership to lose, and checking against a None owner would 409# every CPU-placed audio load.- guard = tail.index("if chat_load_needs_gpu and current_owner() != CHAT:")+ guard = tail.index("if chat_load_needs_gpu and not holds(CHAT):")assert "await asyncio.to_thread(backend.unload_model, config.identifier)" in tail[guard:]assert tail.index("status_code = 409", guard) > guard@@ -380,3 +382,385 @@ def test_restore_owner_account_is_a_noop_once_someone_else_holds_residency(callsrun_as(carol, arb.acquire_for, arb.VIDEO, lambda: None)assert run_as(bob, arb.restore_owner_account, arb.VIDEO) is Falseassert arb.owner_account() == carol.account_id+++# Multi-resident arbiter: Keep multiple models loaded policies, residents, eviction reports.++from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def arb_log(monkeypatch):+ log: list[str] = []+ for name, value in (+ ("_owner", None),+ ("_residents", {}),+ ("_accounts", {}),+ ("_owner_account", None),+ ("_prior_account", None),+ ):+ monkeypatch.setattr(arb, name, value)+ for owner in (arb.CHAT, arb.DIFFUSION, arb.VIDEO, arb.DECISIONS):+ monkeypatch.setitem(arb._EVICTORS, owner, lambda owner = owner: log.append(f"evict-{owner}"))+ for owner in (arb.CHAT, arb.DIFFUSION, arb.VIDEO):+ monkeypatch.setitem(arb._SLOT_REPORTERS, owner, lambda: [])+ monkeypatch.setattr(arb, "_release_idle_video_servers", lambda reason: log.append("release-h3"))+ return log+++def _report(monkeypatch, log, owner, *slots):+ monkeypatch.setitem(+ arb._SLOT_REPORTERS, owner, lambda: (log.append(f"report-{owner}"), list(slots))[1]+ )+++ "resident, owner, kind, model",+ [+ (arb.CHAT, arb.DIFFUSION, "chat", "unsloth/Qwen3-4B-GGUF"),+ (arb.DIFFUSION, arb.CHAT, "image", "black-forest-labs/FLUX.1-dev"),+ (arb.DIFFUSION, arb.VIDEO, "image", "black-forest-labs/FLUX.1-dev"),+ ],+)+def test_always_refuses_instead_of_evicting(arb_log, monkeypatch, resident, owner, kind, model):+ arb.acquire_for(resident)+ _report(monkeypatch, arb_log, resident, {"kind": kind, "model": model, "account": "owner"})+ arb_log.clear()+ registered: list[bool] = []+ with pytest.raises(arb.MultiModelAlwaysRefusal) as excinfo:+ arb.acquire_for(owner, lambda: registered.append(True), policy = "always")+ assert not [entry for entry in arb_log if entry.startswith("evict-")] and registered == []+ message = str(excinfo.value)+ assert f"the {kind} model {model}" in message and "is set to Always" in message+ assert (excinfo.value.kind, excinfo.value.model) == (kind, model)+ assert arb.residents() == {resident: None}++ http = excinfo.value.as_http_exception("/api/inference/load")+ assert http.status_code == 409 and http.headers == {"X-Unsloth-Refusal": "multi-model-always"}+ assert isinstance(http.detail, str) and "is set to Always" in http.detail+ v1 = excinfo.value.as_http_exception("/v1/chat/completions")+ assert v1.status_code == 409 and v1.detail["error"]["code"] == "multi_model_always"+ assert model in v1.detail["error"]["message"]+++def test_always_refusal_for_a_managed_account_hides_another_accounts_model(arb_log, monkeypatch):+ arb.acquire_for(arb.CHAT)+ _report(+ monkeypatch,+ arb_log,+ arb.CHAT,+ {"kind": "chat", "model": "bob/private-GGUF", "account": BOB.account_id},+ )+ with pytest.raises(arb.MultiModelAlwaysRefusal) as excinfo:+ run_as(ALICE, arb.acquire_for, arb.DIFFUSION, policy = "always")+ message = str(excinfo.value)+ assert "bob/private-GGUF" not in message and "the chat model," in message+ assert "is set to keep loaded" in message and "is set to Always" not in message+ # Alice's own model stays named.+ _report(+ monkeypatch,+ arb_log,+ arb.CHAT,+ {"kind": "chat", "model": "alice/mine-GGUF", "account": ALICE.account_id},+ )+ with pytest.raises(arb.MultiModelAlwaysRefusal, match = "alice/mine-GGUF"):+ run_as(ALICE, arb.acquire_for, arb.DIFFUSION, policy = "always")++[email protected]("policy", ["off", "fit"])+def test_off_and_fit_evict_then_release_idle_video_then_register(arb_log, policy):+ arb.acquire_for(arb.DIFFUSION)+ arb_log.clear()+ arb.acquire_for(arb.CHAT, lambda: arb_log.append("register"), **arb.policy_kwargs(policy))+ assert arb_log == ["evict-diffusion", "release-h3", "register"]+ assert arb.residents() == {arb.CHAT: None}+ assert arb.policy_kwargs("off") == {} and arb.policy_kwargs("always") == {"policy": "always"}+++def test_always_still_evicts_decisions_and_allow_evict_false_still_refuses(arb_log):+ arb.acquire_for(arb.DECISIONS)+ arb.acquire_for(arb.CHAT, policy = "always")+ assert "evict-decisions" in arb_log and arb.residents() == {arb.CHAT: None}+ arb.acquire_for(arb.DECISIONS, policy = "always")+ assert "evict-chat" in arb_log+ arb.acquire_for(arb.CHAT)+ with pytest.raises(arb.GpuOwnerBusyError) as excinfo:+ arb.acquire_for(arb.DECISIONS, allow_evict = False, policy = "always")+ assert excinfo.value.owner == arb.CHAT+++def test_residents_use_physical_gpu_ids_under_a_masked_device_list(arb_log, monkeypatch):+ import utils.hardware.hardware as hardware++ monkeypatch.setattr(hardware, "get_parent_visible_gpu_ids", lambda: [2, 3])+ arb.acquire_for(arb.CHAT, gpu_ids = [0])+ assert arb.residents() == {"chat": frozenset({2})}+ assert arb.physical_gpu_ids([1, 5]) == frozenset({3, 5}) and arb.physical_gpu_ids(None) is None+ monkeypatch.setattr(hardware, "get_parent_visible_gpu_ids", lambda: [])+ assert arb.physical_gpu_ids([0]) == frozenset({0})+++def test_a_directly_set_owner_wins_over_stale_residents(arb_log, monkeypatch):+ monkeypatch.setattr(arb, "_owner", arb.DIFFUSION)+ assert arb.holds(arb.DIFFUSION) and arb.residents() == {arb.DIFFUSION: None}+ monkeypatch.setattr(arb, "_residents", {arb.CHAT: None})+ monkeypatch.setattr(arb, "_owner", None)+ assert arb.residents() == {} and not arb.holds(arb.CHAT)+ monkeypatch.setattr(arb, "current_owner", lambda: arb.CHAT)+ assert arb.holds(arb.CHAT) and arb.residents() == {arb.CHAT: None}+++def test_release_and_release_if_keep_owner_and_residents_in_sync(arb_log, monkeypatch):+ monkeypatch.setattr(arb, "_residents", {arb.CHAT: frozenset({0}), arb.DIFFUSION: None})+ monkeypatch.setattr(arb, "_owner", arb.DIFFUSION)+ arb.release(arb.DIFFUSION)+ assert arb.current_owner() == arb.CHAT and arb.residents() == {arb.CHAT: frozenset({0})}+ assert arb.release_if(arb.CHAT, lambda: True) is True+ assert arb.current_owner() is None and arb.residents() == {} and arb._residents == {}+++def test_evicted_collects_chat_primary_and_kept_slots_image_and_video(arb_log, monkeypatch):+ chat = [+ {"kind": "chat", "model": "org/A-GGUF", "account": "owner"},+ {"kind": "chat", "model": "org/B-GGUF", "account": "owner"},+ ]+ _report(monkeypatch, arb_log, arb.CHAT, *chat)+ _report(+ monkeypatch,+ arb_log,+ arb.DIFFUSION,+ {"kind": "image", "model": "org/Img", "account": "owner"},+ )+ _report(+ monkeypatch, arb_log, arb.VIDEO, {"kind": "video", "model": "org/Vid", "account": "owner"}+ )+ arb.acquire_for(arb.CHAT)+ evicted: list = []+ arb.acquire_for(arb.DIFFUSION, evicted = evicted)+ assert evicted == [+ {"kind": "chat", "model": "org/A-GGUF"},+ {"kind": "chat", "model": "org/B-GGUF"},+ ]+ assert arb_log.index("report-chat") < arb_log.index("evict-chat")+ # Through the sink: the idle H3 release and non-resident video report nothing.+ sink: list = []+ token = arb.eviction_sink.set(sink)+ try:+ arb.acquire_for(arb.VIDEO)+ arb.acquire_for(arb.CHAT)+ finally:+ arb.eviction_sink.reset(token)+ assert sink == [{"kind": "image", "model": "org/Img"}, {"kind": "video", "model": "org/Vid"}]+ assert "release-h3" in arb_log+ arb.note_evictions([{"kind": "chat", "model": "x", "account": None}], evicted)+ assert evicted[-1] == {"kind": "chat", "model": "x"}+++def test_owner_account_and_restore_are_tracked_per_owner(arb_log):+ run_as(ALICE, arb.acquire_for, arb.VIDEO, lambda: None)+ run_as(BOB, arb.acquire_for, arb.VIDEO, lambda: None)+ # Two residents at once (as a "fit" acquire leaves them): CHAT claimed by alice beside bob's VIDEO.+ arb._residents[arb.CHAT] = None+ arb._accounts[arb.CHAT] = (ALICE.account_id, None)+ assert arb.owner_account(arb.VIDEO) == BOB.account_id+ assert arb.owner_account(arb.CHAT) == ALICE.account_id+ assert run_as(ALICE, arb.restore_owner_account, arb.CHAT) is False # no prior account+ assert run_as(BOB, arb.restore_owner_account, arb.VIDEO) is True+ assert arb.owner_account(arb.VIDEO) == ALICE.account_id+ assert arb.owner_account(arb.CHAT) == ALICE.account_id+ arb._accounts[arb.CHAT] = (BOB.account_id, ALICE.account_id)+ assert run_as(BOB, arb.restore_owner_account, arb.CHAT) is True+ assert arb.owner_account(arb.CHAT) == ALICE.account_id+++def test_always_evicts_a_media_claim_that_holds_nothing_unless_it_is_loading(arb_log, monkeypatch):+ # An image load that failed in the background keeps its claim yet holds no model.+ probe = {"loading": False, "broken": False}++ def loading(owner):+ if probe["broken"]:+ raise RuntimeError("status unreadable")+ return probe["loading"]++ monkeypatch.setattr(arb, "_media_status", lambda owner: None)+ monkeypatch.setattr(arb, "_media_loading", loading)+ arb.acquire_for(arb.DIFFUSION)+ # Loading, or unreadable: Always keeps it.+ for key in ("loading", "broken"):+ probe[key] = True+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.acquire_for(arb.CHAT, policy = "always")+ probe[key] = False+ arb_log.clear()+ arb.acquire_for(arb.CHAT, policy = "always")+ assert "evict-diffusion" in arb_log and arb.residents() == {arb.CHAT: None}+++ "policy, requested, refused",+ [+ ("always", ("org/Other",), True),+ ("always", ("org/Flux",), False),+ ("always", ("/hf/hub/models--org--Flux/snapshots/abc",), False),+ ("fit", ("org/Other",), False),+ ],+)+def test_always_refuses_replacing_a_loaded_media_model_with_another_repo(+ arb_log, monkeypatch, policy, requested, refused+):+ monkeypatch.setattr(arb, "_media_status", lambda owner: {"loaded": True, "repo_id": "org/Flux"})+ _report(monkeypatch, arb_log, arb.DIFFUSION, {"kind": "image", "model": "org/Flux"})+ if refused:+ with pytest.raises(arb.MultiModelAlwaysRefusal) as excinfo:+ arb.refuse_replacing_media(arb.DIFFUSION, policy, requested)+ assert (excinfo.value.kind, excinfo.value.model) == ("image", "org/Flux")+ else:+ # Off and fit replace it, and the load reports it.+ replaced = arb.refuse_replacing_media(arb.DIFFUSION, policy, requested)+ assert replaced == ([{"kind": "image", "model": "org/Flux"}] if policy == "fit" else [])+ monkeypatch.setattr(arb, "_media_status", lambda owner: None)+ monkeypatch.setattr(arb, "_media_loading", lambda owner: False)+ assert arb.refuse_replacing_media(arb.VIDEO, "always", ("org/Other",)) == []+++def test_always_identifies_media_by_model_path_not_the_callers_display_label(arb_log, monkeypatch):+ import inspect++ import routes.inference as image_routes+ import routes.video as video_routes++ # A resident loaded from a local copy keeps its label, yet only its path says what it holds.+ monkeypatch.setattr(+ arb,+ "_media_status",+ lambda owner: {"loaded": True, "repo_id": "/models/b", "display_repo_id": "org/Flux"},+ )+ _report(monkeypatch, arb_log, arb.DIFFUSION, {"kind": "image", "model": "org/Flux"})+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.refuse_replacing_media(arb.DIFFUSION, "always", ("org/Flux",))+ assert arb.refuse_replacing_media(arb.DIFFUSION, "always", ("/models/b",)) == []+ # Both load routes key the gate on the path alone: a display label naming the resident would+ # pass another repo off as a reload of it.+ for routes in (image_routes, video_routes):+ source = inspect.getsource(routes)+ assert "media_names = (request.model_path,)" in source+ assert "media_names = (request.model_path, request.display_repo_id)" not in source+++def test_a_media_load_registered_meanwhile_is_not_replaced_under_always(arb_log, monkeypatch):+ # Two loads checked before either registered: the second re-checks under the arbiter lock.+ monkeypatch.setattr(arb, "_media_status", lambda owner: None)+ monkeypatch.setattr(arb, "_media_loading", lambda owner: True)+ monkeypatch.setattr(+ arb,+ "_media_backend",+ lambda owner: types.SimpleNamespace(loading_repo_ids = lambda: ("org/First",)),+ )+ begun = []++ def begin():+ begun.append(True)+ return "started"++ second = arb.guarded_media_begin(arb.DIFFUSION, "always", ("org/Second",), begin)+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.acquire_for(arb.DIFFUSION, second, policy = "always")+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.begin_media_load(arb.DIFFUSION, "always", ("org/Second",), begin)+ assert begun == []+ assert arb.begin_media_load(arb.DIFFUSION, "always", ("org/First",), begin) == "started"+ assert arb.guarded_media_begin(arb.DIFFUSION, "fit", ("org/Second",), begin) is begin++ def unreadable(owner):+ raise RuntimeError("status unreadable")++ monkeypatch.setattr(arb, "_media_status", unreadable)+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.refuse_replacing_media(arb.DIFFUSION, "always", ("org/First",))+ assert arb.refuse_replacing_media(arb.DIFFUSION, "off", ("org/First",)) == []+++def test_always_refuses_a_load_of_the_companion_base_an_in_flight_load_reads(arb_log, monkeypatch):+ # A GGUF load in flight lists its diffusers base too; requesting that base is another model.+ monkeypatch.setattr(arb, "_media_status", lambda owner: None)+ monkeypatch.setattr(+ arb,+ "_media_backend",+ lambda owner: types.SimpleNamespace(+ loading_repo_ids = lambda: ("org/Flux-GGUF", "org/Flux", "org/Flux-VAE")+ ),+ )+ for other in ("org/Flux", "org/Flux-VAE"):+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.refuse_replacing_media(arb.DIFFUSION, "always", (other,))+ assert arb.refuse_replacing_media(arb.DIFFUSION, "always", ("org/Flux-GGUF",)) == []+ assert arb.refuse_replacing_media(arb.DIFFUSION, "fit", ("org/Flux",)) == []+++def test_always_evicts_a_chat_claim_that_holds_nothing_unless_a_chat_load_is_in_flight(+ arb_log, monkeypatch+):+ busy = {"now": True}+ monkeypatch.setattr(arb, "_chat_occupied", lambda: busy["now"])+ arb.acquire_for(arb.CHAT)+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.acquire_for(arb.DIFFUSION, policy = "always")+ busy["now"] = False+ arb_log.clear()+ arb.acquire_for(arb.DIFFUSION, policy = "always")+ assert "evict-chat" in arb_log and arb.residents() == {arb.DIFFUSION: None}+++def test_always_keeps_distinct_local_folders_with_one_name_apart(arb_log, monkeypatch):+ monkeypatch.setattr(+ arb, "_media_status", lambda owner: {"loaded": True, "repo_id": "/mnt/a/Flux"}+ )+ _report(monkeypatch, arb_log, arb.DIFFUSION, {"kind": "image", "model": "Flux"})+ with pytest.raises(arb.MultiModelAlwaysRefusal):+ arb.refuse_replacing_media(arb.DIFFUSION, "always", ("/mnt/b/Flux",))+ assert arb.refuse_replacing_media(arb.DIFFUSION, "always", ("/mnt/a/Flux",)) == []+++def test_an_unreadable_primary_counts_as_occupied(monkeypatch):+ import core.inference.llama_cpp as llama_cpp+ import routes.inference as inf+ from core.inference import model_slots++ monkeypatch.setattr(llama_cpp, "chat_load_active", lambda: False)+ monkeypatch.setattr(model_slots, "any_loading", lambda: False)+ monkeypatch.setattr(model_slots, "stuck", [])+ monkeypatch.setattr(inf, "_primary_chat_reports", lambda: [])+ assert arb._chat_occupied() is False++ def broken():+ raise RuntimeError("status unreadable")++ monkeypatch.setattr(inf, "_primary_chat_reports", broken)+ assert arb._chat_occupied() is True+++def test_a_respawning_chat_server_counts_as_occupied(monkeypatch):+ import core.inference.llama_cpp as llama_cpp+ import routes.inference as inf+ from core.inference import model_slots++ monkeypatch.setattr(llama_cpp, "chat_load_active", lambda: False)+ monkeypatch.setattr(model_slots, "any_loading", lambda: False)+ monkeypatch.setattr(model_slots, "stuck", [])+ monkeypatch.setattr(model_slots, "slots", [])+ monkeypatch.setattr(inf, "_primary_chat_reports", lambda: [])+ server = types.SimpleNamespace(is_active = False, is_loaded = False)+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: server)+ assert arb._chat_occupied() is False++ # Process up, health not yet back (auto-respawn after a crash): Always must keep it.+ server.is_active = True+ assert arb._chat_occupied() is True++ server.is_active = False+ kept = types.SimpleNamespace(llama = types.SimpleNamespace(is_active = True, is_loaded = False))+ monkeypatch.setattr(model_slots, "slots", [kept])+ assert arb._chat_occupied() is Truediff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.pyindex 6177a7908c9..3a1c9686aa7 100644--- a/studio/backend/tests/test_gpu_memory_mode.py+++ b/studio/backend/tests/test_gpu_memory_mode.py@@ -1742,7 +1742,8 @@ def test_a_cpu_only_chat_load_does_not_take_the_gpu_arbiter():)assert load_impl.index("if replacing and not chat_load_needs_gpu:", acquire) < releaseassert load_impl.index("success = await load_with_tensor_fallback(", acquire) < release- assert "if chat_load_needs_gpu and current_owner() != CHAT:" in load_impl+ assert "if chat_load_needs_gpu and not holds(CHAT):" in load_impl+ assert "chat_load_needs_gpu and current_owner() != CHAT" not in load_impl# The already-loaded fast path re-asserts ownership too; same exemption.assert "if not llama_backend.holds_no_vram:" in load_impldiff --git a/studio/backend/tests/test_mcp_tools_status.py b/studio/backend/tests/test_mcp_tools_status.pyindex 48c6fb90952..eaffadf5e7b 100644--- a/studio/backend/tests/test_mcp_tools_status.py+++ b/studio/backend/tests/test_mcp_tools_status.py@@ -138,6 +138,7 @@ def test_every_slot_is_reported(monkeypatch):},],"loading": ["unsloth/gemma-3-1b-it"],+ "multi_model_mode": None,}assert status["image"] == {"loaded": True,@@ -208,6 +209,13 @@ def test_every_slot_is_reported(monkeypatch):assert called == set(PAYLOADS)+def test_chat_reports_the_keep_multiple_models_loaded_mode(monkeypatch):+ for mode in ("off", "fit", "always"):+ overrides = {("GET", "/api/inference/status"): {**CHAT, "multi_model_mode": mode}}+ result, _studio = _status(monkeypatch, overrides)+ assert result["structuredContent"]["chat"]["multi_model_mode"] == mode++def test_failing_and_owner_only_slots_do_not_fail_the_tool(monkeypatch):broken = JSONResponse({"detail": "Video backend crashed at /srv/hf/ltx"}, status_code = 500)owner_only = JSONResponse(diff --git a/studio/backend/tests/test_multi_model_always.py b/studio/backend/tests/test_multi_model_always.pynew file mode 100644index 00000000000..1b5c68153a9--- /dev/null+++ b/studio/backend/tests/test_multi_model_always.py@@ -0,0 +1,648 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Keep multiple models loaded set to Always refuses instead of unloading, and every load+reports what it did unload."""++import asyncio+import json+import types++import pytest+from fastapi import HTTPException++import core.inference.diffusion_device as devmod+import core.inference.media_auto_switch as mas+import core.inference.model_slots as model_slots+import routes.inference as inf+from core.inference import gpu_arbiter+from core.inference.gpu_arbiter import MultiModelAlwaysRefusal+from core.inference.llama_cpp import GpuMemoryShortError, _gpu_short_message+from models.inference import InferenceStatusResponse, LoadRequest, LoadResponse+from utils import multi_model_settings++from . import test_diffusion_routes as _diff+from . import test_media_auto_switch as _switching+from . import test_multi_model_serving as _serving+from . import test_preview_routes as _preview+from . import test_tunnel_safe_long_post as _tunnel+from . import test_video_routes as _video+from .test_diffusion_routes import _post_load+from .test_media_auto_switch import _switch+from .test_multi_model_serving import FakeLlama, _gated_load_fakes+from .test_openai_auto_switch import _FakeBackend, _wired+from .test_tunnel_safe_long_post import _collect+from .test_video_routes import _shared_setup_3++# Shared fixtures, bound by assignment so pytest finds them in this module.+image_client = _diff.client+backend = _switching.backend+catalog = _switching.catalog+enabled = _switching.enabled+flux = _switching.flux+backends = _serving.backends+fake_slot = _preview.fake_slot+slot_state = _preview.slot_state+route = _tunnel.route+video_client = _video.client++REFUSAL = "multi-model-always"+_REAL_ENABLED = multi_model_settings.get_multi_model_enabled+++def _mode(monkeypatch, mode):+ """Pin the setting; get_multi_model_enabled is the real one, derived from the mode."""+ multi_model_settings.invalidate_multi_model_cache()+ monkeypatch.setattr(multi_model_settings, "get_multi_model_mode", lambda: mode)+ monkeypatch.setattr(multi_model_settings, "get_multi_model_enabled", _REAL_ENABLED)++[email protected](autouse = True)+def arbiter(monkeypatch):+ for name, value in (("_owner", None), ("_owner_account", None), ("_prior_account", None)):+ monkeypatch.setattr(gpu_arbiter, name, value)+ monkeypatch.setattr(gpu_arbiter, "_residents", {})+ monkeypatch.setattr(gpu_arbiter, "_accounts", {})+ yield+ multi_model_settings.invalidate_multi_model_cache()+++def _reporting(monkeypatch, owner, slots):+ """A resident ``owner`` whose eviction is recorded and reports ``slots``."""+ evicted = []+ monkeypatch.setitem(gpu_arbiter._SLOT_REPORTERS, owner, lambda: [dict(s) for s in slots])+ monkeypatch.setitem(gpu_arbiter._EVICTORS, owner, lambda: evicted.append(owner))+ return evicted+++def _no_slot_eviction(monkeypatch):+ def never(*args, **kwargs):+ raise AssertionError("a kept model was evicted")++ monkeypatch.setattr(model_slots, "evict_these", never)+ monkeypatch.setattr(model_slots, "eviction_victims", never)+ monkeypatch.setattr(model_slots, "evict", never, raising = False)+++def _is_refusal(exc):+ assert exc.status_code == 409+ assert exc.headers["X-Unsloth-Refusal"] == REFUSAL+ assert "Retry-After" not in exc.headers+++# 1. A short fit under Always refuses; a capped one still retries beside the others.+++def test_a_short_fit_under_always_refuses_and_keeps_every_slot(backends, monkeypatch):+ primary, extra = backends+ _mode(monkeypatch, "always")+ _no_slot_eviction(monkeypatch)+ monkeypatch.setattr(inf, "release_chat_gpu_claim", lambda: None)+ copy = _gpu_short_message(13.2, 8.4, 32768, 32768, False)+ assert "is set to Always" in copy++ async def load(request, *args, **kwargs):+ raise GpuMemoryShortError(copy, capped = False, short_mib = 5000)++ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)+ request = LoadRequest(model_path = "org/C-GGUF", alongside = True)+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(inf.load_model_gated(request, None, "s"))+ _is_refusal(excinfo.value)+ assert isinstance(excinfo.value.detail, str) and "is set to Always" in excinfo.value.detail+ assert model_slots.slots == [extra] and extra.llama.is_active and primary.is_active+++def test_a_capped_fit_under_always_retries_beside_the_others(backends, monkeypatch):+ _, extra = backends+ _mode(monkeypatch, "always")+ _no_slot_eviction(monkeypatch)+ loaded = LoadResponse.model_construct(status = "loaded", model = "org/C-GGUF", display_name = "C")+ _gated_load_fakes(monkeypatch, short_fits = ["capped"], response = loaded)+ request = LoadRequest(model_path = "org/C-GGUF", alongside = True)+ response = asyncio.run(inf.load_model_gated(request, None, "s"))+ assert response.evicted == [] and response.evicted_slots == []+ assert model_slots.slots[0] is extra and extra.llama.is_active+ assert model_slots.slots[-1].request.force_alongside is True+++# 2. Another quant of the serving repo is not a replacement.+++def test_always_allows_another_quant_of_the_serving_repo_only(backends, monkeypatch):+ _mode(monkeypatch, "always")+ monkeypatch.setattr(inf, "_llama_cpp_backend", FakeLlama("org/X-GGUF", "Q4_K_M"))+ same = LoadRequest(model_path = "org/X-GGUF", gguf_variant = "Q8_0")+ asyncio.run(inf._guard_primary_replacement(same, ("org/X-GGUF:Q8_0", "org/X-GGUF")))+ other = LoadRequest(model_path = "org/Y-GGUF", gguf_variant = "Q8_0")+ with pytest.raises(MultiModelAlwaysRefusal) as excinfo:+ asyncio.run(inf._guard_primary_replacement(other, ("org/Y-GGUF:Q8_0", "org/Y-GGUF")))+ assert excinfo.value.kind == "chat" and "org/X-GGUF" in str(excinfo.value)+ assert "is set to Always" in str(excinfo.value)+ _mode(monkeypatch, "fit")+ asyncio.run(inf._guard_primary_replacement(other, ("org/Y-GGUF",)))+++def test_always_keys_a_native_lease_reload_on_the_granted_path(backends, monkeypatch):+ import inspect++ _mode(monkeypatch, "always")+ monkeypatch.setattr(inf, "_llama_cpp_backend", FakeLlama("/dir1/dropped.gguf"))+ request = LoadRequest(model_path = "dropped.gguf")+ # The display label alone names no loaded model, so a settings change of the same file was refused.+ with pytest.raises(MultiModelAlwaysRefusal):+ asyncio.run(inf._guard_primary_replacement(request, ("dropped.gguf",)))+ asyncio.run(inf._guard_primary_replacement(request, ("/dir1/dropped.gguf",)))+ with pytest.raises(MultiModelAlwaysRefusal):+ asyncio.run(inf._guard_primary_replacement(request, ("/dir2/dropped.gguf",)))+ source = inspect.getsource(inf._load_model_impl)+ assert "(model_identifier,)\n if native_grant_backed" in source+++# 3. A CPU TTS load that would replace a chat model of another repo.+++def test_a_cpu_tts_replacing_a_chat_model_is_refused_before_teardown(backends, monkeypatch):+ primary, extra = backends+ _mode(monkeypatch, "always")+ _no_slot_eviction(monkeypatch)+ monkeypatch.setattr(inf, "release_chat_gpu_claim", lambda: None)+ unloaded = []+ monkeypatch.setattr(primary, "unload_model", lambda: unloaded.append("primary"))+ gates = []+ monkeypatch.setattr(inf, "_raise_or_cancel_active_generations", lambda **k: gates.append(k))+ request = LoadRequest(model_path = "org/Higgs-TTS", audio_device = "cpu")+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(inf.load_model_gated(request, None, "s"))+ _is_refusal(excinfo.value)+ assert "org/A-GGUF" in excinfo.value.detail+ assert unloaded == [] and gates == [] and primary.is_active and model_slots.slots == [extra]+++def test_a_cpu_tts_alongside_under_always_takes_a_kept_slot(backends, monkeypatch):+ primary, extra = backends+ _mode(monkeypatch, "always")+ _no_slot_eviction(monkeypatch)+ loaded = LoadResponse.model_construct(status = "loaded", model = "org/Higgs-TTS", display_name = "T")+ _gated_load_fakes(monkeypatch, short_fits = [], response = loaded)+ request = LoadRequest(model_path = "org/Higgs-TTS", audio_device = "cpu", alongside = True)+ response = asyncio.run(inf.load_model_gated(request, None, "s"))+ assert response.evicted == [] and response.evicted_slots == []+ assert (+ model_slots.slots[0] is extra+ and model_slots.slots[-1].request.model_path == "org/Higgs-TTS"+ )+ assert primary.model_identifier == "org/A-GGUF" and primary.is_active+++# 4. audio.cpp reports out of memory as a structured detail.+++def test_a_structured_out_of_memory_still_makes_room_under_fit(backends, monkeypatch):+ primary, extra = backends+ extra.request = LoadRequest(model_path = "org/B-GGUF", gguf_variant = "Q8_0")+ _mode(monkeypatch, "fit")+ monkeypatch.setattr(inf, "release_chat_gpu_claim", lambda: None)+ oom = {"code": "out_of_memory", "message": "audio.cpp ran out of GPU memory"}+ failures = [HTTPException(503, detail = oom)]+ seen = []++ async def load(request, *args, **kwargs):+ seen.append(request.alongside)+ if failures:+ raise failures.pop()+ llama = inf.get_llama_cpp_backend()+ llama.model_identifier, llama.is_loaded, llama.is_active = request.model_path, True, True+ return LoadResponse.model_construct(status = "loaded", model = request.model_path)++ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)+ request = LoadRequest(model_path = "org/Drama-TTS", alongside = True)+ response = asyncio.run(inf.load_model_gated(request, None, "s"))+ assert seen == [True, True] and not extra.llama.is_active+ assert response.evicted == ["org/B-GGUF:Q8_0"]+ assert response.evicted_slots == [{"kind": "chat", "model": "org/B-GGUF"}]+ assert [s.request.model_path for s in model_slots.slots] == ["org/Drama-TTS"]++[email protected]("status", [500, 503, 507])+def test_a_structured_out_of_memory_counts_at_any_status(status):+ assert inf._ran_out_of_memory(+ HTTPException(status, detail = {"code": "out_of_memory", "message": "m"})+ )+ assert not inf._ran_out_of_memory(HTTPException(status, detail = {"code": "bad_request"}))+ assert inf._ran_out_of_memory(HTTPException(status, detail = "CUDA out of memory")) is (+ status == 500+ )+++# 5. The image and video load routes.++_CHAT_SLOTS = [+ {"kind": "chat", "model": "org/A-GGUF", "account": None},+ {"kind": "chat", "model": "org/B-GGUF", "account": None},+]+_IMAGE = {"model_path": "unsloth/Z-Image-Turbo-GGUF", "gguf_filename": "q.gguf"}+_VIDEO = {"model_path": "unsloth/LTX-2.3-GGUF", "gguf_filename": "ltx-2.3-distilled-Q4_K_M.gguf"}+++def _image_on_gpu(monkeypatch):+ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+++def _expect_chat_evicted(body, evicted):+ assert body["evicted_slots"] == [+ {"kind": "chat", "model": "org/A-GGUF"},+ {"kind": "chat", "model": "org/B-GGUF"},+ ]+ assert body["evicted"] == ["org/A-GGUF", "org/B-GGUF"] and evicted == [gpu_arbiter.CHAT]+++def test_the_image_load_under_always_refuses_with_the_header(image_client, monkeypatch):+ _image_on_gpu(monkeypatch)+ _mode(monkeypatch, "always")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)+ evicted = _reporting(monkeypatch, gpu_arbiter.CHAT, _CHAT_SLOTS)+ resp = _post_load(image_client, **_IMAGE)+ assert resp.status_code == 409 and resp.headers["x-unsloth-refusal"] == REFUSAL+ assert "org/A-GGUF" in resp.json()["detail"] and "is set to Always" in resp.json()["detail"]+ assert evicted == [] and gpu_arbiter.holds(gpu_arbiter.CHAT)+++def test_the_image_load_under_off_reports_every_chat_model_it_unloaded(image_client, monkeypatch):+ _image_on_gpu(monkeypatch)+ _mode(monkeypatch, "off")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)+ evicted = _reporting(monkeypatch, gpu_arbiter.CHAT, _CHAT_SLOTS)+ resp = _post_load(image_client, **_IMAGE)+ assert resp.status_code == 200+ _expect_chat_evicted(resp.json(), evicted)+ status = image_client.get("/api/inference/images/status").json()+ assert status["evicted"] == [] and status["evicted_slots"] == []+++def test_the_video_load_under_always_refuses_with_the_header(video_client, monkeypatch):+ _shared_setup_3(monkeypatch)+ _mode(monkeypatch, "always")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)+ evicted = _reporting(monkeypatch, gpu_arbiter.CHAT, _CHAT_SLOTS)+ resp = video_client.post("/api/inference/video/load", json = _VIDEO)+ assert resp.status_code == 409 and resp.headers["x-unsloth-refusal"] == REFUSAL+ assert "is set to Always" in resp.json()["detail"]+ assert evicted == [] and gpu_arbiter.holds(gpu_arbiter.CHAT)+++def test_the_video_load_under_off_reports_every_chat_model_it_unloaded(video_client, monkeypatch):+ _shared_setup_3(monkeypatch)+ _mode(monkeypatch, "off")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)+ evicted = _reporting(monkeypatch, gpu_arbiter.CHAT, _CHAT_SLOTS)+ resp = video_client.post("/api/inference/video/load", json = _VIDEO)+ assert resp.status_code == 200+ _expect_chat_evicted(resp.json(), evicted)+ status = video_client.get("/api/inference/video/status").json()+ assert status["evicted"] == [] and status["evicted_slots"] == []+++# 6. A chat load that frees an image model names it.+++def test_a_chat_load_that_evicts_an_image_model_lists_it(backends, monkeypatch):+ _mode(monkeypatch, "off")+ monkeypatch.setattr(model_slots, "slots", [])+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.DIFFUSION)+ evicted = _reporting(+ monkeypatch,+ gpu_arbiter.DIFFUSION,+ [{"kind": "image", "model": "org/Flux", "account": None}],+ )+ monkeypatch.setattr(inf, "release_chat_gpu_claim", lambda: None)++ async def load(request, *args, **kwargs):+ # What _load_model_impl does once the load is known viable.+ await asyncio.to_thread(gpu_arbiter.acquire_for_request, gpu_arbiter.CHAT)+ return LoadResponse.model_construct(status = "loaded", model = request.model_path)++ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)+ response = asyncio.run(inf.load_model_gated(LoadRequest(model_path = "org/C-GGUF"), None, "s"))+ assert response.evicted_slots == [{"kind": "image", "model": "org/Flux"}]+ assert response.evicted == ["org/Flux"] and evicted == [gpu_arbiter.DIFFUSION]+ assert gpu_arbiter.residents() == {gpu_arbiter.CHAT: None}+++def test_idle_kept_models_unloaded_by_a_load_under_off_are_listed_in_both_fields(+ backends, monkeypatch+):+ _mode(monkeypatch, "off")++ async def load(request, *args, **kwargs):+ return LoadResponse.model_construct(status = "loaded", model = request.model_path)++ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)+ response = asyncio.run(inf.load_model_gated(LoadRequest(model_path = "org/C-GGUF"), None, "s"))+ assert model_slots.slots == []+ assert response.evicted_slots == [{"kind": "chat", "model": "org/B-GGUF"}]+ assert response.evicted == ["org/B-GGUF"]+++def test_kept_models_a_vllm_load_retires_are_listed_in_both_fields(backends, monkeypatch):+ _mode(monkeypatch, "fit")+ monkeypatch.setattr(inf, "_gate_kept_models", lambda *args, **kwargs: None)++ async def load(request, *args, **kwargs):+ # What _load_model_impl does at the point of no return for a vLLM or SGLang load.+ await inf._retire_kept_models(request)+ return LoadResponse.model_construct(status = "loaded", model = request.model_path)++ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)+ request = LoadRequest(model_path = "org/C", engine = "vllm")+ response = asyncio.run(inf.load_model_gated(request, None, "s"))+ assert model_slots.slots == []+ assert response.evicted_slots == [{"kind": "chat", "model": "org/B-GGUF"}]+ assert response.evicted == ["org/B-GGUF"]+++def test_an_ordinary_switch_is_listed_in_evicted_slots_but_not_in_the_toast_list(+ backends, monkeypatch+):+ _mode(monkeypatch, "fit")+ monkeypatch.setattr(model_slots, "slots", [])+ monkeypatch.setattr(+ inf, "_primary_chat_reports", lambda: [{"kind": "chat", "model": "org/A", "account": None}]+ )+ monkeypatch.setattr(inf, "_loaded_satisfies", lambda ref: ref == "org/A")++ async def load(request, *args, **kwargs):+ # Twice, as a retried attempt does; the switch is listed once.+ for _ in range(2):+ await inf._guard_primary_replacement(request, (request.model_path,))+ return LoadResponse.model_construct(status = "loaded", model = request.model_path)++ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)+ response = asyncio.run(inf.load_model_gated(LoadRequest(model_path = "org/C"), None, "s"))+ assert response.evicted_slots == [{"kind": "chat", "model": "org/A"}]+ assert not response.evicted+ same = asyncio.run(inf.load_model_gated(LoadRequest(model_path = "org/A"), None, "s"))+ assert same.evicted_slots == []+++def test_a_vllm_load_under_always_refuses_while_a_kept_slot_is_stuck(backends, monkeypatch):+ _mode(monkeypatch, "always")+ stuck = object()+ monkeypatch.setattr(model_slots, "slots", [])+ monkeypatch.setattr(model_slots, "stuck", [stuck])+ monkeypatch.setattr(+ inf,+ "_kept_slot_reports",+ lambda slot: [{"kind": "chat", "model": "org/Stuck", "account": None}],+ )+ with pytest.raises(MultiModelAlwaysRefusal) as excinfo:+ asyncio.run(+ inf._guard_primary_replacement(LoadRequest(model_path = "org/C", engine = "vllm"), ())+ )+ assert excinfo.value.model == "org/Stuck"+++def test_an_engine_switch_under_always_rechecks_before_it_unloads(monkeypatch):+ import core.inference.diffusion_engine_router as router++ unloaded = []+ old = types.SimpleNamespace(unload = lambda: unloaded.append("old"))+ monkeypatch.setattr(router, "_active_engine_name", router.ENGINE_DIFFUSERS)+ monkeypatch.setattr(router, "get_active_diffusion_engine", lambda: old)++ def landed_meanwhile():+ raise gpu_arbiter.refusal_for([{"kind": "image", "model": "org/Flux"}], "image")++ with pytest.raises(MultiModelAlwaysRefusal):+ inf._activate_checked(+ landed_meanwhile, lambda: router._activate(router.ENGINE_SD_CPP, None)+ )+ assert unloaded == [] and router._active_engine_name == router.ENGINE_DIFFUSERS+ assert router.before_engine_switch.get() is None+++def _loaded_media(monkeypatch, owner, kind, repo):+ monkeypatch.setattr(+ gpu_arbiter,+ "_media_status",+ lambda o: {"loaded": True, "repo_id": repo} if o == owner else None,+ )+ return _reporting(monkeypatch, owner, [{"kind": kind, "model": repo, "account": None}])+++def test_the_image_load_under_always_refuses_to_replace_another_image_model(+ image_client, monkeypatch+):+ _image_on_gpu(monkeypatch)+ _mode(monkeypatch, "always")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.DIFFUSION)+ evicted = _loaded_media(monkeypatch, gpu_arbiter.DIFFUSION, "image", "org/Flux")+ resp = _post_load(image_client, **_IMAGE)+ assert resp.status_code == 409 and resp.headers["x-unsloth-refusal"] == REFUSAL+ assert "the image model org/Flux" in resp.json()["detail"] and evicted == []+++def test_the_video_load_under_always_refuses_to_replace_another_video_model(+ video_client, monkeypatch+):+ _shared_setup_3(monkeypatch)+ _mode(monkeypatch, "always")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)+ evicted = _loaded_media(monkeypatch, gpu_arbiter.VIDEO, "video", "org/Wan")+ resp = video_client.post("/api/inference/video/load", json = _VIDEO)+ assert resp.status_code == 409 and resp.headers["x-unsloth-refusal"] == REFUSAL+ assert "the video model org/Wan" in resp.json()["detail"] and evicted == []+++def test_an_image_load_under_fit_reports_the_image_model_it_replaces(image_client, monkeypatch):+ _image_on_gpu(monkeypatch)+ _mode(monkeypatch, "fit")+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.DIFFUSION)+ _loaded_media(monkeypatch, gpu_arbiter.DIFFUSION, "image", "org/Flux")+ resp = _post_load(image_client, **_IMAGE)+ assert resp.status_code == 200+ assert resp.json()["evicted_slots"] == [{"kind": "image", "model": "org/Flux"}]+ assert resp.json()["evicted"] == ["org/Flux"]++[email protected]("policy", ["off", "always"])+def test_an_off_torch_image_load_reports_or_refuses_the_native_video_model(monkeypatch, policy):+ import core.inference.video as video_mod++ unloaded = []+ video = types.SimpleNamespace(+ _loading = None, status = lambda: {"engine": "sd_cpp"}, unload = lambda: unloaded.append(1)+ )+ monkeypatch.setattr(video_mod, "get_video_backend", lambda: video)+ _reporting(+ monkeypatch, gpu_arbiter.VIDEO, [{"kind": "video", "model": "org/H3", "account": None}]+ )+ evicted = []+ if policy == "always":+ with pytest.raises(MultiModelAlwaysRefusal):+ inf._unload_native_video_sharing_the_sd_cpp_tree(policy, evicted)+ assert unloaded == [] and evicted == []+ else:+ inf._unload_native_video_sharing_the_sd_cpp_tree(policy, evicted)+ assert unloaded == [1] and evicted == [{"kind": "video", "model": "org/H3"}]+++# 7. Auto-switch and the public preview.+++def test_the_openai_auto_switch_under_always_answers_an_openai_409(monkeypatch):+ backend, _ = _wired(+ monkeypatch, _FakeBackend("unsloth/A-GGUF"), ("unsloth/B-GGUF", None, "unsloth/B-GGUF")+ )+ _mode(monkeypatch, "always")+ calls = []++ async def impl(+ request,+ fastapi_request,+ current_subject = None,+ **kwargs,+ ):+ # The real impl's first check on a replacing load, before any teardown.+ calls.append(request.model_path)+ await inf._guard_primary_replacement(request, (request.model_path,))+ raise AssertionError("the switch went past the refusal")++ monkeypatch.setattr(inf, "_load_model_impl", impl)+ request = types.SimpleNamespace(+ state = types.SimpleNamespace(),+ url = types.SimpleNamespace(path = "/v1/chat/completions"),+ method = "POST",+ headers = {},+ )+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(inf._maybe_auto_switch_model("unsloth/B-GGUF", request, "tester"))+ _is_refusal(excinfo.value)+ error = excinfo.value.detail["error"]+ assert error["code"] == "multi_model_always" and "unsloth/A-GGUF" in error["message"]+ assert calls == ["unsloth/B-GGUF"]+ assert backend.model_identifier == "unsloth/A-GGUF" and backend.is_loaded+++def test_the_media_auto_switch_under_always_answers_an_openai_409(+ flux, enabled, backend, monkeypatch+):+ backend.repo_id = "Qwen/Qwen-Image"+ refusal = gpu_arbiter.refusal_for(_CHAT_SLOTS)++ async def start(+ owner,+ pick,+ current_subject,+ hf_token = None,+ ):+ raise refusal.as_http_exception()++ monkeypatch.setattr(mas, "_start_load", start)+ with pytest.raises(HTTPException) as excinfo:+ _switch("black-forest-labs/FLUX.1-dev")+ _is_refusal(excinfo.value)+ error = excinfo.value.detail["error"]+ assert error["code"] == "multi_model_always" and error["message"] == str(refusal)+ assert backend.repo_id == "Qwen/Qwen-Image"+++def test_a_preview_refused_under_always_gets_the_preview_503(fake_slot, monkeypatch):+ async def refused(*args, **kwargs):+ raise gpu_arbiter.refusal_for(_CHAT_SLOTS)++ monkeypatch.setattr(inf, "_load_model_impl", refused)+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(+ inf.load_model_for_preview(+ LoadRequest(model_path = "/outputs/run/ckpt-a"),+ types.SimpleNamespace(app = None, scope = {"path": "/p/a/v1/chat/completions"}),+ "admin",+ )+ )+ assert excinfo.value.status_code == 503 and excinfo.value.headers.get("Retry-After")+ assert excinfo.value.detail.startswith("Unsloth is using the GPU")+ assert inf._get_preview_resident() is None+++# 8. A refusal found after the padded reply committed keeps its header in the body.+++def test_a_padded_refusal_keeps_its_header(route):+ async def slow_refusal():+ await asyncio.sleep(0.2)+ raise gpu_arbiter.refusal_for(_CHAT_SLOTS).as_http_exception()++ async def run():+ return await _collect(await route._tunnel_safe_json(slow_refusal(), label = "t"))++ deferred = json.loads(b"".join(asyncio.run(run())))["_deferred_error"]+ assert deferred["status_code"] == 409 and "is set to Always" in deferred["detail"]+ assert deferred["headers"] == {"x-unsloth-refusal": REFUSAL}+++def test_a_deferred_error_keeps_only_the_headers_a_client_reads():+ headers = {"X-Unsloth-Refusal": REFUSAL, "Retry-After": "5", "X-Other": "1"}+ body = json.loads(inf._deferred_error_body(409, "no", headers))["_deferred_error"]+ assert body["headers"] == {"x-unsloth-refusal": REFUSAL, "retry-after": "5"}+ plain = json.loads(inf._deferred_error_body(500, "no", {"X-Other": "1"}))["_deferred_error"]+ assert plain == {"status_code": 500, "detail": "no"}+++# 9. Status reports the mode.++[email protected]("mode", ["off", "fit", "always"])+def test_status_reports_the_multi_model_mode(backends, monkeypatch, mode):+ _mode(monkeypatch, mode)++ async def slot_status(subject):+ return InferenceStatusResponse(active_model = "org/A-GGUF")++ monkeypatch.setattr(inf, "_slot_status", slot_status)+ assert asyncio.run(inf.get_status("s")).multi_model_mode == mode+++def test_an_unreadable_primary_under_always_refuses_instead_of_replacing(backends, monkeypatch):+ from core.inference.gpu_arbiter import MultiModelAlwaysRefusal++ _mode(monkeypatch, "always")+ monkeypatch.setattr(model_slots, "slots", [])++ def broken():+ raise RuntimeError("status unreadable")++ monkeypatch.setattr(inf, "_primary_chat_reports", broken)+ with pytest.raises(MultiModelAlwaysRefusal):+ asyncio.run(inf._guard_primary_replacement(LoadRequest(model_path = "org/C"), ("org/C",)))+++ "model_path, managed, status",+ [("lemonade:", False, 400), ("lemonade:a/b", False, 400), ("lemonade:qwen", True, 403)],+)+def test_an_npu_load_that_can_only_fail_never_asks_to_unload(+ monkeypatch, model_path, managed, status+):+ async def refuse(*args, **kwargs):+ raise AssertionError("the Always guard ran before the NPU checks")++ monkeypatch.setattr(inf, "_guard_primary_replacement", refuse)+ monkeypatch.setattr(inf.account_access, "managed_account", lambda: managed)+ with pytest.raises(HTTPException) as caught:+ asyncio.run(inf._load_model_impl(LoadRequest(model_path = model_path), None, "owner"))+ assert caught.value.status_code == status+++def test_a_respawning_primary_under_always_refuses_another_model(monkeypatch):+ _mode(monkeypatch, "always")+ monkeypatch.setattr(model_slots, "slots", [])+ monkeypatch.setattr(inf, "_primary_chat_reports", lambda: [])+ respawning = types.SimpleNamespace(is_active = True, is_loaded = False)+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: respawning)+ with pytest.raises(MultiModelAlwaysRefusal):+ asyncio.run(inf._guard_primary_replacement(LoadRequest(model_path = "org/C"), ("org/C",)))+ respawning.is_active = False+ asyncio.run(inf._guard_primary_replacement(LoadRequest(model_path = "org/C"), ("org/C",)))diff --git a/studio/backend/tests/test_multi_model_serving.py b/studio/backend/tests/test_multi_model_serving.pyindex 425a3b8abb9..d64fba0ac20 100644--- a/studio/backend/tests/test_multi_model_serving.py+++ b/studio/backend/tests/test_multi_model_serving.py@@ -186,9 +186,10 @@ def test_the_multi_model_setting_defaults_off(monkeypatch):import storage.studio_db as studio_dbmonkeypatch.setattr(- studio_db, "get_app_setting", lambda key, fallback: stored.get(key, fallback)+ studio_db, "get_app_settings", lambda keys: {k: stored[k] for k in keys if k in stored})monkeypatch.setattr(studio_db, "upsert_app_settings", stored.update)+ multi_model_settings.invalidate_multi_model_cache()assert multi_model_settings.get_multi_model_enabled() is Falseassert multi_model_settings.set_multi_model_enabled(True) is Trueassert multi_model_settings.get_multi_model_enabled() is True@@ -201,7 +202,7 @@ def test_turning_the_setting_off_saves_first_and_unloads_after_the_reply(backendimport routes.settings as settings_routes_, extra = backends- monkeypatch.setattr(settings_routes, "set_multi_model_enabled", lambda value: value)+ monkeypatch.setattr(settings_routes, "set_multi_model_mode", lambda mode: True)def fail():raise RuntimeError("llama-server would not exit")@@ -972,7 +973,7 @@ def test_a_model_that_does_not_fit_says_so_without_api_flags():from core.inference.llama_cpp import _gpu_short_messagespill = _gpu_short_message(13.2, 8.4, 32768, 32768, False)- assert "13.2 GB" in spill and "8.4 GB" in spill and "Keep other models loaded" in spill+ assert "13.2 GB" in spill and "8.4 GB" in spill and "Keep multiple models loaded" in spillcapped = _gpu_short_message(13.2, 8.4, 32768, 8192, True)assert "8192 context" in cappedassert "force_alongside" not in spill + capped@@ -1228,7 +1229,7 @@ def test_turning_the_setting_off_drops_the_claim_its_kept_models_held(backends,_hold_chat_claim(monkeypatch)# The primary was ejected earlier and kept CHAT for the model still loaded beside it.primary.unload_model()- monkeypatch.setattr(settings_routes, "set_multi_model_enabled", lambda value: value)+ monkeypatch.setattr(settings_routes, "set_multi_model_mode", lambda mode: True)tasks = BackgroundTasks()settings_routes.update_multi_model(settings_routes.MultiModelPayload(enabled = False), tasks, "s")assert gpu_arbiter.current_owner() == gpu_arbiter.CHATdiff --git a/studio/backend/tests/test_multi_model_settings.py b/studio/backend/tests/test_multi_model_settings.pynew file mode 100644index 00000000000..1d7e71d280f--- /dev/null+++ b/studio/backend/tests/test_multi_model_settings.py@@ -0,0 +1,174 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Keep multiple models loaded: the off / fit / always mode, its migration and its route."""++from __future__ import annotations++import pytest++import utils.multi_model_settings as mms+from utils.account_context import OWNER, AccountContext, ROLE_USER, run_as+++def store(monkeypatch):+ """One fake studio.db per account, so a read from the wrong account shows up."""+ import storage.studio_db as studio_db+ from utils.account_context import current_account_id++ dbs: dict[str, dict] = {}+ writes: list[dict] = []++ def get_app_settings(keys):+ db = dbs.get(current_account_id(), {})+ return {key: db[key] for key in keys if key in db}++ def upsert_app_settings(settings, **_kwargs):+ writes.append(dict(settings))+ dbs.setdefault(current_account_id(), {}).update(settings)+ return dict(settings)++ monkeypatch.setattr(studio_db, "get_app_settings", get_app_settings)+ monkeypatch.setattr(studio_db, "upsert_app_settings", upsert_app_settings)+ mms.invalidate_multi_model_cache()+ yield dbs, writes+ mms.invalidate_multi_model_cache()+++ ("stored", "mode"),+ [+ ({}, "off"),+ ({"keep_multiple_models_loaded": False}, "off"),+ ({"keep_multiple_models_loaded": False, "multi_model_mode": "fit"}, "off"),+ ({"keep_multiple_models_loaded": False, "multi_model_mode": "always"}, "off"),+ ({"multi_model_mode": "always"}, "off"),+ ({"keep_multiple_models_loaded": True}, "fit"),+ ({"keep_multiple_models_loaded": True, "multi_model_mode": "fit"}, "fit"),+ ({"keep_multiple_models_loaded": True, "multi_model_mode": "off"}, "fit"),+ ({"keep_multiple_models_loaded": True, "multi_model_mode": "bogus"}, "fit"),+ ({"keep_multiple_models_loaded": True, "multi_model_mode": "always"}, "always"),+ ({"keep_multiple_models_loaded": "yes", "multi_model_mode": "always"}, "off"),+ ],+)+def test_the_bool_decides_on_or_off_and_the_mode_picks_fit_or_always(store, stored, mode):+ dbs, _ = store+ dbs[OWNER.account_id] = dict(stored)+ assert mms.get_multi_model_mode() == mode+ assert mms.get_multi_model_enabled() is (mode != "off")+++def test_both_keys_are_written_in_one_call(store):+ dbs, writes = store+ assert mms.set_multi_model_mode("always") is True+ assert writes == [{"multi_model_mode": "always", "keep_multiple_models_loaded": True}]+ assert mms.set_multi_model_mode("always") is False+ assert mms.set_multi_model_mode("off") is True+ assert writes[-1] == {"multi_model_mode": "off", "keep_multiple_models_loaded": False}+ assert dbs[OWNER.account_id]["keep_multiple_models_loaded"] is False++[email protected]("bad", ["on", "", None, True, "Always"])+def test_a_bad_mode_is_refused_with_the_setting_name(store, bad):+ _, writes = store+ with pytest.raises(+ ValueError, match = "^Keep multiple models loaded must be off, fit or always.$"+ ):+ mms.set_multi_model_mode(bad)+ assert writes == []+++def test_a_write_invalidates_the_cached_mode(store):+ dbs, _ = store+ assert mms.get_multi_model_mode() == "off"+ # A write made behind the module's back stays hidden for the TTL...+ dbs[OWNER.account_id] = {"keep_multiple_models_loaded": True}+ assert mms.get_multi_model_mode() == "off"+ # ...but one made through it shows at once.+ mms.set_multi_model_mode("always")+ assert mms.get_multi_model_mode() == "always"+++def test_a_managed_account_reads_and_writes_the_owner_database(store):+ dbs, _ = store+ alice = AccountContext("alice", "alice", ROLE_USER)+ dbs[OWNER.account_id] = {"keep_multiple_models_loaded": True, "multi_model_mode": "always"}+ dbs["alice"] = {"keep_multiple_models_loaded": False}+ assert run_as(alice, mms.get_multi_model_mode) == "always"+ run_as(alice, mms.set_multi_model_mode, "fit")+ assert dbs[OWNER.account_id]["multi_model_mode"] == "fit"+ assert dbs["alice"] == {"keep_multiple_models_loaded": False}+++def test_an_unreadable_database_reads_as_off(monkeypatch):+ import storage.studio_db as studio_db++ def broken(_keys):+ raise RuntimeError("database is locked")++ monkeypatch.setattr(studio_db, "get_app_settings", broken)+ mms.invalidate_multi_model_cache()+ assert mms.get_multi_model_mode() == "off"+++def _put(payload):+ from fastapi import BackgroundTasks+ import routes.settings as settings_routes++ tasks = BackgroundTasks()+ response = settings_routes.update_multi_model(+ settings_routes.MultiModelPayload(**payload), tasks, "s"+ )+ return response, tasks+++def test_the_route_takes_a_mode_and_reports_both_shapes(store):+ response, tasks = _put({"mode": "always"})+ assert (response.mode, response.enabled, response.default_mode) == ("always", True, "off")+ assert response.default_enabled is False and not tasks.tasks+ import routes.settings as settings_routes++ current = settings_routes.get_multi_model("s")+ assert (current.mode, current.enabled) == ("always", True)+++def test_a_legacy_enabled_true_keeps_always(store):+ _put({"mode": "always"})+ response, _ = _put({"enabled": True})+ assert response.mode == "always"+++def test_a_legacy_enabled_true_turns_off_into_fit(store):+ response, _ = _put({"enabled": True})+ assert (response.mode, response.enabled) == ("fit", True)+++def test_turning_it_off_queues_the_idle_unload(store):+ _put({"mode": "fit"})+ response, tasks = _put({"enabled": False})+ assert response.mode == "off" and len(tasks.tasks) == 1+ response, tasks = _put({"mode": "off"})+ assert len(tasks.tasks) == 1+++ "payload", [{}, {"mode": "fit", "enabled": True}, {"mode": "sometimes"}, {"enabled": "yes"}]+)+def test_the_payload_needs_exactly_one_valid_field(payload):+ import routes.settings as settings_routes+ from pydantic import ValidationError+ with pytest.raises(ValidationError):+ settings_routes.MultiModelPayload(**payload)+++def test_an_unreadable_setting_keeps_the_last_mode_read(monkeypatch):+ def broken():+ raise RuntimeError("database is locked")++ monkeypatch.setattr(mms, "_read_mode", broken)+ mms.invalidate_multi_model_cache()+ assert mms.get_multi_model_mode() == "off"+ monkeypatch.setattr(mms, "_cache", (-1e9, "always"))+ assert mms.get_multi_model_mode() == "always"+ mms.invalidate_multi_model_cache()diff --git a/studio/backend/tests/test_sd_cpp_args.py b/studio/backend/tests/test_sd_cpp_args.pyindex 5f567314cfc..990173ac119 100644--- a/studio/backend/tests/test_sd_cpp_args.py+++ b/studio/backend/tests/test_sd_cpp_args.py@@ -314,9 +314,15 @@ def test_video_load_route_skips_the_video_claim_for_a_forced_cpu_h3_load():branch = source.index("if forced_cpu:", guard)# Neither acquires nor releases VIDEO: an old MPS model keeps its claim until the worker tears it down.assert source[branch : source.index('elif device != "cpu":', branch)].strip() == (- "if forced_cpu:\n status_dict = await asyncio.to_thread(_begin_load)"+ "if forced_cpu:\n status_dict = await asyncio.to_thread(begin)")- assert branch < source.index("return acquire_for_request(VIDEO, _begin_load)")+ # ``begin`` only re-checks the Always media gate under the arbiter lock; it takes no GPU claim.+ begin_def = source.rindex("def begin():", 0, branch)+ assert source[begin_def : source.index("\n\n", begin_def)].strip() == (+ "def begin():\n"+ " return begin_media_load(VIDEO, multi_model_mode, media_names, _begin_load)"+ )+ assert branch < source.index("return acquire_for_request(\n VIDEO,")def test_partial_backend_specs_leave_the_diffusion_model_on_metal(monkeypatch):diff --git a/studio/backend/utils/multi_model_settings.py b/studio/backend/utils/multi_model_settings.pyindex d536f04fa51..1c4c4d7d924 100644--- a/studio/backend/utils/multi_model_settings.py+++ b/studio/backend/utils/multi_model_settings.py@@ -1,30 +1,113 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Persisted switch for keeping other models loaded when another one loads."""+"""Persisted "Keep multiple models loaded" mode: off, fit (When they fit) or always.++The setting belongs to the installation, so it is always read and written in the owner's+database. Each account has its own studio.db, and a managed account reading its own would+see the default and unload the owner's kept models.++Older builds stored only the ``keep_multiple_models_loaded`` bool. The bool still decides+on or off, and ``multi_model_mode`` only tells When they fit from Always, so an older build+that turns the setting off wins after an upgrade.+"""from __future__ import annotations+import threading+import timefrom typing import Any+from utils.account_context import OWNER, run_as+MULTI_MODEL_SETTING_KEY = "keep_multiple_models_loaded"+MULTI_MODEL_MODE_SETTING_KEY = "multi_model_mode"+MULTI_MODEL_MODE_CHOICES = ("off", "fit", "always")+_VALID_MODES = frozenset(MULTI_MODEL_MODE_CHOICES)+DEFAULT_MULTI_MODEL_MODE = "off"DEFAULT_MULTI_MODEL_ENABLED = False+# Read on every load, including media loads, so memo briefly to spare SQLite.+_CACHE_TTL_S = 2.0+_cache_lock = threading.Lock()+_cache: tuple[float, str] | None = None+# Bumped on every write, so a read that began before a write never caches the old value.+_generation = 0+_MAX_REREADS = 3+++def _mode_from_stored(stored: dict[str, Any]) -> str:+ if stored.get(MULTI_MODEL_SETTING_KEY) is not True:+ return "off"+ return "always" if stored.get(MULTI_MODEL_MODE_SETTING_KEY) == "always" else "fit"+++def _read_mode() -> str:+ from storage.studio_db import get_app_settings+ stored = run_as(+ OWNER,+ get_app_settings,+ [MULTI_MODEL_SETTING_KEY, MULTI_MODEL_MODE_SETTING_KEY],+ )+ return _mode_from_stored(stored)+++def get_multi_model_mode() -> str:+ """``"off"``, ``"fit"`` or ``"always"``, read as the owner."""+ global _cache+ mode = DEFAULT_MULTI_MODEL_MODE+ for _attempt in range(_MAX_REREADS):+ with _cache_lock:+ if _cache is not None and time.monotonic() - _cache[0] < _CACHE_TTL_S:+ return _cache[1]+ generation = _generation+ try:+ mode = _read_mode()+ except Exception:+ # An unreadable DB must not fail a load: keep the last mode read, else the default.+ with _cache_lock:+ return _cache[1] if _cache is not None else DEFAULT_MULTI_MODEL_MODE+ with _cache_lock:+ if _generation == generation:+ _cache = (time.monotonic(), mode)+ return mode+ return mode+def get_multi_model_enabled() -> bool:- try:- from storage.studio_db import get_app_setting- stored = get_app_setting(MULTI_MODEL_SETTING_KEY, None)- except Exception:- stored = None- return stored if isinstance(stored, bool) else DEFAULT_MULTI_MODEL_ENABLED+ return get_multi_model_mode() != "off"-def set_multi_model_enabled(value: Any) -> bool:- if not isinstance(value, bool):- raise ValueError("Keep multiple models loaded must be true or false.")+def invalidate_multi_model_cache() -> None:+ global _cache, _generation+ with _cache_lock:+ _cache = None+ _generation += 1+++def set_multi_model_mode(value: Any) -> bool:+ """Store the mode and return whether it changed."""+ if not isinstance(value, str) or value not in _VALID_MODES:+ raise ValueError("Keep multiple models loaded must be off, fit or always.")from storage.studio_db import upsert_app_settings- upsert_app_settings({MULTI_MODEL_SETTING_KEY: value})+ previous = _read_mode()+ run_as(+ OWNER,+ upsert_app_settings,+ {MULTI_MODEL_MODE_SETTING_KEY: value, MULTI_MODEL_SETTING_KEY: value != "off"},+ )+ invalidate_multi_model_cache()+ return previous != value+++def set_multi_model_enabled(value: Any) -> bool:+ """Legacy bool write: True keeps an existing When they fit or Always, False turns it off."""+ if not isinstance(value, bool):+ raise ValueError("Keep multiple models loaded must be true or false.")+ if not value:+ set_multi_model_mode("off")+ elif _read_mode() == "off":+ set_multi_model_mode("fit")return value