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:
2026-11-20 07:00:36 +00:00
parent 59fa1f4d08
commit c7e94aa2c9
10 changed files with 1017 additions and 0 deletions

254
scripts/15_m34_v2.py Normal file
View File

@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""Protocol v2: run or resume the VAI DeepSeek T4/C4 and T2 zero-shot baselines, or estimate their token use.
scripts/15_m34_v2.py qa --model vai-deepseek-v4-1-flash --approved-budget-tokens 200000000 [--rep 0] [--mode rag]
scripts/15_m34_v2.py t2 --model vai-deepseek-v4-1-flash --approved-budget-tokens 150000000 [--rep 0]
scripts/15_m34_v2.py estimate
add --limit N for a development-well smoke check written under outputs/m34/v2/smoke/.
The endpoint and key are read from VOLVE_DIA_M34_API_BASE and VOLVE_DIA_M34_API_KEY (environment or the untracked .env)
and are never logged.
"""
from __future__ import annotations
import argparse
import contextlib
import fcntl
import importlib
import json
import os
import sqlite3
import sys
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from pathlib import Path
import pandas as pd
from volve_dia import m2, m34, paths, t4
from volve_dia.m34_v2 import (ApiCaller, BudgetExceeded, ModelAccessError, code_fingerprint, configuration_v2,
make_client, model_spec, open_store)
from volve_dia.m34_features import DELIMITER, 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)
sys.path.insert(0, str(Path(__file__).parent))
qa_runner = importlib.import_module("12_m34_qa")
t2_runner = importlib.import_module("14_m34_t2_llm")
def provenance(digests, v2, spec, rep, extra):
return {"inputs": digests, "protocol_v2_sha256": m2.digest(Path(__file__).parents[1] / "configs/protocol_v2.yaml"),
"model": {"id": spec["id"], "params": v2["inference"]}, "repetition": rep,
"code": code_fingerprint()} | extra
def drain(work, pending, workers, caller):
"""Run `work` over `pending` with a bounded pool, yielding results as they finish. Stop on budget or access."""
with ThreadPoolExecutor(workers) as pool:
running, it = set(), iter(pending)
stop = None
while True:
while stop is None and len(running) < workers * 2:
try:
running.add(pool.submit(work, next(it)))
except StopIteration:
break
if not running:
break
done, running = wait(running, return_when=FIRST_COMPLETED)
for f in done:
try:
yield f.result()
except (BudgetExceeded, ModelAccessError) as error:
stop = stop or error
if stop:
raise stop
def run_qa(args, protocol, cfg, v2, root, digests):
spec = model_spec(v2, args.model, "t4")
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)
settings = cfg["qa"]
modes = [args.mode] if args.mode else ["c4", "c4_clean", "rag", "agent", "tool_only", "zero_shot", "few_shot"]
development = protocol["splits"]["development_wells"]
if args.limit:
questions, paired, clean = ([q for q in s if q["well"] in development][:args.limit]
for s in (questions, paired, clean))
schedule = list(qa_runner.cases(questions, paired, clean, modes))
reps = [args.rep] if args.rep is not None else protocol["statistics"]["seeds"]
base = root / "m34/v2" / ("smoke/qa" if args.limit else "qa") / spec["id"]
base.mkdir(parents=True, exist_ok=True)
db = root / "ddr/volve_ddr.duckdb"
for rep in reps:
path = base / f"rep{rep}.sqlite"
with path.with_suffix(".lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
prov = provenance(digests, v2, spec, rep, {"limit": args.limit, "modes": sorted(modes) if args.limit else None})
with contextlib.closing(open_store(path, prov)) as store, t4.connect(db) as con:
store.execute("""CREATE TABLE IF NOT EXISTS predictions (
mode TEXT, modality TEXT, seed INTEGER, item TEXT, data TEXT,
PRIMARY KEY (mode, modality, seed, item))""")
done = set(store.execute("SELECT mode, modality, item FROM predictions").fetchall())
pending = [(m, s, q) for m, s, q in schedule if (m, s, q["id"]) not in done]
print(f"{spec['id']} rep{rep}: {len(pending)} pending of {len(schedule)}", flush=True)
if not pending:
continue
caller = ApiCaller(make_client(), spec, v2, store, args.approved_budget_tokens, rep)
known = dict(con.execute("SELECT report_id, wellbore FROM reports").fetchall())
indexes = {}
for key in {(m if m in C4_MODES else "full", s) for m, s, _ in pending
if m in ("rag", "agent", *C4_MODES)}:
mode_key, source = key
allowed = {"c4": docs, "c4_clean": docs - excluded_reports}.get(mode_key)
passages = xml_passages(con, allowed) if source == "xml" else rendered_passages(root, source, allowed)
indexes[key] = Retriever(passages, settings["passages"], settings["context_chars"])
def work(job, caller=caller):
mode, source, q = job
retrieve = mode in ("rag", "agent", *C4_MODES)
retriever = indexes[(mode if mode in C4_MODES else "full", source)] if retrieve else None
examples = few_examples(questions, q, development, settings["few_shot_count"]) \
if mode == "few_shot" else []
caller.bind(mode, source, q["id"])
if mode in ("agent", "tool_only"):
with t4.connect(db) as local: # One DuckDB connection per worker call.
return finish(q, mode, source, caller, settings, examples, retriever,
QueryTool(local), known)
return finish(q, mode, source, caller, settings, examples, retriever, None, known)
def finish(q, mode, source, caller, settings, examples, retriever, tool, known):
try:
predicted, evidence, trace = answer_question(
{"question": q["question"]}, caller, settings, mode, examples, retriever, tool)
error = None
except ValueError as failure:
error, predicted, evidence, trace = str(failure), {"answer": None, "citations": []}, [], []
score = scoring_row(q, predicted, known, evidence, trace, failed=error is not None)
return mode, source, q["id"], score | {
"prediction": predicted, "retrieved": evidence, "trace": trace, "error": error,
"date_flag": q["id"] in date_flagged, "n_examples": len(examples)}
n = 0
for mode, source, item, record in drain(work, pending, args.workers, caller):
with caller.lock, store: # Workers log calls on the same connection.
store.execute("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)",
[mode, source, rep, item, json_text(record)])
n += 1
if n == 1 or n % 100 == 0 or n == len(pending):
print(f"{spec['id']} rep{rep}: {n}/{len(pending)} ({mode}/{source}) "
f"tokens {caller.spent}", flush=True)
def run_t2(args, protocol, cfg, v2, root, digests):
spec = model_spec(v2, args.model, "t2_zero_shot")
meta = m2.read_json(root / "m34/features_provenance.json")
if meta["inputs"] != digests:
raise ValueError("Prepared T2 inputs are stale.")
feats = root / "m34/features_t2.parquet"
inputs = pd.read_parquet(feats, columns=["item", "well", "text_xml"])
if args.limit:
inputs = inputs[inputs["well"].isin(protocol["splits"]["development_wells"])].head(args.limit)
reps = [args.rep] if args.rep is not None else protocol["statistics"]["seeds"]
base = root / "m34/v2" / ("smoke/t2_llm" if args.limit else "t2_llm") / spec["id"]
base.mkdir(parents=True, exist_ok=True)
for rep in reps:
path = base / f"rep{rep}.sqlite"
with path.with_suffix(".lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
prov = provenance(digests, v2, spec, rep, {"features_sha256": m2.digest(feats), "limit": args.limit})
with contextlib.closing(open_store(path, prov)) as store:
store.execute("""CREATE TABLE IF NOT EXISTS predictions (
seed INTEGER, item TEXT, a REAL, b REAL, error TEXT, PRIMARY KEY (seed, item))""")
done = {r[0] for r in store.execute("SELECT item FROM predictions")}
pending = [r for r in inputs.itertuples(index=False) if r.item not in done]
print(f"{spec['id']} T2 rep{rep}: {len(pending)} pending", flush=True)
if not pending:
continue
caller = ApiCaller(make_client(), spec, v2, store, args.approved_budget_tokens, rep)
fields = ["TARGET", "PREVIOUS", "NEXT", "24H SUMMARY", "24H OUTLOOK"]
def work(row):
text = "\n".join(f"{k}: {v}" for k, v in zip(fields, row.text_xml.split(DELIMITER, 4)))
messages = [{"role": "system", "content": t2_runner.INSTRUCTION},
{"role": "user", "content": text[:12000]}]
caller.bind("t2", "xml", row.item)
try:
a, b = t2_runner.probabilities(caller(messages, t2_runner.SCHEMA))
return row.item, a, b, None
except ValueError as issue:
return row.item, 0.5, 0.5, str(issue)
for n, (item, a, b, error) in enumerate(drain(work, pending, args.workers, caller), 1):
with caller.lock, store: # Workers log calls on the same connection.
store.execute("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)", (rep, item, a, b, error))
if n == 1 or n % 200 == 0 or n == len(pending):
print(f"{spec['id']} T2 rep{rep}: {n}/{len(pending)} tokens {caller.spent}", flush=True)
def run_estimate(args, protocol, cfg, v2, root, digests):
"""Token estimate. Means come from smoke checkpoints when present, otherwise from stated assumptions."""
questions, paired, docs, flagged = qa_universe(root, protocol)
clean = [q for q in paired if q["id"] not in flagged]
counts = {"c4": 3 * len(paired), "c4_clean": 3 * len(clean), "rag": len(questions), "agent": len(questions),
"tool_only": len(questions), "zero_shot": len(questions), "few_shot": len(questions)}
assumed = {"c4": (3500, 60, 1), "c4_clean": (3500, 60, 1), "rag": (3500, 60, 1), "zero_shot": (400, 60, 1),
"few_shot": (900, 60, 1), "agent": (2500, 80, 3.0), "tool_only": (2000, 80, 3.0)}
rows, total = [], 0
for spec in v2["baselines"]["api"]:
measured = {}
for p in (root / "m34/v2/smoke/qa" / spec["id"]).glob("rep*.sqlite"):
with contextlib.closing(sqlite3.connect(f"{p.resolve().as_uri()}?mode=ro", uri=True)) as c:
for mode, n_calls, n_items, i, o in c.execute(
"SELECT mode, COUNT(*), COUNT(DISTINCT item || modality), AVG(input_tokens), "
"AVG(output_tokens) FROM calls GROUP BY mode"):
measured[mode] = (i, o, n_calls / max(n_items, 1))
for mode, n in counts.items():
i, o, calls_per_item = measured.get(mode, assumed[mode])
tokens = int(3 * n * calls_per_item * (i + o))
total += tokens
rows.append((spec["id"], "t4", mode, "measured" if mode in measured else "assumed", calls_per_item * n * 3,
tokens))
t2_calls, t2_tokens, source = 3 * 23447, 1500 + 40, "assumed"
for p in (root / "m34/v2/smoke/t2_llm" / spec["id"]).glob("rep*.sqlite"):
with contextlib.closing(sqlite3.connect(f"{p.resolve().as_uri()}?mode=ro", uri=True)) as c:
mean = c.execute("SELECT AVG(input_tokens + output_tokens) FROM calls").fetchone()[0]
if mean:
t2_tokens, source = mean, "measured"
rows.append((spec["id"], "t2", "zero_shot", source, t2_calls, int(t2_calls * t2_tokens)))
total += int(t2_calls * t2_tokens)
print(pd.DataFrame(rows, columns=["model", "task", "mode", "tokens", "calls_3_reps", "total_tokens"])
.to_string(index=False))
print(f"Total estimate for protocol v2: {total / 1e6:.0f} M tokens over three repetitions "
"(prompt + completion; no price: VAI rates are unknown).")
def main():
paths.load_env()
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("task", choices=["qa", "t2", "estimate"])
parser.add_argument("--model")
parser.add_argument("--mode", choices=MODES)
parser.add_argument("--rep", type=int, choices=[0, 1, 2])
parser.add_argument("--limit", type=int, help="Development-well smoke check on the first N items per subset.")
parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--approved-budget-tokens", type=int)
args = parser.parse_args()
protocol, cfg, v2 = configuration_v2()
root, digests = m34.inputs(protocol)
if args.task == "estimate":
return run_estimate(args, protocol, cfg, v2, root, digests)
if not args.model:
parser.error("--model is required.")
if not args.approved_budget_tokens or args.approved_budget_tokens <= 0:
parser.error("--approved-budget-tokens is required and must be positive.")
try:
(run_qa if args.task == "qa" else run_t2)(args, protocol, cfg, v2, root, digests)
except (ModelAccessError, BudgetExceeded) as error:
print(f"STOPPED: {error}", file=sys.stderr)
sys.exit(3)
if __name__ == "__main__":
main()