vox-tier2-backup / scripts /test_harness.py
addyo07's picture
Tier-2 parking snapshot 2026-10-04
46e27b5 verified
Raw History Blame Contribute Delete
5.48 kB
#!/usr/bin/env python3
"""Harness self-test. Fails loudly rather than producing a fake-green bakeoff.
T1 oracle : perfect word probabilities must decode + reconstruct to the
gold clean_text. Catches any encode/decode/slice-cut bug.
T2 word_ids : is_pretokenized must yield real per-word ids (transformers 5
silently collapses is_split_into_words to word 0).
T3 decoder : threshold monotonicity + B/I span splitting.
T4 truncation : confirm nothing is lost at MAX_LEN.
"""
import sys
import numpy as np
sys.path.insert(0, "/opt/vox/sandbox/scripts")
from compiler import clean_punctuation_whitespace
from span_common import (B, I, O, decode_bio, encode_bio, load_jsonl, reconstruct,
same_text, score_predictions, split_words)
VAL = "/opt/vox/sandbox/corpus/pilot_v2_val.jsonl"
fails = []
def check(name, cond, detail=""):
print(f" {'PASS' if cond else 'FAIL'} {name}{' ' + detail if detail else ''}", flush=True)
if not cond:
fails.append(name)
rows = load_jsonl(VAL)
print("T1 oracle decode+reconstruct (perfect probabilities)")
bad = []
for r in rows:
words, _, _ = split_words(r["raw_text"])
lab = encode_bio(r["raw_text"], [s["span"] for s in r.get("spans", [])])
p_inspan = np.array([0.0 if l == O else 1.0 for l in lab])
p_begin = np.array([1.0 if l == B else 0.0 if l == O else 0.0 for l in lab])
spans = decode_bio(r["raw_text"], p_inspan, p_begin, 0.5)
rec = reconstruct(r["raw_text"], spans)
if not same_text(rec, r["clean_text"]):
bad.append((r["id"], rec, r["clean_text"]))
# KNOWN DATASET CEILING: 3/800 val turns have gold char spans that are not
# word-aligned. The compiler's orphan-comma absorption (invariant 12) glues a
# leading comma onto the PRECEDING word (", sorry, " straddles "spirits,"), so a
# word-granularity tagger cannot delete it without also deleting that word.
# Measured: 4/433 spans non-word-aligned, 0 trapping kept alphabetic content,
# 3 turns affected -> exact_match ceiling 99.625%. Fix belongs in Layer 3
# (align gold spans to word boundaries), not in the harness.
check("oracle mismatches within documented word-alignment ceiling (<=3)",
len(bad) <= 3, f"{len(bad)} mismatches (ceiling 3)")
for b in bad[:5]:
print(f" {b[0]}\n got {b[1]!r}\n want {b[2]!r}")
# T1b the oracle scored through the real metric must be perfect
preds = []
for r in rows:
w, _, _ = split_words(r["raw_text"])
lab = encode_bio(r["raw_text"], [s["span"] for s in r.get("spans", [])])
pi = np.array([0.0 if l == O else 1.0 for l in lab])
pb = np.array([1.0 if l == B else 0.0 for l in lab])
preds.append(decode_bio(r["raw_text"], pi, pb, 0.5))
m = score_predictions(rows, preds, 0.5)
check("oracle exact_match >= 99.625% (word-alignment ceiling)", m["exact_match"] >= 99.625, f"got {m['exact_match']}")
check("oracle span_word P=R=F1 == 100%", m["span_word"]["f1"] == 1.0, f"got {m['span_word']}")
check("oracle over_deletion_rate == 0", m["over_deletion_rate"] == 0.0, f"got {m['over_deletion_rate']}")
print("T1c metric must punish a wrong prediction (no false green)")
noisy = [[] for _ in rows]
noise_pred = []
for r in rows:
w, _, _ = split_words(r["raw_text"])
if r["category"] == "CLEAN":
_, ws_, we_ = split_words(r["raw_text"])
noise_pred.append([(ws_[0], we_[0])] if ws_ else []) # delete first word
else:
noise_pred.append([])
m2 = score_predictions(rows, noise_pred, 0.5)
check("predicting one deletion on every CLEAN row is caught",
m2["over_deletion_rate"] > 50.0, f"over_deletion_rate={m2['over_deletion_rate']}%")
check("oracle-vs-noise exact_match strictly separates", m["exact_match"] > m2["exact_match"],
f"{m['exact_match']} vs {m2['exact_match']}")
print("T2 word_ids alignment")
try:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
s = "Because I thought, well anyway, we need to upgrade the database version."
w, _, _ = split_words(s)
good = tok(w, is_split_into_words=True).word_ids()
check("is_split_into_words over pre-split words gives distinct word ids",
len({x for x in good if x is not None}) == len(w), f"{len(w)} words")
bad = tok(w, is_pretokenized=True).word_ids()
check("is_pretokenized=True is BROKEN in v5 (silently truncates) and must not be used",
len([x for x in bad if x is not None]) < len(w),
f"got {len([x for x in bad if x is not None])} word ids for {len(w)} words")
except Exception as e:
check("tokenizer probe", False, str(e)[:120])
print("T3 decoder behaviour")
t = "a b c d e"
pi = np.array([0.0, 0.9, 0.9, 0.0, 0.0]); pb = np.array([0.0, 1.0, 0.0, 0.0, 0.0])
check("threshold 0.5 keeps one span", len(decode_bio(t, pi, pb, 0.5)) == 1)
check("threshold 0.95 drops it", len(decode_bio(t, pi, pb, 0.95)) == 0)
pi2 = np.array([0.0, 0.9, 0.9, 0.9, 0.0]); pb2 = np.array([0.0, 1.0, 0.0, 1.0, 0.0])
check("B tag splits two adjacent spans", len(decode_bio(t, pi2, pb2, 0.5)) == 2)
print("T4 length headroom")
longest = max(rows, key=lambda r: len(r["raw_text"].split()))
check("max val sentence well under MAX_LEN=128 words", len(longest["raw_text"].split()) < 128,
f"longest={len(longest['raw_text'].split())} words")
print()
print("HARNESS SELFTEST:", "ALL PASS" if not fails else f"{len(fails)} FAILED -> {fails}")
sys.exit(1 if fails else 0)