Download code/trace_numbers.py from earino/ecbs5200-jev-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/earino/ecbs5200-jev-benchmark/resolve/main/code/trace_numbers.py
- Command line
-
hf download hf://datasets/earino/ecbs5200-jev-benchmark/code/trace_numbers.py
-
curl -L -o trace_numbers.py https://huggingface.co/datasets/earino/ecbs5200-jev-benchmark/resolve/main/code/trace_numbers.py
14.2 kB
| """ | |
| 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"(?<!\\)%.*", "", doc) | |
| doc = re.sub(r"\\begin\{(tabular|align\*?)\}.*?\\end\{\1\}", " ", doc, flags=re.S) | |
| doc = re.sub(r"\\(cite|ref|label|input|includegraphics|url|texttt|resizebox|setlength|bibliography\w*)\*?(\{[^{}]*\})+", " ", doc) | |
| doc = re.sub(r"\\(begin|end)\{[^}]*\}(\[[^]]*\])?(\{[^}]*\})?", " ", doc) | |
| doc = re.sub(r"\\(small|footnotesize|scriptsize|centering|toprule|midrule|bottomrule|hfill|smallskip|noindent|linewidth)", " ", doc) | |
| doc = re.sub(r"\[tbp\]|\{0\.\d+\\linewidth\}|\[b\]", " ", doc) | |
| for n, rep in NAMES: | |
| doc = re.sub(n, f" {rep} ", doc) | |
| return doc | |
| NUM = re.compile(r"(?<![\w.])([-+\u2212]?\d{1,3}(?:,\d{3})+|[-+\u2212]?\d+(?:\.\d+)?)(?![\w])") | |
| def tokens(tex): | |
| t = prose(tex) | |
| out = [] | |
| for m in NUM.finditer(t): | |
| tok = m.group(1).replace("\u2212", "-") | |
| before = re.sub(r"\s+", " ", t[max(0, m.start() - 110):m.start()]) | |
| after = re.sub(r"\s+", " ", t[m.end():m.end() + 50]) | |
| out.append({"token": tok, "before": before, "context": before + m.group(1) + after}) | |
| return out | |
| # ------------------------------------------------------------------ sources | |
| def flatten(x, path=()): | |
| if isinstance(x, dict): | |
| for k, v in x.items(): | |
| yield from flatten(v, path + (str(k),)) | |
| elif isinstance(x, list): | |
| for i, v in enumerate(x): | |
| yield from flatten(v, path + (str(i),)) | |
| elif isinstance(x, (int, float)) and not isinstance(x, bool): | |
| yield path, float(x) | |
| SOURCES = ["results/numbers_reference.json", "results/token_usage.json", "results/latency_jev.json", | |
| "results/latency_probes.json", "results/jev-1.13.0_results_full.json", "results/jev-1.13.0_manifest_full.json", | |
| "results/semif_features_fit20000_results.json", "results/controls_v2_results.json", | |
| "results/embedding_control_results.json", "MANIFEST.json"] | |
| def load_sources(): | |
| idx = [] | |
| for rel in SOURCES + [str(p.relative_to(ROOT)) for p in sorted((ROOT / "results").glob("*/*_results_full.json"))]: | |
| p = ROOT / rel | |
| if p.exists(): | |
| for path, v in flatten(json.loads(p.read_text())): | |
| idx.append((rel, "/".join(path), v)) | |
| return idx | |
| FORMATS = { | |
| "f0": lambda v: f"{v:.0f}", "f1": lambda v: f"{v:.1f}", "f2": lambda v: f"{v:.2f}", "f3": lambda v: f"{v:.3f}", | |
| "f4": lambda v: f"{v:.4f}", "pct0": lambda v: f"{100 * v:.0f}", "pct1": lambda v: f"{100 * v:.1f}", | |
| "int": lambda v: f"{int(round(v)):,}" if abs(v - round(v)) < 1e-9 else None, | |
| "round": lambda v: f"{int(round(v)):,}", "mil": lambda v: f"{v / 1e6:.0f}", | |
| } | |
| EXEMPT = ("date", "version", "name", "formula", "external") | |
| def render(v, fmt, signed): | |
| s = FORMATS[fmt](v if signed else abs(v)) | |
| return None if s is None else ("+" + s if signed and v >= 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() | |