Buckets:
| """Metrics, statistical tests and tables built from scored outputs, as fixed in PLAN.md. | |
| Usage: | |
| python -m src.report pilot <scored.jsonl> <out_dir> | |
| python -m src.report full <scored.jsonl> <results_dir> | |
| """ | |
| import csv | |
| import json | |
| import math | |
| import sys | |
| from collections import Counter, defaultdict | |
| from decimal import Decimal | |
| from pathlib import Path | |
| import numpy as np | |
| from scipy.stats import binomtest | |
| Z95 = 1.959963984540054 | |
| TASKS = ("copy", "convert", "compare", "compute", "statement_qa") | |
| VALUE_TASKS = ("compute", "statement_qa") | |
| SYSTEMS = ("western", "eastern_arabic", "persian") | |
| LANGS = ("en", "ar") | |
| FAMILY = [("western", "eastern_arabic"), ("western", "persian")] | |
| FACTORS = ("length", "decimals", "separators", "subtype", "gold_negative") | |
| ALPHA = 0.05 | |
| EQUIVALENCE_MARGIN = 0.05 | |
| def wilson(k, n, z=Z95): | |
| """Wilson score interval for k successes in n trials.""" | |
| if n == 0: | |
| return math.nan, math.nan | |
| p = k / n | |
| denom = 1 + z * z / n | |
| centre = (p + z * z / (2 * n)) / denom | |
| half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom | |
| return centre - half, centre + half | |
| def mcnemar_exact(b, c): | |
| """Two-sided exact McNemar test on the discordant counts b and c.""" | |
| return 1.0 if b + c == 0 else binomtest(b, b + c, 0.5).pvalue | |
| def paired_bootstrap(x, y, n_boot=10000, seed=0): | |
| """95% percentile interval for mean(x) - mean(y), resampling paired items.""" | |
| x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float) | |
| rng = np.random.default_rng(seed) | |
| idx = rng.integers(0, len(x), size=(n_boot, len(x))) | |
| diffs = x[idx].mean(axis=1) - y[idx].mean(axis=1) | |
| return float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5)) | |
| def holm(pvalues): | |
| """Holm step-down adjusted p-values, in the input order.""" | |
| order = sorted(range(len(pvalues)), key=lambda i: pvalues[i]) | |
| adjusted, running = [0.0] * len(pvalues), 0.0 | |
| for rank, i in enumerate(order): | |
| running = max(running, (len(pvalues) - rank) * pvalues[i]) | |
| adjusted[i] = min(1.0, running) | |
| return adjusted | |
| def load_jsonl(path): | |
| with open(path, encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def with_metadata(scored, items): | |
| """Scored rows joined with the item metadata they were scored against.""" | |
| meta = {i["item_id"]: i["metadata"] for i in items} | |
| return [{**r, **{f: meta[r["item_id"]].get(f, "") for f in FACTORS}} for r in scored] | |
| def cell_key(r): | |
| return r["task"], r["numeral_system"], r["prompt_lang"] | |
| def sort_key(key): | |
| task, system, lang = key | |
| return TASKS.index(task), SYSTEMS.index(system), LANGS.index(lang) | |
| def cells(rows): | |
| grouped = defaultdict(list) | |
| for r in rows: | |
| grouped[cell_key(r)].append(r) | |
| return dict(sorted(grouped.items(), key=lambda kv: sort_key(kv[0]))) | |
| def rate_row(k, n): | |
| lo, hi = wilson(k, n) | |
| return {"n": n, "correct": k, "accuracy": round(k / n, 4) if n else "", | |
| "ci_low": round(lo, 4) if n else "", "ci_high": round(hi, 4) if n else ""} | |
| def accuracy_table(rows): | |
| out = [] | |
| for (task, system, lang), group in cells(rows).items(): | |
| row = {"task": task, "numeral_system": system, "prompt_lang": lang} | |
| row.update(rate_row(sum(r["correct"] for r in group), len(group))) | |
| row["parse_failures"] = sum(r["error_type"] == "parse_failure" for r in group) | |
| row["hit_token_limit"] = sum(r["hit_token_limit"] for r in group) | |
| out.append(row) | |
| return out | |
| def secondary_table(rows): | |
| """Value correctness and number-only replies on copy and convert, format match on compute and statement QA.""" | |
| out = [] | |
| for (task, system, lang), group in cells(rows).items(): | |
| if task in ("copy", "convert"): | |
| metrics = ["value_correct", "only_number"] | |
| elif task in VALUE_TASKS: | |
| metrics = ["format_match"] | |
| else: | |
| continue | |
| for metric in metrics: | |
| k = sum(r[metric] for r in group) | |
| out.append({"task": task, "numeral_system": system, "prompt_lang": lang, "metric": metric, **rate_row(k, len(group))}) | |
| return out | |
| def by_base(rows, task, system, lang): | |
| return {r["base_id"]: r["correct"] for r in rows if cell_key(r) == (task, system, lang)} | |
| def twin_consistency(rows): | |
| out = [] | |
| for task in TASKS: | |
| twins = defaultdict(list) | |
| for r in rows: | |
| if r["task"] == task: | |
| twins[r["base_id"]].append(r["correct"]) | |
| if not twins: | |
| continue | |
| if any(len(v) != 6 for v in twins.values()): | |
| raise RuntimeError(f"{task}: some base items do not have 6 scored twins") | |
| k = sum(all(v) for v in twins.values()) | |
| out.append({"task": task, **rate_row(k, len(twins)), "metric": "all 6 twins correct"}) | |
| return out | |
| def compare_cells(rows, task, cell_a, cell_b, n_boot, seed): | |
| """Paired comparison of two (numeral system, prompt language) cells over the same base items.""" | |
| a, b = by_base(rows, task, *cell_a), by_base(rows, task, *cell_b) | |
| if set(a) != set(b): | |
| raise RuntimeError(f"{task}: {cell_a} and {cell_b} cover different base items") | |
| bases = sorted(a) | |
| x, y = [int(a[i]) for i in bases], [int(b[i]) for i in bases] | |
| only_a = sum(1 for i, j in zip(x, y) if i and not j) | |
| only_b = sum(1 for i, j in zip(x, y) if j and not i) | |
| lo, hi = paired_bootstrap(x, y, n_boot, seed) | |
| return {"task": task, "system_a": cell_a[0], "lang_a": cell_a[1], "system_b": cell_b[0], "lang_b": cell_b[1], | |
| "n_pairs": len(bases), "accuracy_a": round(float(np.mean(x)), 4), "accuracy_b": round(float(np.mean(y)), 4), | |
| "difference": round(float(np.mean(x) - np.mean(y)), 4), "ci_low": round(lo, 4), "ci_high": round(hi, 4), | |
| "only_a_correct": only_a, "only_b_correct": only_b, "p_exact": mcnemar_exact(only_a, only_b)} | |
| def paired_family(rows, n_boot=10000, seed=0): | |
| """The 20 pre-registered comparisons with Holm-adjusted p-values and the gap rule from PLAN.md.""" | |
| out = [compare_cells(rows, t, (a, lang), (b, lang), n_boot, seed) for t in TASKS for lang in LANGS for a, b in FAMILY] | |
| for row, p_holm in zip(out, holm([r["p_exact"] for r in out])): | |
| row["p_holm"] = p_holm | |
| row["gap"] = p_holm < ALPHA and (row["ci_low"] > 0 or row["ci_high"] < 0) | |
| row["within_5_points"] = row["ci_low"] >= -EQUIVALENCE_MARGIN and row["ci_high"] <= EQUIVALENCE_MARGIN | |
| return out | |
| def exploratory_comparisons(rows, n_boot=10000, seed=0): | |
| """Eastern Arabic against Persian, and English against Arabic prompts. Not part of the Holm family.""" | |
| pairs = [(("eastern_arabic", lang), ("persian", lang)) for lang in LANGS] | |
| pairs += [((system, "en"), (system, "ar")) for system in SYSTEMS] | |
| return [compare_cells(rows, t, a, b, n_boot, seed) for t in TASKS for a, b in pairs] | |
| def factor_table(rows): | |
| out = [] | |
| for (task, system, lang), group in cells(rows).items(): | |
| for factor in FACTORS: | |
| levels = defaultdict(list) | |
| for r in group: | |
| if r[factor] != "": | |
| levels[r[factor]].append(r["correct"]) | |
| for level, values in sorted(levels.items(), key=lambda kv: str(kv[0])): | |
| out.append({"task": task, "numeral_system": system, "prompt_lang": lang, "factor": factor, | |
| "level": level, **rate_row(sum(values), len(values))}) | |
| return out | |
| def relative_error_table(rows): | |
| out = [] | |
| for (task, system, lang), group in cells(rows).items(): | |
| if task not in VALUE_TASKS: | |
| continue | |
| errors = sorted(r["relative_error"] for r in group if "relative_error" in r) | |
| q = np.percentile(errors, [25, 50, 75]) if errors else [math.nan] * 3 | |
| out.append({"task": task, "numeral_system": system, "prompt_lang": lang, "n_wrong_parsed": len(errors), | |
| "q25": round(float(q[0]), 6), "median": round(float(q[1]), 6), "q75": round(float(q[2]), 6), | |
| "share_below_0.01": round(sum(e < 0.01 for e in errors) / len(errors), 4) if errors else "", | |
| "share_above_1": round(sum(e > 1 for e in errors) / len(errors), 4) if errors else ""}) | |
| return out | |
| def error_table(rows): | |
| out = [] | |
| for (task, system, lang), group in cells(rows).items(): | |
| for error, n in sorted(Counter(r["error_type"] for r in group if r["error_type"]).items()): | |
| out.append({"task": task, "numeral_system": system, "prompt_lang": lang, "error_type": error, "n": n}) | |
| return out | |
| def first_digit_misleads(item): | |
| """True when the smaller amount of a compare pair starts with a larger digit than the larger amount.""" | |
| a, b = Decimal(item["operands"]["a"]), Decimal(item["operands"]["b"]) | |
| larger, smaller = (a, b) if a > b else (b, a) | |
| return str(smaller)[0] > str(larger)[0] | |
| def compare_first_digit_table(rows, items): | |
| """Exploratory. Accuracy on easy compare pairs, split by whether the first digits point to the wrong option.""" | |
| by_id = {i["item_id"]: i for i in items} | |
| groups = defaultdict(list) | |
| for r in rows: | |
| item = by_id[r["item_id"]] | |
| if r["task"] != "compare" or item["metadata"]["subtype"] != "easy": | |
| continue | |
| first = "misleading" if first_digit_misleads(item) else "agrees" | |
| for lang in (r["prompt_lang"], "both"): | |
| groups[(r["numeral_system"], lang, first)].append(r["correct"]) | |
| out = [] | |
| for system in SYSTEMS: | |
| for lang in (*LANGS, "both"): | |
| for first in ("misleading", "agrees"): | |
| values = groups[(system, lang, first)] | |
| out.append({"numeral_system": system, "prompt_lang": lang, "first_digit": first, | |
| **rate_row(sum(values), len(values))}) | |
| return out | |
| def error_types_by_system(rows): | |
| """Wrong answers per numeral system, over all tasks and both prompt languages, by error type.""" | |
| out = [] | |
| for system in SYSTEMS: | |
| wrong = [r["error_type"] for r in rows if r["numeral_system"] == system and not r["correct"]] | |
| for error, n in sorted(Counter(wrong).items()): | |
| out.append({"numeral_system": system, "error_type": error, "n": n, "n_wrong": len(wrong), | |
| "share_of_wrong": round(n / len(wrong), 4)}) | |
| return out | |
| def write_csv(rows, path): | |
| Path(path).parent.mkdir(parents=True, exist_ok=True) | |
| with open(path, "w", newline="", encoding="utf-8") as f: | |
| if rows: | |
| w = csv.DictWriter(f, fieldnames=list(rows[0])) | |
| w.writeheader() | |
| w.writerows(rows) | |
| return Path(path) | |
| def pilot(scored_path, out_dir): | |
| rows = load_jsonl(scored_path) | |
| write_csv(accuracy_table(rows), Path(out_dir) / "accuracy_by_cell.csv") | |
| write_csv(secondary_table(rows), Path(out_dir) / "secondary_by_cell.csv") | |
| write_csv(error_table(rows), Path(out_dir) / "error_types.csv") | |
| n_fail = sum(r["error_type"] == "parse_failure" for r in rows) | |
| print(f"{len(rows)} scored outputs, {n_fail} parse failures, tables written to {out_dir}") | |
| def full(scored_path, results_dir, eval_path="data/eval_set.jsonl", n_boot=10000, seed=0): | |
| items = load_jsonl(eval_path) | |
| rows = with_metadata(load_jsonl(scored_path), items) | |
| out = Path(results_dir) | |
| write_csv(accuracy_table(rows), out / "accuracy_by_cell.csv") | |
| write_csv(secondary_table(rows), out / "secondary_by_cell.csv") | |
| write_csv(twin_consistency(rows), out / "twin_consistency.csv") | |
| write_csv(paired_family(rows, n_boot, seed), out / "paired_tests.csv") | |
| write_csv(exploratory_comparisons(rows, n_boot, seed), out / "exploratory_tests.csv") | |
| write_csv(factor_table(rows), out / "accuracy_by_factor.csv") | |
| write_csv(relative_error_table(rows), out / "relative_errors.csv") | |
| write_csv(error_table(rows), out / "error_types.csv") | |
| write_csv(error_types_by_system(rows), out / "error_types_by_system.csv") | |
| write_csv(compare_first_digit_table(rows, items), out / "compare_first_digit.csv") | |
| print(f"{len(rows)} scored outputs, tables written to {out}") | |
| if __name__ == "__main__": | |
| {"pilot": pilot, "full": full}[sys.argv[1]](*sys.argv[2:]) | |
Xet Storage Details
- Size:
- 12.2 kB
- Xet hash:
- 6d01066d57af39967804040c1ef0555b450d6e70bd9fedcd2e8e9f751b45e74c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.