#!/usr/bin/env python3 """Run or resume one T4/C4 model through a local llama.cpp server or an explicitly configured API.""" from __future__ import annotations import argparse import contextlib import fcntl import json import os import socket import sqlite3 import subprocess import time from pathlib import Path import httpx from volve_dia import m2, m34, paths, t4 from volve_dia.m34_features import render_status from volve_dia.m34_qa import (C4_MODES, MODES, QueryTool, Retriever, answer_question, few_examples, json_text, qa_universe, rendered_passages, scoring_row, xml_passages) MODALITIES = ("xml", "html", "ocr") class ModelFailure(RuntimeError): pass @contextlib.contextmanager def local_server(args, cfg, exact_model): weights = Path(exact_model["path"]) binary = args.server.resolve() version = subprocess.run([binary, "--version"], capture_output=True, check=True) if b"12491" not in version.stdout + version.stderr: raise ValueError("Expected llama.cpp b12491.") with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] command = [str(binary), "--model", str(weights), "--alias", args.model, "--host", "127.0.0.1", "--port", str(port), "--ctx-size", str(cfg["context_size"]), "--parallel", "1", "--threads", "4", "--n-gpu-layers", args.gpu_layers, "--reasoning", "off", "--no-webui", "--no-context-shift", "--verbosity", "1"] with subprocess.Popen(command) as server, httpx.Client( base_url=f"http://127.0.0.1:{port}/v1/", timeout=100, trust_env=False, ) as client: try: deadline = time.monotonic() + 120 while time.monotonic() < deadline and server.poll() is None: try: if client.get("/health", timeout=2).is_success: break except httpx.TransportError: pass time.sleep(0.4) else: raise ModelFailure("Local llama.cpp server failed to start.") yield client finally: if server.poll() is None: server.terminate() try: server.wait(timeout=10) except subprocess.TimeoutExpired: server.kill() def chat(client, model, local, messages, schema, seed, cfg): response_format = {"type": "json_object"} if local: response_format["schema"] = schema data = {"model": model, "messages": messages, "temperature": cfg["temperature"], "max_tokens": cfg["max_tokens"], "seed": seed, "response_format": response_format} for attempt in range(3): try: res = client.post("chat/completions", json=data) status = res.status_code if status in (401, 403, 404, 429) and not local: raise ModelFailure(f"API service returned HTTP {status}.") res.raise_for_status() choice = res.json()["choices"][0] body = json.loads(choice["message"]["content"]) if not isinstance(body, dict) or not set(schema["required"]) <= body.keys(): raise ValueError("Invalid response shape.") if "citations" in body and (not isinstance(body["citations"], list) or not all(isinstance(c, str) for c in body["citations"])): raise ValueError("Invalid citation shape.") if "answer" in body: if body["answer"] is not None and not isinstance(body["answer"], (str, list, int, float, bool)): raise ValueError("Invalid answer.") if not isinstance(body["unit"], str): raise ValueError("Invalid unit.") if "tool" in body and (body["tool"] not in ("query", "search", "finish") or not isinstance(body["arguments"], dict)): raise ValueError("Invalid tool call.") json_text(body) # Reject non-finite numeric values from a non-conforming server. return body except (httpx.HTTPError, ValueError, IndexError, KeyError, TypeError) as error: if attempt == 2: # Exception details may contain provider URLs or request data. raise ValueError(f"Completion failed: {type(error).__name__}") from None time.sleep(attempt + 1) def model_config(args, root, cfg): if args.model == "api": base = os.environ.get("VOLVE_DIA_M34_API_BASE") name = os.environ.get("VOLVE_DIA_M34_API_MODEL") token = os.environ.get("VOLVE_DIA_M34_API_KEY") if not all((base, name, token)): raise ValueError("Set VOLVE_DIA_M34_API_BASE, VOLVE_DIA_M34_API_MODEL and VOLVE_DIA_M34_API_KEY.") client = httpx.Client(base_url=base.rstrip("/") + "/", headers={"Authorization": f"Bearer {token}"}, timeout=100) return {"model": name, "provider": httpx.URL(base).host}, client args.server = args.server or (root / "audit/m2_runtime/llama-b12491/llama-server") pin = cfg["llama"] if args.model == "llama" else m2.spec()["raters"][args.model] model = (args.weights or (root / "audit/m2_runtime" / pin["file"])).resolve() exact = {"model": args.model, "path": str(model), "pin": pin, "weights_sha256": m2.digest(model), "runtime_sha256": m2.digest(args.server), "gpu_layers": args.gpu_layers} return exact, local_server(args, cfg, exact) def cases(questions, paired, clean, selected_modes): for mode in selected_modes: eligible = {"c4": paired, "c4_clean": clean}.get(mode, questions) for q in eligible: for modality in (MODALITIES if mode in C4_MODES else ("xml",)): yield mode, modality, q def run(args, protocol, cfg, root, provenance, checkpoint): questions, paired, docs, date_flagged = qa_universe(root, protocol) clean = [q for q in paired if q["id"] not in date_flagged] _, excluded_reports, _ = render_status(root) spec = cfg["qa"] model, client_context = model_config(args, root, spec) provenance |= {"model": model} db = root / "ddr/volve_ddr.duckdb" modes = [args.mode] if args.mode else ["c4", "c4_clean", "rag", "agent", "tool_only", "zero_shot", "few_shot"] if args.limit: development = protocol["splits"]["development_wells"] questions, paired, clean = ([q for q in subset if q["well"] in development][:args.limit] for subset in (questions, paired, clean)) schedule = list(cases(questions, paired, clean, modes)) seeds = [args.seed] if args.seed is not None else protocol["statistics"]["seeds"] with contextlib.closing(sqlite3.connect(checkpoint)) as store, t4.connect(db) as con: store.execute("CREATE TABLE IF NOT EXISTS metadata (provenance TEXT)") store.execute("""CREATE TABLE IF NOT EXISTS predictions ( mode TEXT, modality TEXT, seed INTEGER, item TEXT, data TEXT, PRIMARY KEY (mode, modality, seed, item))""") if prior := store.execute("SELECT provenance FROM metadata").fetchone(): if json.loads(prior[0]) != provenance: raise ValueError("T4 checkpoint provenance differs.") else: store.execute("INSERT INTO metadata VALUES (?)", [json_text(provenance)]) store.commit() done = set(store.execute("SELECT mode, modality, seed, item FROM predictions").fetchall()) pending = [(mode, source, seed, q) for seed in seeds for mode, source, q in schedule if (mode, source, seed, q["id"]) not in done] if not pending: print("All requested T4 predictions are already present.") return known_reports = dict(con.execute("SELECT report_id, wellbore FROM reports").fetchall()) tool = QueryTool(con) if any(mode in ("agent", "tool_only") for mode in modes) else None indexes = {} with client_context as client: for i, (mode, source, seed, q) in enumerate(pending, 1): index_key = (mode if mode in C4_MODES else "full", source) retrieve = mode in ("rag", "agent", *C4_MODES) if retrieve and index_key not in indexes: allowed = {"c4": docs, "c4_clean": docs - excluded_reports}.get(mode) passages = (xml_passages(con, allowed) if source == "xml" else rendered_passages(root, source, allowed)) indexes[index_key] = Retriever(passages, spec["passages"], spec["context_chars"]) examples = few_examples(questions, q, protocol["splits"]["development_wells"], spec["few_shot_count"]) if mode == "few_shot" else [] try: predicted, evidence, trace = answer_question( {"question": q["question"]}, lambda messages, schema: chat(client, model["model"], args.model != "api", messages, schema, seed, spec), spec, mode, examples, indexes.get(index_key) if retrieve else None, tool) error = None except ValueError as failure: error = str(failure) predicted, evidence, trace = {"answer": None, "citations": []}, [], [] score = scoring_row(q, predicted, known_reports, evidence, trace, failed=error is not None) record = score | {"prediction": predicted, "retrieved": evidence, "trace": trace, "error": error, "date_flag": q["id"] in date_flagged, "n_examples": len(examples)} with store: store.execute("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)", [mode, source, seed, q["id"], json_text(record)]) if i == 1 or i % 50 == 0 or i == len(pending): print(f"{args.model}: {i}/{len(pending)} new predictions ({mode}/{source})", flush=True) def main(): paths.load_env() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", default="qwen", choices=["qwen", "llama", "api"]) parser.add_argument("--mode", choices=MODES) parser.add_argument("--seed", type=int, choices=[0, 1, 2]) parser.add_argument("--server", type=Path) parser.add_argument("--weights", type=Path) parser.add_argument("--gpu-layers", default="all") parser.add_argument("--limit", type=int, help="Run an isolated smoke check on the first N items in each subset.") args = parser.parse_args() if args.limit is not None and args.limit < 1: parser.error("--limit must be positive.") protocol, cfg = m34.configuration() root, inputs = m34.inputs(protocol) out = root / "m34" / ("smoke" if args.limit else "qa") out.mkdir(parents=True, exist_ok=True) name = f"{args.model}-{m34.code_fingerprint('qa')[:12]}" if args.limit else args.model path = out / f"{name}.sqlite" with path.with_suffix(".lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) run(args, protocol, cfg, root, {"inputs": inputs, "code": m34.code_fingerprint('qa')}, path) if __name__ == "__main__": main()