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

258 lines
14 KiB
Python

#!/usr/bin/env python3
"""An isolated llama.cpp build and inference benchmark for the Debian host."""
import json
import hashlib
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
from datetime import datetime, timezone
TAG = "b10931"
COMMIT_PREFIX = "3057bb6"
REPOSITORY = "https://github.com/ggml-org/llama.cpp.git"
STATE = Path(os.environ.get("HOMELAB_STATE_DIR") or Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share") / "homelab")
ROOT = Path(os.environ.get("JEANNIE_AI_LAB_DIR") or STATE / "ai-lab")
SOURCE = ROOT / ("llama.cpp-" + TAG)
CLI = SOURCE / "build/bin/llama-cli"
COLIBRI_TAG = "v2.1.0"
COLIBRI_COMMIT = "704a3f6"
COLIBRI_REPO = "https://github.com/JustVugg/colibri.git"
COLIBRI_SOURCE = ROOT / ("colibri-" + COLIBRI_TAG)
COLIBRI_CLI = COLIBRI_SOURCE / "c/coli"
QWEN_FILE = ROOT / "models/Qwen3-0.6B-Q8_0.gguf"
QWEN_DIR = ROOT / "models/qwen3-0.6b-colibri"
QWEN_SHA256 = "9465e63a22add5354d9bb4b99e90117043c7124007664907259bd16d043bb031"
QWEN_URL = "https://huggingface.co/Qwen/Qwen3-0.6B-GGUF/resolve/main/Qwen3-0.6B-Q8_0.gguf"
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 workspace():
try:
ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
except PermissionError as exc:
raise RuntimeError(f"Cannot create {ROOT}; choose a writable JEANNIE_AI_LAB_DIR or use the default user-owned workspace") from exc
if not os.access(ROOT, os.W_OK | os.X_OK):
raise RuntimeError(f"AI lab directory is not writable: {ROOT}; choose a writable JEANNIE_AI_LAB_DIR")
def checkout(destination, repo, tag, prefix):
if not destination.exists():
command(["git", "clone", "--depth", "1", "--branch", tag, repo, str(destination)])
if not (destination / ".git").is_dir():
raise RuntimeError(f"Existing lab source directory is not a Git checkout: {destination}")
origin = command(["git", "-C", str(destination), "remote", "get-url", "origin"], capture=True).stdout.strip()
commit = command(["git", "-C", str(destination), "rev-parse", "HEAD"], capture=True).stdout.strip()
dirty = command(["git", "-C", str(destination), "status", "--porcelain", "--untracked-files=no"], capture=True).stdout.strip()
if origin != repo or not commit.startswith(prefix) or dirty:
raise RuntimeError("Lab checkout differs from the pinned source or has local edits; refusing to change it")
return commit
def install():
workspace()
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])
commit = checkout(SOURCE, REPOSITORY, TAG, COMMIT_PREFIX)
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 install_colibri():
workspace()
if shutil.disk_usage(ROOT).free < 2 * 1024 ** 3:
raise RuntimeError("Colibri build requires at least 2 GiB free in the lab workspace")
if not all(shutil.which(tool) for tool in ("git", "gcc", "make")):
command(["sudo", "apt-get", "update"])
command(["sudo", "apt-get", "install", "-y", "git", "build-essential"])
commit = checkout(COLIBRI_SOURCE, COLIBRI_REPO, COLIBRI_TAG, COLIBRI_COMMIT)
command(["make", "-C", str(COLIBRI_SOURCE / "c"), "qwen36", "ARCH=native", "-j2"])
if not COLIBRI_CLI.is_file() or not (COLIBRI_SOURCE / "c/qwen36").is_file():
raise RuntimeError("Colibri build completed but the Qwen engine is missing")
print(f"Colibri installed: {COLIBRI_TAG} ({commit}); CPU Qwen engine")
print("Next: ./jeannie ai-lab colibri-prepare (downloads a 639 MB demo model)")
def digest(path):
checksum = hashlib.sha256()
with path.open("rb") as file:
for chunk in iter(lambda: file.read(1024 * 1024), b""):
checksum.update(chunk)
return checksum.hexdigest()
def prepare_colibri():
if not COLIBRI_CLI.is_file() or not (COLIBRI_SOURCE / "c/qwen36").is_file():
raise RuntimeError("Colibri is not installed; run ./jeannie ai-lab colibri-install")
workspace()
QWEN_FILE.parent.mkdir(parents=True, exist_ok=True)
if not QWEN_FILE.exists():
if shutil.disk_usage(ROOT).free < 2 * 1024 ** 3:
raise RuntimeError("Model preparation requires at least 2 GiB free")
print("Downloading Qwen3-0.6B Q8_0 (approximately 639 MB) to the AI lab...")
with tempfile.TemporaryDirectory(prefix=".qwen-download-", dir=QWEN_FILE.parent) as staging:
temporary = Path(staging) / "model.gguf"
with urllib.request.urlopen(QWEN_URL, timeout=60) as response, temporary.open("xb") as file:
shutil.copyfileobj(response, file, length=1024 * 1024)
if digest(temporary) != QWEN_SHA256:
raise RuntimeError("Downloaded model checksum did not match")
os.link(temporary, QWEN_FILE)
if digest(QWEN_FILE) != QWEN_SHA256:
raise RuntimeError(f"Existing model checksum does not match: {QWEN_FILE}")
marker = QWEN_DIR / ".jeannie-source.json"
expected = {"sha256": QWEN_SHA256, "file": str(QWEN_FILE.resolve())}
if QWEN_DIR.exists():
if not marker.is_file() or json.loads(marker.read_text()) != expected:
raise RuntimeError(f"Existing Colibri model directory is not verified: {QWEN_DIR}")
else:
with tempfile.TemporaryDirectory(prefix=".qwen-import-", dir=QWEN_FILE.parent) as staging:
imported = Path(staging) / "model"
command([sys.executable, str(COLIBRI_CLI), "import", str(QWEN_FILE), "--mode", "link", "--out", str(imported)])
if not (imported / "config.json").is_file() or not (imported / "tokenizer.json").is_file():
raise RuntimeError("Colibri import did not create its expected model files")
(imported / ".jeannie-source.json").write_text(json.dumps(expected) + "\n")
imported.rename(QWEN_DIR)
print("Colibri demo model verified and prepared. Next: ./jeannie ai-lab bench colibri")
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", "colibri", "qwen-cpu"):
raise RuntimeError("Choose ollama, cpu, vulkan, colibri or qwen-cpu")
if backend in ("colibri", "qwen-cpu"):
if not QWEN_FILE.is_file() or digest(QWEN_FILE) != QWEN_SHA256:
raise RuntimeError("Verified Qwen3 demo model is missing; run ./jeannie ai-lab colibri-prepare")
path = QWEN_FILE
else:
path = model_path()
require_idle_ollama()
common = {"backend": backend, "model": "Qwen3-0.6B-Q8_0" if backend in ("colibri", "qwen-cpu") else MODEL, "model_file": str(path), "context": 4096, "max_tokens": 128, "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 backend == "colibri":
marker = QWEN_DIR / ".jeannie-source.json"
if not COLIBRI_CLI.is_file() or not marker.is_file() or json.loads(marker.read_text()) != {"sha256": QWEN_SHA256, "file": str(QWEN_FILE.resolve())}:
raise RuntimeError("Colibri or its verified demo model is missing; run colibri-install and colibri-prepare")
available = next((int(line.split()[1]) for line in Path("/proc/meminfo").read_text().splitlines() if line.startswith("MemAvailable:")), 0)
if available < 2 * 1024 * 1024:
raise RuntimeError("Less than 2 GiB RAM is currently available; retry when the host has more headroom")
started = time.monotonic()
completed = command(["env", "COLI_VULKAN=0", "COLI_CUDA=0", sys.executable, str(COLIBRI_CLI), "run", "--model", str(QWEN_DIR), "--gpu", "none", "--ctx", "4096", "--ngen", "128", PROMPT], capture=True, timeout=600)
log = completed.stdout + "\n" + completed.stderr
common.update({"device": "cpu", "elapsed_seconds": round(time.monotonic() - started, 3), "colibri_version": COLIBRI_TAG, "note": common["note"] + " Review the log for generation timings and output quality."})
make_report(backend, common, log)
return
if not CLI.is_file():
raise RuntimeError("AI lab is not installed; run ./jeannie ai-lab install")
device = "none" if backend in ("cpu", "qwen-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 in ("cpu", "qwen-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, "colibri": {"source": COLIBRI_REPO, "version": COLIBRI_TAG, "model": "Qwen3-0.6B-Q8_0", "download_mb": 639}, "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 == "colibri-install":
install_colibri()
elif action == "colibri-prepare":
prepare_colibri()
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|colibri-install|colibri-prepare|bench BACKEND}")
if __name__ == "__main__":
try:
main()
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
print(f"AI lab: {exc}", file=sys.stderr)
sys.exit(1)