Add isolated llama.cpp AI lab
This commit is contained in:
parent
688fe9f0f0
commit
099fa6ac0d
|
|
@ -0,0 +1,49 @@
|
|||
# Jeannie AI lab
|
||||
|
||||
The AI lab builds a pinned, separate llama.cpp checkout on the Debian server.
|
||||
It does not change Ollama, OmniRoute, the Jeannie model routes, or cluster
|
||||
configuration. The build has CPU and Vulkan support; Vulkan detection does not
|
||||
guarantee that the integrated GPU will be faster than the CPU.
|
||||
|
||||
After pushing this change, on Debian:
|
||||
|
||||
```sh
|
||||
cd ~/my-homelab-configs
|
||||
git pull --ff-only gitea main
|
||||
./jeannie ai-lab plan
|
||||
./jeannie ai-lab install
|
||||
./jeannie ai-lab devices
|
||||
```
|
||||
|
||||
Installation uses `sudo apt-get` for build and Vulkan packages, downloads the
|
||||
pinned source, and compiles with two parallel jobs. The default lab directory is
|
||||
`/data/homelab-ai-lab`; set `JEANNIE_AI_LAB_DIR` to use a different directory.
|
||||
The install refuses to overwrite an existing source checkout whose origin,
|
||||
commit, or tracked files do not match the expected source.
|
||||
|
||||
Once `ollama ps` shows no loaded models, run:
|
||||
|
||||
```sh
|
||||
./jeannie ai-lab bench ollama
|
||||
./jeannie ai-lab bench cpu
|
||||
./jeannie ai-lab bench vulkan
|
||||
```
|
||||
|
||||
The Vulkan run defaults to `Vulkan0`. If `devices` shows a different Radeon
|
||||
device, set `JEANNIE_AI_LAB_VULKAN_DEVICE` to that name for the run. The lab
|
||||
refuses to start if Ollama currently has a loaded model; it never stops another
|
||||
model. The Ollama benchmark asks Ollama to unload the model after its own
|
||||
request. Avoid concurrent AI workloads when comparing results.
|
||||
|
||||
Each run reads the existing `llama3.2:3b` GGUF blob; it does not copy, delete,
|
||||
or modify the model. The Debian user must be able to read the path printed by
|
||||
`ollama show --modelfile llama3.2:3b`. Inaccessible or non-GGUF files stop the
|
||||
test. Reports and model output are saved with mode 0600 under the lab's `reports`
|
||||
directory. Review the llama.cpp log for actual GPU offload and prompt versus
|
||||
generation timing; the parsed timing values alone do not identify the phase.
|
||||
|
||||
Each benchmark is one cold request, using the same prompt, maximum output,
|
||||
context size and temperature. CLI and Ollama prompt templates, sampling options,
|
||||
backend allocation and measured time boundaries can differ, so this is an
|
||||
initial comparison rather than a controlled scientific benchmark. Repeat runs,
|
||||
inspect answers, and compare end-to-end user experience before changing routes.
|
||||
11
jeannie
11
jeannie
|
|
@ -83,6 +83,7 @@ Build And Bootstrap
|
|||
deploy-ai-tools Install/wire local AI CLIs to the AI gateway.
|
||||
goose-graph <update|context|learn|propose> [question]
|
||||
Explore the repo with Goose and Graphify.
|
||||
ai-lab {plan|install|devices|bench BACKEND} Build and benchmark isolated llama.cpp.
|
||||
lab-window <start|stop|status> Apply the scheduled lab power window.
|
||||
deploy-omniroute Deploy the OmniRoute LLM routing gateway.
|
||||
deploy-hermes Deploy the Hermes agent (git-install + venv + gateway service).
|
||||
|
|
@ -316,6 +317,16 @@ case "${1:-}" in
|
|||
esac
|
||||
|
||||
case "${1:-}" in
|
||||
ai-lab)
|
||||
require_debian_server "ai-lab"
|
||||
case "${2:-plan}" in
|
||||
plan|install|devices) [[ $# -le 2 ]] || { echo "Usage: ./jeannie ai-lab {plan|install|devices|bench {ollama|cpu|vulkan}}" >&2; exit 2; } ;;
|
||||
bench) [[ $# -eq 3 && "${3}" =~ ^(ollama|cpu|vulkan)$ ]] || { echo "Usage: ./jeannie ai-lab bench {ollama|cpu|vulkan}" >&2; exit 2; } ;;
|
||||
*) echo "Usage: ./jeannie ai-lab {plan|install|devices|bench {ollama|cpu|vulkan}}" >&2; exit 2 ;;
|
||||
esac
|
||||
if [[ "${2:-plan}" == install ]]; then record_change_journal "ai-lab" "$@"; fi
|
||||
python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}"
|
||||
;;
|
||||
progressive-lab)
|
||||
[[ $# -le 3 && ( $# -le 2 || "${2:-}" == run ) ]] || { echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2; }
|
||||
case "${2:-plan}" in
|
||||
|
|
|
|||
|
|
@ -0,0 +1,152 @@
|
|||
#!/usr/bin/env python3
|
||||
"""An isolated llama.cpp build and inference benchmark for the Debian host."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
TAG = "b10931"
|
||||
COMMIT_PREFIX = "3057bb6"
|
||||
REPOSITORY = "https://github.com/ggml-org/llama.cpp.git"
|
||||
ROOT = Path(os.environ.get("JEANNIE_AI_LAB_DIR", "/data/homelab-ai-lab"))
|
||||
SOURCE = ROOT / ("llama.cpp-" + TAG)
|
||||
CLI = SOURCE / "build/bin/llama-cli"
|
||||
MODEL = "llama3.2:3b"
|
||||
PROMPT = "Explain the difference between a Kubernetes Service and an Ingress in three sentences."
|
||||
ENDPOINT = os.environ.get("LAB_OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/")
|
||||
|
||||
|
||||
def command(args, *, capture=False, timeout=None):
|
||||
result = subprocess.run(args, text=True, capture_output=capture, timeout=timeout)
|
||||
if result.returncode:
|
||||
detail = (result.stderr or "").strip() if capture else ""
|
||||
raise RuntimeError(f"{args[0]} failed (exit {result.returncode})" + (f": {detail[-1000:]}" if detail else ""))
|
||||
return result
|
||||
|
||||
|
||||
def read_url(path, payload=None, timeout=15):
|
||||
data = json.dumps(payload).encode() if payload is not None else None
|
||||
request = urllib.request.Request(ENDPOINT + path, data=data, headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def require_idle_ollama():
|
||||
models = read_url("/api/ps").get("models", [])
|
||||
if models:
|
||||
names = ", ".join(model.get("name", "unknown") for model in models)
|
||||
raise RuntimeError(f"Ollama has loaded models ({names}); wait until they unload before benchmarking. No model was stopped.")
|
||||
|
||||
|
||||
def model_path():
|
||||
output = command(["ollama", "show", "--modelfile", MODEL], capture=True).stdout
|
||||
paths = [line.split(maxsplit=1)[1] for line in output.splitlines() if line.startswith("FROM /")]
|
||||
if len(paths) != 1:
|
||||
raise RuntimeError("Could not identify one local model file from the Ollama Modelfile")
|
||||
path = Path(paths[0])
|
||||
try:
|
||||
with path.open("rb") as model:
|
||||
magic = model.read(4)
|
||||
except OSError as exc:
|
||||
raise RuntimeError(f"Model file is not readable by this user: {path}") from exc
|
||||
if magic != b"GGUF":
|
||||
raise RuntimeError("The Ollama model file is not a GGUF file")
|
||||
return path
|
||||
|
||||
|
||||
def install():
|
||||
ROOT.mkdir(parents=True, exist_ok=True)
|
||||
if shutil.disk_usage(ROOT).free < 5 * 1024 ** 3:
|
||||
raise RuntimeError(f"Need at least 5 GiB free in {ROOT} to build the lab")
|
||||
packages = ["git", "build-essential", "cmake", "libvulkan-dev", "glslc", "spirv-headers", "vulkan-tools", "mesa-vulkan-drivers"]
|
||||
command(["sudo", "apt-get", "update"])
|
||||
command(["sudo", "apt-get", "install", "-y", *packages])
|
||||
if not SOURCE.exists():
|
||||
command(["git", "clone", "--depth", "1", "--branch", TAG, REPOSITORY, str(SOURCE)])
|
||||
if not (SOURCE / ".git").is_dir():
|
||||
raise RuntimeError(f"Existing lab source directory is not a Git checkout: {SOURCE}")
|
||||
origin = command(["git", "-C", str(SOURCE), "remote", "get-url", "origin"], capture=True).stdout.strip()
|
||||
commit = command(["git", "-C", str(SOURCE), "rev-parse", "HEAD"], capture=True).stdout.strip()
|
||||
dirty = command(["git", "-C", str(SOURCE), "status", "--porcelain", "--untracked-files=no"], capture=True).stdout.strip()
|
||||
if origin != REPOSITORY or not commit.startswith(COMMIT_PREFIX) or dirty:
|
||||
raise RuntimeError("Lab checkout differs from the pinned source or has local edits; refusing to change it")
|
||||
command(["cmake", "-S", str(SOURCE), "-B", str(SOURCE / "build"), "-DCMAKE_BUILD_TYPE=Release", "-DGGML_VULKAN=ON"])
|
||||
command(["cmake", "--build", str(SOURCE / "build"), "--config", "Release", "--parallel", "2"])
|
||||
if not CLI.is_file():
|
||||
raise RuntimeError("Build completed but llama-cli was not found")
|
||||
print(f"AI lab installed: {CLI} ({TAG}, {commit})")
|
||||
print("Next: ./jeannie ai-lab devices")
|
||||
|
||||
|
||||
def devices():
|
||||
if not CLI.is_file():
|
||||
raise RuntimeError("AI lab is not installed; run ./jeannie ai-lab install")
|
||||
command([str(CLI), "--list-devices"])
|
||||
|
||||
|
||||
def make_report(backend, result, log):
|
||||
reports = ROOT / "reports"
|
||||
reports.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
name = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + backend + f"-{time.time_ns() % 1000000:06d}"
|
||||
for suffix, data in ((".json", json.dumps(result, indent=2) + "\n"), (".log", log)):
|
||||
path = reports / (name + suffix)
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, "w") as file:
|
||||
file.write(data)
|
||||
print(json.dumps(result, indent=2))
|
||||
print(f"Private report: {reports / (name + '.json')}")
|
||||
|
||||
|
||||
def benchmark(backend):
|
||||
if backend not in ("ollama", "cpu", "vulkan"):
|
||||
raise RuntimeError("Choose ollama, cpu or vulkan")
|
||||
path = model_path()
|
||||
require_idle_ollama()
|
||||
common = {"backend": backend, "model": MODEL, "model_file": str(path), "context": 4096, "max_tokens": 128, "temperature": 0, "prompt": PROMPT, "note": "Single cold request; prompt templates and sampling may differ across backends."}
|
||||
if backend == "ollama":
|
||||
payload = {"model": MODEL, "prompt": PROMPT, "stream": False, "keep_alive": 0, "options": {"num_ctx": 4096, "num_predict": 128, "temperature": 0}}
|
||||
result = read_url("/api/generate", payload, timeout=300)
|
||||
eval_ns = result.get("eval_duration", 0)
|
||||
common.update({"total_seconds": result.get("total_duration", 0) / 1e9, "load_seconds": result.get("load_duration", 0) / 1e9, "generated_tokens": result.get("eval_count"), "generation_tokens_per_second": result.get("eval_count", 0) * 1e9 / eval_ns if eval_ns else None})
|
||||
make_report(backend, common, result.get("response", "") + "\n")
|
||||
return
|
||||
if not CLI.is_file():
|
||||
raise RuntimeError("AI lab is not installed; run ./jeannie ai-lab install")
|
||||
device = "none" if backend == "cpu" else os.environ.get("JEANNIE_AI_LAB_VULKAN_DEVICE", "Vulkan0")
|
||||
if backend == "vulkan" and not re.fullmatch(r"Vulkan[0-9]+", device):
|
||||
raise RuntimeError("Vulkan device must have a name such as Vulkan0")
|
||||
args = [str(CLI), "-m", str(path), "--device", device, "-ngl", "0" if backend == "cpu" else "999", "-c", "4096", "-n", "128", "--temp", "0", "--single-turn", "--perf", "-p", PROMPT]
|
||||
started = time.monotonic()
|
||||
completed = command(args, capture=True, timeout=600)
|
||||
log = completed.stdout + "\n" + completed.stderr
|
||||
rates = re.findall(r"([0-9]+(?:\.[0-9]+)?)\s+tokens per second", log)
|
||||
common.update({"device": device, "elapsed_seconds": round(time.monotonic() - started, 3), "llama_cpp_version": TAG, "tokens_per_second_reported": [float(rate) for rate in rates], "note": common["note"] + " Confirm actual GPU offload and identify prompt/generation rates in the log."})
|
||||
make_report(backend, common, log)
|
||||
|
||||
|
||||
def main():
|
||||
action = sys.argv[1] if len(sys.argv) > 1 else "plan"
|
||||
if action == "plan":
|
||||
print(json.dumps({"directory": str(ROOT), "source": REPOSITORY, "version": TAG, "expected_commit_prefix": COMMIT_PREFIX, "packages": ["git", "build-essential", "cmake", "libvulkan-dev", "glslc", "spirv-headers", "vulkan-tools", "mesa-vulkan-drivers"], "production_routes": "unchanged"}, indent=2))
|
||||
elif action == "install":
|
||||
install()
|
||||
elif action == "devices":
|
||||
devices()
|
||||
elif action == "bench" and len(sys.argv) == 3:
|
||||
benchmark(sys.argv[2])
|
||||
else:
|
||||
raise RuntimeError("Usage: ./jeannie ai-lab {plan|install|devices|bench {ollama|cpu|vulkan}}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
print(f"AI lab: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
|
@ -120,6 +120,7 @@ validate_unit_tests() {
|
|||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_gateway_lab.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_secrets_lab.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_progressive_lab.py'
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ai_lab.py'
|
||||
}
|
||||
|
||||
main() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location("ai_lab", ROOT / "scripts/ai-lab.py")
|
||||
lab = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(lab)
|
||||
|
||||
|
||||
class AiLabTest(unittest.TestCase):
|
||||
def test_refuses_to_evict_ollama_model(self):
|
||||
with mock.patch.object(lab, "read_url", return_value={"models": [{"name": "active"}]}):
|
||||
with self.assertRaisesRegex(RuntimeError, "No model was stopped"):
|
||||
lab.require_idle_ollama()
|
||||
|
||||
def test_allows_empty_ollama(self):
|
||||
with mock.patch.object(lab, "read_url", return_value={"models": []}):
|
||||
lab.require_idle_ollama()
|
||||
|
||||
def test_invalid_backend_does_not_start_inference(self):
|
||||
with mock.patch.object(lab, "model_path") as path:
|
||||
with self.assertRaisesRegex(RuntimeError, "Choose"):
|
||||
lab.benchmark("unknown")
|
||||
path.assert_not_called()
|
||||
|
||||
def test_ollama_request_has_bounded_context_and_output(self):
|
||||
output = {"eval_duration": 1000000000, "eval_count": 12, "response": "ok"}
|
||||
with mock.patch.object(lab, "model_path", return_value=Path("/demo/model")), mock.patch.object(lab, "require_idle_ollama"), mock.patch.object(lab, "read_url", return_value=output) as request, mock.patch.object(lab, "make_report") as report:
|
||||
lab.benchmark("ollama")
|
||||
payload = request.call_args.args[1]
|
||||
self.assertEqual(payload["options"]["num_ctx"], 4096)
|
||||
self.assertEqual(payload["options"]["num_predict"], 128)
|
||||
self.assertEqual(payload["keep_alive"], 0)
|
||||
self.assertEqual(report.call_args.args[1]["generation_tokens_per_second"], 12)
|
||||
|
||||
def test_model_must_be_a_unique_absolute_path(self):
|
||||
result = SimpleNamespace(stdout="FROM llama3.2:3b\n")
|
||||
with mock.patch.object(lab, "command", return_value=result):
|
||||
with self.assertRaisesRegex(RuntimeError, "identify"):
|
||||
lab.model_path()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue