my-homelab-configs/scripts/ai-lab.py

153 lines
7.7 KiB
Python

#!/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)