Compare installed models in doctor lab

This commit is contained in:
juvenal.diaz 2026-11-12 13:06:34 -06:00
parent 94e25263a5
commit f487e701c9
3 changed files with 70 additions and 20 deletions

View File

@ -105,13 +105,18 @@ verifies its SHA-256 before importing it for Colibri:
The suite runs ten synthetic diagnostic cases twice per backend, including
contrasting known and unknown intent for the runner, stopped services, and a
maintenance window. Sandbox intent is tested as unknown. Pass a repeat
count from 1 to 5 to `doctor-suite` to change that. It uses the existing
`qwen2.5-coder:7b` Ollama model on CPU for Ollama and llama.cpp, and
Qwen3-Coder-30B-A3B Q4_K_M on CPU for Colibri. The 30B model is the largest
count from 1 to 5 to `doctor-suite` to change that. It tests the existing
Ollama models `qwen2.5:0.5b`, `llama3.2:3b`, `qwen2.5-coder:7b`, and
`qwen2.5:14b` sequentially on CPU. Missing models are reported as skipped;
models whose GGUF weights alone reach the 8 GiB limit are also skipped. The
installed 14B model is approximately 9 GB, so it is expected to be skipped.
It also tests the 7B GGUF using llama.cpp and Qwen3-Coder-30B-A3B Q4_K_M
using Colibri, both on CPU. The 30B model is the largest
candidate in Colibri's pinned catalog with an 8 GB minimum, not a guarantee
that this particular GGUF and context will fit. Keep at least 22 GiB free in
the lab workspace for the download and at least 9 GiB of host MemAvailable
before each backend starts. The suite requires a functioning systemd user
before each backend starts; it waits up to 60 seconds for memory to recover
between runs. The suite requires a functioning systemd user
manager and cgroup v2 memory controller. It refuses to load a model unless an
8 GiB memory limit and zero swap are verified; a low-memory watchdog stops its
own scope. This limit can terminate a model and cannot eliminate host pressure.
@ -123,6 +128,7 @@ 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.
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.

View File

@ -38,6 +38,7 @@ MODEL_SHA256 = "f6050b4da22869aa3fb9d94bb3314e9fc5a027d4741c1f97761c387d6b2b2335
MODEL_FILE = lab.ROOT / "models" / MODEL_NAME
MODEL_DIR = lab.ROOT / "models" / "qwen3-coder-30b-doctor-colibri"
OLLAMA_MODEL = "qwen2.5-coder:7b"
OLLAMA_MODELS = ("qwen2.5:0.5b", "llama3.2:3b", OLLAMA_MODEL, "qwen2.5:14b")
MEMORY_MAX = 8 * 1024 ** 3
START_AVAILABLE = 9 * 1024 ** 3
STOP_AVAILABLE = 768 * 1024 ** 2
@ -76,6 +77,14 @@ def available_bytes():
raise RuntimeError("Cannot read MemAvailable")
def wait_for_available_memory():
deadline = time.monotonic() + 60
while available_bytes() < START_AVAILABLE:
if time.monotonic() >= deadline:
raise RuntimeError("Need at least 9 GiB MemAvailable before starting a model with a 1 GiB reserve")
time.sleep(2)
def prepare():
lab.workspace()
if not lab.COLIBRI_CLI.is_file() or not (lab.COLIBRI_SOURCE / "c/qwen36").is_file():
@ -185,8 +194,7 @@ class ScopedServer:
return
def start(self):
if available_bytes() < START_AVAILABLE:
raise RuntimeError("Need at least 9 GiB MemAvailable before starting a model with a 1 GiB reserve")
wait_for_available_memory()
if not shutil.which("systemd-run") or not shutil.which("systemctl"):
raise RuntimeError("systemd-run and a working user manager are required for the 8 GiB memory limit")
path = self.directory / (self.backend + "-server.log")
@ -246,7 +254,7 @@ def case_report(case_id, tsv, directory):
def answer(server, backend, model, report):
prompt = doctor.build_prompt(report)
if backend == "ollama":
if backend.startswith("ollama-"):
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)
@ -276,29 +284,47 @@ def suite_run(repeats):
if not server_bin.is_file() or not shutil.which("ollama"):
raise RuntimeError("Install llama.cpp with ./jeannie ai-lab install and ensure Ollama is installed")
lab.require_idle_ollama()
model_path = suite.model_from_modelfile(OLLAMA_MODEL)
if not model_path.is_file() or model_path.parent.name != "blobs":
raise RuntimeError("The Ollama 7B GGUF blob is unavailable or not in a model store")
with model_path.open("rb") as stream:
if stream.read(4) != b"GGUF":
raise RuntimeError("The Ollama 7B model is not a GGUF file")
model_sha = lab.digest(model_path)
models = {}
skipped = {}
for name in OLLAMA_MODELS:
key = "ollama-" + name.replace(":", "-")
try:
path = suite.model_from_modelfile(name)
if not path.is_file() or path.parent.name != "blobs":
raise RuntimeError("model GGUF is unavailable or not in an Ollama model store")
with path.open("rb") as stream:
if stream.read(4) != b"GGUF":
raise RuntimeError("model file is not GGUF")
if path.stat().st_size >= MEMORY_MAX:
raise RuntimeError("model weights alone are at least the 8 GiB scope limit")
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]
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"
report_dir = lab.ROOT / "reports" / (datetime.now(timezone.utc).strftime("doctor-suite-%Y%m%dT%H%M%SZ-") + uuid.uuid4().hex[:8])
report_dir.mkdir(parents=True, mode=0o700)
results = []
resource_usage = {}
try:
for backend in ("ollama", "llama-cpu", "colibri"):
for backend, selected_model in backends:
if backend in skipped:
print(f"Skipping {backend}: {skipped[backend]}", flush=True)
continue
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 == "ollama":
if 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"], OLLAMA_MODEL, "/api/tags"
command, model, health = [shutil.which("ollama"), "serve"], selected_model, "/api/tags"
elif backend == "llama-cpu":
model_path = models[OLLAMA_MODEL]["path"]
command = [str(server_bin), "-m", str(model_path), "--host", "127.0.0.1", "--port", str(chosen_port), "--alias", "doctor-lab-7b", "--device", "none", "-ngl", "0", "-c", str(CONTEXT)]
model, health = "doctor-lab-7b", "/health"
else:
@ -340,7 +366,7 @@ def suite_run(repeats):
server.stop()
finally:
summary = {}
for backend in ("ollama", "llama-cpu", "colibri"):
for backend, _ in backends:
rows = [row for row in results if row["backend"] == backend]
times = [row["elapsed_seconds"] for row in rows if "elapsed_seconds" in row]
summary[backend] = {"completed": len(rows), "valid": sum(row.get("contract") == "valid" for row in rows),
@ -348,9 +374,11 @@ def suite_run(repeats):
"errors": sum(row.get("contract") == "error" for row in rows),
"median_seconds": round(statistics.median(times), 2) if times else None,
**resource_usage.get(backend, {})}
if backend in skipped:
summary[backend]["skipped"] = skipped[backend]
output = {"cases": [entry[0] for entry in CASES], "review_rubric": RUBRIC, "repeats": repeats, "results": results,
"summary": summary,
"models": {"ollama_and_llama": {"name": OLLAMA_MODEL, "sha256": model_sha},
"models": {**{name: {"sha256": details["sha256"]} for name, details in models.items()},
"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},

View File

@ -13,6 +13,22 @@ spec.loader.exec_module(lab)
class DoctorModelLabTests(unittest.TestCase):
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"))
def test_each_ollama_model_uses_the_isolated_ollama_api(self):
with tempfile.TemporaryDirectory() as directory:
name, tsv = lab.CASES[0]
report = lab.case_report(name, tsv, Path(directory))
server = mock.Mock(base="http://127.0.0.1:9999")
for model in lab.OLLAMA_MODELS:
backend = "ollama-" + model.replace(":", "-")
with mock.patch.object(lab, "request", return_value={"response": "{}", "eval_count": 2}) as call:
lab.answer(server, backend, model, report)
self.assertEqual(call.call_args.args[0], "http://127.0.0.1:9999/api/generate")
self.assertEqual(call.call_args.args[1]["model"], model)
self.assertEqual(call.call_args.args[1]["options"]["num_gpu"], 0)
def test_desired_state_cases_distinguish_known_from_unknown(self):
cases = dict(lab.CASES)
self.assertIn("intentionally", cases["runner_disabled"])
@ -58,7 +74,7 @@ class DoctorModelLabTests(unittest.TestCase):
lab.doctor.validate(response, report)
def test_memory_preflight_does_not_start_server(self):
with mock.patch.object(lab, "available_bytes", return_value=lab.START_AVAILABLE - 1), \
with mock.patch.object(lab, "wait_for_available_memory", side_effect=RuntimeError("Need at least 9 GiB")), \
mock.patch.object(lab.subprocess, "Popen") as launch:
server = lab.ScopedServer([], {}, "", "", Path("/unused"), "test")
with self.assertRaisesRegex(RuntimeError, "9 GiB"):