engine: opt-in GPU offload for the decision engine

Let the SemIf decision engine run on a GPU via llama.cpp. SemIf's llamacpp
backend is CPU-only by construction (it hardcodes n_gpu_layers=0), so the
agent wraps `_cpu_model_params` for the duration of the load and restores it
after — no patch to the re-cloned engine source.

- `engine.gpu_layers` / `gpu_device` / `gpu_split` in config (default 0 = CPU).
- On the GPU path, force a full cache reset (`llama_memory_clear(mem, True)`):
  SemIf's metadata-only clear leaves stale hybrid-attention state on Vulkan,
  so repeated scores drift (0.08 -> 0.36 -> 0.43) and return wrong
  probabilities.
- Fail loudly when `gpu_layers` is set but the build has no GPU backend.
- bootstrap.sh: opt-in `--gpu auto|vulkan|rocm|cuda|cpu`. A GPU build is
  opt-in because llama.cpp's Vulkan backend splits the graph across CPU and
  Vulkan even at `n_gpu_layers=0`, roughly halving CPU throughput, so a CPU-only
  host must keep the CPU wheel. Detects the backend, installs the Vulkan build
  prereqs, and rebuilds when offload support disagrees (pip's wheel cache
  otherwise serves the CPU wheel back).
- Bump the SemIf pin 1f2dea3 -> 23cf1f3.
- Tests: unit coverage for the config mapping + loader patches; an integration
  test asserting GPU determinism and CPU parity.
- Offload needs the accelerator to itself (~2.9 GiB for the 4B Q4 model): a GPU
  already holding another model makes the engine slower than CPU and can abort
  with `vk::DeviceLostError`.
This commit is contained in:
gabby committed 2026-10-07 05:21:21 +00:00
1 parent 4e70a5889e
commit 17f16a6bfc
9 files changed
+329 -16

No files matched your search

+50 -1
View File
@@ -25,7 +25,7 @@ from semif_agent.codegen import (
parse_contract,
parse_integration,
)
from semif_agent.decisions import Request
from semif_agent.decisions import DecisionRequest, Option, Request
from semif_agent.dream import dream
from semif_agent.engine import EngineUnavailable, SemIfEngine
from semif_agent.log import DecisionLog
@@ -97,6 +97,55 @@ def _install_tracking_fixture(scheduler):
]
def test_engine_gpu_offload_is_deterministic_and_matches_cpu(tmp_path):
"""With a GPU-backed llama-cpp-python and `engine.gpu_layers` set, offload
must be deterministic across repeated calls and match the CPU path.
Regression: SemIf's `_Engine.clear` resets only cache metadata
(`llama_memory_clear(mem, False)`). The CPU backend tolerates that, but the
Vulkan backend keeps stale hybrid-attention state, so successive `score`
calls drifted (0.08 -> 0.36 -> 0.43). The wrapper clears the data too. This
is the honest correctness check: "it loaded" is not enough on Qwen3.5's
hybrid architecture.
"""
import llama_cpp
config = load_config()
require_real(config)
if not llama_cpp.llama_supports_gpu_offload():
pytest.skip("llama-cpp-python has no GPU backend")
base = build_engine_config(config)
if not base.gpu_layers:
pytest.skip("engine.gpu_layers is 0 (CPU-only); set it to exercise offload")
from dataclasses import replace
request = DecisionRequest(
state=(
"The user said: 'check the weather in Paris tomorrow and tell me if "
"I need an umbrella'."
),
question="Is this input an actionable request, or non-action chatter?",
options=[
Option(id="action", description="An actionable request to perform a task."),
Option(
id="non_action",
description="Chit-chat, a statement, or too vague to act on.",
),
],
)
cpu = SemIfEngine(replace(base, gpu_layers=0)).call(request).probabilities
gpu_engine = SemIfEngine(base)
runs = [gpu_engine.call(request).probabilities for _ in range(3)]
print(f"cpu={cpu} gpu={runs}")
for run in runs[1:]:
assert max(abs(a - b) for a, b in zip(runs[0], run)) < 1e-5, (
"GPU offload must be deterministic across repeated calls"
)
diff = max(abs(a - b) for a, b in zip(cpu, runs[0]))
assert diff < 2e-3, f"GPU offload changed the option probabilities by {diff}"
def test_pipeline_end_to_end(tmp_path):
config = load_config()
require_real(config)
+79
View File
@@ -0,0 +1,79 @@
"""Engine config wiring: the per-machine GPU-offload knobs and the loader patch.
Pure stdlib: no SemIf, no llama.cpp, no GGUF. The SemIf backend is CPU-only by
construction, so the patch that lets it offload is exercised against a fake
backend module.
"""
from __future__ import annotations
from types import SimpleNamespace
from semif_agent.cli import build_engine_config
from semif_agent.engine import (
EngineConfig,
_install_gpu_state_reset,
_offloading_params,
)
PINS = {
"engine": {
"source": "Qwen/Qwen3.5-4B",
"revision": "0" * 40,
"gguf_url": "https://example.com/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
}
}
def test_engine_config_defaults_to_cpu():
cfg = build_engine_config({"engine": {"backend": "llamacpp"}}, PINS)
assert cfg.gpu_layers == 0
assert cfg.gpu_device is None
assert cfg.gpu_split == 0
def test_engine_config_reads_gpu_knobs():
cfg = build_engine_config(
{"engine": {"gpu_layers": -1, "gpu_device": 1, "gpu_split": 0}}, PINS
)
assert cfg.gpu_layers == -1
assert cfg.gpu_device == 1
assert cfg.gpu_split == 0
def test_gpu_offload_wrapper_rewrites_model_params():
def original(library):
return SimpleNamespace(n_gpu_layers=0, main_gpu=0, split_mode=1)
offloading = _offloading_params(
original, EngineConfig(gpu_layers=99, gpu_device=1, gpu_split=0)
)
params = offloading(object())
assert params.n_gpu_layers == 99
assert params.main_gpu == 1
assert params.split_mode == 0
def test_gpu_offload_wrapper_leaves_main_gpu_when_device_unset():
def original(library):
return SimpleNamespace(n_gpu_layers=0, main_gpu=7, split_mode=1)
offloading = _offloading_params(original, EngineConfig(gpu_layers=-1))
params = offloading(object())
assert params.n_gpu_layers == -1
assert params.main_gpu == 7 # untouched
assert params.split_mode == 0
def test_gpu_state_reset_clears_cache_data():
calls = []
class FakeLib:
def llama_memory_clear(self, memory, data):
calls.append((memory, data))
engine = SimpleNamespace(lib=FakeLib(), memory="mem")
engine.clear = lambda: engine.lib.llama_memory_clear(engine.memory, False)
_install_gpu_state_reset(SimpleNamespace(engine=engine))
engine.clear()
assert calls == [("mem", True)]