"""Shared span-extraction harness: word prep, BIO encode/decode, metrics. ONE module, called identically by every bakeoff arm. If scoring code differs between arms the comparison is worthless, so nothing in here may be arm-specific. Label scheme: 3 labels, O=0 / B-DISFLUENCY=1 / I-DISFLUENCY=2. transformers>=5 tokenizer detail, verified in temp/logs/probe_api.log: CORRECT tok(words, is_split_into_words=True) with `words` pre-split -> correct word_ids (verified 12/12 distinct on 3 tokenizers) WRONG tok(words, is_pretokenized=True) -> silently returns 3 tokens `[None, 0, None]`, no exception WRONG tok([sentence_string], is_split_into_words=True) -> a 1-element list IS one "word" under this API, so every token gets word_id 0. This is correct behaviour, not a library bug; an earlier probe of mine misread it as one. """ import json import re import sys from typing import Dict, List, Optional, Sequence, Tuple sys.path.insert(0, "/opt/vox/sandbox/scripts") from compiler import clean_punctuation_whitespace, verify_roundtrip # noqa: E402 O, B, I = 0, 1, 2 LABELS = ["O", "B-DISFLUENCY", "I-DISFLUENCY"] MAX_LEN = 128 # AGENTS.md invariant 13 # --- Gate 2 constraints (user-directed 2026-10-03) --------------------------- # # BOTH are hard. over_deletion_rate is sentence-level ("did we edit a turn the # user said correctly"). harmful_span_rate is span-level ("did we delete a word # the user actually said") and is the Golden Rule's fatal failure mode, so it # binds harder. Reporting one without gating on it is how a model gets selected # for something it must never do. OVER_DELETION_GATE = 1.0 # percent of gold-CLEAN turns edited anyway HARMFUL_SPAN_GATE = 2.0 # percent of emitted spans eating kept text # --------------------------------------------------------------------------- # # Word-level preparation # --------------------------------------------------------------------------- # def split_words(text: str) -> Tuple[List[str], List[int], List[int]]: """Whitespace pre-split preserving exact char offsets. Returns (words, starts, ends) where text[starts[i]:ends[i]] == words[i]. This mirrors gliner2's default 'whitespace' word splitter so that the span family and the BIO family score against identical word boundaries. """ words, starts, ends = [], [], [] for m in re.finditer(r"\S+", text): words.append(m.group(0)) starts.append(m.start()) ends.append(m.end()) return words, starts, ends def encode_bio(text: str, spans: Sequence[Sequence[int]]) -> List[int]: """Char spans -> per-word BIO labels. A word is INSIDE a span if any of its characters fall inside it, so a span boundary landing mid-word still produces a recoverable word span. """ words, starts, ends = split_words(text) labels = [O] * len(words) for s, e in spans: hit = False for i, (ws, we) in enumerate(zip(starts, ends)): if ws < e and we > s: # char overlap labels[i] = B if not hit else I hit = True return labels def gold_word_spans(text: str, spans: Sequence[Sequence[int]]) -> List[Tuple[int, int]]: """Gold char spans -> word-index spans, using the same overlap rule as encode_bio. A word-level model CANNOT reproduce a char span that starts or ends mid-word, nor one that carries an absorbed orphan comma or trailing space. Scoring char-exact would therefore measure the representation, not the model. Word-level is the level the model actually predicts at. """ words, starts, ends = split_words(text) out: List[Tuple[int, int]] = [] for s, e in spans: idx = [i for i, (ws, we) in enumerate(zip(starts, ends)) if ws < e and we > s] if idx: out.append((idx[0], idx[-1])) return out def decode_bio( text: str, p_inspan: Sequence[float], p_begin: Sequence[float], threshold: float, ) -> List[Tuple[int, int]]: """Per-word probabilities -> char spans at a tunable precision threshold. p_inspan[w] = 1 - P(O) at word w. A word survives if p_inspan >= threshold. Inside the surviving set, a word opens a new span when P(B) > P(I), which keeps two adjacent disfluencies from being merged into one span. The threshold is the single knob the Golden Rule needs: precision dominates recall, so we must be able to move it without retraining. """ words, starts, ends = split_words(text) spans: List[Tuple[int, int]] = [] cur: Optional[int] = None for i in range(len(words)): if p_inspan[i] < threshold: if cur is not None: spans.append((starts[cur], ends[i - 1])) cur = None continue opens = p_begin[i] > 0.5 # P(B) > P(I) within the surviving set if cur is None or opens: if cur is not None: spans.append((starts[cur], ends[i - 1])) cur = i if cur is not None: spans.append((starts[cur], ends[cur])) return spans # --------------------------------------------------------------------------- # # Slice-cut reconstruction # --------------------------------------------------------------------------- # def reconstruct(raw_text: str, spans: Sequence[Sequence[int]]) -> str: """Deterministic slice cut + Tier 1 punctuation collapse (invariant 12). Case is PRESERVED. Casing is Tier 1's responsibility; Tier 2 only excises. Forcing an initial capital here corrupted the 8% of the corpus whose gold is lowercase Switchboard. """ out, last = [], 0 for s, e in sorted(spans, key=lambda x: x[0]): out.append(raw_text[last:s]) so_far = "".join(out).rstrip() rest = raw_text[e:].lstrip() if so_far and rest and so_far[-1].isalnum() and rest[0].isalnum(): out.append(" ") last = e out.append(raw_text[last:]) return clean_punctuation_whitespace("".join(out)) def same_text(a: str, b: str) -> bool: """Case-insensitive + punctuation-normalised equality for reconstruction scoring.""" return clean_punctuation_whitespace(a).lower() == clean_punctuation_whitespace(b).lower() # --------------------------------------------------------------------------- # # Metrics # --------------------------------------------------------------------------- # def prf(tp: int, fp: int, fn: int) -> Dict[str, float]: p = tp / (tp + fp) if tp + fp else 0.0 r = tp / (tp + fn) if tp + fn else 0.0 f = 2 * p * r / (p + r) if p + r else 0.0 return {"precision": round(p, 4), "recall": round(r, 4), "f1": round(f, 4)} def score_predictions( gold: List[dict], preds: List[List[Tuple[int, int]]], threshold: float, ) -> Dict: """Full metric set, scored at WORD level (the level the model predicts at). The gate metric is `over_deletion_rate`. over_deletion_rate = % of gold-CLEAN turns the model edited anyway. This is the number that must stay under 1.0%. harmful_span_rate = % of predicted spans that eat text the gold says the user actually said. This is the fatal failure mode: it corrupts valid words rather than merely missing a disfluency. exact_match = % of turns where the slice cut reproduces gold clean_text. The true end-to-end number. """ tp = fp = fn = 0 clean_edited = clean_total = 0 harmful = pred_total = 0 exact = 0 per_cat: Dict[str, Dict[str, int]] = {} for ex, sp in zip(gold, preds): raw = ex["raw_text"] gw = set(gold_word_spans(raw, [s["span"] for s in ex.get("spans", [])])) pw = set(gold_word_spans(raw, sp)) tp += len(gw & pw) fp += len(pw - gw) fn += len(gw - pw) # harmful = predicted span covering any char NOT inside a gold span gold_chars = set() for s in ex["spans"]: gold_chars.update(range(s["span"][0], s["span"][1])) for s, e in sp: pred_total += 1 if any(c not in gold_chars for c in range(s, e)): harmful += 1 cat = ex["category"] d = per_cat.setdefault(cat, {"n": 0, "exact": 0, "edited": 0, "tp": 0, "fp": 0, "fn": 0}) d["n"] += 1 d["tp"] += len(gw & pw) d["fp"] += len(pw - gw) d["fn"] += len(gw - pw) if same_text(reconstruct(raw, sp), ex["clean_text"]): exact += 1 d["exact"] += 1 if cat == "CLEAN": clean_total += 1 if sp: clean_edited += 1 d["edited"] += 1 return { "threshold": threshold, "span_word": prf(tp, fp, fn), "over_deletion_rate": round(100.0 * clean_edited / clean_total, 3) if clean_total else 0.0, "harmful_span_rate": round(100.0 * harmful / pred_total, 3) if pred_total else 0.0, "exact_match": round(100.0 * exact / len(gold), 3) if gold else 0.0, "n": len(gold), "per_category": { k: { "n": v["n"], "exact_match": round(100.0 * v["exact"] / v["n"], 2) if v["n"] else 0.0, "span_word": prf(v["tp"], v["fp"], v["fn"]), } for k, v in sorted(per_cat.items()) }, } def load_jsonl(path: str) -> List[dict]: with open(path) as f: return [json.loads(l) for l in f if l.strip()] def sweep_thresholds(gold, preds_by_thr, thresholds: Sequence[float]) -> Dict: """Score every threshold, then pick the operating point. Selection rule, in order: 1. Keep only thresholds where over_deletion_rate < OVER_DELETION_GATE AND harmful_span_rate < HARMFUL_SPAN_GATE. 2. Among those, take the highest exact_match (the Golden Rule: precision first, and exact_match is the only metric a user actually experiences). 3. If NOTHING passes both gates, do not silently pick the best-looking number. Report the most conservative threshold -- the one that minimises the fatal metric -- and mark `no_threshold_satisfies_gate` so the gap is visible instead of buried. """ rows = [] for t in thresholds: m = score_predictions(gold, preds_by_thr[t], t) m["passes_over_deletion_gate"] = m["over_deletion_rate"] < OVER_DELETION_GATE m["passes_harmful_gate"] = m["harmful_span_rate"] < HARMFUL_SPAN_GATE m["passes_gate"] = m["passes_over_deletion_gate"] and m["passes_harmful_gate"] rows.append(m) ok = [r for r in rows if r["passes_gate"]] if ok: best = max(ok, key=lambda r: r["exact_match"]) best["no_threshold_satisfies_gate"] = False else: best = min(rows, key=lambda r: (r["harmful_span_rate"], r["over_deletion_rate"])) best = dict(best) best["no_threshold_satisfies_gate"] = True best["selection_note"] = ( f"NO threshold satisfies both gates " f"(over_deletion<{OVER_DELETION_GATE}%, harmful_span<{HARMFUL_SPAN_GATE}%). " f"Reported point is the most conservative available: " f"harmful={best['harmful_span_rate']}% over_deletion={best['over_deletion_rate']}%." ) return {"sweep": rows, "best": best, "gates": { "over_deletion_rate": OVER_DELETION_GATE, "harmful_span_rate": HARMFUL_SPAN_GATE}}