From d34882f2cc8496f91602f6d95023241fc22db16e Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Tue, 10 Nov 2026 11:37:43 -0600 Subject: [PATCH] Add Colibri to the isolated AI lab --- docs/ai-lab.md | 30 +++++++- jeannie | 10 +-- scripts/ai-lab.py | 143 ++++++++++++++++++++++++++++++----- tests/jeannie/test_ai_lab.py | 19 +++++ 4 files changed, 177 insertions(+), 25 deletions(-) diff --git a/docs/ai-lab.md b/docs/ai-lab.md index 219befe..933393e 100644 --- a/docs/ai-lab.md +++ b/docs/ai-lab.md @@ -17,7 +17,11 @@ git pull --ff-only gitea main 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. +`~/.local/share/homelab/ai-lab` (or `ai-lab` under `HOMELAB_STATE_DIR`); set +`JEANNIE_AI_LAB_DIR` to a writable directory to choose another location. A +previous `/data/homelab-ai-lab` workspace is not moved or deleted. If explicitly +selected, that directory must already be writable; Jeannie does not change its +ownership or permissions. The install refuses to overwrite an existing source checkout whose origin, commit, or tracked files do not match the expected source. @@ -47,3 +51,27 @@ 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. + +## Colibri experiment + +The optional Colibri engine is pinned separately and runs on CPU. Its Qwen3 +engine reads a small Qwen3-0.6B Q8_0 GGUF model. Preparation downloads about +639 MB from Qwen's Hugging Face repository and verifies its pinned SHA-256; +interrupted downloads are cleaned up and can be retried. Existing model files +with a different checksum are preserved and refused. No production model or +service is changed. + +```sh +./jeannie ai-lab colibri-install +./jeannie ai-lab colibri-prepare +./jeannie ai-lab bench colibri +./jeannie ai-lab bench qwen-cpu +``` + +The last two commands use the exact same GGUF with Colibri and llama.cpp. The +llama.cpp build must be installed for `qwen-cpu`. Colibri checks for at least +2 GiB currently available before starting, but other workloads may use memory +while the benchmark runs. The engines may use different prompts, sampling, +context handling and timing boundaries; compare both the logs and answer +quality rather than treating the elapsed times as a conclusive ranking. These +are single-request experiments; neither backend is registered with OmniRoute. diff --git a/jeannie b/jeannie index b3820f1..2bb77b4 100755 --- a/jeannie +++ b/jeannie @@ -83,7 +83,7 @@ Build And Bootstrap deploy-ai-tools Install/wire local AI CLIs to the AI gateway. goose-graph [question] Explore the repo with Goose and Graphify. - ai-lab {plan|install|devices|bench BACKEND} Build and benchmark isolated llama.cpp. + ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND} Manage AI experiments. lab-window 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). @@ -320,11 +320,11 @@ 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 ;; + plan|install|devices|colibri-install|colibri-prepare) [[ $# -le 2 ]] || { echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND}" >&2; exit 2; } ;; + bench) [[ $# -eq 3 && "${3}" =~ ^(ollama|cpu|vulkan|colibri|qwen-cpu)$ ]] || { echo "Usage: ./jeannie ai-lab bench {ollama|cpu|vulkan|colibri|qwen-cpu}" >&2; exit 2; } ;; + *) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND}" >&2; exit 2 ;; esac - if [[ "${2:-plan}" == install ]]; then record_change_journal "ai-lab" "$@"; fi + case "${2:-plan}" in install|colibri-install|colibri-prepare) record_change_journal "ai-lab" "$@" ;; esac python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}" ;; progressive-lab) diff --git a/scripts/ai-lab.py b/scripts/ai-lab.py index 77a8b6b..19ef767 100644 --- a/scripts/ai-lab.py +++ b/scripts/ai-lab.py @@ -1,12 +1,14 @@ #!/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 @@ -14,9 +16,19 @@ 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")) +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("/") @@ -60,22 +72,36 @@ def model_path(): 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(): - ROOT.mkdir(parents=True, exist_ok=True) + 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]) - 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") + 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(): @@ -84,6 +110,63 @@ def install(): 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") @@ -104,11 +187,16 @@ def make_report(backend, result, log): def benchmark(backend): - if backend not in ("ollama", "cpu", "vulkan"): - raise RuntimeError("Choose ollama, cpu or vulkan") - path = model_path() + 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": 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."} + 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) @@ -116,12 +204,25 @@ def benchmark(backend): 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 == "cpu" else os.environ.get("JEANNIE_AI_LAB_VULKAN_DEVICE", "Vulkan0") + 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 == "cpu" else "999", "-c", "4096", "-n", "128", "--temp", "0", "--single-turn", "--perf", "-p", PROMPT] + 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 @@ -133,15 +234,19 @@ def benchmark(backend): 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)) + 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|bench {ollama|cpu|vulkan}}") + raise RuntimeError("Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND}") if __name__ == "__main__": diff --git a/tests/jeannie/test_ai_lab.py b/tests/jeannie/test_ai_lab.py index 97b2ca5..0ce97ae 100644 --- a/tests/jeannie/test_ai_lab.py +++ b/tests/jeannie/test_ai_lab.py @@ -42,6 +42,25 @@ class AiLabTest(unittest.TestCase): with self.assertRaisesRegex(RuntimeError, "identify"): lab.model_path() + def test_permission_error_explains_writable_workspace(self): + directory = mock.Mock() + directory.mkdir.side_effect = PermissionError("denied") + with mock.patch.object(lab, "ROOT", directory): + with self.assertRaisesRegex(RuntimeError, "writable JEANNIE_AI_LAB_DIR"): + lab.workspace() + + def test_colibri_requires_verified_model_before_inference(self): + missing = mock.Mock() + missing.is_file.return_value = False + with mock.patch.object(lab, "QWEN_FILE", missing), mock.patch.object(lab, "command") as call: + with self.assertRaisesRegex(RuntimeError, "colibri-prepare"): + lab.benchmark("colibri") + call.assert_not_called() + + def test_downloaded_model_hash_is_pinned(self): + self.assertEqual(len(lab.QWEN_SHA256), 64) + self.assertIn("Qwen/Qwen3-0.6B-GGUF", lab.QWEN_URL) + if __name__ == "__main__": unittest.main()