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: budget the Metal context fit from free memory, not total (#8706)
Daniel Han9cc6e650c3c0
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 3f7d92eff10..61bfe93a0e8 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -5899,6 +5899,24 @@ class LlamaCppBackend:over-commit unified memory ("Compute error." at decode, #5118/#6529). Use afraction of MLX's Metal working-set, else total RAM; 0 off Apple Silicon orwhen unresolvable, so callers skip the cap.++ Both of those inputs describe the MACHINE, not the moment. MLX's+ max_recommended_working_set_size is a static device property, and+ virtual_memory().total obviously is, so on a 16 GB Mac the budget came+ out around 9 GB whether the machine was idle or already holding several+ gigabytes. Studio's own idle footprint alone is over a gigabyte once the+ warm thread has imported torch and, on Apple Silicon, MLX. The fit then+ sized a context against headroom that was not there, and llama-server+ died in KV or compute allocation.++ So take whichever is smaller: the device ceiling, or what is actually+ available right now. The ceiling still applies on a machine with plenty+ free, which is the case the working-set number was chosen for.++ _APPLE_UNIFIED_MEMORY_FRACTION then earns a second job it did not have+ over a static ceiling: available is a snapshot, and llama-server spends+ seconds loading weights, so another app can take memory inside that+ window. Budgeting all of it would re-create the failure this avoids."""from utils.hardware import is_apple_silicon@@ -5911,12 +5929,31 @@ class LlamaCppBackend:rec_bytes = int(mx.device_info().get("max_recommended_working_set_size") or 0)except Exception:rec_bytes = 0+ vm = None+ try:+ import psutil+ vm = psutil.virtual_memory()+ except Exception:+ vm = Noneif rec_bytes <= 0:+ if vm is None:+ return 0try:- import psutil- rec_bytes = int(psutil.virtual_memory().total)+ rec_bytes = int(vm.total)except Exception:return 0+ # available, not free: psutil's macOS free subtracts speculative pages and+ # leaves out the inactive queue, so it reads far below what a new allocation+ # can get. available is inactive + free (psutil arch/osx/mem.c), which adds+ # that reclaimable cache back. An estimate either way, since it counts dirty+ # inactive pages that cost a compression to reclaim and ignores the+ # compressor entirely. Only ever lowers the budget.+ try:+ available = int(getattr(vm, "available", 0) or 0) if vm is not None else 0+ except Exception:+ available = 0+ if available > 0:+ rec_bytes = min(rec_bytes, available)return int(rec_bytes * _APPLE_UNIFIED_MEMORY_FRACTION)@staticmethoddiff --git a/studio/backend/tests/test_llama_cpp_context_fit.py b/studio/backend/tests/test_llama_cpp_context_fit.pyindex 2a4f6d19d25..8844f78be12 100644--- a/studio/backend/tests/test_llama_cpp_context_fit.py+++ b/studio/backend/tests/test_llama_cpp_context_fit.py@@ -759,6 +759,23 @@ def _install_fake_mlx(monkeypatch, working_set_bytes):monkeypatch.setitem(sys.modules, "mlx.core", mlx_core)+def _install_fake_psutil(+ monkeypatch,+ *,+ total,+ available = None,+):+ """psutil stub. The budget reads both, so a test must pin both to be+ machine-independent: with only `total` stubbed, `available` came from the+ host running the suite."""+ fake = _types.ModuleType("psutil")+ vm = _types.SimpleNamespace(total = total)+ if available is not None:+ vm.available = available+ fake.virtual_memory = lambda: vm+ monkeypatch.setitem(sys.modules, "psutil", fake)++class TestAppleUnifiedMemoryBudget:def test_zero_off_apple_silicon(self, monkeypatch):import platform as _platform@@ -771,6 +788,8 @@ class TestAppleUnifiedMemoryBudget:_force_apple(monkeypatch)ws = 27 * GIB # ~recommended working set on a 36 GB Mac_install_fake_mlx(monkeypatch, ws)+ # Idle machine: the device ceiling is the binding constraint.+ _install_fake_psutil(monkeypatch, total = 36 * GIB, available = 34 * GIB)assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(ws * _APPLE_UNIFIED_MEMORY_FRACTION)@@ -778,13 +797,51 @@ class TestAppleUnifiedMemoryBudget:def test_falls_back_to_total_ram_without_mlx(self, monkeypatch):_force_apple(monkeypatch)monkeypatch.setitem(sys.modules, "mlx", None) # import mlx.core -> ImportError- fake_psutil = _types.ModuleType("psutil")- fake_psutil.virtual_memory = lambda: _types.SimpleNamespace(total = 36 * GIB)- monkeypatch.setitem(sys.modules, "psutil", fake_psutil)+ _install_fake_psutil(monkeypatch, total = 36 * GIB, available = 36 * GIB)assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(36 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION)+ def test_a_busy_machine_budgets_from_what_is_free(self, monkeypatch):+ """The reporter's shape: 16 GB Mac already holding several GB.++ The working set is a static device property, so before this it answered+ the same on an idle and a loaded machine, and the fit sized a context+ against headroom that was not there.+ """+ _force_apple(monkeypatch)+ _install_fake_mlx(monkeypatch, 10 * GIB) # ~working set on a 16 GB Mac+ _install_fake_psutil(monkeypatch, total = 16 * GIB, available = 6 * GIB)+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 6 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )++ def test_available_never_raises_the_budget(self, monkeypatch):+ """Only ever lowers it: the device ceiling still bounds a free machine."""+ _force_apple(monkeypatch)+ _install_fake_mlx(monkeypatch, 10 * GIB)+ _install_fake_psutil(monkeypatch, total = 64 * GIB, available = 60 * GIB)+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 10 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )++ def test_a_psutil_without_available_keeps_the_old_answer(self, monkeypatch):+ """Nothing to cap with, so behave exactly as before rather than zero."""+ _force_apple(monkeypatch)+ _install_fake_mlx(monkeypatch, 10 * GIB)+ _install_fake_psutil(monkeypatch, total = 16 * GIB) # no `available`+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 10 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )++ def test_the_working_set_still_applies_without_psutil(self, monkeypatch):+ _force_apple(monkeypatch)+ _install_fake_mlx(monkeypatch, 10 * GIB)+ monkeypatch.setitem(sys.modules, "psutil", None)+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 10 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )+def test_zero_when_no_budget_resolvable(self, monkeypatch):_force_apple(monkeypatch)monkeypatch.setitem(sys.modules, "mlx", None)