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
volve_dia/m34_distilbert.py
Normal file
112
volve_dia/m34_distilbert.py
Normal file
@@ -0,0 +1,112 @@
|
||||
"""Fixed-setting DistilBERT fine-tuning with a checkpoint per held-out group and seed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import itertools
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.model_selection import GroupKFold, LeaveOneGroupOut
|
||||
|
||||
from . import m2, m34
|
||||
from .m34_classify import datasets, model_inputs, prediction_rows
|
||||
|
||||
|
||||
def distilbert(tables, protocol, spec, out, provenance, task_filter):
|
||||
import torch
|
||||
import transformers
|
||||
from torch.utils.data import DataLoader
|
||||
from transformers import AutoModelForSequenceClassification, AutoTokenizer, set_seed
|
||||
|
||||
cfg = spec["classification"]["distilbert"]
|
||||
batch_size = cfg["batch_size"]
|
||||
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
|
||||
torch.set_num_threads(4)
|
||||
torch.use_deterministic_algorithms(True)
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
provenance |= {"torch": torch.__version__, "transformers": transformers.__version__, "device": str(device)}
|
||||
tokenizer = AutoTokenizer.from_pretrained(cfg["model"], revision=cfg["revision"], trust_remote_code=False)
|
||||
split_names = protocol["splits"]
|
||||
|
||||
def fit_predict(text, y, train, test, n_classes, seed):
|
||||
set_seed(seed)
|
||||
model = AutoModelForSequenceClassification.from_pretrained(
|
||||
cfg["model"], revision=cfg["revision"], num_labels=n_classes, use_safetensors=True,
|
||||
trust_remote_code=False).to(device)
|
||||
adam = torch.optim.AdamW(model.parameters(), lr=cfg["learning_rate"])
|
||||
|
||||
def batches(indices, shuffle):
|
||||
return DataLoader(indices.tolist(), batch_size=batch_size, shuffle=shuffle,
|
||||
generator=torch.Generator().manual_seed(seed))
|
||||
|
||||
def encode(ix):
|
||||
return tokenizer(text.iloc[ix.tolist()].tolist(), padding=True, truncation=True,
|
||||
max_length=cfg["max_tokens"], return_tensors="pt").to(device)
|
||||
|
||||
model.train()
|
||||
for _ in range(cfg["epochs"]):
|
||||
for ix in batches(train, True):
|
||||
adam.zero_grad(set_to_none=True)
|
||||
target = torch.as_tensor(y[ix.numpy()], device=device)
|
||||
model(**encode(ix), labels=target).loss.backward()
|
||||
adam.step()
|
||||
model.eval()
|
||||
with torch.inference_mode():
|
||||
return np.concatenate([model(**encode(ix)).logits.softmax(dim=1).cpu().numpy()
|
||||
for ix in batches(test, False)])
|
||||
|
||||
for task, definition, mode, frame, target in datasets(tables, protocol):
|
||||
if task_filter is not None and task_filter != task:
|
||||
continue
|
||||
frame = frame.reset_index(drop=True)
|
||||
x = model_inputs(frame, mode, "xml")
|
||||
text = x["text"].copy()
|
||||
if task == "t3":
|
||||
text = ("Depth m: " + x["md_top"].astype(str) + " [SEP] " + text)
|
||||
checkpoints = out / "distilbert" / task / definition / mode
|
||||
experiments = itertools.product((split_names["group"], split_names["sensitivity_group"]),
|
||||
protocol["statistics"]["seeds"])
|
||||
for group, seed in experiments:
|
||||
groups = frame[group]
|
||||
for train, test in LeaveOneGroupOut().split(text, frame[target], groups):
|
||||
holdout = groups.iat[test[0]]
|
||||
key = hashlib.sha256(holdout.encode()).hexdigest()[:12]
|
||||
directory = checkpoints / group / str(seed)
|
||||
meta_path = directory / f"{key}.json"
|
||||
path = directory / f"{key}.parquet"
|
||||
run = provenance | {"task": task, "definition": definition, "mode": mode, "split": group,
|
||||
"seed": seed, "holdout": holdout}
|
||||
if meta_path.exists() and path.exists():
|
||||
if m2.read_json(meta_path) != run:
|
||||
raise ValueError(f"DistilBERT checkpoint provenance differs: {path}")
|
||||
continue
|
||||
classes = sorted(frame[target].iloc[train].unique())
|
||||
if task != "t1" and classes != [False, True]:
|
||||
raise ValueError("Binary training fold is missing a class.")
|
||||
mapping = {value: i for i, value in enumerate(classes)}
|
||||
y = frame[target].map(mapping).fillna(-1).to_numpy(dtype=np.int64)
|
||||
threshold = 0.5
|
||||
if task == "t3":
|
||||
inner = GroupKFold(n_splits=split_names["inner"]["n_splits"])
|
||||
valid_y, valid_scores = [], []
|
||||
tune = train[~frame["well"].iloc[train].isin(frame["well"].iloc[test]).to_numpy()]
|
||||
for inner_train, valid in inner.split(text.iloc[tune], y[tune], groups=frame["well"].iloc[tune]):
|
||||
probability = fit_predict(text, y, tune[inner_train], tune[valid], len(classes), seed)
|
||||
valid_scores.extend(probability[:, 1])
|
||||
valid_y.extend(y[tune[valid]].astype(bool))
|
||||
valid_y, valid_scores = np.asarray(valid_y), np.asarray(valid_scores)
|
||||
threshold = max(spec["classification"]["t3_thresholds"], key=lambda t: m34.interval_overlap(
|
||||
valid_y, valid_scores >= t, np.ones(len(valid_y), dtype=np.int64)))
|
||||
probability = fit_predict(text, y, train, test, len(classes), seed)
|
||||
if task == "t1":
|
||||
values, scores = np.asarray(classes)[probability.argmax(axis=1)], np.full(len(test), np.nan)
|
||||
else:
|
||||
scores = probability[:, 1]
|
||||
values = scores >= threshold
|
||||
result = prediction_rows(frame.iloc[test], task, target, definition, mode, group, "distilbert", "xml",
|
||||
values, scores, seed).assign(threshold=threshold)
|
||||
m34.write_parquet(result, path)
|
||||
m2.write_json(meta_path, run)
|
||||
print(f"{task}/{definition}/{mode}/{group}/{seed}: {holdout} complete", flush=True)
|
||||
Reference in New Issue
Block a user