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:
254
scripts/15_m34_v2.py
Normal file
254
scripts/15_m34_v2.py
Normal 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()
|
||||
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()
|
||||
30
scripts/m34_status.sh
Executable file
30
scripts/m34_status.sh
Executable file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-screen status of the M3-M4 runs. Live view: watch -n 30 bash scripts/m34_status.sh
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
echo "== processes =="
|
||||
ps -eo pid,etime,args | grep -E "[1]1_m34_classify|[1]5_m34_v2|[1]6_m34|[r]un_m34_v2" | cut -c1-120 || true
|
||||
echo; echo "== VAI v2 (T4/C4 + T2, 3 repetitions) =="
|
||||
"$PY" - <<'P'
|
||||
import glob, sqlite3
|
||||
def ro(p): return sqlite3.connect(f"file:{p}?mode=ro", uri=True)
|
||||
need = {"qa": 3 * 16317, "t2": 3 * 23447}
|
||||
for kind, pat, sql in (("qa", "outputs/m34/v2/qa/*/rep*.sqlite", "select count(*) from predictions"),
|
||||
("t2", "outputs/m34/v2/t2_llm/*/rep*.sqlite", "select count(*) from predictions")):
|
||||
done = 0
|
||||
for p in sorted(glob.glob(pat)):
|
||||
c = ro(p); n = c.execute(sql).fetchone()[0]; done += n
|
||||
calls, ok, tok = c.execute("select count(*), sum(ok), sum(input_tokens+output_tokens) from calls").fetchone()
|
||||
print(f" {kind} {p.split('/')[-1]}: {n} items, {calls} calls ({calls-ok} failed attempts), {tok or 0:,} tokens")
|
||||
print(f" {kind} total {done}/{need[kind]} ({done/need[kind]:.1%})")
|
||||
P
|
||||
echo; echo "== Sonnet / Haiku session sample =="
|
||||
[[ -f outputs/m34/v2/session/manifest.json ]] && "$PY" scripts/16_m34_session.py status 2>/dev/null || echo " not prepared"
|
||||
echo; echo "== v1 checkpoints (stopped Qwen/Llama, kept) =="
|
||||
"$PY" - <<'P'
|
||||
import sqlite3
|
||||
def ro(p): return sqlite3.connect(f"file:{p}?mode=ro", uri=True)
|
||||
print(" Qwen T4/C4:", ro("outputs/m34/qa/qwen.sqlite").execute("select count(*) from predictions").fetchone()[0], "of 48951 (stopped)")
|
||||
print(" Qwen T2 :", ro("outputs/m34/t2_llm/qwen.sqlite").execute("select seed, count(*) from predictions group by 1").fetchall(), "of 23447 per seed (stopped)")
|
||||
P
|
||||
echo; echo "== latest runs =="; "$PY" -m volve_dia.runlog ls -k 5 2>/dev/null | tail -n 8
|
||||
37
scripts/run_m34_v2.sh
Executable file
37
scripts/run_m34_v2.sh
Executable file
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Protocol v2 VAI DeepSeek baseline, resumed with the same command. Endpoint and key: VOLVE_DIA_M34_API_BASE and
|
||||
# VOLVE_DIA_M34_API_KEY (env or .env).
|
||||
# scripts/run_m34_v2.sh smoke <budget_tokens> # development-well smoke check, T4 and T2
|
||||
# scripts/run_m34_v2.sh full <budget_tokens> # T4/C4 and T2, three repetitions
|
||||
# scripts/run_m34_v2.sh estimate
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 TOKENIZERS_PARALLELISM=false
|
||||
run_python() {
|
||||
exec "$PY" -c '
|
||||
import os
|
||||
import sys
|
||||
from volve_dia.paths import load_env
|
||||
load_env()
|
||||
os.execv(sys.executable, [sys.executable, *sys.argv[1:]])
|
||||
' "$@"
|
||||
}
|
||||
[[ -n "${RUNLOG_DIR:-}" ]] || run_python -m volve_dia.runlog -n "m34_v2_${1:-estimate}" -- bash scripts/run_m34_v2.sh "$@"
|
||||
stage="${1:-estimate}"
|
||||
budget="${2:-}"
|
||||
M=vai-deepseek-v4-1-flash
|
||||
step() { "$PY" -c 'import sys; from volve_dia.paths import load_env; load_env(); import os; os.execv(sys.executable, [sys.executable, *sys.argv[1:]])' scripts/15_m34_v2.py "$@"; }
|
||||
case "$stage" in
|
||||
estimate) step estimate ;;
|
||||
smoke)
|
||||
step qa --model $M --limit 6 --rep 0 --workers 2 --approved-budget-tokens "${budget:?budget}"
|
||||
step t2 --model $M --limit 50 --rep 0 --workers 2 --approved-budget-tokens "$budget"
|
||||
;;
|
||||
full)
|
||||
step qa --model $M --approved-budget-tokens "${budget:?budget}"
|
||||
step t2 --model $M --approved-budget-tokens "${budget}"
|
||||
env -u RUNLOG_DIR bash scripts/run_m34.sh report
|
||||
;;
|
||||
*) echo "Usage: $0 {estimate|smoke|full} [budget_tokens]" >&2; exit 2 ;;
|
||||
esac
|
||||
Reference in New Issue
Block a user