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

+26 -5
View File
@@ -564,9 +564,21 @@ CLI, unit tests (24) + integration tests (2).
### Environment
- The core is pure stdlib and runs anywhere Python does. Never pip-install heavy
deps on a thin client; a full install belongs on a provisioned host.
- The SemIf engine runs via llama.cpp **CPU** backend (its llamacpp backend
forces `n_gpu_layers=0`), so the decision engine does not use a GPU; ollama
does.
- The SemIf engine runs via llama.cpp. It is **CPU by default**: SemIf's
llamacpp backend hardcodes `n_gpu_layers=0`. Setting `engine.gpu_layers` in
config.json offloads to a GPU when llama-cpp-python was built with a GPU
backend (Vulkan/ROCm/CUDA). The agent wraps the backend's `_cpu_model_params`
so the knob works without patching the re-cloned engine source, and on the GPU
path also forces 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 otherwise. **A GPU build is opt-in** — llama.cpp's Vulkan backend
splits the graph across CPU and GPU even at `n_gpu_layers=0`, roughly halving
CPU throughput, so a CPU-only host must not get one (`bootstrap.sh --gpu
vulkan|rocm|cuda`, or set `engine.gpu_layers` and rerun, builds it; the default
stays CPU-only). Offload needs the accelerator **to itself**: the 4B Q4 model
needs ~2.9 GiB, so a GPU already holding another model (e.g. ollama) makes the
engine slower than CPU and can abort the process with `vk::DeviceLostError`.
ollama is a separate GPU user.
- The SemIf tokenizer is fetched from HF (`Qwen/Qwen3.5-4B` at the pinned
revision), cached under each checkout's `.runtime/hf` (`HF_HOME`).
- Per-host specs and model choices for this deployment: `local/ENVIRONMENT.md`.
@@ -584,7 +596,12 @@ CLI, unit tests (24) + integration tests (2).
`pip install -e <semif-clone> --no-deps`, then
`CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install -r requirements/staging.txt`
(numpy 2.3.5, transformers 5.17.0, tokenizers 0.23.2, huggingface-hub 1.31.0,
llama-cpp-python 0.3.35, pytest).
llama-cpp-python 0.3.35, pytest). GPU offload is **opt-in**: set
`engine.gpu_layers` and run `bootstrap.sh --gpu vulkan|rocm|cuda` (with
`--gpu auto`, detection picks a backend when `engine.gpu_layers` is set),
which installs the Vulkan build prereqs
(`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only
host keeps the default CPU wheel — a GPU build is slower on CPU.
- **Expected pip warnings:** pip reports "dependency conflicts" against
semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece
not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging
@@ -595,7 +612,11 @@ CLI, unit tests (24) + integration tests (2).
gcc (`internal compiler error: Segmentation fault`). Limit parallelism:
`CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install llama-cpp-python==0.3.35`.
Do NOT bump the llama-cpp-python version — SemIf calls specific llama.cpp C
APIs that change between versions.
APIs that change between versions. **GPU builds:** pip's wheel cache serves the
prebuilt CPU wheel even when `CMAKE_ARGS` requests a GPU backend, so force a
real source build with
`--force-reinstall --no-cache-dir --no-binary llama-cpp-python` (bootstrap does
this when the installed build reports no GPU offload).
- The pinned GGUF: `Qwen3.5-4B-Q4_K_M.gguf` from bartowski (2.8G), downloaded
into `.runtime/models/` by bootstrap. Load ~34s; score ~0.9s/decision on CPU
at 8 threads.
+4 -2
View File
@@ -422,8 +422,10 @@ machines:
decision engine model generates in-process, with no endpoint and no
`llm.model` at all (see the `llm.semif` block in `config.json`).
The **decision engine is separate** and runs via llama.cpp CPU (or Vulkan if your
build enables it), not ollama.
The **decision engine is separate** and runs via llama.cpp, not ollama. It is CPU
by default; to offload it to a GPU, set `engine.gpu_layers` in `config.json` and
run `scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because
it is slower on CPU).
### Option A: one-command provisioning (`bootstrap.sh`)
+5 -1
View File
@@ -14,9 +14,13 @@
"queue": {"max_size": 100},
"engine": {
"_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.",
"_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).",
"backend": "llamacpp",
"context_tokens": 4096,
"threads": 8
"threads": 8,
"gpu_layers": 0,
"gpu_device": null,
"gpu_split": 0
},
"llm": {
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).",
+1 -1
View File
@@ -2,7 +2,7 @@
"_comment": "Committed pin manifest for the external artifacts this repo downloads: the SemIf engine ref, the pinned GGUF, the HF tokenizer revision, and the simplex-chat binary. These are code-owned, deployment-independent values bumped by a git change and picked up on the next `scripts/bootstrap.sh` run. They are deliberately NOT in config.json (per-machine user config): a ref that changes with every update is not user configuration. The agent reads engine.source/revision from here; the GGUF path is derived from engine.gguf_url unless config.json overrides engine.gguf.",
"engine": {
"semif_repo": "https://github.com/TheoLeeCJ/SemIf.git",
"semif_ref": "1f2dea3e25379f9dfc98cb83c324f00ab5deda37",
"semif_ref": "23cf1f39fc9534fe81437200959b6dfc7106e45a",
"gguf_url": "https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF/resolve/main/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
"gguf_sha256": "13c16f426047e2de38cd075bdade4a7bcbc8c774384876f677740cda65f8a983",
"source": "Qwen/Qwen3.5-4B",
+79 -2
View File
@@ -32,7 +32,7 @@
#
# Usage:
# scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL]
# [--codegen-model MODEL] [--copy-data SRC] [--voice] [-h]
# [--codegen-model MODEL] [--copy-data SRC] [--voice] [--gpu MODE] [-h]
#
# Run as the human user; sudo is used internally for system bits.
set -euo pipefail
@@ -43,6 +43,7 @@ LLM_MODEL=""
CODEGEN_MODEL=""
COPY_DATA=""
VOICE=0
GPU_MODE="auto"
usage() {
sed -n '2,35p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
@@ -53,6 +54,7 @@ usage() {
echo " --codegen-model MODEL override codegen.model from config.json for this run"
echo " --copy-data SRC rsync SRC (e.g. user@host:/path/to/semif-agent/data) to data/ — opt-in"
echo " --voice install the optional voice-gateway stack + download its models"
echo " --gpu MODE decision-engine llama.cpp backend: auto (default; a GPU build only when engine.gpu_layers is set), vulkan, rocm, cuda, cpu"
echo " -h this help"
exit "${1:-0}"
}
@@ -65,6 +67,7 @@ while [[ $# -gt 0 ]]; do
--codegen-model) CODEGEN_MODEL="$2"; shift 2 ;;
--copy-data) COPY_DATA="$2"; shift 2 ;;
--voice) VOICE=1; shift ;;
--gpu) GPU_MODE="$2"; shift 2 ;;
-h|--help) usage 0 ;;
*) echo "unknown option: $1" >&2; usage 1 ;;
esac
@@ -239,6 +242,65 @@ if [[ "$(git -C "$ENGINE" rev-parse HEAD 2>/dev/null)" != "$SEMIF_REF" ]]; then
git -C "$ENGINE" checkout "$SEMIF_REF"
fi
# --- stage 2b: pick the llama.cpp GPU backend ---------------------------------
# The decision engine scores the GGUF through llama.cpp, which runs on CPU
# unless llama-cpp-python was built with a GPU backend. A GPU-enabled build is
# opt-in: llama.cpp's Vulkan backend splits the compute graph across CPU and
# Vulkan even with `n_gpu_layers=0`, roughly doubling CPU latency, so a CPU-only
# host must not get one. `--gpu <backend>` forces a build; `--gpu auto` (the
# default) builds a GPU backend only when config.json asks for offload
# (`engine.gpu_layers` nonzero).
CONFIG_GPU_LAYERS="$(python3 - "$CONFIG" <<'PY'
import json, sys
try:
print(int(json.load(open(sys.argv[1])).get("engine", {}).get("gpu_layers", 0) or 0))
except Exception:
print(0)
PY
)"
detect_gpu_backend() {
if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi >/dev/null 2>&1; then
echo cuda; return
fi
if [[ -d /opt/rocm ]]; then
echo rocm; return
fi
if command -v glslc >/dev/null 2>&1 && compgen -G "/usr/share/vulkan/icd.d/*.json" >/dev/null; then
echo vulkan; return
fi
echo cpu
}
case "$GPU_MODE" in
cpu) GPU_BACKEND=cpu ;;
vulkan|rocm|cuda) GPU_BACKEND="$GPU_MODE" ;;
auto)
if [[ "$CONFIG_GPU_LAYERS" != 0 ]]; then
GPU_BACKEND="$(detect_gpu_backend)"
else
GPU_BACKEND=cpu
fi
;;
*) echo "unknown --gpu mode: $GPU_MODE (want auto, vulkan, rocm, cuda, cpu)" >&2; exit 2 ;;
esac
case "$GPU_BACKEND" in
vulkan) LLAMA_CMAKE_ARGS="-DGGML_VULKAN=on" ;;
rocm) LLAMA_CMAKE_ARGS="-DGGML_HIP=on" ;;
cuda) LLAMA_CMAKE_ARGS="-DGGML_CUDA=on" ;;
*) LLAMA_CMAKE_ARGS="" ;;
esac
echo "== decision-engine llama.cpp backend: $GPU_BACKEND (engine.gpu_layers=$CONFIG_GPU_LAYERS)"
if [[ "$GPU_BACKEND" = vulkan ]]; then
VULKAN_PKGS=(libvulkan-dev glslc spirv-headers glslang-tools)
vk_missing=()
for p in "${VULKAN_PKGS[@]}"; do dpkg -s "$p" >/dev/null 2>&1 || vk_missing+=("$p"); done
if [[ ${#vk_missing[@]} -gt 0 ]]; then
echo "== installing Vulkan build prereqs: ${vk_missing[*]}"
sudo apt-get update
sudo apt-get install -y "${vk_missing[@]}"
fi
fi
# --- stage 3: venv + deps -------------------------------------------------------
if [[ ! -x "$PYTHON" ]]; then
echo "== creating venv at $VENV"
@@ -247,7 +309,22 @@ fi
echo "== installing engine deps into $VENV"
"$PIP" install --upgrade pip setuptools wheel
"$PIP" install -e "$ENGINE" --no-deps
CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 "$PIP" install -r "$REPO_ROOT/requirements/staging.txt"
CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \
"$PIP" install -r "$REPO_ROOT/requirements/staging.txt"
# Make the installed llama-cpp-python match the requested backend: pip ships a
# CPU wheel and its wheel cache hands it back even when CMAKE_ARGS asks for a
# GPU backend, so force a source build whenever offload support disagrees.
installed_gpu=no
"$PYTHON" -c 'import llama_cpp, sys; sys.exit(0 if llama_cpp.llama_supports_gpu_offload() else 1)' 2>/dev/null && installed_gpu=yes
want_gpu=yes
[[ "$GPU_BACKEND" = cpu ]] && want_gpu=no
if [[ "$installed_gpu" != "$want_gpu" ]]; then
LLAMA_PIN="$(grep -m1 -E '^llama-cpp-python==' "$REPO_ROOT/requirements/staging.txt")"
echo "== rebuilding llama-cpp-python for the $GPU_BACKEND backend ($LLAMA_PIN)"
CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \
"$PIP" install --no-deps --force-reinstall --no-cache-dir --no-binary llama-cpp-python "$LLAMA_PIN"
fi
"$PIP" install -e "$REPO_ROOT" --no-deps
# --- stage 3b: optional voice-gateway stack (--voice) --------------------------
+4
View File
@@ -177,6 +177,7 @@ def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig:
gguf = _anchor_path(override) if override else str(
REPO_ROOT / ".runtime" / "models" / os.path.basename(pin_eng.get("gguf_url", ""))
)
gpu_device = eng.get("gpu_device")
return EngineConfig(
backend=eng.get("backend", "llamacpp"),
source=pin_eng.get("source", ""),
@@ -184,6 +185,9 @@ def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig:
gguf=gguf,
context_tokens=int(eng.get("context_tokens", 4096)),
threads=eng.get("threads"),
gpu_layers=int(eng.get("gpu_layers", 0)),
gpu_device=None if gpu_device is None else int(gpu_device),
gpu_split=int(eng.get("gpu_split", 0)),
)
+81 -4
View File
@@ -2,10 +2,11 @@
Wraps the SemIf package (`semif_phase1`). The import and model load happen
lazily so the rest of the agent is pure stdlib and testable without SemIf
installed. On hardware that is neither CUDA nor Apple, use the shipped
llama.cpp backend: a local GGUF scored on CPU (or Vulkan if your llama.cpp
build enables it). This engine is only usable on a machine with SemIf and the
pinned GGUF available; elsewhere calls raise EngineUnavailable.
installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by
default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python
was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a
machine with SemIf and the pinned GGUF available; elsewhere calls raise
EngineUnavailable.
"""
from __future__ import annotations
@@ -29,6 +30,67 @@ class EngineConfig:
gguf: str = ""
context_tokens: int = 4096
threads: int | None = None
# GPU offload (llama.cpp). 0 keeps the CPU-only default; a positive count
# offloads that many layers, -1 offloads all of them. Requires a
# llama-cpp-python built with a GPU backend (Vulkan/ROCm/CUDA).
gpu_layers: int = 0
gpu_device: int | None = None
gpu_split: int = 0
def _require_gpu_offload() -> None:
"""Fail loudly when GPU layers are requested but the build cannot offload."""
import llama_cpp
if not llama_cpp.llama_supports_gpu_offload():
raise EngineUnavailable(
"engine.gpu_layers is set but this llama-cpp-python build has no GPU "
"backend. Rebuild it with one, e.g. "
"CMAKE_ARGS='-DGGML_VULKAN=on' (Vulkan), '-DGGML_HIP=on' (ROCm) or "
"'-DGGML_CUDA=on' (CUDA)."
)
def _install_gpu_state_reset(model) -> None:
"""Force a full cache reset between scored prompts when running on the GPU.
SemIf's `_Engine.clear` calls `llama_memory_clear(memory, False)`: it resets
the cache metadata but leaves the stored data. The CPU backend tolerates that
(the slots are overwritten before use), but the Vulkan backend keeps stale
hybrid-attention/recurrent state, so repeated `score` calls drift and return
wrong probabilities. Clearing the data as well restores determinism and
matches the CPU path. Applied only when offloading, so CPU behaviour is
untouched.
"""
engine = model.engine
library = engine.lib
def clear():
library.llama_memory_clear(engine.memory, True)
engine.clear = clear
def _offloading_params(original, config: EngineConfig):
"""Wrap SemIf's CPU-only model-params factory to offload layers to the GPU.
`semif_phase1.llamacpp_backend` is CPU-only by construction: its
`_cpu_model_params` hardcodes `n_gpu_layers = 0`. The backend looks that name
up on its own module while loading, so wrapping it for the duration of the
load lets the same path offload without patching (and losing) the re-cloned
engine source. The caller restores the original afterwards, so a CPU engine
loaded later in the same process is unaffected.
"""
def offloading(library):
params = original(library)
params.n_gpu_layers = config.gpu_layers
params.split_mode = config.gpu_split
if config.gpu_device is not None:
params.main_gpu = config.gpu_device
return params
return offloading
class SemIfEngine:
@@ -59,6 +121,11 @@ class SemIfEngine:
"SemIf is not installed here. Install it on the target box with "
"`pip install -e '.[test,llamacpp]'`."
) from exc
if self.config.gpu_layers:
_require_gpu_offload()
original_params = backend._cpu_model_params
if self.config.gpu_layers:
backend._cpu_model_params = _offloading_params(original_params, self.config)
try:
model, tokenizer, metadata = backend.load_model(
self.config.source,
@@ -69,6 +136,16 @@ class SemIfEngine:
)
except Exception as exc:
raise EngineUnavailable(f"Failed to load the SemIf model: {exc}") from exc
finally:
backend._cpu_model_params = original_params
if self.config.gpu_layers:
_install_gpu_state_reset(model)
# The backend hardcodes n_gpu_layers=0 in its metadata; record what we
# actually asked llama.cpp to offload instead.
metadata = dict(metadata)
metadata["n_gpu_layers"] = self.config.gpu_layers
if self.config.gpu_device is not None:
metadata["main_gpu"] = self.config.gpu_device
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
return model, tokenizer, metadata
+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)]