File size: 4,671 Bytes
3bbd5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""Aggregate phase-5 evaluation files into per-condition tables.

Tokens per pass for the lexical correction uses a beta chosen on the
even-indexed documents and is reported on the odd-indexed ones; every other
policy is reported on the same odd-indexed documents so the columns are
comparable. Gains carry a paired bootstrap 95% interval over documents.
"""

import glob
import json
import sys
from collections import defaultdict
from pathlib import Path

import numpy as np

ORDER = ["English", "Devanagari", "ITRANS", "IAST", "ISO"]
RNG = np.random.default_rng(0)


def tpp(slot: dict, idx: np.ndarray) -> float:
    c, r = np.asarray(slot["committed"]), np.asarray(slot["rounds"])
    return c[idx].sum() / r[idx].sum()


def gain_ci(a: dict, b: dict, idx: np.ndarray, n_boot: int = 2000) -> tuple:
    """Relative gain of policy b over a on documents idx, with a paired bootstrap interval."""
    ca, ra, cb, rb = (np.asarray(x)[idx] for x in (a["committed"], a["rounds"], b["committed"], b["rounds"]))
    point = (cb.sum() / rb.sum()) / (ca.sum() / ra.sum()) - 1
    draws = RNG.integers(0, len(idx), size=(n_boot, len(idx)))
    boot = (cb[draws].sum(1) / rb[draws].sum(1)) / (ca[draws].sum(1) / ra[draws].sum(1)) - 1
    return point, np.percentile(boot, 2.5), np.percentile(boot, 97.5)


def summarise(path: str, account: str = "one_pass") -> dict:
    r = json.load(open(path))
    rep = r["replay"][account]
    n = len(rep["independent_beta0"]["committed"])
    dev, test = np.arange(0, n, 2), np.arange(1, n, 2)
    out = {"name": r["name"], "docs_test": len(test)}
    arms = sorted({k.rsplit("_beta", 1)[0] for k in rep})
    for arm in arms:
        best = max(r["betas"], key=lambda b: tpp(rep[f"{arm}_beta{b:g}"], dev))
        out[f"{arm}"] = tpp(rep[f"{arm}_beta0"], test)
        out[f"{arm}+lexical"] = tpp(rep[f"{arm}_beta{best:g}"], test)
        out[f"{arm}+lexical_beta"] = best
        for label, key in ((arm, f"{arm}_beta0"), (f"{arm}+lexical", f"{arm}_beta{best:g}")):
            if key != "independent_beta0":
                out[f"gain {label}"] = gain_ci(rep["independent_beta0"], rep[key], test)
        out[f"accept {arm}"] = rep[f"{arm}_beta0"]["accept_by_position"]
        out[f"accept_within {arm}"] = rep[f"{arm}_beta0"]["accept_within_word"]
        out[f"accept_start {arm}"] = rep[f"{arm}_beta0"]["accept_word_start"]
    tf = r["teacher_forced"]["arms"]
    for arm, a in tf.items():
        out[f"acc {arm}"] = a["accuracy"]
        out[f"acc_within {arm}"] = a["accuracy_within_word"]
        out[f"acc_start {arm}"] = a["accuracy_word_start"]
        if "backbone_agreement" in a:
            out[f"agree_backbone {arm}"] = a["backbone_agreement"]
        if "d_relative_pct" in a:
            out[f"D% {arm}"] = a["d_relative_pct"]
    out["timing_ms"] = r.get("timing_ms")
    return out


def main() -> None:
    pattern = sys.argv[1] if len(sys.argv) > 1 else "results/phase5_dependent/eval_*.json"
    runs = defaultdict(list)
    for path in sorted(glob.glob(pattern)):
        for account in ("one_pass", "legacy"):
            runs[account].append((Path(path).stem, summarise(path, account)))
    f3 = lambda xs: "[" + ", ".join(f"{x:.3f}" for x in xs) + "]"
    for account, items in runs.items():
        print(f"\n== tokens per pass, {account} (held-out half of documents) ==")
        for stem, s in sorted(items, key=lambda kv: (ORDER.index(kv[1]["name"]) if kv[1]["name"] in ORDER else 9, kv[0])):
            cols = [k for k in s if not k.startswith(("gain", "acc", "agree", "D%", "name", "docs", "timing")) and not k.endswith("_beta")]
            print(stem, f"({s['docs_test']} docs)")
            for k in cols:
                g = s.get(f"gain {k}")
                extra = f"  {100 * g[0]:+.1f}% [{100 * g[1]:+.1f}, {100 * g[2]:+.1f}]" if g else ""
                beta = f"  beta {s[k + '_beta']}" if k + "_beta" in s else ""
                print(f"   {k:28s} {s[k]:.3f}{extra}{beta}")
    print("\n== acceptance by draft position and teacher-forced accuracy (one_pass) ==")
    for stem, s in runs["one_pass"]:
        print(stem)
        for k, v in s.items():
            if k.startswith(("accept", "acc", "agree")):
                print(f"   {k:44s} {f3(v)}")
            elif k.startswith("D%"):
                print(f"   {k:44s} {v:+.3f}")
        if s["timing_ms"]:
            print("   timing ms", {k: round(v, 2) for k, v in s["timing_ms"].items()})
    Path("results/phase5_dependent/summary.json").write_text(json.dumps(
        {account: {stem: s for stem, s in items} for account, items in runs.items()}, indent=1, default=lambda o: list(o)))


if __name__ == "__main__":
    main()