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:
62
scripts/11_m34_classify.py
Executable file
62
scripts/11_m34_classify.py
Executable file
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the frozen M3–M4 inputs or run grouped classification baselines."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import m2, m34
|
||||
from volve_dia.m34_classify import classical
|
||||
from volve_dia.m34_features import feature_tables
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("stage", choices=["prepare", "classical", "distilbert"])
|
||||
parser.add_argument("--task", choices=["t1", "t2", "t3"])
|
||||
args = parser.parse_args()
|
||||
protocol, spec = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
out = root / "m34"
|
||||
out.mkdir(exist_ok=True)
|
||||
with (out / f"{args.stage}.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
run(args, protocol, spec, root, out, digests)
|
||||
|
||||
|
||||
def run(args, protocol, spec, root, out, digests):
|
||||
provenance = {"inputs": digests, "code": m34.code_fingerprint("classification")}
|
||||
if args.stage == "prepare":
|
||||
for name, frame in feature_tables(root, protocol, spec).items():
|
||||
m34.write_parquet(frame, out / f"features_{name}.parquet")
|
||||
print(f"{name}: {len(frame)} items")
|
||||
m2.write_json(out / "features_provenance.json", {"inputs": digests})
|
||||
return
|
||||
if m2.read_json(out / "features_provenance.json")["inputs"] != digests:
|
||||
raise ValueError("Features were built from other inputs. Run prepare again.")
|
||||
tables = {name: pd.read_parquet(out / f"features_{name}.parquet") for name in ("t1", "t2", "t3")}
|
||||
if args.stage == "distilbert":
|
||||
from volve_dia.m34_distilbert import distilbert
|
||||
distilbert(tables, protocol, spec, out, provenance, args.task)
|
||||
return
|
||||
for task in ([args.task] if args.task else tables):
|
||||
path = out / f"classical_{task}.parquet"
|
||||
meta = path.with_suffix(".json")
|
||||
if path.is_file() and meta.is_file():
|
||||
existing = m2.read_json(meta)
|
||||
if all(existing.get(k) == v for k, v in provenance.items()):
|
||||
print(f"{task}: checkpoint complete ({existing['rows']} predictions)", flush=True)
|
||||
continue
|
||||
print(f"{task}: fitting grouped baselines", flush=True)
|
||||
frames = list(classical(tables, protocol, spec, root, task))
|
||||
result = pd.concat(frames, ignore_index=True)
|
||||
m34.write_parquet(result, path)
|
||||
m2.write_json(meta, provenance | {"rows": len(result)})
|
||||
print(f"{task}: {len(result)} predictions", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
223
scripts/12_m34_qa.py
Executable file
223
scripts/12_m34_qa.py
Executable file
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run or resume one T4/C4 model through a local llama.cpp server or an explicitly configured API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from volve_dia import m2, m34, paths, t4
|
||||
from volve_dia.m34_features import 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)
|
||||
|
||||
MODALITIES = ("xml", "html", "ocr")
|
||||
|
||||
|
||||
class ModelFailure(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def local_server(args, cfg, exact_model):
|
||||
weights = Path(exact_model["path"])
|
||||
binary = args.server.resolve()
|
||||
version = subprocess.run([binary, "--version"], capture_output=True, check=True)
|
||||
if b"12491" not in version.stdout + version.stderr:
|
||||
raise ValueError("Expected llama.cpp b12491.")
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
command = [str(binary), "--model", str(weights), "--alias", args.model, "--host", "127.0.0.1",
|
||||
"--port", str(port), "--ctx-size", str(cfg["context_size"]), "--parallel", "1", "--threads", "4",
|
||||
"--n-gpu-layers", args.gpu_layers, "--reasoning", "off", "--no-webui", "--no-context-shift",
|
||||
"--verbosity", "1"]
|
||||
with subprocess.Popen(command) as server, httpx.Client(
|
||||
base_url=f"http://127.0.0.1:{port}/v1/", timeout=100, trust_env=False,
|
||||
) as client:
|
||||
try:
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline and server.poll() is None:
|
||||
try:
|
||||
if client.get("/health", timeout=2).is_success:
|
||||
break
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(0.4)
|
||||
else:
|
||||
raise ModelFailure("Local llama.cpp server failed to start.")
|
||||
yield client
|
||||
finally:
|
||||
if server.poll() is None:
|
||||
server.terminate()
|
||||
try:
|
||||
server.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
server.kill()
|
||||
|
||||
|
||||
def chat(client, model, local, messages, schema, seed, cfg):
|
||||
response_format = {"type": "json_object"}
|
||||
if local:
|
||||
response_format["schema"] = schema
|
||||
data = {"model": model, "messages": messages, "temperature": cfg["temperature"], "max_tokens": cfg["max_tokens"],
|
||||
"seed": seed, "response_format": response_format}
|
||||
for attempt in range(3):
|
||||
try:
|
||||
res = client.post("chat/completions", json=data)
|
||||
status = res.status_code
|
||||
if status in (401, 403, 404, 429) and not local:
|
||||
raise ModelFailure(f"API service returned HTTP {status}.")
|
||||
res.raise_for_status()
|
||||
choice = res.json()["choices"][0]
|
||||
body = json.loads(choice["message"]["content"])
|
||||
if not isinstance(body, dict) or not set(schema["required"]) <= body.keys():
|
||||
raise ValueError("Invalid response shape.")
|
||||
if "citations" in body and (not isinstance(body["citations"], list) or
|
||||
not all(isinstance(c, str) for c in body["citations"])):
|
||||
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_text(body) # Reject non-finite numeric values from a non-conforming server.
|
||||
return body
|
||||
except (httpx.HTTPError, ValueError, IndexError, KeyError, TypeError) as error:
|
||||
if attempt == 2:
|
||||
# Exception details may contain provider URLs or request data.
|
||||
raise ValueError(f"Completion failed: {type(error).__name__}") from None
|
||||
time.sleep(attempt + 1)
|
||||
|
||||
|
||||
def model_config(args, root, cfg):
|
||||
if args.model == "api":
|
||||
base = os.environ.get("VOLVE_DIA_M34_API_BASE")
|
||||
name = os.environ.get("VOLVE_DIA_M34_API_MODEL")
|
||||
token = os.environ.get("VOLVE_DIA_M34_API_KEY")
|
||||
if not all((base, name, token)):
|
||||
raise ValueError("Set VOLVE_DIA_M34_API_BASE, VOLVE_DIA_M34_API_MODEL and VOLVE_DIA_M34_API_KEY.")
|
||||
client = httpx.Client(base_url=base.rstrip("/") + "/", headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=100)
|
||||
return {"model": name, "provider": httpx.URL(base).host}, client
|
||||
args.server = args.server or (root / "audit/m2_runtime/llama-b12491/llama-server")
|
||||
pin = cfg["llama"] if args.model == "llama" else m2.spec()["raters"][args.model]
|
||||
model = (args.weights or (root / "audit/m2_runtime" / pin["file"])).resolve()
|
||||
exact = {"model": args.model, "path": str(model), "pin": pin, "weights_sha256": m2.digest(model),
|
||||
"runtime_sha256": m2.digest(args.server), "gpu_layers": args.gpu_layers}
|
||||
return exact, local_server(args, cfg, exact)
|
||||
|
||||
|
||||
def cases(questions, paired, clean, selected_modes):
|
||||
for mode in selected_modes:
|
||||
eligible = {"c4": paired, "c4_clean": clean}.get(mode, questions)
|
||||
for q in eligible:
|
||||
for modality in (MODALITIES if mode in C4_MODES else ("xml",)):
|
||||
yield mode, modality, q
|
||||
|
||||
|
||||
def run(args, protocol, cfg, root, provenance, checkpoint):
|
||||
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)
|
||||
spec = cfg["qa"]
|
||||
model, client_context = model_config(args, root, spec)
|
||||
provenance |= {"model": model}
|
||||
db = root / "ddr/volve_ddr.duckdb"
|
||||
modes = [args.mode] if args.mode else ["c4", "c4_clean", "rag", "agent", "tool_only", "zero_shot", "few_shot"]
|
||||
if args.limit:
|
||||
development = protocol["splits"]["development_wells"]
|
||||
questions, paired, clean = ([q for q in subset if q["well"] in development][:args.limit]
|
||||
for subset in (questions, paired, clean))
|
||||
schedule = list(cases(questions, paired, clean, modes))
|
||||
seeds = [args.seed] if args.seed is not None else protocol["statistics"]["seeds"]
|
||||
with contextlib.closing(sqlite3.connect(checkpoint)) as store, t4.connect(db) as con:
|
||||
store.execute("CREATE TABLE IF NOT EXISTS metadata (provenance TEXT)")
|
||||
store.execute("""CREATE TABLE IF NOT EXISTS predictions (
|
||||
mode TEXT, modality TEXT, seed INTEGER, item TEXT, data TEXT,
|
||||
PRIMARY KEY (mode, modality, seed, item))""")
|
||||
if prior := store.execute("SELECT provenance FROM metadata").fetchone():
|
||||
if json.loads(prior[0]) != provenance:
|
||||
raise ValueError("T4 checkpoint provenance differs.")
|
||||
else:
|
||||
store.execute("INSERT INTO metadata VALUES (?)", [json_text(provenance)])
|
||||
store.commit()
|
||||
done = set(store.execute("SELECT mode, modality, seed, item FROM predictions").fetchall())
|
||||
pending = [(mode, source, seed, q) for seed in seeds for mode, source, q in schedule
|
||||
if (mode, source, seed, q["id"]) not in done]
|
||||
if not pending:
|
||||
print("All requested T4 predictions are already present.")
|
||||
return
|
||||
known_reports = dict(con.execute("SELECT report_id, wellbore FROM reports").fetchall())
|
||||
tool = QueryTool(con) if any(mode in ("agent", "tool_only") for mode in modes) else None
|
||||
indexes = {}
|
||||
with client_context as client:
|
||||
for i, (mode, source, seed, q) in enumerate(pending, 1):
|
||||
index_key = (mode if mode in C4_MODES else "full", source)
|
||||
retrieve = mode in ("rag", "agent", *C4_MODES)
|
||||
if retrieve and index_key not in indexes:
|
||||
allowed = {"c4": docs, "c4_clean": docs - excluded_reports}.get(mode)
|
||||
passages = (xml_passages(con, allowed) if source == "xml"
|
||||
else rendered_passages(root, source, allowed))
|
||||
indexes[index_key] = Retriever(passages, spec["passages"], spec["context_chars"])
|
||||
examples = few_examples(questions, q, protocol["splits"]["development_wells"],
|
||||
spec["few_shot_count"]) if mode == "few_shot" else []
|
||||
try:
|
||||
predicted, evidence, trace = answer_question(
|
||||
{"question": q["question"]},
|
||||
lambda messages, schema: chat(client, model["model"], args.model != "api",
|
||||
messages, schema, seed, spec),
|
||||
spec, mode, examples, indexes.get(index_key) if retrieve else None, tool)
|
||||
error = None
|
||||
except ValueError as failure:
|
||||
error = str(failure)
|
||||
predicted, evidence, trace = {"answer": None, "citations": []}, [], []
|
||||
score = scoring_row(q, predicted, known_reports, evidence, trace, failed=error is not None)
|
||||
record = score | {"prediction": predicted, "retrieved": evidence, "trace": trace, "error": error,
|
||||
"date_flag": q["id"] in date_flagged, "n_examples": len(examples)}
|
||||
with store:
|
||||
store.execute("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)",
|
||||
[mode, source, seed, q["id"], json_text(record)])
|
||||
if i == 1 or i % 50 == 0 or i == len(pending):
|
||||
print(f"{args.model}: {i}/{len(pending)} new predictions ({mode}/{source})", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
paths.load_env()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--model", default="qwen", choices=["qwen", "llama", "api"])
|
||||
parser.add_argument("--mode", choices=MODES)
|
||||
parser.add_argument("--seed", type=int, choices=[0, 1, 2])
|
||||
parser.add_argument("--server", type=Path)
|
||||
parser.add_argument("--weights", type=Path)
|
||||
parser.add_argument("--gpu-layers", default="all")
|
||||
parser.add_argument("--limit", type=int, help="Run an isolated smoke check on the first N items in each subset.")
|
||||
args = parser.parse_args()
|
||||
if args.limit is not None and args.limit < 1:
|
||||
parser.error("--limit must be positive.")
|
||||
protocol, cfg = m34.configuration()
|
||||
root, inputs = m34.inputs(protocol)
|
||||
out = root / "m34" / ("smoke" if args.limit else "qa")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
name = f"{args.model}-{m34.code_fingerprint('qa')[:12]}" if args.limit else args.model
|
||||
path = out / f"{name}.sqlite"
|
||||
with path.with_suffix(".lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
run(args, protocol, cfg, root, {"inputs": inputs, "code": m34.code_fingerprint('qa')}, path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
27
scripts/13_m34_report.py
Executable file
27
scripts/13_m34_report.py
Executable file
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build current M3–M4 tables and a G2 coverage report from saved predictions."""
|
||||
|
||||
import fcntl
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import m2, m34
|
||||
from volve_dia.m34_report import build_report
|
||||
|
||||
|
||||
def main():
|
||||
protocol, _ = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
out = root / "m34"
|
||||
with (out / "report.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
report = build_report(out, root, protocol, digests)
|
||||
for name in ("classification", "classification_contrasts", "qa", "qa_contrasts", "qa_coverage"):
|
||||
data = pd.json_normalize(report[name])
|
||||
m34.atomic_write(out / f"{name}.csv", data.to_csv(index=False).encode())
|
||||
m2.write_json(out / "report.json", report)
|
||||
print(f"G2 passed: v1 {report['g2']['passed']}, v2 {report['g2_v2']['passed']}. T4 C4 coverage: {report['c4']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
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()
|
||||
78
scripts/17_m34_distilbert_shard.py
Normal file
78
scripts/17_m34_distilbert_shard.py
Normal file
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the v1 DistilBERT baseline on one block (task, definition, mode) so blocks can share a GPU.
|
||||
|
||||
This replicates the ``distilbert`` stage of ``scripts/11_m34_classify.py`` (same configuration, inputs,
|
||||
provenance and checkpoints under ``outputs/m34/distilbert/``) but takes a per-block lock instead of
|
||||
``distilbert.lock`` and restricts ``volve_dia.m34_distilbert.datasets`` to the chosen block. The v1 code files
|
||||
are not modified, so the classification code fingerprint and every checkpoint provenance stay unchanged.
|
||||
T1 has a single block: ``--task t1 --definition section --mode masked``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import itertools
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from volve_dia import m2, m34
|
||||
from volve_dia import m34_classify
|
||||
|
||||
|
||||
def block_filter(task, definition, mode):
|
||||
"""Return a replacement for ``datasets`` that yields only the chosen block."""
|
||||
def datasets(tables, protocol):
|
||||
for block in m34_classify.datasets(tables, protocol):
|
||||
if block[:3] == (task, definition, mode):
|
||||
yield block
|
||||
return datasets
|
||||
|
||||
|
||||
def completed(out, protocol, task, definition, mode, frame):
|
||||
"""Count finished folds (parquet and json present) against the folds the block requires."""
|
||||
splits = protocol["splits"]
|
||||
seeds = protocol["statistics"]["seeds"]
|
||||
done = total = 0
|
||||
for group, seed in itertools.product((splits["group"], splits["sensitivity_group"]), seeds):
|
||||
directory = out / "distilbert" / task / definition / mode / group / str(seed)
|
||||
total += frame[group].nunique()
|
||||
done += sum(1 for meta in directory.glob("*.json") if meta.with_suffix(".parquet").exists())
|
||||
return done, total
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--task", choices=["t1", "t2", "t3"], required=True)
|
||||
parser.add_argument("--definition", choices=["a", "b", "section"], required=True)
|
||||
parser.add_argument("--mode", choices=["masked", "unmasked"], required=True)
|
||||
parser.add_argument("--dry-run", action="store_true", help="print the block and checkpoint count, then exit")
|
||||
args = parser.parse_args()
|
||||
protocol, spec = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
out = root / "m34"
|
||||
out.mkdir(exist_ok=True)
|
||||
provenance = {"inputs": digests, "code": m34.code_fingerprint("classification")}
|
||||
if m2.read_json(out / "features_provenance.json")["inputs"] != digests:
|
||||
raise ValueError("Features were built from other inputs. Run prepare again.")
|
||||
tables = {name: pd.read_parquet(out / f"features_{name}.parquet") for name in ("t1", "t2", "t3")}
|
||||
selected = block_filter(args.task, args.definition, args.mode)
|
||||
blocks = list(selected(tables, protocol))
|
||||
if len(blocks) != 1:
|
||||
raise ValueError(f"Expected one block for {args.task}/{args.definition}/{args.mode}, found {len(blocks)}.")
|
||||
task, definition, mode, frame, target = blocks[0]
|
||||
if args.dry_run:
|
||||
done, total = completed(out, protocol, task, definition, mode, frame)
|
||||
print(f"block {task}/{definition}/{mode} target={target} items={len(frame)} "
|
||||
f"checkpointed folds {done}/{total}", flush=True)
|
||||
return
|
||||
lock_path = out / f"distilbert_{args.task}_{args.definition}_{args.mode}.lock"
|
||||
with lock_path.open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
from volve_dia import m34_distilbert
|
||||
m34_distilbert.datasets = selected
|
||||
m34_distilbert.distilbert(tables, protocol, spec, out, provenance, args.task)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
45
scripts/run_m34.sh
Executable file
45
scripts/run_m34.sh
Executable file
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# Reproducible M3–M4 stages, resumed with the same command.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 CUBLAS_WORKSPACE_CONFIG=:4096:8
|
||||
export 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_${1:-prepare}" -- bash scripts/run_m34.sh "$@"
|
||||
|
||||
stage="${1:-prepare}"
|
||||
if [[ $# -gt 0 ]]; then
|
||||
shift
|
||||
fi
|
||||
case "$stage" in
|
||||
prepare|classical|distilbert)
|
||||
run_python scripts/11_m34_classify.py "$stage" "$@"
|
||||
;;
|
||||
qa)
|
||||
run_python scripts/12_m34_qa.py "$@"
|
||||
;;
|
||||
t2-llm)
|
||||
run_python scripts/14_m34_t2_llm.py "$@"
|
||||
;;
|
||||
qa-local)
|
||||
env -u RUNLOG_DIR bash scripts/run_m34.sh qa --model qwen "$@"
|
||||
env -u RUNLOG_DIR bash scripts/run_m34.sh qa --model llama "$@"
|
||||
env -u RUNLOG_DIR bash scripts/run_m34.sh report
|
||||
;;
|
||||
report)
|
||||
run_python scripts/13_m34_report.py "$@"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: scripts/run_m34.sh {prepare|classical|distilbert|qa|qa-local|t2-llm|report} [options]" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
Reference in New Issue
Block a user