File size: 5,512 Bytes
88e8448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/env python3
"""Leak analysis for EXP-020 loop-depth runs.

The test set is deterministic (gen(N, 3000, 3000, 0, min(14, N-2)) with N=16),
so every per-item field below is recomputed locally with the generator copied
verbatim from loop_mid.py. No generator change. Item i in a per-item file is
te[i]; the join is validated by asserting that k and y agree on every item.

Field definitions (stated explicitly because they are what the claim rests on):
  wrap        : the answer f^(k+1)(start) already appears among the shown walk
                nodes x_0..x_k. Equivalently the answer is printed in the table
                as some earlier node, so the item is answerable by a shortcut.
  ans_is_start: the answer equals start (the "predict start" shortcut).
  ans_rank    : 1-indexed rank of the answer among nodes NOT present in the
                shown table, sorted ascending; 0 if the answer is shown (i.e. a
                wrapped item). Low rank = guessable by exclusion.
  n_shown     : number of nodes in the shown table.

Usage: leak_analysis.py --run A.jsonl --depth-a 1 --run-b B.jsonl --depth-b 4
"""
import argparse, json, sys
import numpy as np

sys.path.insert(0, "/mnt/PrimeStore/Work/SOTA_open_search/tools/shared/eval")
from metrics import mcnemar_exact, bootstrap_delta  # lab harness


def gen(N, seed, n, k_lo, k_hi):          # verbatim from loop_mid.py / train1p.py
    rng = np.random.default_rng(seed); out = []
    for _ in range(n):
        perm = rng.permutation(N); start = int(rng.integers(N)); k = int(rng.integers(k_lo, k_hi + 1))
        x = start; chain = []
        for _ in range(k + 1): chain.append(x); x = int(perm[x])
        ans = x; need = k + 1; m = int(rng.integers(need + 1, N + 1))
        rest = [u for u in rng.permutation(N) if u not in set(chain)]
        show = chain + rest[:max(0, m - need)]; order = rng.permutation(np.array(show))
        out.append((perm, start, k, order, ans))
    return out


def features(it, N=16):
    perm, start, k, order, ans = it
    chain = []
    x = start
    for _ in range(k + 1): chain.append(x); x = int(perm[x])
    shown = set(int(u) for u in order)
    cand = sorted(set(range(N)) - shown)
    return {"wrap": int(ans in chain), "ans_is_start": int(ans == start),
            "ans_rank": (cand.index(ans) + 1) if ans in cand else 0,
            "n_shown": len(shown)}


def load(path, depth, step):
    r = {}
    for line in open(path):
        o = json.loads(line)
        if o["step"] == step and o["pass"] == depth:
            r[o["item"]] = o
    return r


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", required=True); ap.add_argument("--depth-a", type=int)
    ap.add_argument("--run-b"); ap.add_argument("--depth-b", type=int)
    ap.add_argument("--step", type=int, default=3000)
    ap.add_argument("--tag-a", default="A"); ap.add_argument("--tag-b", default="B")
    a = ap.parse_args()

    te = gen(16, 3000, 3000, 0, min(14, 16 - 2))
    feats = [features(it) for it in te]

    ra = load(a.run, a.depth_a, a.step)
    for i, o in ra.items():                                   # validate the join
        assert o["k"] == te[int(i)][2], f"k mismatch item {i}"
        assert o["y"] == te[int(i)][4], f"y mismatch item {i}"
    print(f"join validated on {len(ra)} items (k and y agree with the generator)")

    ks = np.array([it[2] for it in te]); ans = np.array([it[4] for it in te])
    start = np.array([it[1] for it in te])
    wrap = np.array([f["wrap"] for f in feats])

    print("\nwrap rate and `predict start` baseline by k (n per bucket):")
    print(" k    n   wrap%  pred_start_acc  ans_is_start%")
    for k in range(15):
        m = ks == k
        if not m.any(): continue
        print(f"{k:2d} {m.sum():4d}  {100*wrap[m].mean():5.1f}  "
              f"{(start[m]==ans[m]).mean():.3f}          {100*(start[m]==ans[m]).mean():5.1f}")
    m7 = ks >= 7
    print(f"\nabove k6: n={m7.sum()}  wrap rate {100*wrap[m7].mean():.1f}%")

    def paired(rows_a, rows_b, mask_items, label):
        ids = [i for i in mask_items if i in rows_a and i in rows_b]
        if not ids: print(f"  {label}: no items"); return
        A = [rows_a[i]["pred"] == rows_a[i]["y"] for i in ids]
        B = [rows_b[i]["pred"] == rows_b[i]["y"] for i in ids]
        mc = mcnemar_exact(A, B); bs = bootstrap_delta(A, B, n_resamples=10000, seed=42)
        print(f"  {label:34s} n={len(ids):5d}  A={sum(A)/len(A):.3f} B={sum(B)/len(B):.3f}  "
              f"d={bs['delta']:+.3f} [{bs['ci_low']:+.3f},{bs['ci_high']:+.3f}]  "
              f"b01={mc['b01']} b10={mc['b10']} p={mc['p_value']:.3g}")

    if a.run_b:
        rb = load(a.run_b, a.depth_b, a.step)
        for i, o in rb.items():
            assert o["k"] == te[int(i)][2] and o["y"] == te[int(i)][4]
        items = list(range(len(te)))
        print(f"\n{a.tag_a} (depth {a.depth_a}) vs {a.tag_b} (depth {a.depth_b}) @ step {a.step}")
        for kmin, kmax, name in [(0, 99, "all k"), (7, 14, "above k6"), (7, 7, "k7 only"),
                                 (8, 8, "k8 only"), (9, 14, "k9-k14")]:
            sub = [i for i in items if kmin <= ks[int(i)] <= kmax]
            paired(ra, rb, sub, name)
            nowrap = [i for i in sub if not wrap[int(i)]]
            wrapped = [i for i in sub if wrap[int(i)]]
            paired(ra, rb, nowrap, f"  ... wrap==False")
            if kmin in (0, 7):
                paired(ra, rb, wrapped, f"  ... wrap==True")


if __name__ == "__main__":
    main()