"""Local-only frozen-encoder BASIL reference-span experiment. Publisher prose, upstream annotations, token vocabulary, embeddings, fitted heads and row predictions remain in work/private. Public outputs are aggregate metrics/protocol and original code only. A source span is not an explanation. """ from __future__ import annotations import os for _name in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS"): os.environ[_name] = "1" os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ["HF_HUB_OFFLINE"] = "1" import argparse from collections import Counter, defaultdict import gzip from hashlib import sha256 import json from pathlib import Path import pickle import re import time import numpy as np from scipy.optimize import linear_sum_assignment from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import SGDClassifier HERE = Path(__file__).resolve().parent SOURCE = HERE.parent / "context_data/local/frozen-v2" PRIVATE = HERE / "work/private" PUBLIC = HERE / "public" MODEL = Path("/home/agent/.cache/huggingface/hub/models--sentence-transformers--all-MiniLM-L6-v2/snapshots/1110a243fdf4706b3f48f1d95db1a4f5529b4d41") HEADS = ("lex", "inf") METHODS = ("all_negative", "all_positive", "token_posterior", "char_ngram", "frozen_minilm_probe") WORD = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]") def digest(value): return sha256(value if isinstance(value, bytes) else value.encode()).hexdigest() def dump(path, value): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def load(path): return json.loads(path.read_text(encoding="utf-8")) def protocol(): raw = (HERE / "PROTOCOL.json").read_bytes() return json.loads(raw), digest(raw) def unlock_receipt(): path = HERE / "MAIN_SELECTION_UNLOCK.json" if not path.exists(): raise RuntimeError("Test remains locked: context_model must explicitly confirm LOCKED_SELECTION before any test file access") receipt = load(path) if receipt.get("confirmed_by") != "/root/context_model" or "LOCKED_SELECTION" not in receipt.get("exact_message", ""): raise RuntimeError("Invalid main selection unlock receipt") if not receipt.get("quality_selection_observed") or not re.fullmatch(r"[0-9a-f]{64}", receipt.get("quality_selection_receipt_sha256", "")): raise RuntimeError("Independent quality observation of the locked probe selection is required") if not (PRIVATE / "PROBE_SELECTION_LOCK.json").exists(): raise RuntimeError("Probe train/validation selection is not locked") return receipt def read_split(split): if split == "test": unlock_receipt() # Do this BEFORE opening the held-out file. spec, _ = protocol() path = SOURCE / (split + ".jsonl") raw = path.read_bytes() if split in {"train", "validation"}: assert digest(raw) == spec["role_files"][split]["sha256"] assert digest((SOURCE / "split_manifest.json").read_bytes()) == spec["source_role_manifest_sha256"] rows = [] for line in raw.decode().splitlines(): item = json.loads(line) if not item["input_eligible"]: continue assert item["split"] == split and item["upstream_revision"] == spec["source_revision"] assert digest(item["text"]) == item["text_sha256"] gold = [] for span in item["upstream_spans"]: assert item["text"][span["start"]:span["end"]] == span["txt"] assert span["bias"] in HEADS gold.append({"start": span["start"], "end": span["end"], "head": span["bias"], "upstream_index": span["upstream_span_index"]}) words = [[m.start(), m.end()] for m in WORD.finditer(item["text"])] rows.append({"id": item["id"], "event_id": item["event_id"], "group_id": item["group_id"], "article_id": item["article_id"], "article_start": item["start"], "article_end": item["end"], "text": item["text"], "text_sha256": item["text_sha256"], "gold": gold, "words": words}) return rows, digest(raw) def labels_for(row): result = np.zeros((len(row["words"]), 2), dtype=np.int8) for index, (start, end) in enumerate(row["words"]): for hi, head in enumerate(HEADS): result[index, hi] = any(span["head"] == head and min(end, span["end"]) > max(start, span["start"]) for span in row["gold"]) return result def feature_paths(split): return {name: PRIVATE / (split + suffix) for name, suffix in (("features", "-features.npy"), ("labels", "-labels.npy"), ("covered", "-covered.npy"), ("rows", "-rows.json.gz"), ("receipt", "-feature-receipt.json"))} def extract(split, model_path): if split == "test": unlock_receipt() rows, source_sha = read_split(split) spec, spec_sha = protocol() paths = feature_paths(split) PRIVATE.mkdir(parents=True, exist_ok=True) if paths["receipt"].exists(): receipt = load(paths["receipt"]) if receipt["protocol_sha256"] == spec_sha and receipt["source_sha256"] == source_sha: print(json.dumps({"feature_cache": split, "receipt": receipt}), flush=True) return import torch from transformers import AutoModel, AutoTokenizer torch.set_num_threads(1) torch.set_num_interop_threads(1) tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True, use_fast=True) encoder = AutoModel.from_pretrained(model_path, local_files_only=True, attn_implementation="eager").eval().requires_grad_(False) count = 0 for row in rows: row["unit_start"] = count count += len(row["words"]) row["unit_end"] = count values = np.lib.format.open_memmap(paths["features"], mode="w+", dtype=np.float32, shape=(count, encoder.config.hidden_size)) values[:] = 0 covered = np.zeros(count, dtype=bool) labels = np.concatenate([labels_for(row) for row in rows]) started = time.monotonic() windows_total = 0 with torch.inference_mode(): for batch_start in range(0, len(rows), 16): batch_rows = rows[batch_start:batch_start + 16] batch = tokenizer([x["text"] for x in batch_rows], return_tensors="pt", padding=True, truncation=True, max_length=256, stride=32, return_overflowing_tokens=True, return_offsets_mapping=True) mapping = batch.pop("overflow_to_sample_mapping").numpy() offsets = batch.pop("offset_mapping").numpy() windows_total += len(mapping) for window_start in range(0, len(mapping), 16): inputs = {name: tensor[window_start:window_start + 16] for name, tensor in batch.items()} hidden = encoder(**inputs).last_hidden_state.numpy() for wi in range(len(hidden)): window = window_start + wi row = batch_rows[int(mapping[window])] spans = offsets[window] for index, (start, end) in enumerate(row["words"]): target = row["unit_start"] + index if covered[target]: continue positions = np.flatnonzero((spans[:, 0] < end) & (spans[:, 1] > start)) if not len(positions) or min(spans[positions, 0]) > start or max(spans[positions, 1]) < end: continue feature = hidden[wi, positions].mean(axis=0) values[target] = feature / max(float(np.linalg.norm(feature)), 1e-8) covered[target] = True if batch_start % 128 == 0: print(json.dumps({"split": split, "sentences_done": min(batch_start + 16, len(rows)), "sentences_total": len(rows), "seconds": round(time.monotonic() - started, 2)}), flush=True) values.flush() np.save(paths["covered"], covered) np.save(paths["labels"], labels) paths["rows"].write_bytes(gzip.compress(json.dumps(rows, ensure_ascii=False).encode(), mtime=0)) receipt = {"protocol_sha256": spec_sha, "source_sha256": source_sha, "split": split, "sentences": len(rows), "events": len({x["event_id"] for x in rows}), "regex_tokens": count, "encoder_covered_tokens": int(covered.sum()), "encoder_coverage": float(covered.mean()), "positive_coverage": {head: float(covered[labels[:, hi].astype(bool)].mean()) for hi, head in enumerate(HEADS)}, "windows": windows_total, "seconds": time.monotonic() - started, "feature_dimension": encoder.config.hidden_size, "encoder_frozen": True, "cpu_threads": 1, "new_human_reviews": 0, "files": {name: digest(path.read_bytes()) for name, path in paths.items() if name != "receipt"}} dump(paths["receipt"], receipt) print(json.dumps(receipt), flush=True) def features(split): if split == "test": unlock_receipt() paths = feature_paths(split) spec, spec_sha = protocol() receipt = load(paths["receipt"]) assert receipt["protocol_sha256"] == spec_sha rows = json.loads(gzip.decompress(paths["rows"].read_bytes())) values = np.load(paths["features"], mmap_mode="r") labels = np.load(paths["labels"]) mask = np.load(paths["covered"]) tokens = [row["text"][start:end].casefold() for row in rows for start, end in row["words"]] return rows, values, labels, mask, tokens, receipt def head_model(): return SGDClassifier(loss="log_loss", alpha=.0001, max_iter=20, tol=None, class_weight="balanced", average=True, random_state=1729) def train(train, validation): tr_rows, tr_x, tr_y, tr_mask, tr_tokens, _ = train _, va_x, va_y, va_mask, va_tokens, _ = validation vectorizer = CountVectorizer(analyzer="char", ngram_range=(2, 4), min_df=3, max_features=15000) char_train = vectorizer.fit_transform([token for token, include in zip(tr_tokens, tr_mask) if include]) char_val = vectorizer.transform(va_tokens) models, posterior = {}, [] total = Counter(token for token, include in zip(tr_tokens, tr_mask) if include) probabilities = {name: np.zeros_like(va_y, dtype=float) for name in METHODS} probabilities["all_positive"][:] = 1 for hi, head in enumerate(HEADS): positive = Counter(token for token, include, label in zip(tr_tokens, tr_mask, tr_y[:, hi]) if include and label) prior = float(tr_y[tr_mask, hi].mean()) lookup = {token: (positive[token] + 1) / (frequency + 2) for token, frequency in total.items()} posterior.append({"lookup": lookup, "unseen": prior}) probabilities["token_posterior"][:, hi] = [lookup.get(token, prior) for token in va_tokens] lexical = head_model().fit(char_train, tr_y[tr_mask, hi]) dense = head_model().fit(tr_x[tr_mask], tr_y[tr_mask, hi]) models[head] = {"char_ngram": lexical, "frozen_minilm_probe": dense} probabilities["char_ngram"][:, hi] = lexical.predict_proba(char_val)[:, 1] probabilities["frozen_minilm_probe"][:, hi] = dense.predict_proba(va_x)[:, 1] thresholds = {} for method in METHODS: thresholds[method] = [] for hi in range(2): if method in {"all_negative", "all_positive"}: thresholds[method].append(.5) continue options = [] for threshold in np.arange(.05, 1., .05): yhat = probabilities[method][va_mask, hi] >= threshold stats = binary_counts(va_y[va_mask, hi], yhat) score = scores(stats) options.append((score["f1"], score["precision"], float(threshold))) thresholds[method].append(max(options)[2]) with (PRIVATE / "fitted_heads.pkl").open("wb") as output: pickle.dump({"vectorizer": vectorizer, "models": models, "posterior": posterior, "thresholds": thresholds}, output) np.savez(PRIVATE / "validation-probabilities.npz", **probabilities) return thresholds, probabilities def binary_counts(gold, predicted): gold, predicted = np.asarray(gold, dtype=bool), np.asarray(predicted, dtype=bool) return {"tp": int((gold & predicted).sum()), "fp": int((~gold & predicted).sum()), "fn": int((gold & ~predicted).sum()), "tn": int((~gold & ~predicted).sum())} def scores(counts): precision = counts["tp"] / max(1, counts["tp"] + counts["fp"]) recall = counts["tp"] / max(1, counts["tp"] + counts["fn"]) return {"precision": precision, "recall": recall, "f1": 2 * counts["tp"] / max(1, 2 * counts["tp"] + counts["fp"] + counts["fn"])} def predicted_spans(row, positive): result = [] for (start, end), present in zip(row["words"], positive): if not present: continue if result and not row["text"][result[-1][1]:start].strip() and all( positive[i] for i, (a, b) in enumerate(row["words"]) if result[-1][1] <= a and b <= start): result[-1][1] = end else: result.append([start, end]) return result def span_counts(gold, predicted, relaxed=False): gold = sorted(set(tuple(x) for x in gold)) predicted = sorted(set(tuple(x) for x in predicted)) if not relaxed: matches = len(set(gold) & set(predicted)) elif not gold or not predicted: matches = 0 else: weight = np.zeros((len(gold), len(predicted))) for gi, (a, b) in enumerate(gold): for pi, (c, d) in enumerate(predicted): overlap = max(0, min(b, d) - max(a, c)) iou = overlap / max(1, max(b, d) - min(a, c)) if iou >= .5: weight[gi, pi] = 100 + iou a, b = linear_sum_assignment(-weight) matches = int((weight[a, b] > 0).sum()) return {"tp": matches, "fp": len(predicted) - matches, "fn": len(gold) - matches, "tn": 0} def evaluate(rows, labels, mask, probabilities, thresholds): by_event = defaultdict(lambda: {name: {head: {metric: Counter() for metric in ("token", "strict_span", "relaxed_span", "character")} for head in HEADS} for name in METHODS}) failures = defaultdict(Counter) private_predictions = [] representability = Counter() for row in rows: beginning, ending = row["unit_start"], row["unit_end"] y = labels[beginning:ending] include = mask[beginning:ending] starts, ends = {x[0] for x in row["words"]}, {x[1] for x in row["words"]} for gold in row["gold"]: representability[gold["head"] + "_spans"] += 1 representability[gold["head"] + "_boundaries_on_regex_tokens"] += gold["start"] in starts and gold["end"] in ends for head in HEADS: original = [x for x in row["gold"] if x["head"] == head] distinct = {(x["start"], x["end"]) for x in original} representability[head + "_distinct_reference_intervals"] += len(distinct) representability[head + "_duplicate_exact_reference_records"] += len(original) - len(distinct) for method in METHODS: predictions = probabilities[method][beginning:ending] >= np.array(thresholds[method]) predictions[~include] = False for hi, head in enumerate(HEADS): gold = [[x["start"], x["end"]] for x in row["gold"] if x["head"] == head] spans = predicted_spans(row, predictions[:, hi]) counts = {"token": binary_counts(y[include, hi], predictions[include, hi]), "strict_span": span_counts(gold, spans), "relaxed_span": span_counts(gold, spans, True)} gold_char = np.zeros(len(row["text"]), dtype=bool) predicted_char = np.zeros(len(row["text"]), dtype=bool) for start, end in gold: gold_char[start:end] = True for start, end in spans: predicted_char[start:end] = True counts["character"] = binary_counts(gold_char, predicted_char) for metric, values in counts.items(): by_event[row["event_id"]][method][head][metric].update(values) failures[method][head + "_gold_positive_sentences_with_no_predicted_span"] += bool(gold) and not spans failures[method][head + "_gold_unmarked_sentences_with_predicted_span"] += not gold and bool(spans) private_predictions.append({"id": row["id"], "event_id": row["event_id"], "method": method, "head": head, "article_id": row["article_id"], "sentence_source_start": row["article_start"], "sentence_source_end": row["article_end"], "sentence_text_sha256": row["text_sha256"], "gold": gold, "predicted": spans, "predicted_article_spans": [[row["article_start"] + a, row["article_start"] + b] for a, b in spans], "counts": counts}) totals = {} for method in METHODS: heads = {} for head in HEADS: heads[head] = {} for metric in ("token", "strict_span", "relaxed_span", "character"): values = Counter() for event in by_event.values(): values.update(event[method][head][metric]) heads[head][metric] = {**scores(values), "counts": dict(values)} totals[method] = {"heads": heads, "macro": {metric + "_f1": float(np.mean([heads[h][metric]["f1"] for h in HEADS])) for metric in ("token", "strict_span", "relaxed_span", "character")}} return {"methods": totals, "events": len(by_event), "sentences": len(rows), "covered_tokens": int(mask.sum()), "regex_tokens": len(mask), "coverage": float(mask.mean()), "span_boundary_representability": dict(representability), "failure_counts": {name: dict(values) for name, values in failures.items()}}, dict(by_event), private_predictions def fit(): assert not (PRIVATE / "PROBE_SELECTION_LOCK.json").exists(), "Selection already locked; no refitting" training, validation = features("train"), features("validation") started = time.monotonic() thresholds, probabilities = train(training, validation) rows, _, labels, mask, _, receipt = validation results, events, predictions = evaluate(rows, labels, mask, probabilities, thresholds) controls = [name for name in METHODS if name != "frozen_minilm_probe"] selected = max(controls, key=lambda name: (results["methods"][name]["macro"]["token_f1"], name)) results.update({"split": "validation", "thresholds": thresholds, "selected_control_by_validation": selected, "selection_seconds": time.monotonic() - started, "test_accessed": False, "scope": "development only; no held-out claim or promotion", "new_human_reviews": 0}) dump(PRIVATE / "validation_results.json", results) dump(PRIVATE / "validation_events.json", events) dump(PRIVATE / "validation_predictions.json", predictions) dump(PUBLIC / "VALIDATION_RESULTS.json", {**results, "thresholds": "local_only_pending_technical_and_rights_gates"}) _, spec_sha = protocol() lock = {"protocol_sha256": spec_sha, "thresholds": thresholds, "selected_control_by_validation": selected, "fitted_heads_sha256": digest((PRIVATE / "fitted_heads.pkl").read_bytes()), "validation_results_sha256": digest((PRIVATE / "validation_results.json").read_bytes()), "train_feature_receipt_sha256": digest(feature_paths("train")["receipt"].read_bytes()), "validation_feature_receipt_sha256": digest(feature_paths("validation")["receipt"].read_bytes()), "test_accessed": False, "refitting_allowed": False, "public_weights_eligible": False, "rights_gate": "requires explicit lead approval; upstream BASIL annotation/text rights unresolved"} dump(PRIVATE / "PROBE_SELECTION_LOCK.json", lock) public_lock = {name: value for name, value in lock.items() if name != "thresholds"} public_lock["thresholds_sha256"] = digest(json.dumps(thresholds, sort_keys=True)) dump(PUBLIC / "PROBE_SELECTION_LOCK.json", public_lock) print(json.dumps({"validation": {name: value["macro"] for name, value in results["methods"].items()}, "lock": lock}, indent=2)) def score_test(): unlock = unlock_receipt() test = features("test") rows, values, labels, mask, tokens, feature_receipt = test lock = load(PRIVATE / "PROBE_SELECTION_LOCK.json") assert digest((PRIVATE / "fitted_heads.pkl").read_bytes()) == lock["fitted_heads_sha256"] with (PRIVATE / "fitted_heads.pkl").open("rb") as source: fitted = pickle.load(source) probabilities = {name: np.zeros_like(labels, dtype=float) for name in METHODS} probabilities["all_positive"][:] = 1 char = fitted["vectorizer"].transform(tokens) for hi, head in enumerate(HEADS): posterior = fitted["posterior"][hi] probabilities["token_posterior"][:, hi] = [posterior["lookup"].get(token, posterior["unseen"]) for token in tokens] probabilities["char_ngram"][:, hi] = fitted["models"][head]["char_ngram"].predict_proba(char)[:, 1] probabilities["frozen_minilm_probe"][:, hi] = fitted["models"][head]["frozen_minilm_probe"].predict_proba(values)[:, 1] result, events, predictions = evaluate(rows, labels, mask, probabilities, lock["thresholds"]) selected = lock["selected_control_by_validation"] rng = np.random.default_rng(1729) names = sorted(events) draws = [] for _ in range(2000): picked = rng.choice(names, size=len(names), replace=True) method_scores = {} for method in ("frozen_minilm_probe", selected): per_head = [] for head in HEADS: values_ = Counter() for event in picked: values_.update(events[event][method][head]["token"]) per_head.append(scores(values_)["f1"]) method_scores[method] = np.mean(per_head) draws.append(method_scores["frozen_minilm_probe"] - method_scores[selected]) interval = [float(x) for x in np.quantile(draws, [.025, .975])] probe = result["methods"]["frozen_minilm_probe"] controls = [name for name in METHODS if name != "frozen_minilm_probe"] best_test_control = max(controls, key=lambda name: result["methods"][name]["macro"]["token_f1"]) selected_result = result["methods"][selected] checks = { "token_macro_gain_at_least_05_vs_every_control": all(probe["macro"]["token_f1"] >= result["methods"][name]["macro"]["token_f1"] + .05 for name in controls), "paired_event_bootstrap_lower_bound_positive": interval[0] > 0, "per_head_noninferiority": all(probe["heads"][head]["token"]["f1"] >= selected_result["heads"][head]["token"]["f1"] - .02 for head in HEADS), "strict_and_relaxed_span_noninferiority": all(probe["macro"][metric + "_f1"] >= selected_result["macro"][metric + "_f1"] for metric in ("strict_span", "relaxed_span")), "token_coverage_at_least_995": feature_receipt["encoder_coverage"] >= .995, "positive_coverage_at_least_99": all(x >= .99 for x in feature_receipt["positive_coverage"].values()), } result.update({"split": "test", "thresholds_locked_on_validation": lock["thresholds"], "selected_control_on_validation": selected, "best_fixed_control_on_test_diagnostic_only": best_test_control, "probe_minus_selected_control_macro_token_f1": probe["macro"]["token_f1"] - selected_result["macro"]["token_f1"], "paired_event_bootstrap_95pct": interval, "technical_gate_checks": checks, "technical_gate_pass": all(checks.values()), "public_weights_eligible": False, "model_promotion": "withheld_pending_lead_rights_decision_even_if_technical_gate_passes", "protocol_sha256": lock["protocol_sha256"], "main_selection_unlock_sha256": digest((HERE / "MAIN_SELECTION_UNLOCK.json").read_bytes()), "source_feature_coverage": feature_receipt, "new_human_reviews": 0, "scope": "BASIL marked source-span task only; no evidence sufficiency, rationale faithfulness, prejudice or general political neutrality conclusion"}) dump(PRIVATE / "test_results.json", result) dump(PRIVATE / "test_events.json", events) dump(PRIVATE / "test_predictions.json", predictions) dump(PUBLIC / "TEST_RESULTS.json", {**result, "thresholds_locked_on_validation": "local_only_pending_technical_and_rights_gates"}) print(json.dumps({"test": {name: value["macro"] for name, value in result["methods"].items()}, "technical_gate": checks, "interval": interval}, indent=2)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("action", choices=("features", "fit", "score_test")) parser.add_argument("--split", choices=("train", "validation", "test")) parser.add_argument("--encoder", type=Path, default=MODEL) args = parser.parse_args() PRIVATE.mkdir(parents=True, exist_ok=True) PUBLIC.mkdir(exist_ok=True) if args.action == "features": assert args.split extract(args.split, args.encoder) elif args.action == "fit": fit() else: score_test()