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
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Gate is inert on Vulkan, applies only to automatic placement, and never to the VRAM settle poll."""
from __future__ import annotations
import os
import struct
import subprocess
import sys
import types
from pathlib import Path
from unittest.mock import patch
import pytest
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
from core.inference import llama_cpp # noqa: E402
from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402
_REAL_POPEN = subprocess.Popen
@pytest.fixture
def vulkan_probe(monkeypatch):
"""Vulkan build, discrete GPU and iGPU; any ROCm arch helper call means the gate ran off-ROCm."""
def _explode(*_args, **_kwargs):
raise AssertionError("ROCm arch gate consulted on a Vulkan build")
monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _b = None: True))
monkeypatch.setattr(
LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/fake/llama-server")
)
monkeypatch.setattr(
LlamaCppBackend,
"_run_vulkan_probe",
staticmethod(
lambda _b = None: [
{
"index": 0,
"free_mib": 12049,
"is_igpu": False,
"total_mib": 16384,
"name": "RX 7800 XT",
},
{
"index": 1,
"free_mib": 12176,
"is_igpu": True,
"total_mib": 65536,
"name": "Radeon Graphics",
},
]
),
)
monkeypatch.setattr(LlamaCppBackend, "_installed_llama_gfx_archs", staticmethod(_explode))
monkeypatch.setattr(LlamaCppBackend, "_rocm_arch_by_physical_id", staticmethod(_explode))
monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(_explode))
class TestGateIsInertOnVulkanBuilds:
"""The Vulkan branch returns before ``for_llama_server`` is read, so the three
unfiltered call sites are unaffected by the flag they do not pass. Verified
rather than assumed, since the case for leaving them unfiltered rests on it."""
def test_flag_changes_nothing_on_a_vulkan_build(self, vulkan_probe):
gated = LlamaCppBackend._get_gpu_memory("/fake/llama-server", for_llama_server = True)
plain = LlamaCppBackend._get_gpu_memory("/fake/llama-server")
assert gated == plain
# Real rows, not two empty lists agreeing.
assert [row[0] for row in plain] == [0, 1]
def test_free_memory_wrapper_is_inert_too(self, vulkan_probe):
assert LlamaCppBackend._get_gpu_free_memory(
"/fake/llama-server", for_llama_server = True
) == LlamaCppBackend._get_gpu_free_memory("/fake/llama-server")
def test_vulkan_ordinal_preflight_sees_every_ordinal(self, vulkan_probe):
# The preflight issubset check must still see the iGPU ordinal, or an explicit pin on it 400s.
assert {g[0] for g in LlamaCppBackend._get_gpu_memory("/fake/llama-server")} == {0, 1}
def _write_gguf(path: Path, architecture: str = "llama") -> Path:
def string(value: str) -> bytes:
data = value.encode()
return struct.pack("<Q", len(data)) + data
metadata = string("general.architecture") + struct.pack("<I", 8) + string(architecture)
path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)
return path
def _backend(
tmp_path: Path,
memory,
*,
gated_out = frozenset(),
):
"""Placement harness whose GPU probe HONORS ``for_llama_server``. ``gated_out``
stands in for devices absent from mapped_targets, so the test sees the gate's real
consequence for placement. Calls are recorded in ``backend._probe_calls``."""
backend = LlamaCppBackend()
calls: list[bool] = []
backend._probe_calls = calls
def _probe(_binary = None, *, for_llama_server = False):
calls.append(for_llama_server)
rows = list(memory)
if for_llama_server:
rows = [row for row in rows if row[0] not in gated_out]
return rows
backend._get_gpu_memory = _probe
backend._get_gpu_free_memory = lambda _binary = None, **kw: [
(index, free) for index, free, _total in _probe(_binary, **kw)
]
backend._read_gguf_metadata = lambda _path: None
backend._can_estimate_kv = lambda: False
backend._get_gguf_size_bytes = lambda _path: 1024
backend._mmproj_vram_bytes = lambda _path: 0
backend._resolve_launch_mmproj_path = lambda **kwargs: None
backend._apu_ram_shortfall_message = lambda *args, **kwargs: None
backend._amd_apu_wants_unified_memory = lambda *args, **kwargs: False
backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"
backend._is_vulkan_backend = lambda _binary = None: False
backend._wait_for_health = lambda timeout, **_kw: True
backend._detect_audio_type_strict = lambda: None
backend._apply_detected_audio = lambda _detected: True
return backend, _write_gguf(tmp_path / "model.gguf")
def _launch(backend, gguf, **load_kwargs):
captured: dict = {}
def fake_popen(cmd, **kwargs):
if not cmd or str(cmd[0]) != "/fake/llama-server":
return _REAL_POPEN(cmd, **kwargs)
captured["cmd"] = list(cmd)
captured["env"] = kwargs.get("env") or dict(os.environ)
return type(
"Process",
(),
{
"pid": 123,
"stdout": (),
"poll": lambda self: None,
"terminate": lambda self: None,
"wait": lambda self, timeout = None: 0,
"kill": lambda self: None,
},
)()
with patch.object(subprocess, "Popen", side_effect = fake_popen):
assert backend.load_model(
GgufLoadIntent(gguf_path = str(gguf), model_identifier = "test", **load_kwargs)
)
return captured
class TestPlacementOptsInForAutoOnly:
"""``for_llama_server = not gpu_ids`` at the placement probe."""
def test_automatic_placement_opts_in(self, tmp_path):
backend, gguf = _backend(tmp_path, [(0, 12049, 16384), (1, 40000, 65536)])
_launch(backend, gguf)
assert backend._probe_calls, "placement never probed the GPUs"
assert any(backend._probe_calls), "automatic placement did not opt into the arch gate"
def test_explicit_pin_does_not_opt_in(self, tmp_path):
backend, gguf = _backend(tmp_path, [(0, 12049, 16384), (1, 40000, 65536)])
_launch(backend, gguf, gpu_ids = [1])
assert backend._probe_calls, "placement never probed the GPUs"
assert not any(backend._probe_calls), "an explicit pin was silently arch-gated"
def test_explicit_pin_on_an_uncovered_gpu_still_reaches_that_gpu(self, tmp_path):
# An explicit pin on an uncovered GPU is honoured so llama-server reports the bad card itself.
backend, gguf = _backend(
tmp_path, [(0, 12049, 16384), (1, 40000, 65536)], gated_out = frozenset({1})
)
captured = _launch(backend, gguf, gpu_ids = [1])
env = captured["env"]
assert env.get("HIP_VISIBLE_DEVICES") == "1" or env.get("CUDA_VISIBLE_DEVICES") == "1", (
f"explicit pin on the uncovered GPU did not reach the child: "
f"HIP={env.get('HIP_VISIBLE_DEVICES')!r} CUDA={env.get('CUDA_VISIBLE_DEVICES')!r}"
)
def test_automatic_placement_avoids_the_uncovered_gpu(self, tmp_path):
# The uncovered device has more free memory and would win the rank; auto placement must pick GPU 0.
backend, gguf = _backend(
tmp_path, [(0, 12049, 16384), (1, 40000, 65536)], gated_out = frozenset({1})
)
captured = _launch(backend, gguf)
env = captured["env"]
pinned = env.get("HIP_VISIBLE_DEVICES") or env.get("CUDA_VISIBLE_DEVICES")
assert pinned is None or "1" not in pinned.split(
","
), f"automatic placement selected the uncovered GPU: {pinned!r}"
class TestWaitForVramSettleStaysUnfiltered:
"""The VRAM settle poll must not read the marker per sample or narrow its device list."""
def test_probe_is_never_gated(self, monkeypatch):
import time as _time
seen: list[dict] = []
def _probe(binary = None, **kwargs):
seen.append(dict(kwargs))
return [(0, 12049)]
monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(_probe))
LlamaCppBackend._wait_for_vram_settle(
max_wait = 0.05, interval = 0.01, since_kill = _time.monotonic()
)
assert seen, "the settle poll never probed"
assert all(
not call.get("for_llama_server", False) for call in seen
), f"the settle poll opted into the arch gate: {seen}"
class TestRagAutoStaysUnfiltered:
"""``core/rag/embeddings.py::_resolve_auto`` picks between sentence-transformers
(PyTorch) and llama-server. The PyTorch winner runs on devices the prebuilt knows
nothing about, so gating this probe would push bulk indexing to the CPU."""
def test_resolve_auto_never_gates(self, monkeypatch):
from core.rag import embeddings
seen: list[dict] = []
def _probe(binary = None, **kwargs):
seen.append(dict(kwargs))
return [(0, 12049)]
monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(_probe))
assert embeddings._resolve_auto() == "sentence-transformers"
assert seen, "_resolve_auto never probed"
assert all(
not call.get("for_llama_server", False) for call in seen
), f"_resolve_auto opted into the arch gate: {seen}"
class TestEmbedLlamaServerOptsIn:
"""The GGUF embedding backend is llama-server itself, so it is the one RAG probe to gate."""
def test_gpu_available_opts_in(self, monkeypatch):
import utils.hardware as uh
from core.rag.embed_llama_server import LlamaServerBackend
monkeypatch.setattr(uh, "is_apple_silicon", lambda: False)
seen: list[dict] = []
def _probe(binary = None, **kwargs):
seen.append(dict(kwargs))
return [(0, 12049)]
monkeypatch.setattr(LlamaCppBackend, "_get_gpu_free_memory", staticmethod(_probe))
assert LlamaServerBackend._gpu_available() is True
assert seen and all(
call.get("for_llama_server") is True for call in seen
), f"the embedding llama-server probe was not gated: {seen}"
def _unified(monkeypatch, ids):
monkeypatch.setattr(
LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set(ids))
)
class TestArchCrashRetryEdgeCases:
"""``_arch_crash_retry_gpu_ids`` decides where a "device kernel image is
invalid" crash respawns. Every answer it gives must be a strict improvement
on the set that just crashed, or empty."""
def test_none_inputs(self):
assert LlamaCppBackend._arch_crash_retry_gpu_ids(None, None) == []
assert LlamaCppBackend._arch_crash_retry_gpu_ids(None, [0, 1]) == []
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], None) == []
def test_empty_enumeration_with_a_multi_gpu_selection(self, monkeypatch):
_unified(monkeypatch, {1})
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], []) == [0]
def test_duplicates_collapse(self, monkeypatch):
_unified(monkeypatch, {0})
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 0, 1, 1], [0, 0, 1, 1]) == [1]
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 0], [0, 0, 1, 1, 2]) == [1, 2]
def test_selected_ids_absent_from_the_enumeration(self, monkeypatch):
_unified(monkeypatch, set())
assert LlamaCppBackend._arch_crash_retry_gpu_ids([5], [0, 1]) == [0, 1]
_unified(monkeypatch, {7})
assert LlamaCppBackend._arch_crash_retry_gpu_ids([7, 8], [7]) == [8]
def test_single_gpu_host_never_probes_and_never_retries(self, monkeypatch):
# The narrowing branch swallows exceptions into [], so count calls instead of raising.
calls: list[int] = []
def _counting():
calls.append(1)
return set()
monkeypatch.setattr(
LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(_counting)
)
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0]) == []
assert LlamaCppBackend._arch_crash_retry_gpu_ids([3], [3]) == []
assert calls == [], "a single-GPU host enumerated devices it cannot use"
def test_all_devices_unified(self, monkeypatch):
_unified(monkeypatch, {0, 1, 2})
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1, 2], [0, 1, 2]) == []
def test_no_device_unified(self, monkeypatch):
_unified(monkeypatch, set())
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1, 2], [0, 1, 2]) == []
def test_retry_set_never_contains_a_device_that_just_crashed_alone(self, monkeypatch):
_unified(monkeypatch, {0})
selected = [0, 1, 2]
out = LlamaCppBackend._arch_crash_retry_gpu_ids(selected, selected)
assert out == [1, 2]
assert set(out) < set(selected)
@pytest.mark.parametrize(
"selected,enumerated,unified",
[
([0], [0], set()),
([0], [0, 1], set()),
([0, 1], [0, 1], {0}),
([0, 1], [0, 1], set()),
([0, 1], [0, 1], {0, 1}),
([0, 1, 2], [0, 1, 2, 3], {0}),
([5], [0, 1], {0}),
([0, 1], [], {1}),
],
)
def test_every_answer_differs_from_the_set_that_crashed(
self, selected, enumerated, unified, monkeypatch
):
"""The retry never respawns the crashed launch: a different device set, or nothing."""
_unified(monkeypatch, unified)
out = LlamaCppBackend._arch_crash_retry_gpu_ids(selected, enumerated)
assert not out or set(out) != set(
selected
), f"retry would respawn the identical selection {sorted(set(selected))}"
def test_the_decision_is_stateless_and_so_must_not_be_looped(self, monkeypatch):
"""Retry mapping is stateless and swaps 0 and 1, so it must be applied exactly once."""
_unified(monkeypatch, set())
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0, 1]) == [1]
assert LlamaCppBackend._arch_crash_retry_gpu_ids([1], [0, 1]) == [0]
class TestKernelImageInvalidDoesNotFalsePositive:
"""A false marker match would move an unrelated failure onto a different card on respawn."""
@pytest.mark.parametrize(
"output",
[
"ggml_cuda_compute_forward: RMS_NORM failed\nCUDA error: invalid argument",
"load_model: error loading model: invalid model file magic",
"llama_model_load: error loading model: check_tensor_dims: tensor "
"'blk.0.attn_q.weight' has wrong shape",
"ggml-cuda.cu: kernel launch failed",
"error: invalid value for --n-gpu-layers",
"ROCm error: out of memory",
"warning: the kernel module amdgpu is out of date",
"load_model: error loading model: invalid model file magic",
"error: invalid device id 3",
"srv load_model: the image is invalid",
"device kernel image is valid",
"common_init_from_params: failed to load model 'x.gguf'",
],
)
def test_unrelated_output_does_not_match(self, output):
assert not LlamaCppBackend._kernel_image_invalid(output)
@pytest.mark.parametrize(
"output",
[
"ROCm error: device kernel image is invalid",
"ggml-cuda.cu:76: ROCm error\n device kernel image is invalid\n current device: 1",
"DEVICE KERNEL IMAGE IS INVALID".lower(),
# hipErrorNoBinaryForGpu: HIP's other code for this mismatch; some builds raise it.
"ROCm error: no kernel image is available for execution on the device",
"ggml-cuda.cu:76: ROCm error\n"
" no kernel image is available for execution on the device\n"
" current device: 1",
# Raised at backend init via another format string, so match the message, not the prefix.
"ggml_cuda_init: failed to initialize ROCm: "
"no kernel image is available for execution on the device",
# cudaErrorNoKernelImageForDevice: the retry is not ROCm-gated, so NVIDIA recovers too.
"CUDA error: no kernel image is available for execution on the device",
# hipErrorInvalidKernelFile / InvalidDeviceFunction come from the same fat-binary load.
"ROCm error: invalid kernel file",
"hipErrorInvalidDeviceFunction: invalid device function",
"ggml-cuda.cu:76: ROCm error\n invalid device function\n current device: 1",
# cudaErrorInvalidDeviceFunction: the NVIDIA spelling of the HIP code above.
"CUDA error: invalid device function",
],
)
def test_the_real_crash_matches(self, output):
assert LlamaCppBackend._kernel_image_invalid(output)
@pytest.mark.parametrize(
"output",
[
"Device Kernel Image Is Invalid",
"ROCm error: DEVICE KERNEL IMAGE IS INVALID",
"No kernel image is available for execution on the device",
"ROCM ERROR: NO KERNEL IMAGE IS AVAILABLE FOR EXECUTION ON THE DEVICE",
"ROCm error: Invalid Kernel File",
"CUDA ERROR: INVALID DEVICE FUNCTION",
],
)
def test_matching_is_case_insensitive(self, output):
# Reprinting layers vary case; the markers are specific enough that folding case is safe.
assert LlamaCppBackend._kernel_image_invalid(output)
def test_non_string_input_is_not_a_match(self):
assert not LlamaCppBackend._kernel_image_invalid(None)
assert not LlamaCppBackend._kernel_image_invalid("")
class TestArchCrashRetryFiresAtMostOnce:
"""Recovery is one straight-line if, not a loop; this pins a refactor into a retry loop."""
def test_source_has_a_single_archfallback_spawn(self):
source = Path(LlamaCppBackend.__module__.replace(".", "/"))
path = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
assert path.exists(), source
text = path.read_text(encoding = "utf-8")
assert text.count('label = "-archfallback"') == 1
assert text.count("_arch_crash_retry_gpu_ids(") == 2
def test_a_second_pass_over_the_same_state_yields_nothing(self, monkeypatch):
_unified(monkeypatch, {0})
first = LlamaCppBackend._arch_crash_retry_gpu_ids([0, 1], [0, 1])
assert first == [1]
assert LlamaCppBackend._arch_crash_retry_gpu_ids(first, [0, 1]) == [0]
assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0]) == []
class TestArchRetryDropsTensorSplit:
"""``--tensor-split`` weights are positional over the child's VISIBLE devices, so
the retry masking one out re-indexes the survivors and the crashed set's shares
land on the wrong cards. The retry drops the flag."""
def test_the_two_token_form_goes_with_its_value(self):
cmd = ["llama-server", "-m", "x.gguf", "--tensor-split", "10,20,30", "-ngl", "-1"]
assert LlamaCppBackend._without_tensor_split(cmd) == [
"llama-server",
"-m",
"x.gguf",
"-ngl",
"-1",
]
def test_the_short_and_equals_forms_go_too(self):
assert LlamaCppBackend._without_tensor_split(["s", "-ts", "1,2", "-ngl", "-1"]) == [
"s",
"-ngl",
"-1",
]
# An '=' form carries its value, so the next token (-ngl) must not be skipped.
assert LlamaCppBackend._without_tensor_split(["s", "--tensor-split=1,2", "-ngl"]) == [
"s",
"-ngl",
]
# llama.cpp normalises long-option underscores; _flag_name mirrors it.
assert LlamaCppBackend._without_tensor_split(["s", "--tensor_split", "1,2"]) == ["s"]
def test_a_command_without_a_split_reports_nothing_to_do(self):
cmd = ["llama-server", "-m", "x.gguf", "--split-mode", "tensor", "-ngl", "-1"]
assert LlamaCppBackend._without_tensor_split(cmd) is None
# Known limitation: a value spelled like -ts/--split-mode is removed as a flag; unreachable from
# Unsloth-built argv, so flag arities are not modelled.
assert LlamaCppBackend._without_tensor_split(["s", "--alias", "-ts"]) == ["s", "--alias"]
def test_only_the_split_is_removed(self):
cmd = [
"llama-server",
"-m",
"x.gguf",
"--split-mode",
"tensor",
"--tensor-split",
"10,20,30",
"--flash-attn",
"on",
"-ngl",
"-1",
]
out = LlamaCppBackend._without_tensor_split(cmd)
assert "--tensor-split" not in out and "10,20,30" not in out
assert out == [
"llama-server",
"-m",
"x.gguf",
"--split-mode",
"tensor",
"--flash-attn",
"on",
"-ngl",
"-1",
]
def test_the_retry_call_site_drops_it_before_respawning(self):
# The respawn has no test seam, so pin at source that the drop sits between narrowing and respawn.
path = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
text = path.read_text(encoding = "utf-8")
# Arch-crash retry and the gated manual-split launch both mask devices under a positional ratio.
assert text.count("self._without_tensor_split(") == 2
block = text.split("self._kernel_image_invalid(_arch_crash_tail)")[1]
block = block.split('label = "-archfallback"')[0]
assert "_without_tensor_split(cmd)" in block
assert "self._tensor_split = None" in block # /status must not report a dropped split
_MANUAL_SPLIT_CRASH = (
"ROCm error: invalid kernel file\n"
" current device: 1, in function ggml_cuda_kernel_launch at common.cuh:1740"
)
def _load_manual_split(
monkeypatch,
tmp_path,
*,
outputs,
returncodes,
env = None,
extra_args = None,
):
"""load_model in manual mode over two ROCm GPUs, each spawn answering from the lists."""
for name in (
"HIP_VISIBLE_DEVICES",
"ROCR_VISIBLE_DEVICES",
"CUDA_VISIBLE_DEVICES",
"GPU_DEVICE_ORDINAL",
"LLAMA_ARG_DEVICE",
"LLAMA_ARG_MAIN_GPU",
):
monkeypatch.delenv(name, raising = False)
for name, value in (env or {}).items():
monkeypatch.setenv(name, value)
monkeypatch.setattr(llama_cpp.sys, "platform", "linux")
def _s(value):
return struct.pack("<Q", len(value)) + value.encode()
gguf = tmp_path / "model.gguf"
gguf.write_bytes(
struct.pack("<IIQQ", 0x46554747, 3, 0, 1)
+ _s("general.architecture")
+ struct.pack("<I", 8)
+ _s("llama")
)
gib16 = 16 * 1024**3
backend = LlamaCppBackend()
backend._get_gpu_memory = lambda _b = None, **_k: [(0, gib16, gib16), (1, gib16, gib16)]
backend._get_gpu_free_memory = lambda _b = None, **_k: [(0, gib16), (1, gib16)]
backend._effective_gpu_count = lambda *_a, **_k: 2
backend._read_gguf_metadata = lambda _p: None
backend._can_estimate_kv = lambda: False
backend._get_gguf_size_bytes = lambda _p: 1024
backend._mmproj_vram_bytes = lambda _p: 0
backend._resolve_launch_mmproj_path = lambda **_k: None
backend._apu_ram_shortfall_message = lambda *_a, **_k: None
backend._amd_apu_wants_unified_memory = lambda *_a, **_k: False
backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"
backend.probe_server_capabilities = lambda _b: {"found": True}
backend._record_server_pid = lambda _p: None
backend._clear_server_pid = lambda: None
backend._llama_server_env_for_binary = lambda _b, **_k: dict(os.environ)
backend._prepare_cpu_fallback_launch = lambda *_a, **_k: None
monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))
monkeypatch.setattr(
LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())
)
monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _b = None: False))
monkeypatch.setattr(LlamaCppBackend, "_bundle_only_rocm_dirs", {})
monkeypatch.setattr(llama_cpp, "_swa_cache_path", lambda: tmp_path / "swa.json")
launches = []
class _Process:
pid = 123
stdout = ()
def __init__(self, returncode):
self.returncode = returncode
def poll(self):
return self.returncode
def terminate(self):
return None
def wait(self, timeout = None):
return self.returncode
def kill(self):
return None
real_popen = subprocess.Popen
def _popen(cmd, **kwargs):
if not cmd or str(cmd[0]) != "/fake/llama-server":
return real_popen(cmd, **kwargs)
launches.append((list(cmd), dict(kwargs["env"])))
return _Process(returncodes[min(len(launches), len(returncodes)) - 1])
def _wait_for_health(timeout = 600.0, **_k):
backend._stdout_lines = outputs[min(len(launches), len(outputs)) - 1].splitlines()
return returncodes[min(len(launches), len(returncodes)) - 1] is None
backend._wait_for_health = _wait_for_health
monkeypatch.setattr(subprocess, "Popen", _popen)
try:
loaded = backend.load_model(
GgufLoadIntent(
gguf_path = str(gguf),
model_identifier = "owner/model",
gpu_memory_mode = "manual",
gpu_layers = 999,
tensor_split = (1.0, 1.0),
extra_args = extra_args,
)
)
except RuntimeError:
loaded = False
return backend, launches, loaded
def _tensor_split_arg(cmd):
return cmd[cmd.index("--tensor-split") + 1] if "--tensor-split" in cmd else None
class TestUnpinnedArchCrashRetryLoad:
"""A manual split launches unpinned; the arch-crash retry must still narrow it."""
def test_the_crashed_card_is_dropped_and_the_load_recovers(self, monkeypatch, tmp_path):
backend, launches, loaded = _load_manual_split(
monkeypatch, tmp_path, outputs = [_MANUAL_SPLIT_CRASH, ""], returncodes = [1, None]
)
assert loaded
assert len(launches) == 2
assert _tensor_split_arg(launches[0][0]) == "1,1"
retry_cmd, retry_env = launches[1]
assert _tensor_split_arg(retry_cmd) is None
assert retry_env["CUDA_VISIBLE_DEVICES"] == "0"
assert backend._arch_gate_dropped_tensor_split == (1.0, 1.0)
def test_a_companion_device_on_the_survivor_is_renumbered(self, monkeypatch, tmp_path):
crash_on_0 = _MANUAL_SPLIT_CRASH.replace("current device: 1", "current device: 0")
_backend, launches, loaded = _load_manual_split(
monkeypatch,
tmp_path,
outputs = [crash_on_0, ""],
returncodes = [1, None],
extra_args = ["--spec-draft-device", "ROCm1"],
)
assert loaded
retry_cmd, retry_env = launches[1]
assert retry_env.get("ROCR_VISIBLE_DEVICES", retry_env["CUDA_VISIBLE_DEVICES"]) == "1"
assert retry_cmd[retry_cmd.index("--spec-draft-device") + 1] == "ROCm0"
@pytest.mark.parametrize("env", [{"LLAMA_ARG_MAIN_GPU": "1"}, {"MTMD_BACKEND_DEVICE": "ROCm1"}])
def test_a_user_device_env_keeps_its_error(self, monkeypatch, tmp_path, env):
_backend, launches, loaded = _load_manual_split(
monkeypatch,
tmp_path,
outputs = [_MANUAL_SPLIT_CRASH],
returncodes = [1],
env = env,
)
assert not loaded
assert all(_tensor_split_arg(cmd) == "1,1" for cmd, _env in launches)
class TestArchRetryRestoresTheMemoryPolicy:
"""Arch-crash respawn starts from cmd, so the --fit page-lock the retry added must be restored."""
@staticmethod
def _source():
path = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
return path.read_text(encoding = "utf-8")
def test_the_launch_snapshots_what_cmd_means(self):
text = self._source()
# Snapshot at launch: re-probing survivors would mark an APU mlock-applicable against a lock-free argv.
assert "def _snapshot_policy_for_cmd():" in text
assert "_mem_policy_for_cmd = _snapshot_policy_for_cmd()" in text
_body = text.split("def _snapshot_policy_for_cmd():")[1].split("return (")[1]
_members = []
for _line in _body.splitlines():
if _line.strip() == ")":
break
if _line.strip():
_members.append(_line.strip().rstrip(","))
_snap = _members
assert _snap == [
"_mem_host_resident",
"self._memory_state",
# A stale DirectIO bit beside a restored one is the drift the snapshot prevents.
"self._memory_direct_io",
# A rung stripping a copy clears it while `cmd` still owes DirectIO.
"self._memory_dio_applicable",
# Copied so a later strip cannot reach the snapshot.
"list(self._memory_dio_flags)",
"self._memory_policy_active",
"self._memory_mlock_applicable",
]
def test_the_retry_call_site_restores_it_before_respawning(self):
text = self._source()
block = text.split("_arch_crash_retry_gpu_ids(\n")[-1].split('label = "-archfallback"')[0]
assert "= _mem_policy_for_cmd" in block
_restored = [
_line.strip().rstrip(",")
for _line in block.split(") = _mem_policy_for_cmd")[0].split("(")[-1].splitlines()
if _line.strip()
]
# Exact names in snapshot order: a tuple unpack can't report a mismatch. _mem_host_resident is needed
# or the respawn's --fit retry sees the crashed launch's lock as held.
assert _restored == [
"_mem_host_resident",
"self._memory_state",
"self._memory_direct_io",
"self._memory_dio_applicable",
"self._memory_dio_flags",
"self._memory_policy_active",
"self._memory_mlock_applicable",
]
class TestEmbedLlamaServerPinsTheGatedGpus:
"""The child enumerates every ROCm agent, so the survivors must reach its launch env."""
@staticmethod
def _probes(
monkeypatch,
*,
gated,
everything,
archs = frozenset({"gfx1030"}),
):
"""Stub a ROCm host, the gate marker, and both probes. Returns the
per-call kwargs seen, so a test can COUNT calls -- raising inside a spy
here would be swallowed by the caller's ``except Exception``."""
seen: list[dict] = []
def _probe(binary = None, *, for_llama_server = False):
seen.append({"binary": binary, "for_llama_server": for_llama_server})
rows = gated if for_llama_server else everything
return [(idx, free, 0) for idx, free in rows]
monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))
monkeypatch.setattr(
LlamaCppBackend, "_installed_llama_gfx_archs", staticmethod(lambda _b = None: archs)
)
monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_probe))
return seen
def test_a_narrowing_gate_yields_the_surviving_ids(self, monkeypatch):
self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
from core.rag.embed_llama_server import LlamaServerBackend
assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == [1]
def test_full_coverage_needs_no_mask(self, monkeypatch):
self._probes(
monkeypatch, gated = [(0, 60000), (1, 24000)], everything = [(0, 60000), (1, 24000)]
)
from core.rag.embed_llama_server import LlamaServerBackend
assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []
def test_unknown_coverage_fails_open_without_probing(self, monkeypatch):
# NVIDIA, CPU, Vulkan and macOS have no marker; the marker check must short-circuit both probes.
seen = self._probes(
monkeypatch, gated = [(1, 24000)], everything = [(0, 1), (1, 24000)], archs = None
)
from core.rag.embed_llama_server import LlamaServerBackend
assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []
assert seen == [], f"the GPU probe ran despite unknown arch coverage: {seen}"
def test_a_non_rocm_host_never_probes(self, monkeypatch):
seen = self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 1), (1, 24000)])
monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: False))
from core.rag.embed_llama_server import LlamaServerBackend
assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []
assert seen == [], f"a non-ROCm host paid for the gate probes: {seen}"
def test_a_probe_failure_never_blocks_the_spawn(self, monkeypatch):
monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))
monkeypatch.setattr(
LlamaCppBackend,
"_installed_llama_gfx_archs",
staticmethod(lambda _b = None: (_ for _ in ()).throw(RuntimeError("marker"))),
)
from core.rag.embed_llama_server import LlamaServerBackend
assert LlamaServerBackend._arch_gated_gpu_ids("/fake/llama-server") == []
@staticmethod
def _spy_visibility(monkeypatch):
calls: list[tuple] = []
monkeypatch.setattr(
LlamaCppBackend,
"_emit_child_gpu_visibility",
staticmethod(lambda env, pinned, **kw: calls.append((pinned, kw))),
)
return calls
def test_the_launch_env_masks_the_child_to_them(self, monkeypatch):
self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
calls = self._spy_visibility(monkeypatch)
from core.rag.embed_llama_server import LlamaServerBackend
env = LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = True)
# prefer_rocr: a HIP-only mask still lets HSA enumerate the unsupported agent and segfault.
assert calls == [("1", {"prefer_rocr": True})], calls
assert env.get("CUDA_VISIBLE_DEVICES") != "" # the CPU sentinel, not this path
def test_an_ungated_host_leaves_the_env_alone(self, monkeypatch):
self._probes(
monkeypatch, gated = [(0, 60000), (1, 24000)], everything = [(0, 60000), (1, 24000)]
)
calls = self._spy_visibility(monkeypatch)
from core.rag.embed_llama_server import LlamaServerBackend
LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = True)
assert calls == [], f"an unnarrowed host was masked anyway: {calls}"
def test_a_uuid_mask_leaves_the_inherited_mask_in_place(self, monkeypatch):
"""A UUID ROCR mask must stay in place; pinning torch ordinals would expose cards the parent hid."""
self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
calls = self._spy_visibility(monkeypatch)
# torch must be importable: _active_gpu_visibility_mask reads the ROCr mask only inside `import torch`.
monkeypatch.setitem(sys.modules, "torch", types.SimpleNamespace())
monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda _t: True))
monkeypatch.setattr(sys, "platform", "linux")
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "GPU-DEADBEEFDEADBEEF")
from core.rag.embed_llama_server import LlamaServerBackend
env = LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = True)
assert calls == [], f"an unmappable mask was rewritten with ordinals: {calls}"
assert env["ROCR_VISIBLE_DEVICES"] == "GPU-DEADBEEFDEADBEEF"
def test_the_cpu_path_hides_devices_at_both_layers(self, monkeypatch):
"""CPU on ROCm must blank HIP_VISIBLE_DEVICES too; HIP ignores CUDA_VISIBLE_DEVICES when it
is set."""
self._probes(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
calls = self._spy_visibility(monkeypatch)
monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "0")
from core.rag.embed_llama_server import LlamaServerBackend
env = LlamaServerBackend()._build_env("/fake/llama-server", use_gpu = False)
assert calls == []
assert env["CUDA_VISIBLE_DEVICES"] == ""
assert env["HIP_VISIBLE_DEVICES"] == "-1"
# ROCR hides agents below HIP; clearing it would expose the uncovered arch.
assert env["ROCR_VISIBLE_DEVICES"] == "0"
class TestTheGateNeverRewritesAnUnmappableMask:
"""ROCr/CUDA UUID and MIG tokens resolve to no physical id, so ordinals rank but the pin fails open."""
@staticmethod
def _rocm_host(monkeypatch, *, gated, everything):
seen: list[bool] = []
def _probe(binary = None, *, for_llama_server = False):
seen.append(for_llama_server)
rows = gated if for_llama_server else everything
return [(idx, free, 0) for idx, free in rows]
monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))
monkeypatch.setattr(
LlamaCppBackend,
"_installed_llama_gfx_archs",
staticmethod(lambda _b = None: frozenset({"gfx1030"})),
)
monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory", staticmethod(_probe))
for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
monkeypatch.delenv(_var, raising = False)
return seen
def test_an_unmappable_mask_stops_the_pin_before_either_probe(self, monkeypatch):
seen = self._rocm_host(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-deadbeefdeadbeef")
assert LlamaCppBackend._arch_gate_survivors("/fake/llama-server") == []
assert seen == [], f"the host paid for the probes it cannot use: {seen}"
def test_an_index_mask_still_narrows(self, monkeypatch):
# Fail open only on 'set but unparseable', not on unset.
self._rocm_host(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")
assert LlamaCppBackend._arch_gate_survivors("/fake/llama-server") == [1]
def test_no_mask_at_all_still_narrows(self, monkeypatch):
self._rocm_host(monkeypatch, gated = [(1, 24000)], everything = [(0, 60000), (1, 24000)])
assert LlamaCppBackend._arch_gate_survivors("/fake/llama-server") == [1]
@pytest.mark.parametrize(
"mask, unmappable",
[
(None, False),
("", False), # empty mask means no devices, not unknown
("0,1", False),
(" 2 ", False),
("GPU-DEADBEEFDEADBEEF", True),
("0,GPU-DEADBEEFDEADBEEF", True), # the mixed form ROCm documents
("MIG-GPU-4a2b/1/0", True),
],
)
def test_which_masks_count_as_unmappable(self, monkeypatch, mask, unmappable):
monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
if mask is None:
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
else:
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", mask)
assert LlamaCppBackend._visibility_mask_is_unmappable() is unmappable
class TestCpuSentinelDropsAnInheritedDevicePick:
"""Masking all devices but keeping an inherited LLAMA_ARG_DEVICE pick makes llama.cpp exit; clear it."""
def test_the_cpu_sentinel_clears_the_pick(self):
env = {"LLAMA_ARG_DEVICE": "HIP0", "LLAMA_ARG_MAIN_GPU": "1", "PATH": "/usr/bin"}
LlamaCppBackend._emit_child_gpu_visibility(env, "-1")
assert "LLAMA_ARG_DEVICE" not in env
assert "LLAMA_ARG_MAIN_GPU" not in env
assert env["CUDA_VISIBLE_DEVICES"] == "-1"
assert env["PATH"] == "/usr/bin"
@pytest.mark.parametrize("pinned", ["0", "1,2", ""])
def test_a_real_pin_keeps_it(self, pinned):
"""Only the CPU sentinel clears the pick; a real inherited selection still resolves."""
env = {"LLAMA_ARG_DEVICE": "HIP0"}
LlamaCppBackend._emit_child_gpu_visibility(env, pinned)
assert env["LLAMA_ARG_DEVICE"] == "HIP0"
def test_the_embedding_cpu_launch_clears_it_too(self, tmp_path, monkeypatch):
from core.rag.embed_llama_server import LlamaServerBackend
monkeypatch.setenv("LLAMA_ARG_DEVICE", "HIP0")
monkeypatch.setenv("LLAMA_ARG_MAIN_GPU", "0")
backend = LlamaServerBackend.__new__(LlamaServerBackend)
env = backend._build_env(str(tmp_path / "llama-server"), use_gpu = False)
assert "LLAMA_ARG_DEVICE" not in env
assert "LLAMA_ARG_MAIN_GPU" not in env
assert env["CUDA_VISIBLE_DEVICES"] == ""
assert env["HIP_VISIBLE_DEVICES"] == "-1"
def test_the_embedding_gpu_launch_keeps_it(self, tmp_path, monkeypatch):
from core.rag.embed_llama_server import LlamaServerBackend
monkeypatch.setenv("LLAMA_ARG_DEVICE", "HIP0")
monkeypatch.setattr(
LlamaCppBackend, "_arch_gate_survivors", staticmethod(lambda _b = None: [])
)
backend = LlamaServerBackend.__new__(LlamaServerBackend)
env = backend._build_env(str(tmp_path / "llama-server"), use_gpu = True)
assert env["LLAMA_ARG_DEVICE"] == "HIP0"
class TestArchForcedCpuHoldsNoVram:
"""Arch-gated launches are zero-VRAM; without holds_no_vram the CPU server keeps the CHAT claim."""
def _backend(self):
backend = LlamaCppBackend()
backend._gpu_memory_mode = "auto"
backend._gpu_layers = -1
backend._gpu_offload_active = False
return backend
def test_an_automatic_arch_gated_launch_holds_no_vram(self):
backend = self._backend()
assert backend.holds_no_vram is False, "precondition: auto mode alone is not zero-VRAM"
backend._arch_gate_forced_cpu = True
assert backend.holds_no_vram is True
def test_the_manual_zero_offload_rule_is_unchanged(self):
backend = LlamaCppBackend()
backend._gpu_memory_mode = "manual"
backend._gpu_layers = 0
backend._gpu_offload_active = False
assert backend.holds_no_vram is True
backend._gpu_offload_active = True
assert backend.holds_no_vram is False
backend._gpu_offload_active = None
assert backend.holds_no_vram is False
def test_an_ordinary_gpu_load_still_holds_vram(self):
backend = self._backend()
backend._gpu_offload_active = True
assert backend.holds_no_vram is False
class _StubProcess:
"""``is_loaded`` only asks "is not None"; nothing here is ever spawned."""
def terminate(self):
pass
def wait(self, timeout = None):
return 0
def kill(self):
pass
def poll(self):
return 0
_GATED_REQUEST = dict(
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
gpu_memory_mode = "manual",
gpu_layers = 99,
tensor_split = (0.5, 0.5),
)
def _post_gate_backend(dropped, *, live_split = None):
"""The gate drops the manual split: _tensor_split is None and the drop is recorded."""
backend = LlamaCppBackend()
backend._process = _StubProcess()
backend._healthy = True
backend._model_identifier = "owner/repo"
backend._hf_variant = "Q4_K_M"
backend._requested_n_ctx = 8192
backend._requested_n_parallel = 1
backend._requested_spec_mode = "auto"
backend._gpu_memory_mode = "manual"
backend._gpu_layers = 99
backend._tensor_split = live_split
backend._arch_gate_dropped_tensor_split = dropped
return backend
class TestGatedSplitStillDeduplicates:
"""The gate drops a ratio the UI re-sends on every Apply, so without the recorded
drop each identical request reads as new and reloads a multi-GB model, forever."""
def test_identical_repeat_request_matches(self):
backend = _post_gate_backend((0.5, 0.5))
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**_GATED_REQUEST)) is True
def test_a_different_ratio_still_reloads(self):
"""The excuse is for the ratio that was dropped, not for any ratio."""
backend = _post_gate_backend((0.5, 0.5))
changed = dict(_GATED_REQUEST, tensor_split = (0.9, 0.1))
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**changed)) is False
def test_a_launch_that_dropped_nothing_records_nothing(self):
"""No recorded drop means no excuse: an unsplit live server must reload for a split."""
backend = _post_gate_backend(None)
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**_GATED_REQUEST)) is False
def test_no_drop_never_excuses_a_live_split(self):
"""Both sides None must not read as "the gate dropped this": a server
RUNNING a ratio has to reload for a request that asks for none."""
backend = _post_gate_backend(None, live_split = [0.5, 0.5])
no_split = dict(_GATED_REQUEST, tensor_split = None)
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**no_split)) is False
class TestGatedTensorModeStillDeduplicates:
"""Same rule for split MODE: without the record, an identical Apply reloads the model."""
def _backend(self, dropped_mode):
backend = _post_gate_backend((0.5, 0.5))
backend._tensor_parallel = False # normalized away at launch
backend._arch_gate_dropped_tensor_parallel = dropped_mode
return backend
def test_identical_repeat_request_matches(self):
request = dict(_GATED_REQUEST, tensor_parallel = True)
backend = self._backend(True)
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**request)) is True
def test_a_launch_that_dropped_nothing_still_reloads(self):
"""No drop recorded, no excuse: a layer server must reload for tensor parallelism."""
request = dict(_GATED_REQUEST, tensor_parallel = True)
backend = self._backend(False)
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**request)) is False
def test_the_excuse_never_runs_the_other_way(self):
"""One direction only. A server RUNNING tensor parallelism must still reload
for a request that asks for none, whatever an earlier launch recorded."""
backend = self._backend(True)
backend._tensor_parallel = True
request = dict(_GATED_REQUEST, tensor_parallel = False)
assert backend.adopt_load_intent_if_matched(GgufLoadIntent(**request)) is False
class TestArchRetryAsksResidencyTheSameWayTheLaunchDid:
"""Arch retry must ask residency as the launch does, or it re-records a contradicting placement."""
def _load_model_source(self):
import inspect
from core.inference.llama_cpp import LlamaCppBackend
return inspect.getsource(LlamaCppBackend.load_model)
def test_every_probe_vulkan_gate_admits_the_directio_probe(self):
"""Across all three sites: the defect was that they disagreed."""
gates = [
line.strip()
for line in self._load_model_source().splitlines()
if line.strip().startswith("probe_vulkan = ")
]
assert len(gates) == 3, gates
assert all("_mem_probe_for_dio" in gate for gate in gates), gates
def test_the_residency_arm_records_from_the_argv(self):
"""Residency arm records from argv; rebuilding from parts misses DirectIO flags."""
src = self._load_model_source()
marker = "Arch-crash retry changed where the weights live"
assert marker in src
arm = src[: src.index(marker)]
arm = arm[arm.rindex("_retry_host_resident and not _mem_host_resident") :]
compact = "".join(arm.split())
assert "self._record_memory_state(cmd,env)" in compact
assert "self._record_memory_state(list(_mem_extras)" not in compact