Download expansion_v2/experiments/contextual-discourse/source/train.py from Giuliocc/doxa-methods: direct link, hf CLI and curl.
- Browser
- Download file 20.5 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/train.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-methods/expansion_v2/experiments/contextual-discourse/source/train.py
-
curl -L -o train.py https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/train.py
20.5 kB
| """Fit/lock first, then independently evaluate a fresh contextual task. | |
| Use `fit` and `evaluate` as separate steps. The fit command never loads the | |
| held-out records. All raw text, gold labels and candidate parameters remain | |
| in local/ until publication eligibility is decided. | |
| """ | |
| from __future__ import annotations | |
| from argparse import ArgumentParser | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import time | |
| import joblib | |
| import numpy as np | |
| import onnxruntime as ort | |
| from onnxruntime.quantization import QuantType, quantize_dynamic | |
| from scipy.sparse import hstack | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.linear_model import LogisticRegression | |
| from threadpoolctl import threadpool_limits | |
| import torch | |
| from transformers import AutoTokenizer, get_linear_schedule_with_warmup | |
| from data import ROOT, fingerprint, write_json, locked, rows, labels, prepare, lexical_inputs, input_coverage | |
| from metrics import TASKS, calibrated, decide, resolved, summarize, fit_calibration, paired_interval | |
| from modeling import BASE_PATH, BASE_ID, BASE_REVISION, INPUT_NAMES, ContextEncoder, deterministic, batches, native_logits, encoder_features, install_logistic | |
| LOCAL = ROOT / "local" | |
| LOCAL.mkdir(exist_ok=True) | |
| def valid_mask(packed): | |
| return np.array([row["status"] == "ok" for row in packed]) | |
| def output_metrics(y, logits, calibration, packed): | |
| probabilities = calibrated(logits, calibration) | |
| predictions = decide(probabilities, calibration) | |
| keep = resolved(probabilities, calibration) | |
| valid = valid_mask(packed) | |
| predictions[~valid] = 0 | |
| keep[~valid] = False | |
| metric = summarize(y, predictions, keep=keep) | |
| metric["calibration_on_eligible"] = summarize(y[valid], predictions[valid], probabilities[valid], keep[valid]) | |
| metric["unresolved_targets_count_as_missed_positives"] = int((~valid).sum()) | |
| return metric, predictions, probabilities, keep | |
| def score_validation(y, logits, packed): | |
| valid = valid_mask(packed) | |
| calibration = fit_calibration(logits[valid], y[valid]) | |
| metric, _, _, _ = output_metrics(y, logits, calibration, packed) | |
| return metric, calibration | |
| def fit_logistic(features, truth, validation_features, validation_truth, packed): | |
| attempts = [] | |
| chosen, best = None, -1 | |
| for c in (.1, 1., 10.): | |
| with threadpool_limits(limits=1): | |
| fits = [LogisticRegression(C=c, class_weight="balanced", max_iter=2000, random_state=1729, | |
| solver="lbfgs").fit(features, truth[:, i]) for i in range(2)] | |
| logits = np.column_stack([fit.decision_function(validation_features) for fit in fits]) | |
| metric, calibration = score_validation(validation_truth, logits, packed) | |
| attempt = {"C": c, "validation": metric, "calibration": calibration} | |
| attempts.append(attempt) | |
| if metric["mean_positive_f1"] > best: | |
| best = metric["mean_positive_f1"] | |
| chosen = {"fits": fits, "C": c, "validation": metric, "calibration": calibration} | |
| chosen["attempts"] = attempts | |
| return chosen | |
| def fine_tune(kind, packed_train, train_truth, packed_validation, validation_truth): | |
| deterministic() | |
| model = ContextEncoder() | |
| valid = valid_mask(packed_train) | |
| positive = train_truth[valid].sum(0) | |
| weight = torch.tensor((valid.sum() - positive) / np.maximum(positive, 1), dtype=torch.float32) | |
| optimizer = torch.optim.AdamW(model.parameters(), lr=3e-5, weight_decay=.01) | |
| micro_steps = math.ceil(valid.sum() / 8) | |
| scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(.1 * 2 * math.ceil(micro_steps / 2)), | |
| num_training_steps=2 * math.ceil(micro_steps / 2)) | |
| history, selected, best = [], None, -1 | |
| rng = np.random.default_rng(1729) | |
| for epoch in (1, 2): | |
| started = time.perf_counter() | |
| model.train() | |
| optimizer.zero_grad(set_to_none=True) | |
| total_loss, step = 0., 0 | |
| order = rng.permutation(np.flatnonzero(valid)) | |
| for indices, values in batches(packed_train, batch_size=8, order=order): | |
| target = torch.tensor(train_truth[indices], dtype=torch.float32) | |
| logits = model(**values) | |
| loss = torch.nn.functional.binary_cross_entropy_with_logits(logits, target, pos_weight=weight) | |
| (loss / 2).backward() | |
| total_loss += float(loss.detach()) | |
| step += 1 | |
| if step % 2 == 0 or step == micro_steps: | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1) | |
| optimizer.step() | |
| scheduler.step() | |
| optimizer.zero_grad(set_to_none=True) | |
| logits = native_logits(model, packed_validation) | |
| metric, calibration = score_validation(validation_truth, logits, packed_validation) | |
| folder = LOCAL / f"{kind}-epoch-{epoch}" | |
| model.save(folder) | |
| record = {"kind": kind, "epoch": epoch, "validation": metric, "calibration": calibration, | |
| "training_loss": total_loss / step, "seconds": time.perf_counter() - started, | |
| "weights": str(folder.relative_to(ROOT)), "weights_sha256": fingerprint(folder / "model.safetensors")} | |
| history.append(record) | |
| write_json(LOCAL / f"{kind}-history.json", history) | |
| print(json.dumps({"kind": kind, "epoch": epoch, "validation_mean_positive_f1": metric["mean_positive_f1"], | |
| "seconds": record["seconds"]}), flush=True) | |
| if metric["mean_positive_f1"] > best: | |
| best, selected = metric["mean_positive_f1"], record | |
| return selected | |
| def onnx_logits(path, packed): | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = 1 | |
| options.inter_op_num_threads = 1 | |
| session = ort.InferenceSession(str(path), sess_options=options, providers=["CPUExecutionProvider"]) | |
| output = np.zeros((len(packed), 2), dtype=np.float32) | |
| for indices, values in batches(packed, batch_size=1): | |
| output[indices] = session.run(None, {name: value.numpy() for name, value in values.items() if name in [item.name for item in session.get_inputs()]})[0] | |
| return output | |
| def export_selection(model, packed_validation, truth, calibration): | |
| folder = LOCAL / "export" | |
| folder.mkdir(exist_ok=True) | |
| example = next(batches(packed_validation, batch_size=1))[1] | |
| floating = folder / "model.onnx" | |
| torch.onnx.export(model.eval(), tuple(example[name] for name in INPUT_NAMES), str(floating), | |
| input_names=list(INPUT_NAMES), output_names=["logits"], | |
| dynamic_axes={name: {0: "batch", 1: "sequence"} for name in INPUT_NAMES} | {"logits": {0: "batch"}}, | |
| opset_version=17, dynamo=False) | |
| native = native_logits(model, packed_validation) | |
| native_metric, reference, p, _ = output_metrics(truth, native, calibration, packed_validation) | |
| valid = valid_mask(packed_validation) | |
| attempts = [] | |
| for channel in (False, True): | |
| for reduced in (False, True): | |
| name = f"channel{int(channel)}-range{int(reduced)}" | |
| path = folder / f"{name}.onnx" | |
| quantize_dynamic(str(floating), str(path), op_types_to_quantize=["MatMul", "Gemm", "Gather"], | |
| weight_type=QuantType.QInt8, per_channel=channel, reduce_range=reduced) | |
| values = onnx_logits(path, packed_validation) | |
| metric, prediction, probability, _ = output_metrics(truth, values, calibration, packed_validation) | |
| agreement = float((prediction[valid] == reference[valid]).mean()) | |
| row = {"name": name, "per_channel": channel, "reduce_range": reduced, | |
| "validation": metric, "native_label_agreement": agreement, | |
| "score_mae": float(np.abs(probability[valid] - p[valid]).mean()), | |
| "bytes": path.stat().st_size, "sha256": fingerprint(path)} | |
| row["eligible"] = agreement >= .98 and abs(metric["mean_positive_f1"] - native_metric["mean_positive_f1"]) <= .01 and path.stat().st_size < 40_000_000 | |
| attempts.append(row) | |
| print(json.dumps({"export": name, "agreement": agreement, "eligible": row["eligible"]}), flush=True) | |
| write_json(folder / "validation.json", {"attempts": attempts, "selected": None}) | |
| eligible = [row for row in attempts if row["eligible"]] | |
| selected = max(eligible, key=lambda row: (row["native_label_agreement"], -row["score_mae"], -row["bytes"])) if eligible else None | |
| report = {"attempts": attempts, "selected": selected, "selection_uses_test": False} | |
| write_json(folder / "validation.json", report) | |
| return report | |
| def fit(): | |
| deterministic() | |
| source_lock = locked() | |
| if (LOCAL / "LOCKED_SELECTION.json").exists(): | |
| raise RuntimeError("Selection already locked. Keep previous candidates; do not refit silently.") | |
| tokenizer = AutoTokenizer.from_pretrained(BASE_PATH, local_files_only=True) | |
| training, validation = rows("train"), rows("validation") | |
| truth, val_truth = labels(training), labels(validation) | |
| if any(truth[:, i].sum() < 20 or val_truth[:, i].sum() < 10 for i in range(2)): | |
| raise RuntimeError("Insufficient actual task-positive source labels for this registered fit") | |
| packed = {name: {"train": prepare(training, tokenizer, context), "validation": prepare(validation, tokenizer, context)} | |
| for name, context in (("target_only", False), ("context", True))} | |
| coverage = {kind: {role: input_coverage(value) for role, value in splits.items()} for kind, splits in packed.items()} | |
| write_json(LOCAL / "input-coverage-fit.json", coverage) | |
| print(json.dumps({"input_coverage": coverage}), flush=True) | |
| records = {} | |
| for kind in ("target_only", "context"): | |
| start = time.perf_counter() | |
| train_text, val_text = [lexical_inputs(packed[kind][role], tokenizer) for role in ("train", "validation")] | |
| word = TfidfVectorizer(ngram_range=(1, 2), min_df=2, max_features=40000, sublinear_tf=True) | |
| char = TfidfVectorizer(analyzer="char", ngram_range=(3, 5), min_df=2, max_features=40000, sublinear_tf=True) | |
| features = hstack([word.fit_transform(train_text), char.fit_transform(train_text)]).tocsr() | |
| val_features = hstack([word.transform(val_text), char.transform(val_text)]).tocsr() | |
| chosen = fit_logistic(features, truth, val_features, val_truth, packed[kind]["validation"]) | |
| name = f"tfidf_{kind}" | |
| joblib.dump({"word": word, "char": char, "fits": chosen.pop("fits")}, LOCAL / f"{name}.joblib") | |
| chosen.update({"kind": kind, "type": "tfidf", "seconds": time.perf_counter() - start}) | |
| records[name] = chosen | |
| print(json.dumps({"pipeline": name, "validation_mean_positive_f1": chosen["validation"]["mean_positive_f1"]}), flush=True) | |
| encoder = ContextEncoder().eval() | |
| for kind in ("target_only", "context"): | |
| start = time.perf_counter() | |
| features = encoder_features(encoder, packed[kind]["train"]) | |
| validation_features = encoder_features(encoder, packed[kind]["validation"]) | |
| chosen = fit_logistic(features, truth, validation_features, val_truth, packed[kind]["validation"]) | |
| name = f"frozen_{kind}" | |
| joblib.dump(chosen.pop("fits"), LOCAL / f"{name}.joblib") | |
| chosen.update({"kind": kind, "type": "frozen", "seconds": time.perf_counter() - start}) | |
| records[name] = chosen | |
| print(json.dumps({"pipeline": name, "validation_mean_positive_f1": chosen["validation"]["mean_positive_f1"], "seconds": chosen["seconds"]}), flush=True) | |
| del encoder | |
| write_json(LOCAL / "validation-pipelines.json", records) | |
| for kind in ("target_only", "context"): | |
| chosen = fine_tune(f"fine_{kind}", packed[kind]["train"], truth, packed[kind]["validation"], val_truth) | |
| chosen.update({"kind": kind, "type": "fine"}) | |
| records[f"fine_{kind}"] = chosen | |
| write_json(LOCAL / "validation-pipelines.json", records) | |
| candidates = [name for name in records if records[name]["kind"] == "context" and records[name]["type"] != "tfidf"] | |
| selected_name = max(candidates, key=lambda name: records[name]["validation"]["mean_positive_f1"]) | |
| selected = records[selected_name] | |
| if selected["type"] == "fine": | |
| model = ContextEncoder.load(ROOT / selected["weights"]) | |
| else: | |
| model = install_logistic(ContextEncoder(), joblib.load(LOCAL / f"{selected_name}.joblib")) | |
| model.save(LOCAL / "selected-native") | |
| tokenizer.backend_tokenizer.no_truncation() | |
| tokenizer.backend_tokenizer.no_padding() | |
| tokenizer.save_pretrained(LOCAL / "selected-native") | |
| exports = export_selection(model, packed["context"]["validation"], val_truth, selected["calibration"]) | |
| selection = {"protocol_sha256": fingerprint(ROOT / "PROTOCOL.json"), "data_lock_sha256": fingerprint(ROOT / "DATA_LOCK.json"), | |
| "selected_pipeline": selected_name, "pipelines": records, "calibration": selected["calibration"], | |
| "native_weights_sha256": fingerprint(LOCAL / "selected-native/model.safetensors"), "export": exports, | |
| "test_used": False, "new_spend_usd": 0, "base_model": BASE_ID, "base_revision": BASE_REVISION, | |
| "source_code_sha256": {name: fingerprint(ROOT / name) for name in ("train.py", "data.py", "inputs.py", "metrics.py", "modeling.py")}} | |
| write_json(LOCAL / "LOCKED_SELECTION.json", selection) | |
| print(json.dumps({"selection_locked": selected_name, "lock_sha256": fingerprint(LOCAL / "LOCKED_SELECTION.json"), | |
| "export_eligible": exports["selected"] is not None}), flush=True) | |
| def evaluate(): | |
| deterministic() | |
| source_lock = locked() | |
| selection = json.loads((LOCAL / "LOCKED_SELECTION.json").read_text()) | |
| if selection["data_lock_sha256"] != fingerprint(ROOT / "DATA_LOCK.json") or selection["protocol_sha256"] != fingerprint(ROOT / "PROTOCOL.json"): | |
| raise RuntimeError("Frozen source or protocol changed after validation selection") | |
| if (LOCAL / "EVALUATION.json").exists(): | |
| raise RuntimeError("Held-out evaluation already exists; preserve it and do not repeat selection") | |
| if fingerprint(LOCAL / "selected-native/model.safetensors") != selection["native_weights_sha256"]: | |
| raise RuntimeError("Locked native weights changed") | |
| test = rows("test") | |
| truth = labels(test) | |
| tokenizer = AutoTokenizer.from_pretrained(LOCAL / "selected-native", local_files_only=True) | |
| packed = {kind: prepare(test, tokenizer, kind == "context") for kind in ("target_only", "context")} | |
| outcomes, predictions = {}, {} | |
| encoder = ContextEncoder().eval() | |
| for name, record in selection["pipelines"].items(): | |
| kind = record["kind"] | |
| if record["type"] == "tfidf": | |
| saved = joblib.load(LOCAL / f"{name}.joblib") | |
| text = lexical_inputs(packed[kind], tokenizer) | |
| features = hstack([saved["word"].transform(text), saved["char"].transform(text)]).tocsr() | |
| logits = np.column_stack([fit.decision_function(features) for fit in saved["fits"]]) | |
| elif record["type"] == "frozen": | |
| features = encoder_features(encoder, packed[kind]) | |
| fits = joblib.load(LOCAL / f"{name}.joblib") | |
| logits = np.column_stack([fit.decision_function(features) for fit in fits]) | |
| else: | |
| model = ContextEncoder.load(ROOT / record["weights"]) | |
| logits = native_logits(model, packed[kind]) | |
| del model | |
| metric, predicted, probability, keep = output_metrics(truth, logits, record["calibration"], packed[kind]) | |
| outcomes[name], predictions[name] = metric, {"labels": predicted, "scores": probability, "resolved": keep} | |
| del encoder | |
| selected_name = selection["selected_pipeline"] | |
| candidate = predictions[selected_name]["labels"] | |
| lexical_control = max((name for name in outcomes if name.startswith("tfidf_")), key=lambda name: outcomes[name]["mean_positive_f1"]) | |
| target_control = max((name for name in outcomes if selection["pipelines"][name]["kind"] == "target_only"), key=lambda name: outcomes[name]["mean_positive_f1"]) | |
| groups = [row["group_id"] for row in test] | |
| candidate_score = outcomes[selected_name]["mean_positive_f1"] | |
| gain = candidate_score - outcomes[lexical_control]["mean_positive_f1"] | |
| interval = paired_interval(truth, candidate, predictions[lexical_control]["labels"], groups) | |
| context_gain = candidate_score - outcomes[target_control]["mean_positive_f1"] | |
| context_interval = paired_interval(truth, candidate, predictions[target_control]["labels"], groups) | |
| coverage = input_coverage(packed["context"]) | |
| per_task = all(outcomes[selected_name]["tasks"][task]["positive_f1"] >= outcomes[lexical_control]["tasks"][task]["positive_f1"] - .02 for task in TASKS) | |
| native_gate = gain >= .02 and interval["gain_interval_95"][0] > 0 and per_task and coverage["eligible_fraction"] >= .95 | |
| report = {"method": "doxa-contextual-discourse-v0.2.0", "tasks": list(TASKS), "applied_rubric": "BASIL-source-annotation-v1", | |
| "selection_sha256": fingerprint(LOCAL / "LOCKED_SELECTION.json"), "protocol_sha256": selection["protocol_sha256"], | |
| "data_lock_sha256": selection["data_lock_sha256"], "selected_pipeline": selected_name, | |
| "rows": len(test), "source_groups": len(set(groups)), "pipelines": outcomes, | |
| "strongest_lexical_control": lexical_control, "native_gain": gain, "native_bootstrap": interval, | |
| "strongest_target_only_control": target_control, "context_gain": context_gain, "context_bootstrap": context_interval, | |
| "context_benefit_claim_qualified": context_gain >= .01 and context_interval["gain_interval_95"][0] > 0, | |
| "input_coverage": coverage, "calibration": selection["calibration"], | |
| "gates": {"native": native_gate, "native_no_task_degradation": per_task, "quantized": False, "browser": False, | |
| "rights_review": "pending_lead_review", "release": False}, "new_spend_usd": 0} | |
| exported = selection["export"]["selected"] | |
| if exported: | |
| path = LOCAL / "export" / f"{exported['name']}.onnx" | |
| if fingerprint(path) != exported["sha256"]: | |
| raise RuntimeError("Validation-selected export changed") | |
| logits = onnx_logits(path, packed["context"]) | |
| metric, predicted, probability, keep = output_metrics(truth, logits, selection["calibration"], packed["context"]) | |
| agreement = float((predicted[valid_mask(packed["context"])] == candidate[valid_mask(packed["context"])]).mean()) | |
| quantized_gain = metric["mean_positive_f1"] - outcomes[lexical_control]["mean_positive_f1"] | |
| quantized_interval = paired_interval(truth, predicted, predictions[lexical_control]["labels"], groups) | |
| report["quantized"] = {"metrics": metric, "native_label_agreement": agreement, "bytes": path.stat().st_size, | |
| "sha256": exported["sha256"], "settings": exported["name"], "gain": quantized_gain, "bootstrap": quantized_interval, | |
| "singleton_input": True, "calibration_refit_on_quantized": False} | |
| report["gates"]["quantized"] = quantized_gain >= .02 and quantized_interval["gain_interval_95"][0] > 0 and agreement >= .98 and abs(metric["mean_positive_f1"] - candidate_score) <= .01 and path.stat().st_size < 40_000_000 | |
| predictions["quantized"] = {"labels": predicted, "scores": probability, "resolved": keep} | |
| cases = [] | |
| for index, row in enumerate(test): | |
| cases.append({"id": row["id"], "group_id": row["group_id"], "article_id": row["article_id"], | |
| "reference_labels": truth[index].tolist(), "input_status": packed["context"][index]["status"], | |
| "pipelines": {name: {key: values[index].tolist() for key, values in outcome.items()} for name, outcome in predictions.items()}}) | |
| (LOCAL / "test_predictions.jsonl").write_text("".join(json.dumps(row) + "\n" for row in cases)) | |
| write_json(LOCAL / "EVALUATION.json", report) | |
| print(json.dumps({"selected_pipeline": selected_name, "native_mean_positive_f1": candidate_score, "lexical_control": lexical_control, | |
| "native_gain": gain, "native_interval": interval, "context_gain": context_gain, | |
| "gates": report["gates"], "quantized": report.get("quantized")}, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| parser = ArgumentParser(description=__doc__) | |
| parser.add_argument("command", choices=("fit", "evaluate")) | |
| args = parser.parse_args() | |
| fit() if args.command == "fit" else evaluate() | |