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:
@@ -9,3 +9,7 @@ VOLVE_DIA_OCR_URL=
|
|||||||
# DATASET_HUB_URL=
|
# DATASET_HUB_URL=
|
||||||
# DATASET_HUB_API_KEY=
|
# DATASET_HUB_API_KEY=
|
||||||
# VOLVE_DIA_OCR_HUB_DATASET=
|
# VOLVE_DIA_OCR_HUB_DATASET=
|
||||||
|
# Protocol v2 VAI DeepSeek baseline (scripts/run_m34_v2.sh). Use the complete base URL before /chat/completions.
|
||||||
|
# VOLVE_DIA_M34_API_BASE=
|
||||||
|
# VOLVE_DIA_M34_API_MODEL=
|
||||||
|
# VOLVE_DIA_M34_API_KEY=
|
||||||
|
|||||||
107
configs/protocol_v2.yaml
Normal file
107
configs/protocol_v2.yaml
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
# Protocol v2: VAI DeepSeek is the API baseline; Sonnet and Haiku (session) replace Qwen and Llama on a fixed sample.
|
||||||
|
# It extends locked v1.
|
||||||
|
protocol: volve-dia
|
||||||
|
version: 2
|
||||||
|
status: locked
|
||||||
|
drafted: 2026-11-19
|
||||||
|
revised: "2026-11-19, before any v2 run: roles redefined (VAI = API baseline; Sonnet and Haiku replace Qwen and Llama on a sample)"
|
||||||
|
extends:
|
||||||
|
file: configs/protocol_v1.yaml
|
||||||
|
sha256: fb11c6074b2794d11a65faf0b5425f57fda70eacdb99d0e18e3a6093bc10b477
|
||||||
|
deviation:
|
||||||
|
date: 2026-11-19
|
||||||
|
what: >-
|
||||||
|
Protocol v1 was locked on 2026-11-18 and its local Qwen3-8B / Llama 3.1 8B baselines had already started
|
||||||
|
(Qwen T4/C4 seed 0 and T2 seeds 0-1 in progress, Llama not started). The project owner stopped both on 2026-11-19
|
||||||
|
and replaced them with Claude Sonnet and Claude Haiku run inside the Claude Code session on a fixed sample
|
||||||
|
(no Anthropic API key exists). The API baseline of v1 (the `api` cell) is filled by the VAI model
|
||||||
|
"DeepSeek-V4.1-Flash-1017", the model already used by the vopec-chatbot project, on the full matrix. The model
|
||||||
|
changes were made after v1 baseline runs began and were not driven by a test-well result. Two earlier same-day
|
||||||
|
drafts (Claude through the API; VAI replacing Qwen and Llama) were replaced before any v2 call.
|
||||||
|
v1_artifacts: >-
|
||||||
|
All v1 checkpoints, logs and Qwen results stay unchanged under outputs/m34/qa/, outputs/m34/t2_llm/ and
|
||||||
|
logs/runs/. They are reported as partial v1 results: Qwen T4/C4 seed 0 has 10,214 of 16,317 predictions (c4, c4_clean
|
||||||
|
and rag complete, agent 545 of 1,662); Qwen T2 has seed 0 (23,447) and 17,827 of 23,447 for seed 1; Llama has none.
|
||||||
|
The v1 jobs were stopped, not completed.
|
||||||
|
unchanged_from_v1:
|
||||||
|
- split by well and wellbore sensitivity, development wells and few-shot example rule
|
||||||
|
- T4 question set (1,662 questions, 1,376 paired C4 questions, 1,293 without date-disagreement pages)
|
||||||
|
- masking rules, T2 masked inputs and both NPT definitions
|
||||||
|
- both C4 passes (all paired reports and without the 16 date-disagreement pages), 7 unmatched reports dropped
|
||||||
|
- automatic scoring against the XML/WITSML reference, metrics, whole-well cluster bootstrap (2000 resamples, seed 20261117)
|
||||||
|
- TF-IDF + logistic regression and DistilBERT as comparison baselines (v1 results, not rerun)
|
||||||
|
- retrieval settings (8 passages, 12,000 context characters), 3 tool steps, 2 few-shot examples
|
||||||
|
- sampling: temperature 0.2, max_tokens 320 and the seed field, as in the v1 local runs
|
||||||
|
baselines:
|
||||||
|
api:
|
||||||
|
- id: vai-deepseek-v4-1-flash
|
||||||
|
label: VAI DeepSeek-V4.1-Flash-1017
|
||||||
|
api_model: DeepSeek-V4.1-Flash-1017
|
||||||
|
role: the v1 `api` baseline, full matrix
|
||||||
|
tasks: [t4, c4, t2_zero_shot]
|
||||||
|
choice_note: >-
|
||||||
|
Chosen among the VAI models listed in the vopec-chatbot notes for price (3,600 / 7,100 credits per 1M input /
|
||||||
|
output tokens, about 1 VND per credit), latency (about 1 s per call), JSON compliance in the smoke check (0
|
||||||
|
invalid outputs in 140 calls) and switchable thinking. glm-5.3 costs about nine times more; Qwen3.8-27B about 2.6 times
|
||||||
|
more.
|
||||||
|
only_this_api_model: true
|
||||||
|
missing_access: Abort and report. Do not fall back to another model without a new decision.
|
||||||
|
session_models:
|
||||||
|
- {id: sonnet, replaces: qwen, runs_in: Claude Code session subagents, api_key: none}
|
||||||
|
- {id: haiku, replaces: llama, runs_in: Claude Code session subagents, api_key: none}
|
||||||
|
retired: [qwen, llama]
|
||||||
|
session_sample:
|
||||||
|
status: auxiliary; excluded from G2 coverage, because it does not cover the matrix locked in v1
|
||||||
|
seed: 20261117
|
||||||
|
wells: all 11 wells, drawn once with the fixed seed before any answer exists. The development split has only two wells
|
||||||
|
(F-7, F-9) and 144 eligible questions, too few for 300. No prompt, model setting or threshold is tuned on the sample.
|
||||||
|
t4:
|
||||||
|
questions: 300 from the C4-paired set (printed, answerable, complete OCR, well-scoped, 1,366 eligible), stratified by family and well
|
||||||
|
conditions: [zero_shot_xml, rag_xml, c4_xml, c4_html, c4_ocr]
|
||||||
|
repetitions: 1
|
||||||
|
answers_per_model: 1500
|
||||||
|
t2:
|
||||||
|
items: 500 from the masked T2 table (23,447), stratified by well
|
||||||
|
definitions: [a, b]
|
||||||
|
repetitions: 1
|
||||||
|
batch_size: {t4: 30, t2: 100}
|
||||||
|
prompts: built by the v1 `answer_question` code, so retrieval, context size and instruction match the VAI runs
|
||||||
|
limits: >-
|
||||||
|
Session models read prompts from batch files. They are instructed to read nothing else, but file access is not
|
||||||
|
enforced. One repetition, no seed. Results are reported as a sample, never as G2 coverage.
|
||||||
|
inference:
|
||||||
|
surface: OpenAI-compatible chat/completions on the VAI gateway (httpx; URL and key only in the untracked .env)
|
||||||
|
temperature: 0.2
|
||||||
|
max_tokens: 320
|
||||||
|
chat_template_kwargs: {enable_thinking: false}
|
||||||
|
structured_output: response_format json_object; the v1 ANSWER, ACTION and T2 shapes are enforced locally
|
||||||
|
attempts_per_call: 3
|
||||||
|
repetitions: 3
|
||||||
|
repetition_note: >-
|
||||||
|
Three independent calls per condition, with seed k sent. Whether the gateway honours the seed is not verified, so
|
||||||
|
each is reported as a repetition, not a seeded replicate. The repetition index k is stored in the seed column.
|
||||||
|
logged_per_call: model id returned, response id, finish reason, token usage, attempt, error type
|
||||||
|
shared_key_note: The VAI key is shared by a group and by vopec-chatbot. Default 4 concurrent calls; never touch other jobs.
|
||||||
|
checkpoints:
|
||||||
|
qa: outputs/m34/v2/qa/<model id>/rep<k>.sqlite
|
||||||
|
t2: outputs/m34/v2/t2_llm/<model id>/rep<k>.sqlite
|
||||||
|
smoke: outputs/m34/v2/smoke/
|
||||||
|
separation: one SQLite file per protocol, model and repetition; provenance records the v2 checksum
|
||||||
|
g2:
|
||||||
|
rule: >-
|
||||||
|
G2 is checked per protocol version. v1 requires its own Qwen, Llama and api cells and cannot be met, because the
|
||||||
|
Qwen and Llama runs were stopped. v2 requires TF-IDF, DistilBERT, majority and lexicon cells from v1 plus VAI T2
|
||||||
|
zero-shot (3 repetitions) and VAI on every T4/C4 mode, source and repetition. The Sonnet and Haiku sample is
|
||||||
|
reported beside it as an auxiliary result.
|
||||||
|
v2_required_models_qa: [vai-deepseek-v4-1-flash]
|
||||||
|
v2_required_models_t2: [vai-deepseek-v4-1-flash]
|
||||||
|
budget:
|
||||||
|
gate: >-
|
||||||
|
scripts/15_m34_v2.py refuses to run without --approved-budget-tokens and stops when the logged prompt + completion
|
||||||
|
tokens reach it. VAI list price for DeepSeek-V4.1-Flash: 3,600 credits per 1M input tokens and 7,100 per 1M output
|
||||||
|
tokens (1 credit is about 1 VND; source: vopec-chatbot session notes of 2026-11-11). The 10M-credit quota is shared
|
||||||
|
by the team. Smoke-based estimate for the full v2 run: about 210M input and 4.5M output tokens, about 0.79M credits.
|
||||||
|
session_agents: >-
|
||||||
|
Session subagents (no API key) split by purpose. Writing code, code review and similar engineering or editing work
|
||||||
|
uses Opus. Model-run benchmark tasks that produce predictions or ratings (raters, judge, reference samples) use the
|
||||||
|
lower models, Sonnet or Haiku, chosen per task. Fable is not used.
|
||||||
1
configs/protocol_v2.yaml.sha256
Normal file
1
configs/protocol_v2.yaml.sha256
Normal file
@@ -0,0 +1 @@
|
|||||||
|
370f949f53cc9b2e3a1540f02aede2f8456f3e1cba25e1d42b573d406a416af2 configs/protocol_v2.yaml
|
||||||
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
|
||||||
36
tests/test_m34_session.py
Normal file
36
tests/test_m34_session.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location("s16", Path(__file__).parents[1] / "scripts/16_m34_session.py")
|
||||||
|
sys.path.insert(0, str(Path(__file__).parents[1] / "scripts"))
|
||||||
|
s16 = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(s16)
|
||||||
|
|
||||||
|
|
||||||
|
def pool():
|
||||||
|
fams = ["lookup"] * 40 + ["aggregation"] * 30 + ["multi_hop"] * 5
|
||||||
|
return [{"id": str(i), "family": f, "well": f"W{i % 4}", "scope": "well"} for i, f in enumerate(fams)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_count_reads_the_leading_number():
|
||||||
|
assert s16.count("300 from the C4-paired set") == 300 and s16.count(500) == 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_question_draw_is_deterministic_spread_over_families_and_wells():
|
||||||
|
a = s16.draw_questions(pool(), {"questions": 30}, np.random.default_rng(1))
|
||||||
|
b = s16.draw_questions(pool(), {"questions": 30}, np.random.default_rng(1))
|
||||||
|
assert [q["id"] for q in a] == [q["id"] for q in b] and len({q["id"] for q in a}) == 30
|
||||||
|
assert {q["family"] for q in a} == {"lookup", "aggregation", "multi_hop"}
|
||||||
|
assert len({q["well"] for q in a}) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_t2_draw_is_stratified_by_well():
|
||||||
|
frame = pd.DataFrame({"item": [str(i) for i in range(1000)], "well": ["A"] * 700 + ["B"] * 300})
|
||||||
|
out = s16.draw_t2(frame, 100, np.random.default_rng(2))
|
||||||
|
assert len(out) == 100 and out["well"].value_counts().to_dict() == {"A": 70, "B": 30}
|
||||||
105
tests/test_m34_v2.py
Normal file
105
tests/test_m34_v2.py
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from volve_dia import m34_v2 as mv
|
||||||
|
from volve_dia.m34_qa import ACTION, ANSWER
|
||||||
|
|
||||||
|
V2 = {"inference": {"temperature": 0.2, "max_tokens": 320, "attempts_per_call": 3,
|
||||||
|
"chat_template_kwargs": {"enable_thinking": False}}}
|
||||||
|
SPEC = {"id": "vai-x", "api_model": "DeepSeek-V4.1-Flash-1017"}
|
||||||
|
GOOD = json.dumps({"answer": 5, "unit": "m", "citations": ["reports:1"]})
|
||||||
|
|
||||||
|
|
||||||
|
def completion(text, finish="stop"):
|
||||||
|
return {"id": "resp_1", "model": "DeepSeek-V4.1-Flash-1017",
|
||||||
|
"choices": [{"message": {"content": text}, "finish_reason": finish}],
|
||||||
|
"usage": {"prompt_tokens": 1000, "completion_tokens": 50}}
|
||||||
|
|
||||||
|
|
||||||
|
def caller(tmp_path, responses, budget=None, seed=1):
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
seen.append(json.loads(request.content))
|
||||||
|
out = responses.pop(0)
|
||||||
|
return out if isinstance(out, httpx.Response) else httpx.Response(200, json=out)
|
||||||
|
|
||||||
|
client = httpx.Client(base_url="https://example.invalid/v1/", transport=httpx.MockTransport(handler))
|
||||||
|
store = mv.open_store(tmp_path / "c.sqlite", {"a": 1})
|
||||||
|
c = mv.ApiCaller(client, SPEC, V2, store, budget, seed)
|
||||||
|
c.bind("rag", "xml", "q1")
|
||||||
|
return c, store, seen
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_sends_v1_sampling_and_logs_usage(tmp_path):
|
||||||
|
c, store, seen = caller(tmp_path, [completion(GOOD)])
|
||||||
|
assert c([{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], ANSWER)["answer"] == 5
|
||||||
|
sent = seen[0]
|
||||||
|
assert sent["model"] == "DeepSeek-V4.1-Flash-1017" and sent["temperature"] == 0.2 and sent["seed"] == 1
|
||||||
|
assert sent["chat_template_kwargs"] == {"enable_thinking": False}
|
||||||
|
assert store.execute("SELECT ok, input_tokens, output_tokens, request_id FROM calls").fetchone() == \
|
||||||
|
(1, 1000, 50, "resp_1")
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_output_is_retried_then_fails(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr(mv.time, "sleep", lambda s: None)
|
||||||
|
c, store, _ = caller(tmp_path, [completion("not json"), completion(json.dumps({"answer": 1})),
|
||||||
|
completion(GOOD, "length")])
|
||||||
|
with pytest.raises(ValueError, match="Completion failed"):
|
||||||
|
c([{"role": "user", "content": "u"}], ANSWER)
|
||||||
|
assert store.execute("SELECT COUNT(*), SUM(ok) FROM calls").fetchone() == (3, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_access_errors_stop_without_fallback(tmp_path):
|
||||||
|
for code in (401, 403, 404, 400):
|
||||||
|
c, _, seen = caller(tmp_path, [httpx.Response(code)])
|
||||||
|
with pytest.raises(mv.ModelAccessError):
|
||||||
|
c([{"role": "user", "content": "u"}], ANSWER)
|
||||||
|
assert len(seen) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_budget_stops_after_logging(tmp_path):
|
||||||
|
c, store, _ = caller(tmp_path, [completion(GOOD)], budget=1000)
|
||||||
|
with pytest.raises(mv.BudgetExceeded):
|
||||||
|
c([{"role": "user", "content": "u"}], ANSWER)
|
||||||
|
assert store.execute("SELECT COUNT(*) FROM calls").fetchone()[0] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_resume_keeps_spend_and_rejects_changed_provenance(tmp_path):
|
||||||
|
c, store, _ = caller(tmp_path, [completion(GOOD)])
|
||||||
|
c([{"role": "user", "content": "u"}], ANSWER)
|
||||||
|
store.close()
|
||||||
|
again, _, _ = caller(tmp_path, [])
|
||||||
|
assert again.spent == 1050
|
||||||
|
with pytest.raises(ValueError, match="provenance"):
|
||||||
|
mv.open_store(tmp_path / "c.sqlite", {"a": 2})
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_rejects_bad_shapes():
|
||||||
|
for body in ({"answer": {"x": 1}, "unit": "", "citations": []}, {"answer": 1, "unit": 3, "citations": []},
|
||||||
|
{"answer": 1, "unit": "", "citations": ["a"] * 9}, {"tool": "drop", "arguments": {}}):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
mv.validate(body, ACTION if "tool" in body else ANSWER)
|
||||||
|
|
||||||
|
|
||||||
|
def test_endpoint_needs_env_and_only_one_model(monkeypatch):
|
||||||
|
for name in ("VOLVE_DIA_M34_API_BASE", "VOLVE_DIA_M34_API_KEY"):
|
||||||
|
monkeypatch.delenv(name, raising=False)
|
||||||
|
with pytest.raises(mv.ModelAccessError):
|
||||||
|
mv.endpoint()
|
||||||
|
v2 = {"baselines": {"api": [{"id": "vai-x", "tasks": ["t4"]}]}}
|
||||||
|
assert mv.model_spec(v2, "vai-x", "t4")["id"] == "vai-x"
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
mv.model_spec(v2, "vai-x", "t2_zero_shot")
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
mv.model_spec(v2, "claude-opus-5-5", "t4")
|
||||||
|
|
||||||
|
|
||||||
|
def test_protocol_v2_extends_the_locked_v1():
|
||||||
|
protocol, _, v2 = mv.configuration_v2()
|
||||||
|
assert protocol["version"] == 1 and v2["version"] == 2
|
||||||
|
assert [m["id"] for m in v2["baselines"]["api"]] == ["vai-deepseek-v4-1-flash"]
|
||||||
161
volve_dia/m34_v2.py
Normal file
161
volve_dia/m34_v2.py
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
"""Protocol v2 LLM baseline: VAI DeepSeek through an OpenAI-compatible endpoint, with usage log and token budget."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from . import m2, m34, paths
|
||||||
|
|
||||||
|
PROTOCOL_V2 = paths.REPO_ROOT / "configs" / "protocol_v2.yaml"
|
||||||
|
CALL_COLUMNS = ("mode", "modality", "item", "attempt", "ok", "error", "model_returned", "request_id",
|
||||||
|
"finish_reason", "input_tokens", "output_tokens", "elapsed_s")
|
||||||
|
|
||||||
|
|
||||||
|
class ModelAccessError(RuntimeError):
|
||||||
|
"""The key, endpoint or model is not usable. The run stops and does not substitute a model."""
|
||||||
|
|
||||||
|
|
||||||
|
class BudgetExceeded(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def configuration_v2():
|
||||||
|
"""Verify both locked protocols and return (v1 protocol, v1 baseline config, v2 protocol)."""
|
||||||
|
protocol, cfg = m34.configuration()
|
||||||
|
expected = PROTOCOL_V2.with_suffix(".yaml.sha256").read_text().split()[0]
|
||||||
|
if m2.digest(PROTOCOL_V2) != expected:
|
||||||
|
raise ValueError("The protocol v2 checksum did not match.")
|
||||||
|
v2 = yaml.safe_load(PROTOCOL_V2.read_text())
|
||||||
|
if v2["status"] != "locked" or v2["extends"]["sha256"] != m2.digest(m2.PROTOCOL):
|
||||||
|
raise ValueError("Protocol v2 does not extend the locked v1 protocol.")
|
||||||
|
return protocol, cfg, v2
|
||||||
|
|
||||||
|
|
||||||
|
def model_spec(v2, model_id, task):
|
||||||
|
for spec in v2["baselines"]["api"]:
|
||||||
|
if spec["id"] == model_id:
|
||||||
|
if task not in spec["tasks"]:
|
||||||
|
raise ValueError(f"{model_id} is not a v2 baseline for {task}.")
|
||||||
|
return spec
|
||||||
|
raise ValueError(f"{model_id} is not the v2 API baseline.")
|
||||||
|
|
||||||
|
|
||||||
|
def endpoint():
|
||||||
|
"""Base URL and key come from the environment or the untracked .env, never from a command line or a log."""
|
||||||
|
base, key = os.environ.get("VOLVE_DIA_M34_API_BASE"), os.environ.get("VOLVE_DIA_M34_API_KEY")
|
||||||
|
if not base or not key:
|
||||||
|
raise ModelAccessError("Set VOLVE_DIA_M34_API_BASE and VOLVE_DIA_M34_API_KEY (environment or .env).")
|
||||||
|
return base.rstrip("/") + "/", key
|
||||||
|
|
||||||
|
|
||||||
|
def validate(body, schema):
|
||||||
|
"""Local shape checks, identical in effect to the v1 `chat` validation."""
|
||||||
|
if not isinstance(body, dict) or not set(schema["required"]) <= body.keys():
|
||||||
|
raise ValueError("Invalid response shape.")
|
||||||
|
if "citations" in body:
|
||||||
|
c = body["citations"]
|
||||||
|
if not isinstance(c, list) or not all(isinstance(x, str) for x in c) or len(c) > 8:
|
||||||
|
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.dumps(body, allow_nan=False)
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
class ApiCaller:
|
||||||
|
"""Thread-safe adapter with the v1 call signature `call(messages, schema)`, plus a per-call usage log."""
|
||||||
|
|
||||||
|
def __init__(self, client, spec, v2, store, budget_tokens, seed):
|
||||||
|
self.client, self.spec, self.params, self.store = client, spec, v2["inference"], store
|
||||||
|
self.budget, self.seed = budget_tokens, seed
|
||||||
|
self.lock, self.local = threading.Lock(), threading.local()
|
||||||
|
self.spent = int(store.execute("SELECT COALESCE(SUM(input_tokens + output_tokens), 0) FROM calls").fetchone()[0])
|
||||||
|
|
||||||
|
def bind(self, mode, modality, item):
|
||||||
|
self.local.key = (mode, modality, item)
|
||||||
|
|
||||||
|
def _log(self, attempt, ok, error, data, started):
|
||||||
|
usage = (data or {}).get("usage") or {}
|
||||||
|
choice = ((data or {}).get("choices") or [{}])[0]
|
||||||
|
i, o = int(usage.get("prompt_tokens") or 0), int(usage.get("completion_tokens") or 0)
|
||||||
|
row = (*self.local.key, attempt, int(ok), error, (data or {}).get("model"), (data or {}).get("id"),
|
||||||
|
choice.get("finish_reason"), i, o, round(time.monotonic() - started, 3))
|
||||||
|
with self.lock:
|
||||||
|
self.spent += i + o
|
||||||
|
with self.store:
|
||||||
|
self.store.execute(f"INSERT INTO calls VALUES ({','.join('?' * len(CALL_COLUMNS))})", row)
|
||||||
|
if self.budget is not None and self.spent >= self.budget:
|
||||||
|
raise BudgetExceeded(f"Logged tokens {self.spent} reached the approved budget.")
|
||||||
|
|
||||||
|
def __call__(self, messages, schema):
|
||||||
|
p = self.params
|
||||||
|
request = {"model": self.spec["api_model"], "messages": messages, "temperature": p["temperature"],
|
||||||
|
"max_tokens": p["max_tokens"], "seed": self.seed, "response_format": {"type": "json_object"}}
|
||||||
|
request["chat_template_kwargs"] = p["chat_template_kwargs"]
|
||||||
|
last = None
|
||||||
|
for attempt in range(1, p["attempts_per_call"] + 1):
|
||||||
|
started, data = time.monotonic(), None
|
||||||
|
try:
|
||||||
|
res = self.client.post("chat/completions", json=request)
|
||||||
|
if res.status_code in (401, 403, 404):
|
||||||
|
raise ModelAccessError(f"API service returned HTTP {res.status_code}.")
|
||||||
|
if res.status_code == 400:
|
||||||
|
raise ModelAccessError("API service rejected the request (HTTP 400).")
|
||||||
|
res.raise_for_status()
|
||||||
|
data = res.json()
|
||||||
|
choice = data["choices"][0]
|
||||||
|
if choice.get("finish_reason") == "length":
|
||||||
|
raise ValueError("Output truncated.")
|
||||||
|
body = validate(json.loads(choice["message"]["content"]), schema)
|
||||||
|
self._log(attempt, True, None, data, started)
|
||||||
|
return body
|
||||||
|
except (ModelAccessError, BudgetExceeded):
|
||||||
|
raise
|
||||||
|
except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError) as error:
|
||||||
|
last = type(error).__name__ # Exception text may contain the provider URL.
|
||||||
|
self._log(attempt, False, last, data, started)
|
||||||
|
time.sleep(attempt)
|
||||||
|
raise ValueError(f"Completion failed: {last}")
|
||||||
|
|
||||||
|
|
||||||
|
def make_client(timeout=120.0):
|
||||||
|
base, key = endpoint()
|
||||||
|
return httpx.Client(base_url=base, headers={"Authorization": f"Bearer {key}"}, timeout=timeout, trust_env=False)
|
||||||
|
|
||||||
|
|
||||||
|
def open_store(path, provenance):
|
||||||
|
store = sqlite3.connect(path, check_same_thread=False, timeout=60)
|
||||||
|
store.execute("PRAGMA journal_mode=WAL")
|
||||||
|
store.execute("CREATE TABLE IF NOT EXISTS metadata (provenance TEXT)")
|
||||||
|
store.execute(f"CREATE TABLE IF NOT EXISTS calls ({', '.join(CALL_COLUMNS)})")
|
||||||
|
text = json.dumps(provenance, sort_keys=True, default=str, allow_nan=False)
|
||||||
|
prior = store.execute("SELECT provenance FROM metadata").fetchone()
|
||||||
|
if prior and prior[0] != text:
|
||||||
|
raise ValueError("API checkpoint provenance differs.")
|
||||||
|
if not prior:
|
||||||
|
store.execute("INSERT INTO metadata VALUES (?)", [text])
|
||||||
|
store.commit()
|
||||||
|
return store
|
||||||
|
|
||||||
|
|
||||||
|
def code_fingerprint():
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
for name in ("scripts/15_m34_v2.py", "volve_dia/m34_v2.py", "scripts/12_m34_qa.py",
|
||||||
|
"volve_dia/m34_qa.py", "scripts/14_m34_t2_llm.py"):
|
||||||
|
digest.update(name.encode())
|
||||||
|
digest.update((paths.REPO_ROOT / name).read_bytes())
|
||||||
|
return digest.hexdigest()
|
||||||
Reference in New Issue
Block a user