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: arm the VRAM-settle wait after the startup orphan reaper (#6315)

Daniel Han6c919bba8256
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index a4fd07c3b6f..00dfe14e631 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -816,7 +816,11 @@ class LlamaCppBackend:
# to decide whether to wait for the VRAM reclaim to finish.
self._last_kill_monotonic: float = 0.0
- self._kill_orphaned_servers()
+ _reaped = self._kill_orphaned_servers()
+ if _reaped:
+ # Reaped VRAM frees lazily; arm the settle wait so the first load
+ # waits before ranking GPUs by free memory.
+ self._last_kill_monotonic = time.monotonic()
atexit.register(self._cleanup)
# ── Properties ────────────────────────────────────────────────
@@ -5081,7 +5085,7 @@ class LlamaCppBackend:
self._llama_log_fh = None
@staticmethod
- def _kill_orphaned_servers():
+ def _kill_orphaned_servers() -> int:
"""Kill orphaned llama-server processes started by studio.
Only kills processes whose resolved binary lives under a known
@@ -5093,7 +5097,11 @@ class LlamaCppBackend:
Uses psutil for cross-platform support (Linux, macOS, Windows);
falls back to pgrep + /proc/<pid>/exe on Linux when psutil is
absent.
+
+ Returns the count of processes killed; callers arm the VRAM-settle
+ wait on a positive count.
"""
+ killed = 0
try:
# -- Build the ownership allowlist --------------------------------
# exact_binaries -- env var overrides (exact path match).
@@ -5185,6 +5193,7 @@ class LlamaCppBackend:
continue
proc.kill()
+ killed += 1
logger.info(
f"Killed orphaned llama-server process (pid={proc.info['pid']})"
)
@@ -5197,7 +5206,7 @@ class LlamaCppBackend:
else:
# -- Fallback: pgrep + /proc/<pid>/exe (Linux only) -----------
if sys.platform != "linux":
- return
+ return killed
result = subprocess.run(
["pgrep", "-a", "-f", "llama-server"],
capture_output = True,
@@ -5206,7 +5215,7 @@ class LlamaCppBackend:
env = child_env_without_native_path_secret(),
)
if result.returncode != 0:
- return
+ return killed
for line in result.stdout.strip().splitlines():
parts = line.strip().split(None, 1)
@@ -5237,6 +5246,7 @@ class LlamaCppBackend:
try:
os.kill(pid, signal.SIGKILL)
+ killed += 1
logger.info(f"Killed orphaned llama-server process (pid={pid})")
except ProcessLookupError:
pass
@@ -5244,6 +5254,7 @@ class LlamaCppBackend:
pass
except Exception:
logger.warning("Error during orphan server cleanup", exc_info = True)
+ return killed
def _cleanup(self):
"""atexit handler to ensure llama-server is terminated."""
diff --git a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
index 493bb93e8cc..7f1d0c8a42a 100644
--- a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
+++ b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
@@ -315,3 +315,73 @@ def test_helper_is_static_method_callable_off_class():
LlamaCppBackend._wait_for_vram_settle(
**_kw(max_wait = 0.1, interval = 0.05),
)
+
+
+# ---------------------------------------------------------------------------
+# Startup orphan-reaper arms the settle clock (the "wrong card after restart"
+# root cause: reaped VRAM frees lazily, so the first load must wait).
+# ---------------------------------------------------------------------------
+
+
+def test_kill_orphaned_servers_returns_count():
+ """The reaper reports how many owned orphans it killed, so __init__ can
+ arm the settle wait. Only Studio-owned llama-server procs count."""
+ import os
+
+ mypid = os.getpid()
+ fake_path = "/tmp/unsloth-test-llama/llama-server"
+ killed: list[int] = []
+
+ class _FakeProc:
+ def __init__(self, pid, name, exe):
+ self.info = {"pid": pid, "name": name, "exe": exe}
+
+ def kill(self):
+ killed.append(self.info["pid"])
+
+ owned = _FakeProc(mypid + 1, "llama-server", fake_path) # exact-path match
+ foreign = _FakeProc(mypid + 2, "llama-server", "/usr/bin/llama-server")
+ unrelated = _FakeProc(mypid + 3, "python3", "/usr/bin/python3")
+
+ fake_psutil = _types.ModuleType("psutil")
+ fake_psutil.NoSuchProcess = type("NoSuchProcess", (Exception,), {})
+ fake_psutil.AccessDenied = type("AccessDenied", (Exception,), {})
+ fake_psutil.ZombieProcess = type("ZombieProcess", (Exception,), {})
+ fake_psutil.process_iter = lambda attrs = None: [owned, foreign, unrelated]
+
+ with (
+ patch.dict(sys.modules, {"psutil": fake_psutil}),
+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": fake_path}),
+ ):
+ n = LlamaCppBackend._kill_orphaned_servers()
+ assert n == 1, "only the Studio-owned orphan should be counted"
+ assert killed == [mypid + 1]
+
+ # No owned orphans -> zero, so __init__ leaves the cold-start sentinel.
+ fake_psutil.process_iter = lambda attrs = None: [foreign, unrelated]
+ killed.clear()
+ with (
+ patch.dict(sys.modules, {"psutil": fake_psutil}),
+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": fake_path}),
+ ):
+ assert LlamaCppBackend._kill_orphaned_servers() == 0
+ assert killed == []
+
+
+def test_startup_reaper_arms_settle_timestamp():
+ """__init__ arms ``_last_kill_monotonic`` when the startup reaper kills an
+ orphan (so the first load_model waits for VRAM to settle), and leaves the
+ 0.0 cold-start sentinel when nothing was reaped."""
+ with patch.object(LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 1)):
+ before = time.monotonic()
+ backend = LlamaCppBackend()
+ after = time.monotonic()
+ assert (
+ before <= backend._last_kill_monotonic <= after
+ ), "a positive reap count must arm the settle clock"
+
+ with patch.object(LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)):
+ backend_cold = LlamaCppBackend()
+ assert (
+ backend_cold._last_kill_monotonic == 0.0
+ ), "no reap must leave the cold-start sentinel so the wait is skipped"