Add M3-M4 baselines, C4 comparison and G2 report

Frozen feature tables for T1-T3, TF-IDF + logistic regression and DistilBERT
baselines with grouped splits, T4/C4 question answering (zero-shot, few-shot,
RAG, tool_only, agent), Qwen zero-shot T2, paired well-cluster bootstrap and
the G2 coverage report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 07:00:36 +00:00
parent 2b59d635ce
commit 59fa1f4d08
16 changed files with 1999 additions and 0 deletions

116
volve_dia/m34.py Normal file
View File

@@ -0,0 +1,116 @@
"""Locked benchmark inputs and paired, pooled evaluation utilities for M3–M4."""
from __future__ import annotations
import hashlib
import io
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from . import m2, paths
SPEC = paths.REPO_ROOT / "configs" / "m34_baselines.yaml"
def configuration() -> tuple[dict, dict]:
expected = m2.PROTOCOL.with_suffix(".yaml.sha256").read_text().split()[0]
if m2.digest(m2.PROTOCOL) != expected:
raise ValueError("The G1 protocol checksum did not match.")
protocol = yaml.safe_load(m2.PROTOCOL.read_text())
if protocol["status"] != "locked":
raise ValueError("G1 has not locked the protocol.")
return protocol, yaml.safe_load(SPEC.read_text())
def inputs(protocol: dict) -> tuple[Path, dict]:
root = paths.outputs_dir()
registry = protocol["inputs"]
files = {paths.REPO_ROOT / d["file"]: d["sha256"] for d in registry.values() if isinstance(d, dict) and "file" in d}
for key, folder in (("label_tables", "labels"), ("t4_questions", "t4")):
entry = registry[key]
files[root / folder / "summary.json"] = entry["summary_sha256"]
files.update({root / folder / f"{name}.parquet": digest for name, digest in
entry.get("tables_sha256", {}).items()})
for path, expected in files.items():
if m2.digest(path) != expected:
raise ValueError(f"Locked input checksum did not match: {path}")
for folder, names in {
"ddr": ("reports.parquet", "activities.parquet", "volve_ddr.duckdb"),
"labels": ("t2_inputs.parquet", "t3_activities.parquet", "t3_intervals.parquet"),
"witsml": ("formation_tops.parquet", "wellbores.parquet"),
"ocr": ("hub_docs.csv", "hub/match.csv"),
"ocr_qc_hub": ("items.parquet",),
"t4": ("questions.jsonl",),
}.items():
for name in names:
path = root / folder / name
files[path] = m2.digest(path)
files[m2.PROTOCOL] = m2.digest(m2.PROTOCOL)
files[SPEC] = m2.digest(SPEC)
return root, {str(p.relative_to(root) if p.is_relative_to(root) else p.relative_to(paths.REPO_ROOT)): h
for p, h in files.items()}
def code_fingerprint(group: str) -> str:
digest = hashlib.sha256()
source = paths.REPO_ROOT
common = ["volve_dia/m34.py", "volve_dia/m34_features.py"]
groups = {"classification": ["scripts/11_m34_classify.py", "volve_dia/m34_classify.py",
"volve_dia/m34_distilbert.py"],
"qa": ["scripts/12_m34_qa.py", "volve_dia/m34_qa.py", "volve_dia/t4.py"],
"report": ["scripts/13_m34_report.py", "volve_dia/m34_report.py"]}
files = sorted(source / name for name in common + groups[group])
for path in files:
digest.update(path.name.encode())
digest.update(path.read_bytes())
return digest.hexdigest()
def write_parquet(frame: pd.DataFrame, path: Path) -> None:
tmp = io.BytesIO()
frame.to_parquet(tmp, index=False)
atomic_write(path, tmp.getvalue())
def atomic_write(path: Path, content: bytes) -> None:
import os
import tempfile
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
tmp = Path(stream.name)
try:
stream.write(content)
stream.close()
os.replace(tmp, path)
finally:
tmp.unlink(missing_ok=True)
def confidence(frame: pd.DataFrame, metric, ci: dict) -> dict:
"""Recompute a pooled metric under whole-well resampling. The same draws pair every comparison."""
cluster, wells = pd.factorize(frame["well"], sort=True)
n = len(wells)
point = float(metric(np.ones(len(frame), dtype=np.int64)))
bounds = None
finite = 0
if n > 1 and (cluster >= 0).all():
rng = np.random.default_rng(ci["seed"])
draws = rng.multinomial(n, np.full(n, 1 / n), size=ci["resamples"])
values = np.array([metric(draw[cluster]) for draw in draws])
values = values[np.isfinite(values)]
finite = len(values)
if finite:
alpha = (1 - ci["level"]) / 2
bounds = np.quantile(values, [alpha, 1 - alpha]).tolist()
return {"estimate": point if np.isfinite(point) else None, "ci": bounds,
"n": len(frame), "wells": n, "finite_resamples": finite}
def interval_overlap(y: np.ndarray, predicted: np.ndarray, weights: np.ndarray) -> float:
intersection = weights @ (y & predicted)
union = weights @ (y | predicted)
return float(intersection / union) if union else np.nan