Complete M2 validation and lock the G1 evaluation protocol
Run and record both blind LLM validation passes and the external cross-checks. Freeze the evaluation inputs, well splits, and reporting scope with a SHA-256 checksum. Use NPT definition b for DDR-code prediction with definition a as a sensitivity analysis. Retain the class reporting thresholds and record the empty set of eligible classes. Make T4 and OCR fidelity the headline analyses and align the progress report and project documentation. Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
163
scripts/10_m2_rate.py
Normal file
163
scripts/10_m2_rate.py
Normal file
@@ -0,0 +1,163 @@
|
||||
"""Run one fixed local LLM on each blinded item in a fresh conversation and checkpoint its responses."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from volve_dia import audit, m2, paths
|
||||
|
||||
|
||||
def blind_inputs(root: Path) -> tuple[dict, list]:
|
||||
frozen = {}
|
||||
entries = []
|
||||
for kind in ("activity", "section"):
|
||||
sample = root / f"{kind}.jsonl"
|
||||
prompt = root / f"{kind}_prompt.txt"
|
||||
frozen[kind] = {"blind_sha256": m2.digest(sample), "prompt_sha256": m2.digest(prompt)}
|
||||
entries.extend((kind, prompt.read_text(encoding="utf-8"), row, json.loads(row)["item"])
|
||||
for row in sample.read_text(encoding="utf-8").splitlines())
|
||||
return frozen, entries
|
||||
|
||||
|
||||
def schema(kind: str, sections: list[str]) -> dict:
|
||||
enums = ({"section": [*sections, "?"]} if kind == "section" else
|
||||
{"npt": ["y", "n", "?"], "cause": ["none", *audit.CAUSES, "hse"],
|
||||
"operation": [*audit.OP_CLASSES, "?"]})
|
||||
properties = {key: {"type": "string", "enum": choices} for key, choices in enums.items()}
|
||||
properties["note"] = {"type": "string", "maxLength": 240}
|
||||
return {"type": "object", "required": list(properties), "properties": properties, "additionalProperties": False}
|
||||
|
||||
|
||||
def rate_item(client: httpx.Client, model: str, prompt: str, row: str, response_schema: dict,
|
||||
seed: int, settings: dict) -> dict:
|
||||
request = {"model": model, "temperature": settings["temperature"], "max_tokens": settings["max_tokens"],
|
||||
"seed": seed, "messages": [{"role": "user", "content": f"{prompt.rstrip()}\n\nDDR record\n{row}"}],
|
||||
"response_format": {"type": "json_schema", "json_schema": {"name": "rating", "schema": response_schema}}}
|
||||
for attempt in range(3):
|
||||
try:
|
||||
response = client.post("/v1/chat/completions", json=request)
|
||||
response.raise_for_status()
|
||||
choice = response.json()["choices"][0]
|
||||
if choice["finish_reason"] != "stop":
|
||||
raise ValueError(f"Unexpected finish reason: {choice['finish_reason']}")
|
||||
rating = json.loads(choice["message"]["content"])
|
||||
if set(rating) != set(response_schema["required"]):
|
||||
raise ValueError("Incomplete rating.")
|
||||
for key, rule in response_schema["properties"].items():
|
||||
if not isinstance(rating[key], str) or ("enum" in rule and rating[key] not in rule["enum"]):
|
||||
raise ValueError(f"Invalid rating field: {key}")
|
||||
return rating
|
||||
except (ValueError, httpx.RequestError, httpx.HTTPStatusError) as error:
|
||||
if attempt == 2:
|
||||
raise RuntimeError(f"Rating failed after three attempts: {error}") from error
|
||||
time.sleep(attempt + 1)
|
||||
raise AssertionError("Unreachable rating retry state.")
|
||||
|
||||
|
||||
def wait_ready(client: httpx.Client, server: subprocess.Popen) -> None:
|
||||
deadline = time.monotonic() + 120
|
||||
while server.poll() is None and time.monotonic() < deadline:
|
||||
try:
|
||||
if client.get("/health", timeout=2).is_success:
|
||||
return
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(0.4)
|
||||
raise RuntimeError(f"Local llama-server did not become healthy (exit code {server.poll()}).")
|
||||
|
||||
|
||||
def run(args: argparse.Namespace, checkpoint: Path) -> None:
|
||||
config = m2.spec()
|
||||
model, settings = config["raters"][args.rater], config["rater_settings"]
|
||||
first = None
|
||||
if args.pass_number == 2:
|
||||
first = m2.read_json(checkpoint.parent.parent / "pass1" / checkpoint.name)
|
||||
ready = datetime.fromisoformat(first["completed_at"]) + m2.repeatability_gap()
|
||||
if m2.utc_now() < ready:
|
||||
raise ValueError(f"Second pass is eligible at {ready.isoformat()}.")
|
||||
|
||||
weights = (args.runtime / model["file"]).resolve()
|
||||
server_bin = args.server.resolve()
|
||||
frozen, items = blind_inputs(m2.directory() / "blind")
|
||||
runtime_version = subprocess.run([server_bin, "--version"], capture_output=True, text=True, check=True)
|
||||
if settings["engine"].split()[-1].removeprefix("b") not in runtime_version.stderr + runtime_version.stdout:
|
||||
raise ValueError(f"Unexpected llama.cpp build: {runtime_version.stderr or runtime_version.stdout}")
|
||||
settings = settings | {"spec_sha256": m2.digest(m2.VALIDATION), "gpu_layers": args.gpu_layers}
|
||||
provenance = {"model": model, "weights_sha256": m2.digest(weights), "settings": settings,
|
||||
"runtime_version": (runtime_version.stdout + runtime_version.stderr).strip(), "blind": frozen}
|
||||
|
||||
if first is not None and first["provenance"] != provenance:
|
||||
raise ValueError("The second pass requires the frozen first-pass model, settings and inputs.")
|
||||
|
||||
if checkpoint.exists():
|
||||
state = m2.read_json(checkpoint)
|
||||
if state["provenance"] != provenance:
|
||||
raise ValueError(f"Checkpoint provenance differs: {checkpoint}")
|
||||
if state.get("completed_at"):
|
||||
print(f"{args.rater}: pass {args.pass_number} already complete")
|
||||
return
|
||||
else:
|
||||
state = {"provenance": provenance, "started_at": m2.utc_now().isoformat(), "responses": {}}
|
||||
m2.write_json(checkpoint, state)
|
||||
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
command = [str(server_bin), "--model", str(weights), "--alias", args.rater, "--host", "127.0.0.1",
|
||||
"--port", str(port), "--ctx-size", "8192", "--parallel", "1", "--threads", "4",
|
||||
"--n-gpu-layers", args.gpu_layers, "--reasoning", "off", "--no-webui", "--no-context-shift",
|
||||
"--verbosity", "1"]
|
||||
schemas = {kind: schema(kind, config["section_sample"]["sections"]) for kind in ("activity", "section")}
|
||||
with subprocess.Popen(command) as server, httpx.Client(
|
||||
base_url=f"http://127.0.0.1:{port}", timeout=90, trust_env=False,
|
||||
) as client:
|
||||
try:
|
||||
wait_ready(client, server)
|
||||
for index, (kind, prompt, row, item) in enumerate(items):
|
||||
if item in state["responses"]:
|
||||
continue
|
||||
seed = settings["seed_base"] + (args.pass_number - 1) * len(items) + index
|
||||
try:
|
||||
state["responses"][item] = rate_item(client, args.rater, prompt, row, schemas[kind], seed, settings)
|
||||
except RuntimeError as error:
|
||||
raise RuntimeError(f"{args.rater} item {item}: {error}") from error
|
||||
m2.write_json(checkpoint, state)
|
||||
if len(state["responses"]) % 50 == 0:
|
||||
print(f"{args.rater}: {len(state['responses'])}/{len(items)} items")
|
||||
finally:
|
||||
server.terminate()
|
||||
try:
|
||||
server.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
server.kill()
|
||||
state["completed_at"] = m2.utc_now().isoformat()
|
||||
m2.write_json(checkpoint, state)
|
||||
print(f"{args.rater}: pass {args.pass_number} complete, {len(state['responses'])} items")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("rater", choices=list(m2.spec()["raters"]))
|
||||
parser.add_argument("pass_number", type=int, choices=[1, 2])
|
||||
parser.add_argument("--server", type=Path, required=True, help="Path to the pinned llama-server executable")
|
||||
parser.add_argument("--runtime", type=Path, default=paths.outputs_dir() / "audit" / "m2_runtime")
|
||||
parser.add_argument("--gpu-layers", default="all", help="Use 0 with the CPU build")
|
||||
args = parser.parse_args()
|
||||
out = m2.directory() / "ratings" / f"pass{args.pass_number}"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
with (out / f"{args.rater}.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
run(args, out / f"{args.rater}.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user