AbstractPhil commited on
Commit
216b2a2
·
verified ·
1 Parent(s): c9c2134

v0.2: sweep retracts the fusion-gap reading (storage-position asymmetry: bert front-loads, t5 back-loads; student concat 0.954 > teacher); sequence entry: all 999 states, control still fails, embedding table byte-arbitrary

Browse files
Files changed (1) hide show
  1. proto_frame/proto_v02_gauge.py +97 -0
proto_frame/proto_v02_gauge.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """v0.2 sweep gauge: (side x layer x readout) identification against
2
+ the FROZEN v0.1 codebook. Same sites/splits/seed as v0.1; L_id only
3
+ (bridge row notes the protocol delta vs v0.1's id+mse student row).
4
+ Readouts: first, last, concat[first,last] — linear maps only."""
5
+ import json
6
+ import sys
7
+ import zlib
8
+
9
+ sys.path.insert(0, r"E:\mirel\geolip-bytelex")
10
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from geolip.bytelex.frame import (apply_whitening, fit_whitening,
15
+ procrustes, split_sites,
16
+ top_k_accuracy)
17
+
18
+ D = r"E:\mirel\data\bytelex\proto_frame"
19
+ DEV = "cuda"
20
+ SEED = zlib.crc32(b"frame-proto-v01") & 0xFFFFFFFF
21
+ torch.manual_seed(SEED)
22
+
23
+ dump = np.load(rf"{D}\frame_dump_v2.npz")
24
+ sweep = np.load(rf"{D}\sweep_dump_v02.npz")
25
+ anch = np.load(rf"{D}\frame_anchors_v01.npz")
26
+ states = json.load(open(r"E:\mirel\data\bytelex\words_of_C.json",
27
+ encoding="utf-8"))
28
+ CLS = np.array(["digit" if s["text"].isdigit() else
29
+ ("Name" if s["text"][0].isupper() else "word")
30
+ for s in states])
31
+ sid = dump["sid"].astype(np.int64)
32
+ KK = dump["KK"]
33
+ ok = KK[:, 0] > 0
34
+ sp = split_sites(sid[ok], seed=SEED)
35
+ gix = {k: np.flatnonzero(ok)[v] for k, v in sp.items()}
36
+ E_C = torch.tensor(anch["E_C"], dtype=torch.float32, device=DEV)
37
+ E_Cn = F.normalize(E_C, dim=-1)
38
+ sT = torch.tensor(float(anch["s"]), device=DEV)
39
+ tsid = torch.tensor(sid, device=DEV)
40
+
41
+
42
+ def run_config(H, tag):
43
+ mu, w = fit_whitening(H[gix["fit"]].astype(np.float64))
44
+ Z = apply_whitening(H.astype(np.float64), mu, w)
45
+ m = np.zeros((999, Z.shape[1]))
46
+ for s in range(999):
47
+ r = gix["train"][sid[gix["train"]] == s]
48
+ if len(r):
49
+ m[s] = Z[r].mean(0)
50
+ W = torch.nn.Parameter(torch.tensor(
51
+ procrustes(m, anch["E_C"].astype(np.float64)),
52
+ dtype=torch.float32, device=DEV))
53
+ tZ = torch.tensor(Z, dtype=torch.float32, device=DEV)
54
+ opt = torch.optim.Adam([W], lr=1e-3, weight_decay=0.0)
55
+ rng = np.random.default_rng(SEED + 7)
56
+ for ep in range(6):
57
+ order = rng.permutation(gix["train"])
58
+ for i in range(0, len(order), 512):
59
+ b = torch.tensor(order[i:i + 512], device=DEV)
60
+ opt.zero_grad(set_to_none=True)
61
+ zf = F.normalize(tZ[b] @ W, dim=-1)
62
+ lg = sT.clamp(1, 100) * (zf @ E_Cn.T)
63
+ F.cross_entropy(lg, tsid[b]).backward()
64
+ opt.step()
65
+ ev = gix["eval"]
66
+ with torch.no_grad():
67
+ zf = F.normalize(tZ[torch.tensor(ev, device=DEV)] @ W, -1)
68
+ lg = (sT * zf @ E_Cn.T).cpu().numpy()
69
+ out = {"overall": round(top_k_accuracy(lg, sid[ev]), 4)}
70
+ for c in ("word", "Name", "digit"):
71
+ mm = CLS[sid[ev]] == c
72
+ out[c] = round(top_k_accuracy(lg[mm], sid[ev][mm]), 4)
73
+ print(f"[v02 {tag}] {json.dumps(out)}", flush=True)
74
+ return out
75
+
76
+
77
+ led = {"_protocol": "L_id only, frozen v0.1 E_C, 6 epochs; v0.1 "
78
+ "student row (L6 first) trained id+mse — bridge "
79
+ "row re-run here id-only for comparability"}
80
+ LB, LT = sweep["LB"].tolist(), sweep["LT"].tolist()
81
+ for j, l in enumerate(LT):
82
+ for ri, rname in ((0, "first"), (1, "last")):
83
+ led[f"student_L{l}_{rname}"] = run_config(
84
+ sweep["ST"][:, j, ri], f"student L{l} {rname}")
85
+ led[f"student_L{l}_concat"] = run_config(
86
+ np.concatenate([sweep["ST"][:, j, 0], sweep["ST"][:, j, 1]],
87
+ axis=1), f"student L{l} concat")
88
+ for j, l in enumerate(LB):
89
+ led[f"teacher_L{l}_first"] = run_config(
90
+ sweep["SB"][:, j, 0].astype(np.float32), f"teacher L{l} first")
91
+ led["teacher_L8_concat"] = run_config(
92
+ np.concatenate([sweep["SB"][:, 2, 0], sweep["SB"][:, 2, 1]],
93
+ axis=1).astype(np.float32), "teacher L8 concat")
94
+
95
+ with open(rf"{D}\v02_sweep_ledger.json", "w", encoding="utf-8") as f:
96
+ json.dump(led, f, indent=1)
97
+ print("[v02] SWEEP COMPLETE", flush=True)