my-homelab-configs/tests/jeannie/test_ai_lab.py

109 lines
5.8 KiB
Python

import importlib.util
from pathlib import Path
from types import SimpleNamespace
import sys
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()
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)
def test_llama_cli_phase_timings_are_labeled(self):
result = lab.parse_llama_timings("\x1b[32m[ Prompt: 208.5 t/s | Generation: 44.3 t/s ]\x1b[0m")
self.assertEqual(result, {"prompt_tokens_per_second": 208.5, "generation_tokens_per_second": 44.3})
self.assertEqual(lab.parse_llama_timings("unrecognized"), {"prompt_tokens_per_second": None, "generation_tokens_per_second": None})
def test_benchmark_captures_direct_controlling_terminal_output(self):
code = 'import os; f = os.open("/dev/tty", os.O_WRONLY); os.write(f, b"[ Prompt: 290.7 t/s | Generation: 44.4 t/s ]\\n"); os.close(f)'
log = lab.terminal_command([sys.executable, "-c", code], timeout=10)
self.assertEqual(lab.parse_llama_timings(log), {"prompt_tokens_per_second": 290.7, "generation_tokens_per_second": 44.4})
def test_qwen_runs_request_no_thinking_and_greedy_sampling(self):
colibri = lab.colibri_args()
llama = lab.llama_args(Path("/demo/qwen.gguf"), "qwen-cpu", "none")
self.assertIn("--no-think", colibri)
self.assertEqual(colibri[colibri.index("--temp") + 1], "0")
self.assertEqual(llama[llama.index("--reasoning") + 1], "off")
self.assertEqual(llama[llama.index("--temp") + 1], "0")
def test_colibri_log_reports_load_memory_and_lookup_counts(self):
log = "resident weights loaded in 0.3s | RSS after load: 0.88 GB\n[qwen36 lookup] turn 1: 1.09 tokens/forward (70 forwards per 76 tokens) | acceptance 60.0% (6/10 drafts in 7 verifies) | gate on\n"
metrics = lab.parse_colibri_metrics(log, 3.27)
self.assertEqual(metrics["weight_load_seconds"], 0.3)
self.assertEqual(metrics["rss_after_weight_load_gb"], 0.88)
self.assertEqual(metrics["lookup_decode_tokens"], 76)
self.assertEqual(metrics["lookup_forwards"], 70)
self.assertEqual(metrics["lookup_acceptance_percent"], 60.0)
self.assertEqual(metrics["lookup_decode_tokens_per_second_including_startup"], 23.24)
self.assertIsNone(metrics["generation_tokens_per_second"])
def test_colibri_missing_metrics_are_not_invented(self):
metrics = lab.parse_colibri_metrics("no lookup statistics", 0)
self.assertIsNone(metrics["lookup_decode_tokens"])
self.assertIsNone(metrics["lookup_decode_tokens_per_second_including_startup"])
self.assertIsNone(metrics["rss_after_weight_load_gb"])
def test_remote_install_reports_unavailable_sudo_without_prompting(self):
with mock.patch.dict(lab.os.environ, {"JEANNIE_REMOTE_SERVER": "true"}), mock.patch.object(lab, "command", side_effect=RuntimeError("failed")) as run:
with self.assertRaisesRegex(RuntimeError, "non-interactive sudo"):
lab.apt_command("update")
self.assertEqual(run.call_args.args[0], ["sudo", "-n", "apt-get", "update"])
if __name__ == "__main__":
unittest.main()