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: keep llama.cpp's Metal fit inside the GPU wired headroom (#13319)
Daniel Han548fe076fa0b
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4d4b835844a..0abd775cd06 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -13603,6 +13603,30 @@ class LlamaCppBackend:return 0return max(0, int((cap_bytes - in_use) * _APPLE_WIRED_CEILING_FRACTION))+ @staticmethod+ def _metal_fit_target_floor_mib() -> float:+ """Smallest ``--fit-target`` that keeps llama.cpp's Metal fit inside the wired headroom.++ ggml-metal reports free as recommendedMaxWorkingSetSize minus this process's own+ allocations (ggml-metal-device.m, ggml_metal_device_get_memory), blind to the GPU+ memory WindowServer and other apps already hold, so --fit packs to within 1 GiB of+ the static ceiling and over-commits the wired limit (#9279). 0 when either side is+ unreadable, which leaves llama.cpp's own margin.+ """+ headroom = LlamaCppBackend._apple_metal_wired_ceiling_bytes()+ if headroom <= 0:+ return 0.0+ try:+ import mlx.core as mx+ from utils.hardware.hardware import _mlx_device_info++ if not mx.metal.is_available():+ return 0.0+ seen = int(_mlx_device_info(mx).get("max_recommended_working_set_size") or 0)+ except Exception:+ return 0.0+ return max(0.0, (seen - headroom) / (1024 * 1024))+@staticmethoddef _rocm_arch_gate_keep(binary: Optional[str], torch_mod, for_llama_server: bool@@ -25608,6 +25632,8 @@ class LlamaCppBackend:_metal_ctx_warning: Optional[str] = None# A discounted Metal ceiling must launch the measured full-offload placement._metal_full_offload_pinned = False+ # --fit-target floor from the Metal wired headroom; 0 off Apple Silicon.+ _metal_fit_target_floor_mib = 0.0# The fit and launch must use the same Model Memory snapshot.from utils.model_memory_settings import capture_model_memory_settings@@ -27689,10 +27715,25 @@ class LlamaCppBackend:<= _fit_wired_mibelse None)+ # Auto launches a fixed -c, so llama.cpp's fitter could only move+ # layers to CPU; give up context first, down to the Auto floor,+ # so every layer stays on Metal.+ if (+ not explicit_ctx+ and _vram_fit_ctx+ and min(_FIT_MIN_CTX, effective_ctx)+ <= _vram_fit_ctx+ < effective_ctx+ ):+ effective_ctx = max_available_ctx = _vram_fit_ctx# Unmeasured floors still rely on llama.cpp's fitter._metal_full_offload_pinned = bool(_apple_host_embd and _apple_measured_ceiling is not None)+ # Weights over the budget launch here too and the fitter places+ # them, so it must see the same wired limit the refusals do.+ if not _caller_owns_budget and not _paravirtual_cpu_forced:+ _metal_fit_target_floor_mib = self._metal_fit_target_floor_mib()# Prefer fewer serving slots on GPU over --fit on offload: when the extra# --parallel slots push the footprint past the pin budget, llama-server@@ -28164,6 +28205,7 @@ class LlamaCppBackend:fit_target_delta_mib = _fit_target_delta_mib if use_fit else 0.0,supports_fit_target = use_fitand bool(server_caps.get("supports_fit_target")),+ floor_mib = _metal_fit_target_floor_mib,),fit_target_margin_in(_fit_extras, _fit_env) or 0.0,)@@ -28937,19 +28979,30 @@ class LlamaCppBackend:except OSError:self._slot_save_dir = Noneself._slot_save_binary = None- _integrity_flags = self._ctx_integrity_flags(+ _integrity_args = (n_parallel,use_fit,auto_fit,requested_ctx,effective_ctx,server_caps,+ )+ _integrity_flags = self._ctx_integrity_flags(+ *_integrity_args,fit_target_delta_mib = _fit_target_delta_mib,)# From the flags, not the inputs: --fit off, an older server without# the capability and a budget at the default all leave the child# unpriced, and each is decided inside that call._fit_target_priced = "--fit-target" in _integrity_flags+ if _metal_fit_target_floor_mib:+ # Rebuilt after the price is read: the floor is the machine's+ # margin, not the budget slider's.+ _integrity_flags = self._ctx_integrity_flags(+ *_integrity_args,+ fit_target_delta_mib = _fit_target_delta_mib,+ fit_target_floor_mib = _metal_fit_target_floor_mib,+ )cmd.extend(_integrity_flags)offload_overridden = _extra_args_set_any_flag(extra_args, _GPU_OFFLOAD_OVERRIDE_FLAGS@@ -36292,6 +36345,7 @@ class LlamaCppBackend:auto_fit: bool,fit_target_delta_mib: float = 0.0,supports_fit_target: bool = True,+ floor_mib: float = 0.0,) -> float:"""Free VRAM per device llama.cpp's fitter keeps for itself under ``--fit on``.@@ -36299,12 +36353,13 @@ class LlamaCppBackend:told to keep and the margin the fit refuses to spend cannot drift. A servertoo old for ``--fit-target`` still keeps llama.cpp's own 1024 MiB default(common/common.h, ``fit_params_target``), which is also what the legacy path- deliberately stays silent about.+ deliberately stays silent about. ``floor_mib`` is a margin the host needs kept+ whatever the budget says (the Metal wired headroom)."""if not supports_fit_target:return _LLAMA_FIT_TARGET_DEFAULT_MIBbase = _VRAM_FLOOR_RESERVE_MIB if auto_fit else _LLAMA_FIT_TARGET_DEFAULT_MIB- return max(_VRAM_FLOOR_RESERVE_MIB, base + fit_target_delta_mib)+ return max(_VRAM_FLOOR_RESERVE_MIB, base + fit_target_delta_mib, floor_mib)@staticmethoddef _ctx_integrity_flags(@@ -36316,6 +36371,7 @@ class LlamaCppBackend:caps: dict,*,fit_target_delta_mib: float = 0.0,+ fit_target_floor_mib: float = 0.0,) -> list[str]:"""Flags that keep the per-request window equal to the advertised ctx.@@ -36353,6 +36409,7 @@ class LlamaCppBackend:_target = LlamaCppBackend._fit_target_margin_mib(auto_fit = auto_fit,fit_target_delta_mib = fit_target_delta_mib,+ floor_mib = fit_target_floor_mib,)# The legacy path stays silent when it would only restate llama.cpp's# own default, so an untouched slider leaves the command unchanged.diff --git a/studio/backend/tests/test_metal_explicit_context_guard.py b/studio/backend/tests/test_metal_explicit_context_guard.pyindex e8f0dfc8341..f74b8021e31 100644--- a/studio/backend/tests/test_metal_explicit_context_guard.py+++ b/studio/backend/tests/test_metal_explicit_context_guard.py@@ -1754,3 +1754,190 @@ def test_every_forced_full_offload_arm_owes_the_fit_on_retry():]assert len(arms) == 2, f"expected the two forced full-offload arms, found {len(arms)}"assert all(claims_full_offload(arm) for arm in arms)+++class TestFitterKeepsTheWiredHeadroom:+ """Weights over the budget still launch, and llama.cpp's fitter places them against+ ggml-metal's free report: recommendedMaxWorkingSetSize minus this process's own+ allocations, blind to what WindowServer and other apps hold. On a 24 GB Mac that+ packs a 27B Q4 to within 1 GiB of the 16 GiB ceiling and the display starves+ (#9279), so the launch carries the measured gap as --fit-target."""++ GiB = 1024**3+ OVER_BUDGET = dict(real_fit = True, budget_bytes = 9 * 1024**3, weights_bytes = 16 * 1024**3)++ @pytest.fixture+ def fit_caps(self, monkeypatch):+ probe = LlamaCppBackend.probe_server_capabilities.__func__+ monkeypatch.setattr(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(+ lambda cls, binary = None: {+ **probe(cls, binary),+ "supports_fit_target": True,+ "supports_fit_ctx": True,+ }+ ),+ )++ @staticmethod+ def _floor(monkeypatch, mib):+ calls = []++ def floor():+ calls.append(1)+ return mib++ monkeypatch.setattr(LlamaCppBackend, "_metal_fit_target_floor_mib", staticmethod(floor))+ return calls++ @staticmethod+ def _fit_target(cmd):+ values = [cmd[i + 1] for i, t in enumerate(cmd) if t == "--fit-target"]+ return values[-1] if values else None++ @pytest.mark.parametrize("n_ctx", [0, 32768])+ def test_an_over_budget_load_keeps_the_gap(self, tmp_path, monkeypatch, fit_caps, n_ctx):+ self._floor(monkeypatch, 2764.8)+ cmd = _launch(tmp_path, monkeypatch, n_ctx = n_ctx, **self.OVER_BUDGET)["cmd"]+ assert "--fit" in cmd and cmd[cmd.index("--fit") + 1] == "on"+ assert self._fit_target(cmd) == "2764"++ def test_a_margin_below_llama_cpps_own_leaves_argv_alone(self, tmp_path, monkeypatch, fit_caps):+ self._floor(monkeypatch, 0.0)+ cmd = _launch(tmp_path, monkeypatch, n_ctx = 0, **self.OVER_BUDGET)["cmd"]+ assert self._fit_target(cmd) is None++ def test_a_pass_through_fit_target_still_wins(self, tmp_path, monkeypatch, fit_caps):+ self._floor(monkeypatch, 2764.8)+ cmd = _launch(+ tmp_path,+ monkeypatch,+ n_ctx = 0,+ extra_args = ["--fit-target", "4096"],+ **self.OVER_BUDGET,+ )["cmd"]+ assert self._fit_target(cmd) == "4096"++ @pytest.mark.parametrize(+ "kwargs",+ [+ {"gpu_memory_mode": "manual", "gpu_layers": 20},+ {"paravirtual": True},+ ],+ ids = ["caller_owns_layers", "paravirtual_cpu_pin"],+ )+ def test_loads_that_do_not_place_on_metal_are_untouched(+ self, tmp_path, monkeypatch, fit_caps, kwargs+ ):+ calls = self._floor(monkeypatch, 2764.8)+ cmd = _launch(tmp_path, monkeypatch, n_ctx = 0, **self.OVER_BUDGET, **kwargs)["cmd"]+ assert not calls+ assert self._fit_target(cmd) is None++ def test_off_apple_silicon_the_floor_is_never_read(self, tmp_path, monkeypatch, fit_caps):+ calls = self._floor(monkeypatch, 2764.8)+ _launch(tmp_path, monkeypatch, n_ctx = 0, metal = False, **self.OVER_BUDGET)+ assert not calls++ def test_the_floor_is_not_a_budget_price(self, tmp_path, monkeypatch, fit_caps):+ """A VRAM slider change must not evict a Mac child over the machine's margin."""+ self._floor(monkeypatch, 2764.8)+ backend = _launch(tmp_path, monkeypatch, n_ctx = 0, **self.OVER_BUDGET)["backend"]+ assert getattr(backend, "_vram_fraction_launched", None) is None++ @staticmethod+ def _fake_mlx(+ monkeypatch,+ seen_bytes,+ available = True,+ ):+ mlx = _types.ModuleType("mlx")+ core = _types.ModuleType("mlx.core")+ core.metal = _types.SimpleNamespace(is_available = lambda: available)+ core.device_info = lambda: {"max_recommended_working_set_size": seen_bytes}+ mlx.core = core+ monkeypatch.setitem(sys.modules, "mlx", mlx)+ monkeypatch.setitem(sys.modules, "mlx.core", core)++ @pytest.mark.parametrize(+ "seen_gib,headroom_gib,expected_mib",+ [(16, 13.3, (16 - 13.3) * 1024), (16, 16, 0.0), (16, 20, 0.0)],+ )+ def test_the_floor_is_the_gap_between_what_ggml_sees_and_the_headroom(+ self, monkeypatch, seen_gib, headroom_gib, expected_mib+ ):+ self._fake_mlx(monkeypatch, int(seen_gib * self.GiB))+ monkeypatch.setattr(+ LlamaCppBackend,+ "_apple_metal_wired_ceiling_bytes",+ staticmethod(lambda: int(headroom_gib * self.GiB)),+ )+ assert LlamaCppBackend._metal_fit_target_floor_mib() == pytest.approx(expected_mib, abs = 1)++ @pytest.mark.parametrize(+ "headroom,seen,available", [(0, 16, True), (13, 0, True), (13, 16, False)]+ )+ def test_an_unreadable_side_keeps_llama_cpps_margin(+ self, monkeypatch, headroom, seen, available+ ):+ self._fake_mlx(monkeypatch, seen * self.GiB, available)+ monkeypatch.setattr(+ LlamaCppBackend,+ "_apple_metal_wired_ceiling_bytes",+ staticmethod(lambda: headroom * self.GiB),+ )+ assert LlamaCppBackend._metal_fit_target_floor_mib() == 0.0++ def test_an_old_server_without_the_flag_gets_none(self):+ assert "--fit-target" not in LlamaCppBackend._ctx_integrity_flags(+ 1, True, False, 0, 8192, {"supports_fit_target": False}, fit_target_floor_mib = 4096+ )+++class TestAutoGivesUpContextBeforeLayers:+ """Auto launches a fixed -c, so past the wired headroom llama.cpp's fitter can only+ move layers to CPU. The context the headroom holds is already measured; Auto launches+ at it while that stays at or above the Auto floor."""++ GiB = 1024**3+ # Footprint here is 6 GiB plus 64 KiB per token: the 9 GiB budget holds 49,152,+ # 7.5 GiB of headroom 24,576, and 6.4 GiB less than the 8,192 floor.+ FITS = dict(+ real_fit = True,+ budget_bytes = 9 * 1024**3,+ weights_bytes = 1024**3,+ kv_per_token = 64 * 1024,+ native = 131072,+ )++ def _ctx(+ self,+ tmp_path,+ monkeypatch,+ wired_gib,+ n_ctx = 0,+ ):+ cap = _launch(+ tmp_path, monkeypatch, n_ctx = n_ctx, wired_bytes = int(wired_gib * self.GiB), **self.FITS+ )+ return int(_ctx_values(cap["cmd"])[-1]), cap["backend"]++ def test_auto_launches_at_the_wired_ceiling(self, tmp_path, monkeypatch):+ budget_ctx, _ = self._ctx(tmp_path, monkeypatch, 0)+ ctx, backend = self._ctx(tmp_path, monkeypatch, 7.5)+ assert _FIT_MIN_CTX <= ctx <= 24576 < budget_ctx+ assert backend._max_context_length == ctx++ def test_ample_headroom_keeps_the_budget_context(self, tmp_path, monkeypatch):+ assert self._ctx(tmp_path, monkeypatch, 20)[0] == self._ctx(tmp_path, monkeypatch, 0)[0]++ def test_a_ceiling_under_the_auto_floor_leaves_it_to_the_fitter(self, tmp_path, monkeypatch):+ """Under 8,192 the context is worth more than the layers the fitter would move."""+ assert self._ctx(tmp_path, monkeypatch, 6.4)[0] == self._ctx(tmp_path, monkeypatch, 0)[0]++ def test_a_hand_set_context_is_not_lowered(self, tmp_path, monkeypatch):+ """The explicit path refuses against the wired limit instead (#10804)."""+ with pytest.raises(RuntimeError, match = "24,576"):+ self._ctx(tmp_path, monkeypatch, 7.5, n_ctx = 32768)