""" Number trace for the paper: every number in the prose of paper/main.tex, with the committed file and field (or the script setting) it comes from. python code/trace_numbers.py --root . --build # propose a trace (paper/number_trace.csv) from the sources python code/trace_numbers.py --root . --check # verify every traced number still matches its source Tables and figures are not traced here: code/make_tables.py and code/analysis.py generate them from results/numbers.json, and `make reproduce` checks them byte for byte. """ import argparse, csv, json, re, sys from pathlib import Path ap = argparse.ArgumentParser() ap.add_argument("--root", default=".") ap.add_argument("--tex", default=None) ap.add_argument("--build", action="store_true") ap.add_argument("--check", action="store_true") args = ap.parse_args() ROOT = Path(args.root).resolve() TEX = Path(args.tex) if args.tex else ROOT / "paper" / "main.tex" TRACE = TEX.with_name("number_trace.csv") SPEC = TEX.with_name("number_trace_spec.json") # ------------------------------------------------------------------ text extraction NAMES = [ # (pattern, placeholder): names whose digits are not numbers of record; the placeholder keeps the meaning (r"GLM-5\.3", "GLM"), (r"Jev~?1\.13", "Jev"), (r"jev-1\.13\.0", "Jev"), (r"Qwen/Qwen3\.5-4B", "QwenSmall"), (r"Qwen3\.5-4B", "QwenSmall"), (r"Qwen3-32B", "QwenBig"), (r"Qwen3", "QwenBig"), (r"all-mpnet-base-v2", "MPNet"), (r"ModernBERT-base", "MBbase"), (r"ModernBERT-large", "MBlarge"), (r"M4 Max", "Mac"), (r"NVIDIA T4", "GPU"), (r"\bT4\b", "GPU"), (r"\bp95\b", "pNinetyFive"), (r"20-NN", "Vote"), (r"1-NN", "OneNN"), (r"\bB0\b", "Bzero"), (r"fp16|bf16|BF16|FP32", "Precision"), (r"F1", "Fone"), (r"U\.S\.", "US"), (r"G_\d|G_\{[^}]*\}", "G"), (r"p_[12]", "p"), (r"z_[ts]", "z"), (r"T_[cd]", "T"), (r"\\ell", "l"), (r"g\^\\star", "g"), (r"\[20k\]", "Twentyk"), (r"LR\(\w+\)", "LR"), (r"typesafe-sdk", "SDK"), (r"TF-IDF", "TFIDF"), (r"\\S", " "), (r"A\}\\ldots", "A"), (r"MLX", "Mlx"), (r"\$k=20\$", "kTwenty"), (r"Qwen", "Qwen")] def prose(tex): doc = tex[tex.index(r"\begin{document}"):] doc = doc.split(r"\bibliographystyle")[0] + "\n" + doc.split(r"\appendix")[1] doc = re.sub(r"(?= 0 and not s.startswith("-") else s) def norm_tok(tok): return tok.replace(",", "") if re.fullmatch(r"[-+]?\d{1,3}(,\d{3})+", tok) else tok def candidates(tok, idx): signed = tok[0] in "+-" out = [] for rel, path, v in idx: for fmt in FORMATS: r = render(v, fmt, signed) if r is not None and (r == tok or r.replace(",", "") == norm_tok(tok)): out.append((rel, path, fmt)) return out def words(s): return set(w for w in re.findall(r"[a-z][a-z0-9]+", s.lower()) if len(w) > 2) ALIASES = [ # (context cue, system key in results): nearest cue before the number wins ("labels only", "GLM-5.3, labels of 20 retrieved complaints"), ("labels-only", "GLM-5.3, labels of 20 retrieved complaints"), ("GLM with retrieved", "GLM-5.3, 20 retrieved examples"), ("retrieved examples", "GLM-5.3, 20 retrieved examples"), ("full prompt", "GLM-5.3, 20 retrieved examples"), ("Retrieval", "GLM-5.3, 20 retrieved examples"), ("similar labelled complaints in its prompt", "GLM-5.3, 20 retrieved examples"), ("GLM", "GLM-5.3 (generative)"), ("vote", "20-nearest-neighbour vote"), ("OneNN", "1-nearest-neighbour"), ("Jev with definitions", "Jev + form instruction + definitions"), ("instruction alone", "Jev + form instruction"), ("SemIf with definitions", "SemIf bracket + definitions"), ("one-versus-rest", "SemIf one-vs-rest"), ("SemIf", "SemIf bracket"), ("TFIDF with Jev", "TF-IDF + Jev + LR"), ("label-name similarity", "TF-IDF + label-name similarity"), ("top choice", "TF-IDF + Jev top choice"), ("returned choice alone", "TF-IDF + Jev top choice"), ("sentence embeddings themselves", "TF-IDF + embeddings + LR"), ("stacked", "TF-IDF + stacked embedding probabilities"), ("TFIDF", "TF-IDF + LR"), ("MBbase", "ModernBERT-base (vanilla)"), ("distilled", "ModernBERT-base (distilled)"), ("MBlarge", "ModernBERT-large"), ("QwenBig", "Qwen3-32B + LoRA"), ("Jev", "Jev zero-shot")] PREFERRED = ("point/", "paired/", "decomposition/", "deduplicated/", "paper_derived/", "retrieval_shortlist/", "glm_tokens/", "learning_curve_nested/", "risk_coverage/", "confident_decile/", "near_duplicates/", "semif_diagnostics/", "semif_grouping_seeds/", "merged/", "cluster_bootstrap/", "mapping_sensitivity/", "tier_", "n_val", "classes", "singleton", "jev_top_probability_buckets/", "overprediction_correlation", "returned_choice", "glm_matching/", "semif/") def systems_near(ctx): """System keys mentioned before the number in its context, nearest last.""" hits = [] low = ctx.lower() for cue, key in ALIASES: for m in re.finditer(re.escape(cue.lower()), low): hits.append((m.start(), key)) hits.sort() out = [] for _, k in hits: if k in out: out.remove(k) out.append(k) return out def score(ctx, rel, path, fmt): sc = 0.0 if rel == "results/numbers_reference.json": sc += 2 if path.startswith(PREFERRED) else -3 near = systems_near(ctx) parts = path.split("/") sys_in_path = [p for p in parts for q in p.split(" || ") if q in dict(ALIASES).values() or q == p and p in dict(ALIASES).values()] for i, k in enumerate(reversed(near)): if any(k in p for p in parts): sc += 3 / (1 + i) pw = words(path.replace("_", " ").replace("||", " ")) sc += 0.5 * len(pw & words(ctx[-80:])) sc += 0.3 if fmt in ("f3", "pct1", "int") else 0 return sc # ------------------------------------------------------------------ build / check def resolve(rel, path): """Follow a "/"-separated path; a key may itself contain "/", so match the longest key at each level.""" x, rest = json.loads((ROOT / rel).read_text()), path while rest: if isinstance(x, list): k, _, rest = rest.partition("/") x = x[int(k)] continue k = max((k for k in x if rest == k or rest.startswith(k + "/")), key=len) x, rest = x[k], rest[len(k) + 1:] return float(x) def check_row(r): try: return _check_row(r) except (KeyError, ValueError, IndexError, FileNotFoundError, TypeError): return False def _check_row(r): if r["kind"] in EXEMPT: return True if r["kind"] == "setting": return re.search(r["field"], (ROOT / r["source"]).read_text()) is not None v = resolve(r["source"], r["field"]) got = render(v, r["format"], r["token"][0] in "+-") return got is not None and (got == r["token"] or got.replace(",", "") == norm_tok(r["token"])) def find_spec(spec, t): return next((e for e in spec if "token" in e and e["token"] == t["token"] and (t["before"] + t["token"]).endswith(e["match"])), None) WORDS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9} def check_word(e, text): """A number written as a word: the phrase must be in the text and the source value must round to the word.""" if e["phrase"] not in text: return False try: v = resolve(e["source"], e["field"]) except (KeyError, ValueError, IndexError, FileNotFoundError, TypeError): return False return round(v) == WORDS[e["word"]] def main(): toks = tokens(TEX.read_text()) spec = json.loads(SPEC.read_text()) if SPEC.exists() else [] prose_text = re.sub(r"\s+", " ", prose(TEX.read_text())) words = [e for e in spec if "phrase" in e] rows = [] for i, t in enumerate(toks): row = {"n": i + 1, "token": t["token"], "kind": "", "source": "", "field": "", "format": "", "context": t["context"]} e = find_spec(spec, t) if e: row.update({k: e.get(k, "") for k in ("kind", "source", "field", "format")}) elif args.build: c = candidates(t["token"], load_sources.cache) if hasattr(load_sources, "cache") else [] if c: rel, path, fmt = max(c, key=lambda x: score(t["context"], *x)) row.update(kind="UNREVIEWED", source=rel, field=path, format=fmt) else: row.update(kind="UNTRACED") else: row.update(kind="UNTRACED") rows.append(row) if args.build: with TRACE.open("w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0])) w.writeheader(); w.writerows(rows) bad = [r for r in rows if r["kind"] in ("UNTRACED", "UNREVIEWED") or not check_row(r) and not (args.build and r["source"].endswith("number_trace_summary.json"))] bad += [{"n": "word", "token": e["word"], "kind": "word", "source": e["source"], "field": e["field"], "context": e["phrase"]} for e in words if not check_word(e, prose_text)] if args.check: # the committed CSV must be exactly what the text and the mapping produce keys = ("n", "token", "kind", "source", "field", "format", "context") committed = [tuple(r[k] for k in keys) for r in csv.DictReader(TRACE.open())] if TRACE.exists() else [] if committed != [tuple(str(r[k]) for k in keys) for r in rows]: bad.append({"n": "csv", "token": "", "kind": "", "source": str(TRACE.name), "field": "", "context": "committed number_trace.csv differs from the text and mapping; rebuild with --build"}) emp = [r for r in rows if r["kind"] in ("result", "data", "UNTRACED", "UNREVIEWED")] book = [r for r in rows if r["kind"] == "bookkeeping"] # counts about the trace itself, checked but not evidence self_ref = lambda r: r["source"].endswith("number_trace_summary.json") # verified against the summary written below traced = [r for r in emp if r["kind"] in ("result", "data") and (check_row(r) or args.build and self_ref(r))] kinds = {} for r in rows: kinds[r["kind"]] = kinds.get(r["kind"], 0) + 1 summary = {"numbers_in_text": len(rows), "by_kind": kinds, "empirical": len(emp), "empirical_traced": len(traced), "settings_traced_to_code": sum(r["kind"] == "setting" and check_row(r) for r in rows), "dates_versions_names_formulas_external": sum(r["kind"] in EXEMPT for r in rows), "bookkeeping": len(book), "numbers_written_as_words_checked": sum(check_word(e, prose_text) for e in words)} TRACE.with_name("number_trace_summary.json").write_text(json.dumps(summary, indent=2) + "\n") if args.build else None print(f"{len(rows)} numbers in the text: {len(emp)} empirical, {len(traced)} of them traced to committed files and " f"matching ({100 * len(traced) / max(1, len(emp)):.1f} percent); {summary['settings_traced_to_code']} settings " f"traced to scripts; {sum(r['kind'] in EXEMPT for r in rows)} dates, versions, names, formulas or external " f"settings. Kinds: {kinds}") for r in bad[:80]: print(f"FAIL #{r['n']} {r['token']!r} ({r['kind']}) {r['source']}:{r['field']} ...{r['context'][-90:]}") sys.exit(1 if bad else 0) if args.build: load_sources.cache = load_sources() main()