Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: make Keep multiple models loaded unload idle models before spilling a load to the CPU (#15246)

Michael Han6112594f45ec
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index fb891895001..f41f149b832 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -637,9 +637,10 @@ def _gpu_short_message(
class GpuMemoryShortError(RuntimeError):
"""A load that must fit next to the loaded models does not. ``capped``: it would, at a
smaller context than asked for. ``gpu_indices``: the GPUs ``short_mib`` was measured on.
- ``discrete``: none of them shares host RAM, so a server off them or on the CPU frees nothing there."""
+ ``discrete``: none of them shares host RAM, so a server off them or on the CPU frees nothing there.
+ ``host``: short on free VRAM and RAM together."""
- __slots__ = ("capped", "short_mib", "gpu_indices", "discrete")
+ __slots__ = ("capped", "short_mib", "gpu_indices", "discrete", "host")
def __init__(
self,
@@ -648,12 +649,14 @@ class GpuMemoryShortError(RuntimeError):
short_mib: int = 0,
gpu_indices = None,
discrete: bool = False,
+ host: bool = False,
):
super().__init__(message)
self.capped = capped
self.short_mib = short_mib
self.gpu_indices = gpu_indices
self.discrete = discrete
+ self.host = host
def _apple_wired_headroom_bytes() -> Optional[int]:
@@ -33902,6 +33905,13 @@ class LlamaCppBackend:
avail_mib = _preflight_avail_mib,
shared_gpu_ids = _shared_gpu_ids,
)
+ if (
+ _offload_msg
+ and intent.refuse_partial_gpu_fit
+ and gpu_memory_mode != "manual"
+ and self._other_servers_running()
+ ):
+ raise GpuMemoryShortError(_offload_msg, host = True)
# Snapshotted BEFORE the override note is appended below, so a re-price
# that promotes this notice appends that note once rather than twice.
_host_ram_msg = _offload_msg
@@ -37899,6 +37909,10 @@ class LlamaCppBackend:
for backend in serving:
if backend is self or not getattr(backend, "is_active", False):
continue
+ # A dead server keeps _process until respawned, but its VRAM is free.
+ poll = getattr(getattr(backend, "_process", None), "poll", None)
+ if callable(poll) and poll() is not None:
+ continue
for idx, mib in getattr(backend, "_planned_vram_mib", {}).items():
held[idx] = held.get(idx, 0) + mib
# Weights plus generation headroom, the full figure _net_of_held_vram needs (empty under Off).
@@ -37908,6 +37922,18 @@ class LlamaCppBackend:
held[idx] = held.get(idx, 0) + mib
return held
+ def _other_servers_running(self) -> bool:
+ serving = _serving_backends_snapshot()
+ if self not in serving:
+ return False
+ for backend in serving:
+ process = getattr(backend, "_process", None) if backend is not self else None
+ if process is not None and (not hasattr(process, "poll") or process.poll() is None):
+ return True
+ from core.inference.gpu_residency import media_held_mib
+
+ return bool(media_held_mib())
+
def _media_unallocated_vram_mib(self) -> dict[int, int]:
"""MiB per GPU of the resident image/video models' price not yet allocated (empty under Off)."""
if self not in _serving_backends_snapshot():
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index accd9771d81..26df8964dc5 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -12907,13 +12907,21 @@ def _media_on_target_gpus(placement) -> bool:
return bool(held) and (not gpus or bool(set(held) & set(gpus)))
+def _idle_kept_chat_on_target_gpus(placement) -> bool:
+ gpus = None if placement.gpu_ids_are_vulkan_ordinals else _placement_gpu_ids(placement)
+ return bool(model_slots.eviction_victims(None, 0, set(gpus) if gpus else None, discrete = True))
+
+
def _primary_refuses_partial_fit(serving: bool, policy: str, placement) -> bool:
- """Whether a primary GGUF load refuses a partial GPU fit beside an image or video model, to retry once room is
- made. Not under Always while a primary serves: the refusal lands after its teardown, leaving nothing loaded."""
+ """Whether a primary GGUF load refuses a partial fit so room can be made first. Not under Always while a primary
+ serves: the refusal lands after its teardown, leaving nothing loaded."""
return (
_primary_can_retry_fit.get()
and not (serving and policy == "always")
- and _media_on_target_gpus(placement)
+ and (
+ _media_on_target_gpus(placement)
+ or (policy == "fit" and _idle_kept_chat_on_target_gpus(placement))
+ )
)
@@ -12999,16 +13007,17 @@ def _outgoing_chat_credit_gb(
async def _make_room_for_primary(request: LoadRequest, exc, evicted: list) -> LoadRequest:
- """A primary chat load refused a partial GPU fit beside an image or video model: return the request to retry.
+ """A primary chat load refused a partial GPU fit beside other models: return the request to retry.
- When they fit frees the image or video model (cheapest first), else lets llama-server fit what it can. Always
- only accepts a smaller context; otherwise it refuses, since nothing may be unloaded.
+ When they fit frees the cheapest residents, else lets llama-server fit what it can. Always only accepts a
+ smaller context or a host RAM spill, else refuses.
"""
from core.inference import gpu_arbiter, gpu_residency
- if exc.capped:
+ policy = await asyncio.to_thread(gpu_residency.current_policy)
+ if exc.capped or (policy == "always" and getattr(exc, "host", False)):
return request.model_copy(update = {"force_alongside": True})
- if await asyncio.to_thread(gpu_residency.current_policy) == "always":
+ if policy == "always":
rows = (await asyncio.to_thread(gpu_residency._free_mib_by_gpu))[0] or {}
gpus = [g for g in exc.gpu_indices or () if "free_mib" in rows.get(g, {})]
free = sum(rows[g]["free_mib"] for g in gpus)
@@ -19348,7 +19357,9 @@ async def load_model_gated(
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:
+ if (
+ exc.capped or getattr(exc, "host", False)
+ ) and not request.force_alongside:
request = request.model_copy(update = {"force_alongside": True})
continue
if measured and not account_access.managed_account():
@@ -19418,6 +19429,19 @@ async def load_model_gated(
force = request.force_cancel_active,
action = "Loading a model",
)
+ victims = await asyncio.to_thread(
+ model_slots.in_slot,
+ None,
+ lambda: _kept_victims_beside_primary(exc),
+ )
+ 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, ())])
+ evicted += [
+ _model_key(s.request) for s in dropped if s.request is not None
+ ]
# 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)
@@ -19570,6 +19594,21 @@ def _active_model_holds_none_of(exc) -> bool:
)
+def _kept_victims_beside_primary(exc) -> list:
+ """Idle kept slots that cover ``exc``'s shortfall together with the active server; call via ``in_slot(None, ...)``."""
+ if getattr(exc, "host", False) or not exc.short_mib:
+ return []
+ gpus = exc.gpu_indices or None
+ held = sum(
+ mib
+ for idx, mib in (getattr(get_llama_cpp_backend(), "_planned_vram_mib", None) or {}).items()
+ if not gpus or idx in gpus
+ )
+ if not held or held >= exc.short_mib:
+ return []
+ return model_slots.eviction_victims(None, exc.short_mib - held, gpus, exc.discrete)
+
+
def _primary_model_label() -> Optional[str]:
llama = get_llama_cpp_backend()
if getattr(llama, "is_loaded", False):
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index f8d732c3f02..16653b2591a 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1521,7 +1521,7 @@ def update_multi_model(
background_tasks: BackgroundTasks,
current_subject: str = Depends(get_current_subject),
) -> MultiModelResponse:
- """Off, When they fit or Always. Takes effect on the next load."""
+ """Off, When they fit or Always. Takes effect on the next load; Off also unloads the idle kept models."""
try:
mode = payload.mode
if mode is None:
diff --git a/studio/backend/tests/test_multi_model_primary_fit.py b/studio/backend/tests/test_multi_model_primary_fit.py
index 160b23da1aa..a58450345d5 100644
--- a/studio/backend/tests/test_multi_model_primary_fit.py
+++ b/studio/backend/tests/test_multi_model_primary_fit.py
@@ -388,6 +388,39 @@ def test_a_serving_primary_reloaded_under_always_is_not_torn_down_for_a_refusal(
inf._primary_can_retry_fit.reset(token)
+def test_always_loads_a_primary_that_spills_to_host_ram_without_refusing(env):
+ env.policy = "always"
+ env.errors = [GpuMemoryShortError("spills", host = True)]
+ response, _ = _gated()
+ assert response.status == "loaded" and env.requests[-1].force_alongside
+ assert env.free_calls == []
+ _nothing_unloaded(env)
+
+
+ ("policy", "kept_on", "placement", "expected"),
+ [
+ ("fit", {0: 6000}, _placement([0]), True),
+ ("fit", {0: 6000}, _placement(None), True),
+ ("fit", {1: 6000}, _placement([0]), False),
+ ("fit", None, _placement([0]), False),
+ ("always", {0: 6000}, _placement([0]), False),
+ ],
+)
+def test_a_primary_reload_under_fit_refuses_a_partial_fit_beside_an_idle_kept_chat_model(
+ monkeypatch, policy, kept_on, placement, expected
+):
+ monkeypatch.setattr(gpu_residency, "media_held_mib", lambda: {})
+ kept = model_slots.ExtraSlot(FakeLlama("org/B-GGUF"), FakeOrchestrator(), "owner")
+ kept.llama._planned_vram_mib = kept_on or {}
+ monkeypatch.setattr(model_slots, "slots", [kept] if kept_on else [])
+ token = inf._primary_can_retry_fit.set(True)
+ try:
+ assert inf._primary_refuses_partial_fit(True, policy, placement) is expected
+ finally:
+ inf._primary_can_retry_fit.reset(token)
+
+
def test_an_extra_chat_load_frees_an_idle_image_before_replacing_the_primary(env, monkeypatch):
# Chat A + an idle image under When they fit: chat B loaded alongside comes up short. The image goes and B
# loads beside A, instead of A being unloaded (and the image after it, by the replacement primary load).
diff --git a/studio/backend/tests/test_multi_model_serving.py b/studio/backend/tests/test_multi_model_serving.py
index 29bbfa82781..7be9d7eeb38 100644
--- a/studio/backend/tests/test_multi_model_serving.py
+++ b/studio/backend/tests/test_multi_model_serving.py
@@ -480,6 +480,74 @@ def test_a_model_that_fits_nowhere_beside_the_others_replaces_the_active_one(bac
assert primary.model_identifier == "org/C-GGUF" and primary.is_loaded
+def _short_load_fakes(monkeypatch, errors):
+ monkeypatch.setattr(inf, "release_chat_gpu_claim", lambda: None)
+ seen = []
+
+ async def load(request, *args, **kwargs):
+ seen.append(request)
+ if errors and not request.force_alongside:
+ raise errors.pop(0)
+ llama = inf.get_llama_cpp_backend()
+ llama.model_identifier, llama.hf_variant = request.model_path, request.gguf_variant
+ llama.is_loaded = llama.is_active = True
+ return LoadResponse.model_construct(status = "loaded", model = request.model_path)
+
+ monkeypatch.setattr(inf, "_run_tracked_load_model_impl", load)
+ return seen
+
+
+def test_idle_kept_models_go_with_the_active_one_when_only_together_they_make_room(
+ backends, monkeypatch
+):
+ # B and C alone free 12 of the 14 GB D is short; with A they cover it.
+ primary, extra = backends
+ primary._planned_vram_mib = {0: 6000}
+ extra.request, extra.last_used = LoadRequest(model_path = "org/B-GGUF"), 1.0
+ extra.llama._planned_vram_mib = {0: 6000}
+ other = _slot("org/C-GGUF", last_used = 2.0)
+ other.llama._planned_vram_mib = {0: 6000}
+ model_slots.slots.append(other)
+ monkeypatch.setattr(inf, "_unload_primary", lambda: primary.unload_model())
+ _short_load_fakes(monkeypatch, [GpuMemoryShortError("short", short_mib = 14000)])
+ request = LoadRequest(model_path = "org/D-GGUF", alongside = True)
+ response = asyncio.run(inf.load_model_gated(request, None, "s"))
+ assert response.evicted == ["org/B-GGUF", "org/C-GGUF", "org/A-GGUF"]
+ assert model_slots.slots == [] and not extra.llama.is_active and not other.llama.is_active
+ assert primary.model_identifier == "org/D-GGUF"
+
+
+def test_idle_kept_models_stay_when_the_active_one_alone_makes_room(backends, monkeypatch):
+ primary, extra = backends
+ primary._planned_vram_mib = {0: 16000}
+ extra.request = LoadRequest(model_path = "org/B-GGUF")
+ extra.llama._planned_vram_mib = {0: 6000}
+ monkeypatch.setattr(inf, "_unload_primary", lambda: primary.unload_model())
+ _short_load_fakes(monkeypatch, [GpuMemoryShortError("short", short_mib = 14000)])
+ request = LoadRequest(model_path = "org/D-GGUF", alongside = True)
+ assert asyncio.run(inf.load_model_gated(request, None, "s")).evicted == ["org/A-GGUF"]
+ assert model_slots.slots == [extra] and extra.llama.is_active
+
+
+def test_a_host_ram_spill_evicts_an_idle_kept_model_under_when_they_fit(backends, monkeypatch):
+ _, extra = backends
+ extra.request = LoadRequest(model_path = "org/B-GGUF")
+ monkeypatch.setattr(multi_model_settings, "get_multi_model_mode", lambda: "fit")
+ _short_load_fakes(monkeypatch, [GpuMemoryShortError("spills", host = True)])
+ request = LoadRequest(model_path = "org/C-GGUF", alongside = True)
+ assert asyncio.run(inf.load_model_gated(request, None, "s")).evicted == ["org/B-GGUF"]
+ assert [s.llama.model_identifier for s in model_slots.slots] == ["org/C-GGUF"]
+
+
+def test_a_host_ram_spill_loads_beside_the_others_under_always(backends, monkeypatch):
+ _, extra = backends
+ monkeypatch.setattr(multi_model_settings, "get_multi_model_mode", lambda: "always")
+ seen = _short_load_fakes(monkeypatch, [GpuMemoryShortError("spills", host = True)])
+ request = LoadRequest(model_path = "org/C-GGUF", alongside = True)
+ assert not asyncio.run(inf.load_model_gated(request, None, "s")).evicted
+ assert seen[-1].force_alongside and extra.llama.is_active
+
+
def test_a_capped_context_is_taken_only_once_nothing_is_left_to_evict(backends, monkeypatch):
_, extra = backends
extra.request = LoadRequest(model_path = "org/B-GGUF", gguf_variant = "Q8_0")
@@ -522,6 +590,28 @@ def test_a_load_prices_the_vram_the_other_servers_hold():
llama_cpp.unregister_serving_backend(backend)
+def test_a_kept_server_that_died_no_longer_holds_vram(monkeypatch):
+ from core.inference import gpu_residency
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(gpu_residency, "media_held_mib", lambda: {})
+ a, c = (LlamaCppBackend(manages_processes = False) for _ in range(2))
+ for backend in (a, c):
+ llama_cpp.register_serving_backend(backend)
+ try:
+ a._planned_vram_mib = {0: 12000}
+ a._process = SimpleNamespace(poll = lambda: None)
+ assert c._other_planned_vram_mib() == {0: 12000} and c._other_servers_running()
+ a._process = SimpleNamespace(poll = lambda: -9)
+ assert c._other_planned_vram_mib() == {} and not c._other_servers_running()
+ monkeypatch.setattr(gpu_residency, "media_held_mib", lambda: {0: 2048})
+ assert c._other_servers_running()
+ finally:
+ a._process = None
+ for backend in (a, c):
+ llama_cpp.unregister_serving_backend(backend)
+
+
def _hold_chat_claim(monkeypatch):
monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
monkeypatch.setattr(llama_cpp, "chat_load_active", lambda: False)
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 4432dcc89fd..454aacedb8b 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -905,6 +905,17 @@ export async function resyncInferenceStatusAfterServerModelChange(): Promise<voi
notifyModelLifecycle({ runtime: "stt", loading: false, model: null });
}
+/** Off unloads idle kept models after the reply: wait for them to go, or the picker keeps listing them. */
+export async function resyncInferenceStatusAfterKeptModelsUnload(): Promise<void> {
+ for (let attempt = 0; attempt < 15; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ const status = await getInferenceStatus().catch(() => null);
+ if (!status || (status.serving?.length ?? 0) <= 1) break;
+ }
+ await syncInferenceStatusToStore({ includeLoras: false, quiet: true });
+ notifyModelLifecycle({ runtime: "chat", loading: false, model: null });
+}
+
function pickOf(info: {
id: string;
ggufVariant?: string | null;
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 8b4c68b0d85..c880e499021 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -331,6 +331,7 @@ export {
} from "./stores/plus-menu-prefs-store";
export {
useChatModelRuntime,
+ resyncInferenceStatusAfterKeptModelsUnload,
resyncInferenceStatusAfterServerModelChange,
} from "./hooks/use-chat-model-runtime";
export { compareModelDisplayName } from "./lib/external-model-label";
diff --git a/studio/frontend/src/features/settings/components/model-memory-section.tsx b/studio/frontend/src/features/settings/components/model-memory-section.tsx
index 59a4afcde78..d15b17dd0fa 100644
--- a/studio/frontend/src/features/settings/components/model-memory-section.tsx
+++ b/studio/frontend/src/features/settings/components/model-memory-section.tsx
@@ -9,7 +9,10 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
-import { useChatRuntimeStore } from "@/features/chat";
+import {
+ resyncInferenceStatusAfterKeptModelsUnload,
+ useChatRuntimeStore,
+} from "@/features/chat";
import { formatBytes } from "@/features/hub/lib/format";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { useT } from "@/i18n";
@@ -130,10 +133,14 @@ export function ModelMemorySection({ ref }: { ref?: Ref<HTMLElement> }) {
next,
t("settings.resources.modelMemory.saveError"),
);
+ const wasKeeping = keepsModelsLoaded(mode);
setMode(saved);
useChatRuntimeStore
.getState()
.setKeepModelsLoaded(keepsModelsLoaded(saved));
+ if (wasKeeping && !keepsModelsLoaded(saved)) {
+ void resyncInferenceStatusAfterKeptModelsUnload();
+ }
} catch (saveError) {
setError(
saveError instanceof Error
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index d4d89a3ec9c..cb1edef8966 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2506,7 +2506,7 @@ export const en = {
"Loading a model keeps the others when they fit. When they don't, it unloads the ones not in use first, then the active one.",
multiModelDescriptionAlways:
"Loading a model never unloads another. A model that does not fit is not loaded. Idle auto-unload and training still free memory.",
- multiModelHint: "Covers chat, speech, image and video models. Each loaded chat model answers the requests that name it. With several GPUs, Unsloth tries to place a new model on a GPU no other model uses. “When they fit” leaves about 1 GB spare. “When they fit” and “Always” never unload a model on another GPU.",
+ multiModelHint: "Covers chat, speech, image and video models. Each loaded chat model answers the requests that name it. With several GPUs, Unsloth tries to place a new model on a GPU no other model uses. “When they fit” leaves about 1 GB spare. A model loaded beside others gets the memory they leave free, so it may start with a shorter context. “When they fit” and “Always” never unload a model on another GPU.",
allowOversizedLoad: "Allow oversized model loads",
allowOversizedLoadDescription: "Load image and video models even when the memory check says they will not fit.",
allowOversizedLoadHint: "Applies where the CPU and GPU share one memory pool (Apple Silicon, integrated GPUs). Unsloth refuses a load when its estimate of the model weights is larger than the memory left after reserving room for the operating system. With this on, those loads are attempted anyway. The estimate can be wrong either way: an oversized load can fail, use up all memory, make the computer swap heavily or stop responding, or stop Unsloth. Off by default.",