Rank doctor models with blinded reviews
Homelab Main / validate (push) Successful in 1m18s Details
Homelab Main / running-update (push) Successful in 3s Details
Homelab Main / debian-ops (push) Failing after 3s Details

This commit is contained in:
juvenal.diaz 2026-11-12 17:43:15 -06:00
parent f487e701c9
commit e3564e211b
5 changed files with 234 additions and 18 deletions

View File

@ -128,10 +128,36 @@ review the cases and responses manually. The lab accepts one complete outer
JSON code fence before applying the same validator and preserves raw answers;
it does not change production Doctor parsing. Different model sizes and output
constraints also mean Colibri quality results do not isolate engine performance.
OmniRoute's external model route is not part of this local-only comparison.
The suite also sends the same **synthetic cases** to the smart direct model in
`models.env` through the loopback OmniRoute gateway. If no direct model is
recorded, it uses the smart route alias. Override with
`LAB_DOCTOR_LAB_OMNI_MODEL` or `LAB_DOCTOR_LAB_OMNI_URL` (loopback `/v1` only).
OmniRoute can fall back or change providers; the report records the requested
and returned model names where available, which are not proof of backend identity.
This can use an external provider and its quotas; no live Doctor evidence is sent.
External inference has no local scope memory measurement or GPU equivalence.
This experiment does not change the production doctor model or stop services.
Ollama must be idle before the test; stop or unload models deliberately first.
Each run writes `report.json` and a shuffled `blind-review.json` in its private
report directory. Review the evidence, rubric and answer in each entry and fill
in three integer fields: `accuracy` (0 wrong, 1 partial, 2 supported),
`uncertainty` (0 unsupported certainty, 1 partial, 2 appropriate uncertainty),
and `next_step` (0 unhelpful or unsafe, 1 useful and safe). IDs conceal the
backend but output style may reveal it. Leave null if not reviewed. Then run:
```sh
./jeannie ai-lab doctor-rank /path/to/report.json /path/to/blind-review.json
```
The ranking averages the five available points over all cases and repeats.
Contract failures or request errors score zero; skipped, incomplete, and
partially reviewed backends remain unranked. Equal scores tie; latency and
memory are separate columns and do not change quality rank. This is a small,
human-scored benchmark, not a statistical accuracy guarantee. Scores depend on
the evaluator and the cases; run additional cases and independent reviews before
changing production routing.
## Repeated comparison suite
After the llama.cpp and Colibri installation and model preparation above:

View File

@ -86,7 +86,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|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]} Manage AI experiments.
ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-rank REPORT REVIEW} Manage AI experiments.
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).
@ -330,7 +330,8 @@ case "${1:-}" in
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; } ;;
suite) [[ $# -le 3 && "${3:-3}" =~ ^([1-9]|10)$ ]] || { echo "Usage: ./jeannie ai-lab suite [REPEATS 1-10]" >&2; exit 2; } ;;
doctor-suite) [[ $# -le 3 && "${3:-2}" =~ ^[1-5]$ ]] || { echo "Usage: ./jeannie ai-lab doctor-suite [REPEATS 1-5]" >&2; exit 2; } ;;
*) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench|suite|doctor-prepare|doctor-suite}" >&2; exit 2 ;;
doctor-rank) [[ $# -eq 4 ]] || { echo "Usage: ./jeannie ai-lab doctor-rank REPORT REVIEW" >&2; exit 2; } ;;
*) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench|suite|doctor-prepare|doctor-suite|doctor-rank}" >&2; exit 2 ;;
esac
case "${2:-plan}" in install|colibri-install|colibri-prepare|doctor-prepare) record_change_journal "ai-lab" "$@" ;; esac
if [[ "${2:-plan}" == suite ]]; then
@ -339,6 +340,8 @@ case "${1:-}" in
python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" prepare
elif [[ "${2:-plan}" == doctor-suite ]]; then
python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" suite "${@:3}"
elif [[ "${2:-plan}" == doctor-rank ]]; then
python3 "${REPO_ROOT}/scripts/doctor-model-rank.py" "${@:3}"
else
python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}"
fi

View File

@ -6,6 +6,7 @@ import json
import os
import re
import signal
import secrets
from pathlib import Path
import shutil
import socket
@ -18,6 +19,7 @@ import time
import urllib.error
import urllib.request
import uuid
from urllib.parse import urlsplit
from datetime import datetime, timezone
@ -131,9 +133,9 @@ def port():
return sock.getsockname()[1]
def request(url, payload=None, timeout=5):
def request(url, payload=None, timeout=5, headers=None):
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", **(headers or {})})
with urllib.request.urlopen(req, timeout=timeout) as response:
return json.load(response)
@ -244,6 +246,24 @@ class ScopedServer:
raise
class ExternalServer:
"""An already running gateway; never stop it or claim its memory use."""
cgroup = None
minimum_available = None
low_memory = False
process = None
def __init__(self, base, api_key):
self.base = base
self.api_key = api_key
def start(self):
pass
def stop(self):
pass
def case_report(case_id, tsv, directory):
path = directory / (case_id + ".tsv")
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
@ -258,13 +278,48 @@ def answer(server, backend, model, report):
payload = {"model": model, "prompt": prompt, "format": doctor.schema(report), "stream": False,
"keep_alive": "5m", "options": {"num_ctx": CONTEXT, "num_predict": OUTPUT_TOKENS, "temperature": 0, "num_gpu": 0}}
data = request(server.base + "/api/generate", payload, timeout=1800)
return data.get("response", ""), data.get("eval_count")
return data.get("response", ""), data.get("eval_count"), data.get("model")
payload = {"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0,
"max_tokens": OUTPUT_TOKENS, "stream": False}
if backend == "llama-cpu":
payload["response_format"] = {"type": "json_object"}
data = request(server.base + "/v1/chat/completions", payload, timeout=1800)
return data["choices"][0]["message"].get("content", ""), (data.get("usage") or {}).get("completion_tokens")
if backend == "omniroute":
payload["response_format"] = {"type": "json_object"}
headers = {"Authorization": "Bearer " + server.api_key} if backend == "omniroute" else None
if headers is None:
data = request(server.base + "/v1/chat/completions", payload, timeout=1800)
else:
data = request(server.base + "/v1/chat/completions", payload, timeout=1800, headers=headers)
return data["choices"][0]["message"].get("content", ""), (data.get("usage") or {}).get("completion_tokens"), data.get("model")
def read_env_values(path, keys):
"""Read generated KEY=value files as data without executing shell code."""
values = {}
try:
for line in Path(path).read_text().splitlines():
key, separator, value = line.removeprefix("export ").partition("=")
if separator and key in keys:
values[key] = value.strip().strip("\"'")
except FileNotFoundError:
pass
return values
def external_config():
routes = read_env_values(os.getenv("LAB_AI_STACK_MODEL_ROUTES_FILE", "/data/homelab-ai-stack/models.env"),
{"AI_STACK_AGENT_SMART_DIRECT_MODEL", "AI_STACK_AGENT_SMART_MODEL"})
settings = read_env_values(os.getenv("LAB_AI_STACK_TOOLS_ENV_FILE", "/data/homelab-ai-stack/ai-tools.env"),
{"OPENAI_BASE_URL", "OPENAI_API_KEY", "OMNIROUTE_API_KEY"})
url = os.getenv("LAB_DOCTOR_LAB_OMNI_URL", settings.get("OPENAI_BASE_URL", "http://127.0.0.1:20128/v1")).rstrip("/")
parsed = urlsplit(url)
if parsed.scheme != "http" or parsed.hostname not in ("localhost", "127.0.0.1", "::1") or parsed.path != "/v1" or parsed.query or parsed.fragment or parsed.username or parsed.password:
raise RuntimeError("Doctor lab OmniRoute endpoint must be local HTTP with a /v1 path")
model = os.getenv("LAB_DOCTOR_LAB_OMNI_MODEL") or routes.get("AI_STACK_AGENT_SMART_DIRECT_MODEL") or routes.get("AI_STACK_AGENT_SMART_MODEL")
if not model:
raise RuntimeError("No OmniRoute model found in the generated routes file")
key = os.getenv("LAB_DOCTOR_LAB_OMNI_KEY") or settings.get("OMNIROUTE_API_KEY") or settings.get("OPENAI_API_KEY") or "sk_omniroute"
return url[:-3], model, key
def parse_answer(response):
@ -300,7 +355,13 @@ def suite_run(repeats):
models[name] = {"path": path, "sha256": lab.digest(path)}
except (RuntimeError, OSError, subprocess.TimeoutExpired) as exc:
skipped[key] = str(exc)
backends = [("ollama-" + name.replace(":", "-"), name) for name in OLLAMA_MODELS]
try:
external_base, external_model, external_key = external_config()
except (OSError, RuntimeError, ValueError):
external_base, external_model, external_key = "", "unavailable", ""
skipped["omniroute"] = "OmniRoute local endpoint or generated model route is unavailable"
backends = [("omniroute", external_model)]
backends += [("ollama-" + name.replace(":", "-"), name) for name in OLLAMA_MODELS]
backends += [("llama-cpu", OLLAMA_MODEL), ("colibri", MODEL_NAME)]
if OLLAMA_MODEL not in models:
skipped["llama-cpu"] = "The 7B Ollama GGUF is unavailable or exceeds the scope limit"
@ -313,13 +374,17 @@ def suite_run(repeats):
if backend in skipped:
print(f"Skipping {backend}: {skipped[backend]}", flush=True)
continue
lab.require_idle_ollama()
if backend != "omniroute":
lab.require_idle_ollama()
chosen_port = port()
base = f"http://127.0.0.1:{chosen_port}"
env = dict(os.environ)
env.pop("COLI_API_KEY", None)
env.update(COLI_VULKAN="0", COLI_CUDA="0")
if backend.startswith("ollama-"):
if backend == "omniroute":
server = ExternalServer(external_base, external_key)
model = selected_model
elif backend.startswith("ollama-"):
model_path = models[selected_model]["path"]
env.update(OLLAMA_HOST=f"127.0.0.1:{chosen_port}", OLLAMA_MODELS=str(model_path.parent.parent), OLLAMA_VULKAN="0")
command, model, health = [shutil.which("ollama"), "serve"], selected_model, "/api/tags"
@ -330,9 +395,10 @@ def suite_run(repeats):
else:
command = [sys.executable, str(lab.COLIBRI_CLI), "serve", "--model", str(MODEL_DIR), "--host", "127.0.0.1", "--port", str(chosen_port), "--model-id", "doctor-lab-30b", "--cap", "32", "--gpu", "none", "--ctx", str(CONTEXT), "--ngen", str(OUTPUT_TOKENS)]
model, health = "doctor-lab-30b", "/health"
server = ScopedServer(command, env, base, health, report_dir, backend)
if backend != "omniroute":
server = ScopedServer(command, env, base, health, report_dir, backend)
try:
print(f"Starting {backend} ({model}) in an 8 GiB, zero-swap scope...", flush=True)
print(f"Testing {backend} ({model})" + (" through OmniRoute; synthetic cases leave this host." if backend == "omniroute" else " in an 8 GiB, zero-swap scope..."), flush=True)
server.start()
for repeat in range(repeats):
for case_id, tsv in CASES:
@ -340,10 +406,10 @@ def suite_run(repeats):
report = case_report(case_id + f"-{repeat + 1}-{backend}", tsv, report_dir)
start = time.monotonic()
row = {"backend": backend, "model": model, "case": case_id, "repeat": repeat + 1,
"manual_review_required": True}
"review_id": uuid.uuid4().hex, "manual_review_required": True}
try:
response, tokens = answer(server, backend, model, report)
row.update(elapsed_seconds=round(time.monotonic() - start, 2), generated_tokens=tokens)
response, tokens, returned_model = answer(server, backend, model, report)
row.update(elapsed_seconds=round(time.monotonic() - start, 2), generated_tokens=tokens, returned_model=returned_model)
try:
doctor.validate(parse_answer(response), report)
row["contract"] = "valid"
@ -353,7 +419,7 @@ def suite_run(repeats):
except (OSError, ValueError, KeyError, IndexError, urllib.error.URLError) as exc:
row.update(contract="error", error=str(exc), elapsed_seconds=round(time.monotonic() - start, 2))
results.append(row)
if server.low_memory or server.process.poll() is not None:
if server.low_memory or (server.process is not None and server.process.poll() is not None):
raise RuntimeError(f"{backend} stopped during inference; see its private server log")
finally:
peak = None
@ -382,13 +448,25 @@ def suite_run(repeats):
"colibri": {"name": MODEL_NAME, "sha256": MODEL_SHA256}},
"limits": {"scope_memory_max_bytes": MEMORY_MAX, "scope_swap_max_bytes": 0,
"minimum_start_available_bytes": START_AVAILABLE, "watchdog_stop_available_bytes": STOP_AVAILABLE},
"interpretation": "Contract validation does not establish diagnostic correctness. Compare responses manually; models differ between Colibri and the other engines."}
"interpretation": "Contract validation does not establish diagnostic correctness. Compare responses manually; model families, provider constraints and hardware differ. OmniRoute can route or fall back to another model."}
path = report_dir / "report.json"
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as stream:
json.dump(output, stream, indent=2)
stream.write("\n")
print(f"Private report: {path}", flush=True)
cases = dict(CASES)
review = [{"id": row["review_id"], "case": row["case"], "evidence": cases[row["case"]],
"rubric": RUBRIC[row["case"]], "response": row.get("response", ""),
"accuracy": None, "uncertainty": None, "next_step": None}
for row in results if row.get("contract") == "valid"]
secrets.SystemRandom().shuffle(review)
review_path = report_dir / "blind-review.json"
fd = os.open(review_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as stream:
json.dump({"instructions": "Score accuracy and uncertainty 0-2 each, next_step 0-1. Leave null if unreviewed. Answers are blinded; do not include sensitive information.", "responses": review}, stream, indent=2)
stream.write("\n")
print(f"Blinded review: {review_path}", flush=True)
print(json.dumps(summary, indent=2), flush=True)
if any(row.get("contract") == "error" for row in results):
raise RuntimeError("One or more inference requests failed; see the private report and logs")

View File

@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Rank Doctor lab results after a blinded human review."""
import json
from pathlib import Path
import sys
def rank(report, review):
rows = report["results"]
reviewed = {}
for item in review["responses"]:
key = item["id"]
if key in reviewed:
raise ValueError("duplicate review ID")
scores = [item.get("accuracy"), item.get("uncertainty"), item.get("next_step")]
if any(value is None for value in scores):
reviewed[key] = None
continue
if any(type(value) is not int or not 0 <= value <= maximum
for value, maximum in zip(scores, (2, 2, 1))):
raise ValueError("review scores must be integers: accuracy 0-2, uncertainty 0-2, next_step 0-1")
reviewed[key] = sum(scores)
ids = [row.get("review_id") for row in rows]
if None in ids or len(ids) != len(set(ids)):
raise ValueError("report review IDs missing or duplicated")
expected_ids = {row["review_id"] for row in rows if row.get("contract") == "valid"}
if set(reviewed) != expected_ids:
raise ValueError("review IDs do not match the report's valid responses")
expected_cases = {(case, repeat) for case in report["cases"] for repeat in range(1, report["repeats"] + 1)}
entries = []
for backend, summary in report["summary"].items():
selected = [row for row in rows if row["backend"] == backend]
keys = [(row["case"], row["repeat"]) for row in selected]
complete = len(keys) == len(expected_cases) and set(keys) == expected_cases
pending = sum(reviewed[row["review_id"]] is None for row in selected if row.get("contract") == "valid")
scores = [reviewed[row["review_id"]] if row.get("contract") == "valid" else 0 for row in selected]
entry = {"backend": backend, "model": selected[0]["model"] if selected else None,
"completed": len(selected), "expected": len(expected_cases), "pending_review": pending,
"contract_failures_scored_zero": sum(row.get("contract") != "valid" for row in selected),
"median_seconds": summary.get("median_seconds"), "scope_peak_bytes": summary.get("scope_peak_bytes"),
"score_out_of_5": round(sum(scores) / len(expected_cases), 3) if complete and not pending else None}
if summary.get("skipped"):
entry["skipped"] = summary["skipped"]
entries.append(entry)
entries.sort(key=lambda entry: (entry["score_out_of_5"] is None, -(entry["score_out_of_5"] or 0), entry["backend"]))
return {"method": "Blinded human accuracy 0-2, uncertainty 0-2 and next step 0-1 per valid response; contract failures score zero. Complete runs only; equal scores tie. Speed and memory are reported separately.", "ranking": entries}
def main():
if len(sys.argv) != 3:
raise ValueError("Usage: ./jeannie ai-lab doctor-rank REPORT.json blind-review.json")
with Path(sys.argv[1]).open() as stream:
report = json.load(stream)
with Path(sys.argv[2]).open() as stream:
review = json.load(stream)
print(json.dumps(rank(report, review), indent=2))
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as exc:
print(f"Doctor model ranking: {exc}", file=sys.stderr)
sys.exit(1)

View File

@ -10,9 +10,54 @@ ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("doctor_model_lab", ROOT / "scripts/doctor-model-lab.py")
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
rank_spec = importlib.util.spec_from_file_location("doctor_model_rank", ROOT / "scripts/doctor-model-rank.py")
ranker = importlib.util.module_from_spec(rank_spec)
rank_spec.loader.exec_module(ranker)
class DoctorModelLabTests(unittest.TestCase):
def test_external_request_uses_the_same_evidence_and_private_key(self):
with tempfile.TemporaryDirectory() as directory:
name, tsv = lab.CASES[0]
report = lab.case_report(name, tsv, Path(directory))
server = lab.ExternalServer("http://127.0.0.1:20128", "example-private-key")
result = {"choices": [{"message": {"content": "{}"}}], "model": "provider/model"}
with mock.patch.object(lab, "request", return_value=result) as call:
_, _, actual = lab.answer(server, "omniroute", "provider/model", report)
self.assertEqual(actual, "provider/model")
self.assertEqual(call.call_args.args[0], "http://127.0.0.1:20128/v1/chat/completions")
self.assertIn("gitea-runner", call.call_args.args[1]["messages"][0]["content"])
self.assertEqual(call.call_args.kwargs["headers"]["Authorization"], "Bearer example-private-key")
def test_external_config_reads_values_without_executing_them_and_requires_loopback(self):
with tempfile.TemporaryDirectory() as directory:
routes = Path(directory) / "routes"
config = Path(directory) / "settings"
routes.write_text("AI_STACK_AGENT_SMART_DIRECT_MODEL=provider/model\n")
config.write_text("OPENAI_BASE_URL=http://127.0.0.1:20128/v1\nOPENAI_API_KEY=private\n")
env = {"LAB_AI_STACK_MODEL_ROUTES_FILE": str(routes), "LAB_AI_STACK_TOOLS_ENV_FILE": str(config)}
with mock.patch.dict(lab.os.environ, env, clear=True):
self.assertEqual(lab.external_config(), ("http://127.0.0.1:20128", "provider/model", "private"))
with mock.patch.dict(lab.os.environ, {**env, "LAB_DOCTOR_LAB_OMNI_URL": "http://outside.example/v1"}, clear=True):
with self.assertRaises(RuntimeError):
lab.external_config()
def test_ranking_requires_complete_blind_reviews_and_scores_failures_zero(self):
report = {"cases": ["one", "two"], "repeats": 1,
"summary": {"a": {"median_seconds": 2}, "b": {}, "skipped": {"skipped": "missing"}},
"results": [{"backend": "a", "model": "A", "case": "one", "repeat": 1, "review_id": "1", "contract": "valid"},
{"backend": "a", "model": "A", "case": "two", "repeat": 1, "review_id": "2", "contract": "rejected"},
{"backend": "b", "model": "B", "case": "one", "repeat": 1, "review_id": "3", "contract": "valid"}]}
review = {"responses": [{"id": "1", "accuracy": 2, "uncertainty": 2, "next_step": 1},
{"id": "3", "accuracy": None, "uncertainty": None, "next_step": None}]}
result = ranker.rank(report, review)["ranking"]
self.assertEqual(result[0]["score_out_of_5"], 2.5)
self.assertEqual(result[0]["contract_failures_scored_zero"], 1)
self.assertTrue(all(row["score_out_of_5"] is None for row in result[1:]))
review["responses"][0]["accuracy"] = 3
with self.assertRaises(ValueError):
ranker.rank(report, review)
def test_comparison_includes_the_installed_models(self):
self.assertEqual(lab.OLLAMA_MODELS, ("qwen2.5:0.5b", "llama3.2:3b", "qwen2.5-coder:7b", "qwen2.5:14b"))