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: admit GGUFs that fit carved-out Vulkan UMA (#9461)

alkinun7a0ecc2a5608
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 535de0009c7..692219068c5 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -354,7 +354,7 @@ from state.tool_approvals import (
new_approval_id,
wait_tool_decision,
)
-from utils.paths.path_utils import is_appledouble_metadata
+from utils.paths.path_utils import _is_wsl, is_appledouble_metadata
logger = get_logger(__name__)
@@ -3009,6 +3009,7 @@ _CPU_PLACEMENT_PRESENCE_FLAGS = (_MOE_OFFLOAD_FLAGS - _CPU_MOE_COUNT_FLAGS) | fr
)
_CPU_PLACEMENT_FLAGS = _MOE_OFFLOAD_FLAGS | frozenset({"-ot", "--override-tensor"})
_THREAD_OVERRIDE_FLAGS = frozenset({"-t", "--threads"})
+_TENSOR_SPLIT_FLAGS = frozenset({"--tensor-split", "-ts"})
def _strip_flag_pairs(args: Iterable[str], flags: frozenset[str]) -> list[str]:
@@ -4063,6 +4064,19 @@ def _device_selection_is_cpu(
return not devices or all(d in _CPU_DEVICE_VALUES for d in devices)
+def _split_mode_confines_to_one_device(
+ args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
+) -> bool:
+ """Whether the effective split mode confines all weights to one device."""
+ try:
+ mode = parse_split_mode_override(args)
+ except ValueError:
+ return False
+ if mode is None and env:
+ mode = env.get("LLAMA_ARG_SPLIT_MODE")
+ return str(mode or "").strip().lower() == "none"
+
+
def _extra_args_draft_device(extra_args: Optional[Iterable[str]]) -> Optional[str]:
"""Return the last explicit draft-device value, if any."""
return _extra_args_device(extra_args, {"--spec-draft-device", "-devd", "--device-draft"})
@@ -4326,6 +4340,7 @@ def _report_live_llama_timings(callback, chunk) -> None:
# margin (default 1024 MiB per device). ggml reports an iGPU's "VRAM" as shared
# system RAM, so hold back the same margin rather than inventing a larger one.
_IGPU_HOST_RESERVE_MIB = 1024
+_HOST_RAM_HEADROOM_MIB = 2048
_CGROUP_ROOT = "/sys/fs/cgroup"
_PROC_SELF_CGROUP = "/proc/self/cgroup"
@@ -8137,6 +8152,42 @@ class LlamaCppBackend:
)
return gpus
+ @staticmethod
+ def _igpu_backed_free_mib(free_mib: int, headroom_mib: int = 0) -> int:
+ """Bound a raw iGPU free reading by host RAM plus any firmware carve-out.
+
+ Vulkan combines OS-visible RAM with carve-outs. Memory above ``MemTotal``
+ is a conservative floor for the free carve-out; add ``MemAvailable`` for
+ the host-backed share after its required headroom. WSL cannot use this
+ inference because the VM and adapter report different memory scopes.
+ """
+ available = LlamaCppBackend._available_system_memory_mib()
+ total_ram = LlamaCppBackend._total_system_memory_mib()
+ if available is None or total_ram is None:
+ return free_mib
+ unseen = 0 if _is_wsl() else max(0, free_mib - total_ram)
+ host_backed = max(0, available - max(0, headroom_mib))
+ return min(free_mib, unseen + host_backed)
+
+ @staticmethod
+ def _igpu_backed_usable_mib(usable_mib: int) -> int:
+ """Bound a post-reserve iGPU budget for shared-heap admission.
+
+ Placement keeps the Vulkan reading so an existing full-offload plan is
+ not demoted to the fitter. The host guard alone reconstructs the raw
+ reading, bounds its host-backed share with the whole-system headroom,
+ and caps that against the already-reserved placement budget. A zero
+ budget stays zero because the raw value below the reserve is no longer
+ recoverable and could not admit weights either way.
+ """
+ if usable_mib <= 0:
+ return 0
+ raw_free_mib = usable_mib + _IGPU_HOST_RESERVE_MIB
+ backed_mib = LlamaCppBackend._igpu_backed_free_mib(
+ raw_free_mib, headroom_mib = _HOST_RAM_HEADROOM_MIB
+ )
+ return min(usable_mib, backed_mib)
+
@staticmethod
def _cgroup_available_memory_mib() -> Optional[int]:
"""Memory this process can still charge to an enforcing cgroup.
@@ -8327,6 +8378,89 @@ class LlamaCppBackend:
split_library = any(name.startswith((cpu_stem, base_stem)) for name in files)
return split_library and not any(_GGML_GPU_BACKEND_RE.match(name) for name in files)
+ def _argv_offloads_every_layer(
+ self,
+ argv: Iterable[str],
+ env: Optional[Mapping[str, str]] = None,
+ ) -> bool:
+ """Whether the final command puts every model layer on a GPU.
+
+ Unknown placement is treated as partial offload so unverified GPU memory
+ is never credited.
+ """
+ args = [str(a) for a in argv or ()]
+ if _device_selection_is_cpu(args, env):
+ return False
+ if _args_place_tensors_on_cpu(args) or _env_places_tensors_on_cpu(env):
+ return False
+ # The fitter owns placement unless it is explicitly disabled.
+ if fit_is_effectively_on(args, env):
+ return False
+ try:
+ requested = parse_gpu_layers_override(args)
+ except ValueError:
+ return False
+ if requested is None:
+ return False
+ # -1 means every layer; otherwise the count must exceed the block count.
+ n_layers = self.n_layers
+ return requested == -1 or (bool(n_layers) and requested > n_layers)
+
+ def _shared_heap_budget(
+ self,
+ gpus: Iterable[tuple],
+ shared_gpu_ids: Collection[int],
+ model_bytes: int,
+ argv: list[str],
+ env: Optional[Mapping[str, str]] = None,
+ ) -> tuple[int, int]:
+ """Return reachable shared Vulkan memory and the bytes it must hold.
+
+ Shared iGPU rows overlap, so only the largest pool is credited. The pool
+ must be reachable by an unambiguous full offload -- a device pin that
+ names it, or no pin on a host where llama.cpp finds no discrete card --
+ and only selected discrete cards reduce the bytes assigned to it.
+ """
+ rows = [(row[0], max(0, row[1])) for row in gpus]
+ pinned = _extra_args_main_device(argv)
+ if pinned is None and env:
+ pinned = env.get("LLAMA_ARG_DEVICE")
+ if pinned is None:
+ reachable = {idx for idx, _free in rows}
+ # Unpinned, llama.cpp builds the device list itself and appends
+ # integrated GPUs only when it found no discrete one, so a shared
+ # heap beside a discrete card receives nothing.
+ if any(idx not in shared_gpu_ids for idx in reachable):
+ reachable -= set(shared_gpu_ids)
+ else:
+ # Match the ggml registry names emitted by _vulkan_pin_args.
+ names = {device.strip().lower() for device in str(pinned).split(",")}
+ reachable = {idx for idx, _free in rows if f"vulkan{idx}" in names}
+ pool = 0
+ if (
+ shared_gpu_ids
+ and self._argv_offloads_every_layer(argv, env)
+ # Tensor-split positions cannot be mapped reliably to probe indices.
+ and not _extra_args_set_any_flag(argv, _TENSOR_SPLIT_FLAGS)
+ and not str((env or {}).get("LLAMA_ARG_TENSOR_SPLIT") or "").strip()
+ # With multiple devices, split-mode none does not identify the recipient.
+ and not (len(reachable) > 1 and _split_mode_confines_to_one_device(argv, env))
+ ):
+ budgets = []
+ for idx, free in rows:
+ if idx not in shared_gpu_ids or idx not in reachable:
+ continue
+ backed = self._igpu_backed_usable_mib(free)
+ if backed < free:
+ logger.info(
+ f"Vulkan device VK{idx} offers {free}MiB to placement; "
+ f"host admission credits {backed}MiB"
+ )
+ budgets.append(backed)
+ pool = max(budgets, default = 0)
+ on_cards = sum(free for idx, free in rows if idx not in shared_gpu_ids and idx in reachable)
+ return pool, model_bytes - on_cards * 1024 * 1024
+
def _launch_host_shortfall_message(
self,
cmd: Iterable[str],
@@ -8357,8 +8491,8 @@ class LlamaCppBackend:
``avail_mib`` overrides the host figure for a caller that runs before the resident
owners are released; the launch reads what is available now. ``shared_gpu_ids``
- names Vulkan iGPUs whose reported free memory is the same host pool, so it must
- not also be credited as dedicated VRAM.
+ names Vulkan iGPUs whose reported free memory overlaps the host pool. Either
+ reading can hold the remaining weights, but they must never be added together.
"""
argv = [str(a) for a in cmd or ()]
if not argv:
@@ -8391,8 +8525,18 @@ class LlamaCppBackend:
return None
shared = set(shared_gpu_ids or ())
free_vram_mib = sum(max(0, row[1]) for row in gpus if row[0] not in shared)
+ heap_free_mib, heap_bytes = self._shared_heap_budget(gpus, shared, model_bytes, argv, _env)
+ offload_bytes = model_bytes - free_vram_mib * 1024 * 1024
+ # A carve-out can satisfy the dedicated-VRAM shortfall. Skip card-resident
+ # loads so a cgroup budget is never applied to a nonpositive need.
+ if 0 < offload_bytes and heap_bytes <= heap_free_mib * 1024 * 1024:
+ # A finite cgroup still limits host-backed GPU allocations.
+ cgroup_mib = self._cgroup_available_memory_mib()
+ if cgroup_mib is None:
+ return None
+ return self._apu_ram_shortfall_message(heap_bytes, cgroup_mib)
return self._host_offload_shortfall_message(
- model_bytes - free_vram_mib * 1024 * 1024,
+ offload_bytes,
self._available_system_memory_mib() if avail_mib is None else avail_mib,
)
@@ -8400,7 +8544,7 @@ class LlamaCppBackend:
def _apu_ram_shortfall_message(
model_size_bytes: int,
avail_mib: Optional[int],
- headroom_mib: int = 2048,
+ headroom_mib: int = _HOST_RAM_HEADROOM_MIB,
) -> Optional[str]:
"""On a unified-memory APU, return a user-facing refusal when the weights
cannot fit in available system RAM (else None). Weights only: KV/context
@@ -8423,7 +8567,7 @@ class LlamaCppBackend:
def _host_offload_shortfall_message(
offload_bytes: int,
avail_mib: Optional[int],
- headroom_mib: int = 2048,
+ headroom_mib: int = _HOST_RAM_HEADROOM_MIB,
) -> Optional[str]:
"""On a discrete GPU, return a user-facing refusal when the part of a load
that misses VRAM cannot fit in available system RAM (else None). The spill is
diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.py
index 41fd40d73fb..0a4849fba68 100644
--- a/studio/backend/tests/test_llama_cpp_placement.py
+++ b/studio/backend/tests/test_llama_cpp_placement.py
@@ -1590,13 +1590,20 @@ def test_free_vram_offsets_the_charge(tmp_path, monkeypatch):
assert "--fit" in _launch(backend, gguf)["cmd"]
-def test_vulkan_igpu_shared_memory_is_not_counted_twice(tmp_path, monkeypatch):
- """A Vulkan iGPU's free memory and MemAvailable describe the same unified pool.
- Crediting both let a 20 GiB model through on a 14 GiB host (12 + 14 on paper)."""
+ "memory",
+ [
+ [(0, 12 * 1024, 0)],
+ [(0, 12 * 1024, 0), (1, 12 * 1024, 0)],
+ ],
+ ids = ["one-shared-device", "two-shared-devices"],
+)
+def test_vulkan_igpu_shared_memory_is_not_counted_twice(tmp_path, monkeypatch, memory):
+ """Shared Vulkan rows and host RAM describe one pool."""
backend, gguf = _backend(
tmp_path,
vulkan = True,
- memory = [(0, 12 * 1024, 0)],
+ memory = memory,
)
_restore_host_guard(backend)
backend._get_gguf_size_bytes = lambda _path: 20 * 1024**3
@@ -1604,11 +1611,304 @@ def test_vulkan_igpu_shared_memory_is_not_counted_twice(tmp_path, monkeypatch):
monkeypatch.setattr(
LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 14 * 1024)
)
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
_launch(backend, gguf)
+def test_vulkan_igpu_heap_can_hold_weights_missing_from_host_available(tmp_path, monkeypatch):
+ """A firmware carve-out remains usable when host-available RAM is low."""
+ backend, gguf = _backend(
+ tmp_path,
+ vulkan = True,
+ memory = [(0, 107 * 1024, 0)],
+ )
+ _restore_host_guard(backend)
+ backend._get_gguf_size_bytes = lambda _path: int(16.5 * 1024**3)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 13 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 32 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+
+ assert _launch(backend, gguf)["cmd"]
+
+
+ "gguf_mib,admitted",
+ [(4096, True), (8192, True), (8256, False), (8704, False), (9216, False)],
+ ids = ["4-gib", "8-gib", "8.06-gib", "8.5-gib", "9-gib"],
+)
+def test_vulkan_igpu_backing_bound_preserves_placement_and_host_headroom(
+ tmp_path, monkeypatch, gguf_mib, admitted
+):
+ """The raw planner reading never lets host-backed credit lose system headroom."""
+ backend, gguf = _backend(tmp_path, vulkan = True, memory = [(0, 15 * 1024, 0)])
+ _restore_host_guard(backend)
+ backend._get_gpu_memory = (
+ lambda _binary = None, **_kw: LlamaCppBackend._get_gpu_free_memory_vulkan(_binary)
+ )
+ backend._get_gguf_size_bytes = lambda _path: gguf_mib * 1024**2
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_run_vulkan_probe",
+ staticmethod(
+ lambda _binary = None: [
+ {
+ "index": 0,
+ "free_mib": 16 * 1024,
+ "is_igpu": True,
+ "total_mib": 16 * 1024,
+ "name": "Vulkan0",
+ }
+ ]
+ ),
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 10 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 16 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+
+ if not admitted:
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(backend, gguf)
+ return
+
+ cmd = _launch(backend, gguf)["cmd"]
+ assert cmd[cmd.index("-ngl") + 1] == "-1"
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ assert cmd[cmd.index("--device") + 1] == "Vulkan0"
+
+
+ "placement",
+ [
+ {"gpu_memory_mode": "manual", "gpu_layers": 0},
+ {"gpu_memory_mode": "manual", "gpu_layers": 8},
+ {"extra_args": ["--device", "none"]},
+ {"extra_args": ["-ngl", "0"]},
+ ],
+ ids = ["manual-zero-offload", "manual-partial-offload", "device-none", "extras-zero-offload"],
+)
+def test_vulkan_igpu_heap_is_not_credited_to_a_host_resident_launch(
+ tmp_path, monkeypatch, placement
+):
+ """Only a full GPU offload may credit the shared heap."""
+ backend, gguf = _backend(tmp_path, vulkan = True, memory = [(0, 107 * 1024, 0)])
+ _restore_host_guard(backend)
+ backend._get_gguf_size_bytes = lambda _path: int(16.5 * 1024**3)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 13 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 32 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(backend, gguf, **placement)
+
+
+def test_a_device_pin_decides_whether_the_shared_heap_is_reachable(tmp_path, monkeypatch):
+ """Only a selected shared device contributes its heap."""
+
+ def _mixed():
+ backend, gguf = _backend(
+ tmp_path, vulkan = True, memory = [(0, 6 * 1024, 8 * 1024), (1, 94641, 0)]
+ )
+ _restore_host_guard(backend)
+ backend._get_gguf_size_bytes = lambda _path: 30 * 1024**3
+ # gpu_layers=33 fully offloads this 32-layer model.
+ backend._n_layers = 32
+ return backend, gguf
+
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 13 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 32 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+ manual = {"gpu_memory_mode": "manual", "gpu_layers": 33}
+
+ backend, gguf = _mixed()
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(backend, gguf, extra_args = ["--device", "Vulkan0"], **manual)
+
+ backend, gguf = _mixed()
+ assert _launch(backend, gguf, extra_args = ["--device", "Vulkan1"], **manual)["cmd"]
+
+
+def test_an_unselected_card_does_not_shrink_what_the_shared_heap_must_hold(tmp_path, monkeypatch):
+ """Only selected cards reduce the bytes assigned to the shared heap."""
+ backend, gguf = _backend(
+ tmp_path, vulkan = True, memory = [(0, 24 * 1024, 24 * 1024), (1, 10 * 1024, 0)]
+ )
+ _restore_host_guard(backend)
+ backend._get_gguf_size_bytes = lambda _path: 30 * 1024**3
+ backend._n_layers = 32
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 4 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 32 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = 33,
+ extra_args = ["--device", "Vulkan1"],
+ )
+
+
+ "split",
+ [{"tensor_split": [1.0, 0.0]}, {"extra_args": ["--tensor-split", "1,0"]}],
+ ids = ["picker-share", "user-flag"],
+)
+def test_an_explicit_tensor_split_leaves_the_shared_heap_uncredited(tmp_path, monkeypatch, split):
+ """An ambiguous tensor split must not credit a shared heap."""
+ backend, gguf = _backend(tmp_path, vulkan = True, memory = [(0, 6 * 1024, 8 * 1024), (1, 94641, 0)])
+ _restore_host_guard(backend)
+ backend._get_gguf_size_bytes = lambda _path: 30 * 1024**3
+ backend._n_layers = 32
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 4 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 32 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = 33,
+ gpu_ids = [0, 1],
+ **split,
+ )
+
+
+def _mixed_vulkan(tmp_path, monkeypatch, memory):
+ """A 30 GiB GGUF on a host with 4 GiB of RAM left, full manual offload."""
+ backend, gguf = _backend(tmp_path, vulkan = True, memory = memory)
+ _restore_host_guard(backend)
+ backend._get_gguf_size_bytes = lambda _path: 30 * 1024**3
+ backend._n_layers = 32
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 4 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 32 * 1024)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+ return backend, gguf
+
+
+ "extras",
+ [["--split-mode", "none", "--main-gpu", "0"], ["-sm", "none"]],
+ ids = ["with-main-gpu", "bare"],
+)
+def test_split_mode_none_leaves_a_second_device_heap_uncredited(tmp_path, monkeypatch, extras):
+ """Split mode none cannot select a shared heap among multiple devices."""
+ backend, gguf = _mixed_vulkan(tmp_path, monkeypatch, [(0, 6 * 1024, 8 * 1024), (1, 94641, 0)])
+
+ # Both devices pinned, so the split mode is the only thing left to decide.
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = 33,
+ extra_args = ["--device", "Vulkan0,Vulkan1", *extras],
+ )
+
+
+def test_an_unpinned_launch_beside_a_discrete_card_leaves_the_heap_uncredited(
+ tmp_path, monkeypatch
+):
+ """llama.cpp drops integrated GPUs when its own device list finds a discrete one."""
+ backend, gguf = _mixed_vulkan(tmp_path, monkeypatch, [(0, 94641, 0), (1, 6 * 1024, 8 * 1024)])
+
+ with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):
+ _launch(backend, gguf, gpu_memory_mode = "manual", gpu_layers = 33)
+
+
+def test_a_pin_still_reaches_the_heap_beside_a_discrete_card(tmp_path, monkeypatch):
+ """Naming the shared device puts it back in llama.cpp's list."""
+ backend, gguf = _mixed_vulkan(tmp_path, monkeypatch, [(0, 94641, 0), (1, 6 * 1024, 8 * 1024)])
+
+ assert _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = 33,
+ extra_args = ["--device", "Vulkan0"],
+ )["cmd"]
+
+
+def test_split_mode_none_still_credits_a_lone_shared_device(tmp_path, monkeypatch):
+ """A lone shared device remains reachable under split mode none."""
+ backend, gguf = _mixed_vulkan(tmp_path, monkeypatch, [(0, 94641, 0)])
+
+ assert _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = 33,
+ extra_args = ["--split-mode", "none"],
+ )["cmd"]
+
+
+def test_vulkan_igpu_heap_does_not_bypass_a_cgroup_limit(tmp_path, monkeypatch):
+ """A shared Vulkan heap remains subject to the process cgroup limit."""
+ backend, gguf = _backend(
+ tmp_path,
+ vulkan = True,
+ memory = [(0, 64 * 1024, 0)],
+ )
+ _restore_host_guard(backend)
+ backend._apu_ram_shortfall_message = LlamaCppBackend._apu_ram_shortfall_message
+ backend._get_gguf_size_bytes = lambda _path: 20 * 1024**3
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 64 * 1024)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: 8 * 1024)
+ )
+
+ with pytest.raises(RuntimeError, match = "unified-memory APU"):
+ _launch(backend, gguf)
+
+
+def test_a_card_resident_model_is_not_refused_by_a_container_ceiling(tmp_path, monkeypatch):
+ """A card-resident model is independent of the cgroup memory budget."""
+ backend, gguf = _offload_backend(
+ tmp_path,
+ gguf_gb = 23.4,
+ free_mib = 24 * 1024,
+ avail_mib = 1024,
+ monkeypatch = monkeypatch,
+ )
+ backend._apu_ram_shortfall_message = LlamaCppBackend._apu_ram_shortfall_message
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: 1024))
+
+ assert _launch(backend, gguf)["cmd"]
+
+
def test_unknown_available_ram_abstains(tmp_path, monkeypatch):
backend, gguf = _offload_backend(
tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = None, monkeypatch = monkeypatch
diff --git a/studio/backend/tests/test_llama_cpp_vulkan_probe.py b/studio/backend/tests/test_llama_cpp_vulkan_probe.py
index bf0327de0ed..b02a94d1cfd 100644
--- a/studio/backend/tests/test_llama_cpp_vulkan_probe.py
+++ b/studio/backend/tests/test_llama_cpp_vulkan_probe.py
@@ -127,14 +127,84 @@ def _row(
return f"{row}\t{name}" if name is not None else row
-def test_integrated_gpu_leaves_host_margin(tmp_path):
+def _host_memory(monkeypatch, *, available_mib, total_mib):
+ """Set deterministic host-memory bounds for iGPU tests."""
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: available_mib)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: total_mib)
+ )
+
+
+def test_integrated_gpu_leaves_host_margin(tmp_path, monkeypatch):
binary = _make_vulkan_install(tmp_path)
# iGPU with 30 GiB free; reserve a flat 1024 MiB (llama.cpp --fit-target).
# total stays 0: shared system RAM is not a VRAM budget for the fit.
+ _host_memory(monkeypatch, available_mib = 31 * 1024, total_mib = 32 * 1024)
+ rows = [_row(0, 30 * GIB, is_igpu = 1, total_bytes = 32 * GIB)]
+ with _mock_probe(rows):
+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
+ assert gpus == [(0, 30 * 1024 - 1024, 0)], gpus
+
+
+def test_integrated_gpu_host_bound_does_not_replace_planner_reading(tmp_path, monkeypatch):
+ """Placement keeps Vulkan free while admission caps its host-backed share."""
+ binary = _make_vulkan_install(tmp_path)
+ _host_memory(monkeypatch, available_mib = 4000, total_mib = 31000)
+ # 512 MiB of UMA plus a GTT heap half the size of RAM
+ rows = [_row(0, 15900 * MIB, is_igpu = 1, total_bytes = 16012 * MIB)]
+ with _mock_probe(rows):
+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
+ assert gpus == [(0, 15900 - 1024, 0)], gpus
+ assert LlamaCppBackend._igpu_backed_usable_mib(gpus[0][1]) == 4000 - 2048
+
+
+def test_integrated_gpu_keeps_a_heap_the_os_cannot_see(tmp_path, monkeypatch):
+ """Free memory above MemTotal is a conservative carve-out floor."""
+ binary = _make_vulkan_install(tmp_path)
+ _host_memory(monkeypatch, available_mib = 13312, total_mib = 32154)
+ rows = [_row(0, 108782 * MIB, is_igpu = 1, total_bytes = 114507 * MIB)]
+ with _mock_probe(rows):
+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
+ assert gpus == [(0, 108782 - 1024, 0)], gpus
+ expected = (108782 - 32154) + 13312 - 2048
+ assert LlamaCppBackend._igpu_backed_usable_mib(gpus[0][1]) == expected
+
+
+def test_a_carve_out_another_process_holds_is_not_credited(tmp_path, monkeypatch):
+ """Use free, not total, to exclude carve-out memory held elsewhere."""
+ binary = _make_vulkan_install(tmp_path)
+ _host_memory(monkeypatch, available_mib = 4096, total_mib = 32768)
+ # The free reading does not exceed MemTotal, so no carve-out is credited.
+ rows = [_row(0, 22528 * MIB, is_igpu = 1, total_bytes = 114688 * MIB)]
+ with _mock_probe(rows):
+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
+ assert gpus == [(0, 22528 - 1024, 0)], gpus
+ assert LlamaCppBackend._igpu_backed_usable_mib(gpus[0][1]) == 4096 - 2048
+
+
+def test_wsl_credits_no_heap_beyond_its_own_memtotal(tmp_path, monkeypatch):
+ """WSL MemTotal does not describe the adapter's host pool."""
+ binary = _make_vulkan_install(tmp_path)
+ _host_memory(monkeypatch, available_mib = 6000, total_mib = 8192)
+ monkeypatch.setattr(_llama_mod, "_is_wsl", lambda: True)
+ rows = [_row(0, 11000 * MIB, is_igpu = 1, total_bytes = 12000 * MIB)]
+ with _mock_probe(rows):
+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
+ assert gpus == [(0, 11000 - 1024, 0)], gpus
+ assert LlamaCppBackend._igpu_backed_usable_mib(gpus[0][1]) == 6000 - 2048
+
+
+def test_unreadable_host_memory_leaves_the_integrated_reading_alone(tmp_path, monkeypatch):
+ """Missing host readings leave the Vulkan value unchanged."""
+ binary = _make_vulkan_install(tmp_path)
+ _host_memory(monkeypatch, available_mib = None, total_mib = None)
rows = [_row(0, 30 * GIB, is_igpu = 1, total_bytes = 32 * GIB)]
with _mock_probe(rows):
gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
assert gpus == [(0, 30 * 1024 - 1024, 0)], gpus
+ assert LlamaCppBackend._igpu_backed_usable_mib(gpus[0][1]) == 30 * 1024 - 1024
def test_discrete_gpu_free_is_untouched_and_total_passed_through(tmp_path):