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:
112
scripts/14_m34_t2_llm.py
Executable file
112
scripts/14_m34_t2_llm.py
Executable file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Qwen zero-shot T2 comparison against TF-IDF on the locked masked inputs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import importlib
|
||||
import math
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import m2, m34, paths
|
||||
from volve_dia.m34_features import DELIMITER
|
||||
from volve_dia.m34_qa import json_text
|
||||
|
||||
SCHEMA = {"type": "object", "properties": {f"npt_{d}": {"type": "number"} for d in ("a", "b")},
|
||||
"required": ["npt_a", "npt_b"], "additionalProperties": False}
|
||||
INSTRUCTION = (
|
||||
"Estimate the two probabilities that the TARGET daily drilling report activity would be booked as NPT. "
|
||||
"Definition (a) requires main activity interruption. Definition (b) also includes a failed state or "
|
||||
"a non-success activity outcome. Infer these labels from the target text with context. Preserve the "
|
||||
"distinction between the target row and context about other rows. Use a number from 0 to 1 for each. "
|
||||
"Return only JSON with npt_a and npt_b, with npt_b at least npt_a."
|
||||
)
|
||||
|
||||
|
||||
def probabilities(response):
|
||||
a, b = (response[f"npt_{d}"] for d in ("a", "b"))
|
||||
if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in (a, b)):
|
||||
raise ValueError("Invalid NPT probability.")
|
||||
if not 0 <= a <= b <= 1:
|
||||
raise ValueError("NPT probabilities are out of order or range.")
|
||||
return float(a), float(b)
|
||||
|
||||
|
||||
def run(args, protocol, config, root, digests, out):
|
||||
runner = importlib.import_module("12_m34_qa")
|
||||
args.model = "qwen"
|
||||
model, client_context = runner.model_config(args, root, config)
|
||||
features_meta = m2.read_json(root / "m34/features_provenance.json")
|
||||
if features_meta["inputs"] != digests:
|
||||
raise ValueError("Prepared T2 inputs are stale.")
|
||||
path = root / "m34/features_t2.parquet"
|
||||
columns = ["item", "well", "text_xml"]
|
||||
inputs = pd.read_parquet(path, columns=columns)
|
||||
if args.limit:
|
||||
inputs = inputs[inputs["well"].isin(protocol["splits"]["development_wells"])].head(args.limit)
|
||||
seeds = protocol["statistics"]["seeds"] if args.seed is None else [args.seed]
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
provenance = {"inputs": digests, "model": model, "features_sha256": m2.digest(path),
|
||||
"code": m2.digest(Path(__file__)), "client_code": m34.code_fingerprint("qa")}
|
||||
with (out / "qwen.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
with closing(sqlite3.connect(out / "qwen.sqlite")) as store:
|
||||
evaluate(store, client_context, runner, config, inputs, seeds, provenance)
|
||||
|
||||
|
||||
def evaluate(store, client_context, runner, config, inputs, seeds, provenance):
|
||||
store.execute("CREATE TABLE IF NOT EXISTS metadata (provenance TEXT)")
|
||||
store.execute("""CREATE TABLE IF NOT EXISTS predictions (
|
||||
seed INTEGER, item TEXT, a REAL, b REAL, error TEXT, PRIMARY KEY (seed, item))""")
|
||||
fingerprint = json_text(provenance)
|
||||
prior = store.execute("SELECT provenance FROM metadata").fetchone()
|
||||
if prior and prior[0] != fingerprint:
|
||||
raise ValueError("T2 LLM checkpoint provenance differs.")
|
||||
if not prior:
|
||||
store.execute("INSERT INTO metadata VALUES (?)", [fingerprint])
|
||||
store.commit()
|
||||
done = set(store.execute("SELECT seed, item FROM predictions").fetchall())
|
||||
pending = [(seed, row) for seed in seeds for row in inputs.itertuples(index=False)
|
||||
if (seed, row.item) not in done]
|
||||
if not pending:
|
||||
return
|
||||
with client_context as client:
|
||||
for i, (seed, row) in enumerate(pending, 1):
|
||||
fields = ["TARGET", "PREVIOUS", "NEXT", "24H SUMMARY", "24H OUTLOOK"]
|
||||
text = "\n".join(f"{key}: {value}" for key, value in zip(fields, row.text_xml.split(DELIMITER, 4)))
|
||||
messages = [{"role": "system", "content": INSTRUCTION}, {"role": "user", "content": text[:12000]}]
|
||||
try:
|
||||
a, b = probabilities(runner.chat(client, "qwen", True, messages, SCHEMA, seed, config))
|
||||
error = None
|
||||
except ValueError as issue:
|
||||
a, b, error = 0.5, 0.5, str(issue)
|
||||
with store:
|
||||
store.execute("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)", (seed, row.item, a, b, error))
|
||||
if i == 1 or i % 100 == 0 or i == len(pending):
|
||||
print(f"Qwen T2: {i}/{len(pending)} new predictions", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
paths.load_env()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--seed", type=int, choices=[0, 1, 2])
|
||||
parser.add_argument("--limit", type=int)
|
||||
parser.add_argument("--server", type=Path)
|
||||
parser.add_argument("--weights", type=Path)
|
||||
parser.add_argument("--gpu-layers", default="all")
|
||||
args = parser.parse_args()
|
||||
if args.limit is not None and args.limit < 1:
|
||||
parser.error("--limit must be positive.")
|
||||
protocol, config = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
folder = "smoke/t2_llm" if args.limit else "t2_llm"
|
||||
run(args, protocol, config["qa"], root, digests, root / "m34" / folder)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user