Add protocol v2: VAI DeepSeek baseline and session sample
Protocol v2 extends locked v1 after Qwen and Llama were stopped: the API cell is filled by DeepSeek-V4.1-Flash on the full T4/C4 and T2 matrix (three repetitions, token cap, checkpoints keyed to the protocol hash), and Sonnet and Haiku answer a fixed auxiliary sample as session subagents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
282
scripts/16_m34_session.py
Normal file
282
scripts/16_m34_session.py
Normal file
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Protocol v2 auxiliary sample for Sonnet and Haiku run as Claude Code session subagents (no API key).
|
||||
|
||||
scripts/16_m34_session.py prepare draw the fixed sample and write prompt batches
|
||||
scripts/16_m34_session.py regroup re-split into smaller batches plus readable .txt copies
|
||||
scripts/16_m34_session.py status batches answered per model
|
||||
scripts/16_m34_session.py collect --model sonnet|haiku validate answers, score, summarise
|
||||
|
||||
Subagents read one batch file and write one answers file under outputs/m34/v2/session/answers/<model>/.
|
||||
Prompts come from the v1 `answer_question` code, so retrieval and instructions match the VAI runs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import m2, m34, t4
|
||||
from volve_dia.m34_features import DELIMITER, render_status
|
||||
from volve_dia.m34_qa import (INSTRUCTION, Retriever, answer_question, json_text, qa_universe, rendered_passages,
|
||||
scoring_row, xml_passages)
|
||||
from volve_dia.m34_report import binary_metric, qa_estimates
|
||||
from volve_dia.m34_v2 import configuration_v2, validate
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
t2_runner = __import__("14_m34_t2_llm")
|
||||
|
||||
CONDITIONS = (("zero_shot", "xml"), ("rag", "xml"), ("c4", "xml"), ("c4", "html"), ("c4", "ocr"))
|
||||
MODELS = ("sonnet", "haiku")
|
||||
|
||||
|
||||
def count(text):
|
||||
"""The protocol states sizes as '300 from ...'; the leading number is the size."""
|
||||
return int(str(text).split()[0])
|
||||
|
||||
|
||||
def paths_for(root):
|
||||
base = root / "m34/v2/session"
|
||||
return base, base / "batches", base / "answers"
|
||||
|
||||
|
||||
def draw_questions(paired, spec, rng):
|
||||
pool = [q for q in paired if q["well"] is not None and q["scope"] != "field"]
|
||||
by_family = {}
|
||||
for family in sorted({q["family"] for q in pool}):
|
||||
items = [q for q in pool if q["family"] == family]
|
||||
order = rng.permutation(len(items))
|
||||
items = [items[i] for i in order]
|
||||
by_well = {}
|
||||
for q in items:
|
||||
by_well.setdefault(q["well"], []).append(q)
|
||||
wells = sorted(by_well)
|
||||
rng.shuffle(wells)
|
||||
queue = []
|
||||
while any(by_well.values()): # Interleave wells so every family spreads over wells.
|
||||
for w in wells:
|
||||
if by_well[w]:
|
||||
queue.append(by_well[w].pop())
|
||||
by_family[family] = queue
|
||||
chosen, round_ = [], 0
|
||||
while len(chosen) < count(spec["questions"]) and any(round_ < len(v) for v in by_family.values()):
|
||||
for family in sorted(by_family):
|
||||
if round_ < len(by_family[family]) and len(chosen) < count(spec["questions"]):
|
||||
chosen.append(by_family[family][round_])
|
||||
round_ += 1
|
||||
return chosen
|
||||
|
||||
|
||||
def draw_t2(frame, n, rng):
|
||||
shares = frame["well"].value_counts()
|
||||
quota = (shares / shares.sum() * n)
|
||||
take = quota.astype(int)
|
||||
for w in (quota - take).sort_values(ascending=False).index[: n - int(take.sum())]:
|
||||
take[w] += 1
|
||||
pieces = [frame[frame["well"].eq(w)].sample(int(k), random_state=int(rng.integers(2**31)))
|
||||
for w, k in take.items() if k]
|
||||
return pd.concat(pieces).sort_values("item")
|
||||
|
||||
|
||||
def prepare(args, protocol, cfg, v2, root, digests):
|
||||
spec = v2["session_sample"]
|
||||
base, batches, _ = paths_for(root)
|
||||
batches.mkdir(parents=True, exist_ok=True)
|
||||
rng = np.random.default_rng(spec["seed"])
|
||||
questions, paired, docs, flagged = qa_universe(root, protocol)
|
||||
chosen = draw_questions(paired, spec["t4"], rng)
|
||||
settings = cfg["qa"]
|
||||
db = root / "ddr/volve_ddr.duckdb"
|
||||
prompts, evidence = {}, {}
|
||||
with t4.connect(db) as con:
|
||||
for mode, source in CONDITIONS:
|
||||
retriever = None
|
||||
if mode != "zero_shot":
|
||||
allowed = docs if mode == "c4" else None
|
||||
passages = xml_passages(con, allowed) if source == "xml" else rendered_passages(root, source, allowed)
|
||||
retriever = Retriever(passages, settings["passages"], settings["context_chars"])
|
||||
for q in chosen:
|
||||
captured = []
|
||||
|
||||
def capture(messages, schema, captured=captured):
|
||||
captured.append(messages)
|
||||
return {"answer": None, "unit": "", "citations": []}
|
||||
|
||||
_, used, _ = answer_question({"question": q["question"]}, capture, settings, mode, [], retriever, None)
|
||||
key = f"{mode}|{source}|{q['id']}"
|
||||
prompts[key] = captured[0][1]["content"]
|
||||
evidence[key] = used
|
||||
keys = sorted(prompts)
|
||||
size = spec["batch_size"]["t4"]
|
||||
files = []
|
||||
for i in range(0, len(keys), size):
|
||||
name = f"t4_{i // size:03d}.json"
|
||||
payload = {"task": "t4", "instruction": INSTRUCTION,
|
||||
"items": [{"key": k, "user": prompts[k]} for k in keys[i:i + size]]}
|
||||
m34.atomic_write(batches / name, json_text(payload).encode())
|
||||
files.append(name)
|
||||
m34.atomic_write(base / "t4_evidence.json", json_text(evidence).encode())
|
||||
features = pd.read_parquet(root / "m34/features_t2.parquet", columns=["item", "well", "text_xml"])
|
||||
sample = draw_t2(features, count(spec["t2"]["items"]), rng)
|
||||
fields = ["TARGET", "PREVIOUS", "NEXT", "24H SUMMARY", "24H OUTLOOK"]
|
||||
texts = {r.item: "\n".join(f"{k}: {v}" for k, v in zip(fields, r.text_xml.split(DELIMITER, 4)))[:12000]
|
||||
for r in sample.itertuples(index=False)}
|
||||
size = spec["batch_size"]["t2"]
|
||||
ids = sorted(texts)
|
||||
for i in range(0, len(ids), size):
|
||||
name = f"t2_{i // size:03d}.json"
|
||||
payload = {"task": "t2", "instruction": t2_runner.INSTRUCTION,
|
||||
"items": [{"key": k, "user": texts[k]} for k in ids[i:i + size]]}
|
||||
m34.atomic_write(batches / name, json_text(payload).encode())
|
||||
files.append(name)
|
||||
manifest = {"seed": spec["seed"], "t4_questions": [q["id"] for q in chosen], "t2_items": ids,
|
||||
"batches": files, "protocol_v2_sha256": m2.digest(Path("configs/protocol_v2.yaml")),
|
||||
"inputs": digests}
|
||||
m2.write_json(base / "manifest.json", manifest)
|
||||
print(f"{len(chosen)} questions, {len(prompts)} T4 prompts, {len(ids)} T2 items, {len(files)} batches")
|
||||
|
||||
|
||||
def regroup(args, protocol, cfg, v2, root, digests):
|
||||
"""Re-split the prompts into smaller batches and write readable .txt copies for subagents (Read tool limit)."""
|
||||
base, batches, answers = paths_for(root)
|
||||
manifest = m2.read_json(base / "manifest.json")
|
||||
items = {"t4": [], "t2": []}
|
||||
instruction = {}
|
||||
for name in manifest["batches"]:
|
||||
payload = json.loads((batches / name).read_text())
|
||||
items[payload["task"]] += payload["items"]
|
||||
instruction[payload["task"]] = payload["instruction"]
|
||||
for old in batches.glob("*"):
|
||||
old.unlink()
|
||||
(base / "batches_txt").mkdir(exist_ok=True)
|
||||
for old in (base / "batches_txt").glob("*"):
|
||||
old.unlink()
|
||||
files = []
|
||||
for task, size in (("t4", args.t4_batch), ("t2", args.t2_batch)):
|
||||
rows = sorted(items[task], key=lambda r: r["key"])
|
||||
for i in range(0, len(rows), size):
|
||||
name = f"{task}_{i // size:03d}.json"
|
||||
part = rows[i:i + size]
|
||||
m34.atomic_write(batches / name, json_text({"task": task, "instruction": instruction[task],
|
||||
"items": part}).encode())
|
||||
text = "\n".join([f"INSTRUCTION: {instruction[task]}", ""] + [
|
||||
f"### ITEM key={r['key']}\n{r['user']}\n### END ITEM" for r in part])
|
||||
m34.atomic_write(base / "batches_txt" / name.replace(".json", ".txt"), text.encode())
|
||||
files.append(name)
|
||||
manifest["batches"] = files
|
||||
manifest["batch_sizes"] = {"t4": args.t4_batch, "t2": args.t2_batch}
|
||||
m2.write_json(base / "manifest.json", manifest)
|
||||
print(f"{len(files)} batches ({args.t4_batch} T4 items, {args.t2_batch} T2 items per batch)")
|
||||
|
||||
|
||||
def status(args, protocol, cfg, v2, root, digests):
|
||||
"""Batches answered per model, incomplete answer files (moved to answers_quarantine) and what is still missing."""
|
||||
base, batches, answers = paths_for(root)
|
||||
manifest = m2.read_json(base / "manifest.json")
|
||||
for model in MODELS:
|
||||
folder = answers / model
|
||||
done, incomplete = [], []
|
||||
for name in manifest["batches"]:
|
||||
path = folder / name
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
given = json.loads(path.read_text())
|
||||
except ValueError:
|
||||
given = {}
|
||||
keys = {i["key"] for i in json.loads((batches / name).read_text())["items"]}
|
||||
(done if set(given) == keys else incomplete).append(name)
|
||||
for name in incomplete:
|
||||
quarantine = answers.parent / "answers_quarantine" / model
|
||||
quarantine.mkdir(parents=True, exist_ok=True)
|
||||
(folder / name).replace(quarantine / name)
|
||||
todo = [b for b in manifest["batches"] if b not in done]
|
||||
print(f"{model}: {len(done)}/{len(manifest['batches'])} batches complete; incomplete moved: {incomplete}; "
|
||||
f"missing ({len(todo)}): {' '.join(t.removesuffix('.json') for t in todo)}")
|
||||
|
||||
|
||||
def collect(args, protocol, cfg, v2, root, digests):
|
||||
base, batches, answers = paths_for(root)
|
||||
manifest = m2.read_json(base / "manifest.json")
|
||||
folder = answers / args.model
|
||||
evidence = json.loads((base / "t4_evidence.json").read_text())
|
||||
questions, paired, _, flagged = qa_universe(root, protocol)
|
||||
by_id = {q["id"]: q for q in questions}
|
||||
db = root / "ddr/volve_ddr.duckdb"
|
||||
out = base / args.model
|
||||
out.mkdir(exist_ok=True)
|
||||
rows, t2_rows = [], []
|
||||
with t4.connect(db) as con:
|
||||
known = dict(con.execute("SELECT report_id, wellbore FROM reports").fetchall())
|
||||
for name in manifest["batches"]:
|
||||
batch = json.loads((batches / name).read_text())
|
||||
path = folder / name
|
||||
given = json.loads(path.read_text()) if path.is_file() else {}
|
||||
for item in batch["items"]:
|
||||
key, response = item["key"], given.get(item["key"])
|
||||
if batch["task"] == "t4":
|
||||
mode, source, qid = key.split("|")
|
||||
try:
|
||||
pred = validate(response, {"required": ["answer", "unit", "citations"]})
|
||||
error = None
|
||||
except (ValueError, TypeError) as e:
|
||||
pred, error = {"answer": None, "citations": []}, "missing" if response is None else str(e)
|
||||
score = scoring_row(by_id[qid], pred, known, evidence[key], [], failed=error is not None)
|
||||
rows.append(score | {"mode": mode, "modality": source, "prediction": pred, "error": error})
|
||||
else:
|
||||
try:
|
||||
a, b = t2_runner.probabilities(response)
|
||||
error = None
|
||||
except (ValueError, TypeError, KeyError) as e:
|
||||
a, b, error = 0.5, 0.5, "missing" if response is None else str(e)
|
||||
t2_rows.append({"item": key, "a": a, "b": b, "error": error})
|
||||
frame = pd.DataFrame(rows)
|
||||
pending = int((frame["error"] == "missing").sum()) # Not answered yet: excluded, not counted as failures.
|
||||
frame = frame[frame["error"] != "missing"].reset_index(drop=True)
|
||||
t2_rows = [r for r in t2_rows if r["error"] != "missing"]
|
||||
ci = protocol["statistics"]["ci"]
|
||||
summary = {"model": args.model, "protocol_v2_sha256": manifest["protocol_v2_sha256"], "t4_unanswered": pending,
|
||||
"t4": [], "t2": []}
|
||||
for (mode, source), data in frame.groupby(["mode", "modality"]):
|
||||
est = qa_estimates(data, ci, True)
|
||||
micro = qa_estimates(data, ci, False)
|
||||
summary["t4"].append({"mode": mode, "modality": source, "n": len(data), "failed": int(data["failed"].sum()),
|
||||
"macro_family": est.get("correct"), "micro": micro.get("correct")})
|
||||
if t2_rows:
|
||||
features = pd.read_parquet(root / "m34/features_t2.parquet", columns=["item", "well", "npt_a", "npt_b"])
|
||||
scores = pd.DataFrame(t2_rows).merge(features, on="item", validate="one_to_one")
|
||||
for d in ("a", "b"):
|
||||
frame2 = pd.DataFrame({"target": scores[f"npt_{d}"].astype(str), "score": scores[d], "well": scores["well"]})
|
||||
metric = binary_metric(frame2)
|
||||
summary["t2"].append({"definition": d, "n": len(scores), "failed": int(scores["error"].notna().sum()),
|
||||
"prevalence": float(scores[f"npt_{d}"].mean()),
|
||||
**m34.confidence(frame2, metric, ci)})
|
||||
with contextlib.closing(sqlite3.connect(out / "results.sqlite")) as store:
|
||||
store.execute("DROP TABLE IF EXISTS t4")
|
||||
store.execute("DROP TABLE IF EXISTS t2")
|
||||
frame.assign(prediction=frame["prediction"].map(json_text)).to_sql("t4", store, index=False)
|
||||
pd.DataFrame(t2_rows).to_sql("t2", store, index=False)
|
||||
m2.write_json(out / "summary.json", summary)
|
||||
print(json.dumps(summary, indent=1)[:3000])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=["prepare", "regroup", "status", "collect"])
|
||||
parser.add_argument("--t4-batch", type=int, default=15)
|
||||
parser.add_argument("--t2-batch", type=int, default=50)
|
||||
parser.add_argument("--model", choices=MODELS)
|
||||
args = parser.parse_args()
|
||||
protocol, cfg, v2 = configuration_v2()
|
||||
root, digests = m34.inputs(protocol)
|
||||
{"prepare": prepare, "regroup": regroup, "status": status, "collect": collect}[args.action](args, protocol, cfg, v2, root, digests)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user