File size: 6,215 Bytes
a110318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""Fit token-only programs from the 300k-sequence contingency tables and score
them on the UNCHANGED test split.

Design decisions that make this comparable to the shipped run:
  * Same selection pipeline (S.select_tokens): resolve_min_fires -> best_k(50)
    -> expand_roots -> prune_tail_families. Nothing is retuned for scale.
  * Same test split, untouched: owt_test_tokens.npz, 1,270,000 read positions.
    Only the FITTING corpus changes, so every delta is attributable to data.
  * Same scorer: S.score_batch runs the emitted programs over the corpus, which
    is what produced the shipped numbers.

The two rate-based constants carry over correctly by construction:
resolve_min_fires gates on firings/positions, and TAIL_SHARE is a share, so
both mean the same thing at 36.8M positions as at 1.27M. MIN_FIRES_IN_SET
stays absolute on purpose -- two observations is thin evidence however long you
looked, and a string seen once at 1.27M positions is seen ~29 times here and
stops being thin, which is the intended behaviour.

    python fit_programs.py --layer 6 --emit
"""
from __future__ import annotations
import argparse, csv, json, sys, time
from pathlib import Path
import numpy as np

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
for p in (ROOT / "lib", ROOT / "eda_phase0", ROOT):
    sys.path.insert(0, str(p))
import config as C
import sae_synthesis as S

THR, CAP, MIN_POS = 0.1, 50, 5


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--layer", type=int, required=True)
    ap.add_argument("--emit", action="store_true")
    ap.add_argument("--jobs", type=int, default=8)
    ap.add_argument("--counts", default=str(HERE / "counts_300k.npz"))
    a = ap.parse_args()
    L = a.layer

    z = np.load(a.counts, allow_pickle=True)
    strings = z["strings"]
    occ_tr = z["occ"]
    NS = len(strings)
    n_seq, n_read = int(z["n_seq"]), int(z["n_read"])
    n_positions = n_seq * n_read
    keys, cnt = z[f"keys_{L}"], z[f"cnt_{L}"]
    feat = (keys // NS).astype(np.int64)
    sid = (keys % NS).astype(np.int64)
    print(f"[layer {L}] fitting corpus {n_seq:,} seqs = {n_positions:,} positions "
          f"({n_positions/1_270_000:.1f}x shipped); {len(keys):,} (feature,string) pairs",
          flush=True)

    bounds = np.searchsorted(feat, np.arange(24577))
    occ_lookup = {int(i): int(occ_tr[i]) for i in np.unique(sid)}

    out_dir = HERE / f"layer{L}_thr0p1" / "capped50"
    (out_dir / "programs").mkdir(parents=True, exist_ok=True)
    rows, items, meta = [], [], {}
    t0 = time.time()
    for f in range(24576):
        i0, i1 = int(bounds[f]), int(bounds[f + 1])
        n_pos = int(cnt[i0:i1].sum())
        if i1 <= i0 or n_pos < MIN_POS:
            rows.append({"layer": L, "feature": f, "status": "too_rare",
                         "f1": 0.0, "precision": 0.0, "recall": 0.0,
                         "n_pos_train": n_pos})
            continue
        s_ids, fires = sid[i0:i1], cnt[i0:i1].astype(np.int64)
        order = np.argsort(-fires)
        cum = 0
        rws = []
        for j in order:
            t = str(strings[s_ids[j]])
            fr = int(fires[j])
            ap_ = max(occ_lookup.get(int(s_ids[j]), fr), fr)
            cum += fr
            rws.append({"token": t, "token_ids": [int(s_ids[j])], "fires": fr,
                        "appears": ap_, "p_fire": fr / ap_,
                        "lift": (fr / ap_) / (n_pos / n_positions),
                        "cum_recall": cum / n_pos})
        opt_f1, opt_toks = S.token_optimum(rws, n_pos)
        ct = S.Contingency(L, f, THR, n_positions, n_pos, rws, [t["token"] for t in rws[:50]],
                           opt_f1, opt_toks)
        code = S.grouped_token_program(L, f, ct, cap=CAP)
        if code is None:
            rows.append({"layer": L, "feature": f, "status": "no_tokens",
                         "f1": 0.0, "precision": 0.0, "recall": 0.0,
                         "n_pos_train": n_pos})
            continue
        toks = S.select_tokens(ct, cap=CAP)
        items.append((f, code, S.prog_name(L, f)))
        meta[f] = {"layer": L, "feature": f, "status": "ok", "regime": ct.regime,
                   "token_optimum": round(opt_f1, 4), "n_tokens": len(toks),
                   "n_families": len({S.word_root(t) for t in toks}),
                   "n_tokens_uncapped": len(opt_toks), "n_pos_train": n_pos}
        if a.emit:
            d = out_dir / "programs" / f"{f // 1000:02d}"
            d.mkdir(parents=True, exist_ok=True)
            (d / f"{S.feature_key(L, f)}.py").write_text(code)
        if (f + 1) % 5000 == 0:
            print(f"  select {f+1:,}/24,576  {(time.time()-t0)/60:.1f} min", flush=True)

    print(f"[emit] {len(items):,} programs in {(time.time()-t0)/60:.1f} min; scoring "
          f"on the UNCHANGED test split...", flush=True)
    scores = S.score_batch(ROOT / f"synthesis/layer{L}_thr0p1/stores/store_L{L:02d}_test.npz",
                           C.CACHE / "owt_test_tokens.npz",
                           ROOT / "layer_plots" / "vocab_strings.npy",
                           items, THR, C.FIRST_READ_POSITION, workers=a.jobs)
    for f, _, _ in items:
        sc = dict(scores[f]); sc.update(meta[f]); rows.append(sc)

    cols = ["layer", "feature", "status", "regime", "token_optimum", "n_tokens",
            "n_families", "n_tokens_uncapped", "n_pos_train", "precision",
            "recall", "f1", "tp", "fp", "fn", "tn", "errors", "n_positions"]
    out = out_dir / "scores_test.csv"
    with open(out, "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=cols, extrasaction="ignore")
        w.writeheader(); w.writerows(rows)
    ok = [r for r in rows if r.get("status") == "ok"]
    f1 = np.array([r["f1"] for r in ok])
    nt = np.array([r["n_tokens"] for r in ok])
    print(f"\n=== layer {L}: {len(rows):,} features, {len(ok):,} scored, "
          f"{(time.time()-t0)/60:.1f} min ===")
    print(f"TEST F1  median {np.median(f1):.4f}  mean {f1.mean():.4f}  max {f1.max():.4f}")
    print(f"program size: median {np.median(nt):.0f} strings")
    print(f"above 0.8: {(f1>0.8).mean():.1%}")
    print(f"wrote {out}", flush=True)


if __name__ == "__main__":
    main()