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- proto_frame/proto_v02_entry.py +190 -0
proto_frame/proto_v02_entry.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v0.2 sequence entry: position-specific linear maps G_0..G_3 emit
|
| 2 |
+
the length-matched embedding sequence for ANY state (k<=4), opening
|
| 3 |
+
entry from 149 whole-walk states to the full inventory. Same
|
| 4 |
+
generalization discipline: fit on train states, probe with UNSEEN
|
| 5 |
+
states; counterfactual restricted to SAME-k pairs (length confound
|
| 6 |
+
excluded); random-codebook control retained (Gate 4)."""
|
| 7 |
+
import json
|
| 8 |
+
import sys
|
| 9 |
+
import zlib
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, r"E:\mirel\geolip-bytelex")
|
| 12 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
import transformers
|
| 17 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 18 |
+
import transformers.utils.logging as hlog
|
| 19 |
+
|
| 20 |
+
hlog.set_verbosity_error()
|
| 21 |
+
D = r"E:\mirel\data\bytelex\proto_frame"
|
| 22 |
+
DEV = "cuda"
|
| 23 |
+
SEED = zlib.crc32(b"frame-proto-v01") & 0xFFFFFFFF
|
| 24 |
+
L_T5 = 6
|
| 25 |
+
KMAX = 4
|
| 26 |
+
torch.manual_seed(SEED)
|
| 27 |
+
from geolip.bytelex.frame import (apply_whitening, fit_whitening,
|
| 28 |
+
split_sites)
|
| 29 |
+
|
| 30 |
+
dump = np.load(rf"{D}\frame_dump_v2.npz")
|
| 31 |
+
anch = np.load(rf"{D}\frame_anchors_v01.npz")
|
| 32 |
+
walk = json.load(open(rf"{D}\t5_walk_of_C.json", encoding="utf-8"))
|
| 33 |
+
sid = dump["sid"].astype(np.int64)
|
| 34 |
+
KK = dump["KK"]
|
| 35 |
+
ok = KK[:, 0] > 0
|
| 36 |
+
sp = split_sites(sid[ok], seed=SEED)
|
| 37 |
+
gix = {k: np.flatnonzero(ok)[v] for k, v in sp.items()}
|
| 38 |
+
|
| 39 |
+
kk = np.array([w["k"] for w in walk])
|
| 40 |
+
ids_of = [w["ids"] for w in walk]
|
| 41 |
+
usable = np.flatnonzero((kk >= 1) & (kk <= KMAX))
|
| 42 |
+
KMAX = int(kk[usable].max())
|
| 43 |
+
print(f"[v02e] observed KMAX={KMAX}, k census: "
|
| 44 |
+
f"{np.bincount(kk[usable]).tolist()}", flush=True)
|
| 45 |
+
rngw = np.random.default_rng(SEED + 41)
|
| 46 |
+
perm = rngw.permutation(len(usable))
|
| 47 |
+
gfit = usable[perm[:int(0.6 * len(usable))]]
|
| 48 |
+
gprobe = usable[perm[int(0.6 * len(usable)):]]
|
| 49 |
+
print(f"[v02e] usable {len(usable)}/999 (k<=4) -> fit {len(gfit)} / "
|
| 50 |
+
f"probe {len(gprobe)}", flush=True)
|
| 51 |
+
|
| 52 |
+
tkA = AutoTokenizer.from_pretrained("google/flan-t5-small")
|
| 53 |
+
mT = T5EncoderModel.from_pretrained("google/flan-t5-small").to(DEV)
|
| 54 |
+
mT.eval()
|
| 55 |
+
for p in mT.parameters():
|
| 56 |
+
p.requires_grad_(False)
|
| 57 |
+
emb = mT.get_input_embeddings().weight.detach()
|
| 58 |
+
E_C = torch.tensor(anch["E_C"], dtype=torch.float32, device=DEV)
|
| 59 |
+
E_Cn = F.normalize(E_C, dim=-1)
|
| 60 |
+
W_S = torch.tensor(anch["W_S"], dtype=torch.float32, device=DEV)
|
| 61 |
+
H_T = dump["H_T"][:, 0].astype(np.float64)
|
| 62 |
+
muT, wTw = fit_whitening(H_T[gix["fit"]])
|
| 63 |
+
tmu = torch.tensor(muT, dtype=torch.float32, device=DEV)
|
| 64 |
+
tw = torch.tensor(wTw, dtype=torch.float32, device=DEV)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def frame_readout(h):
|
| 68 |
+
return F.normalize(((h - tmu) @ tw) @ W_S, dim=-1)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def fit_seq_g(E_use):
|
| 72 |
+
"""G_i: 256->512 per piece position, lstsq on fit states with
|
| 73 |
+
k > i. Returns (list of G, per-position held-out residual)."""
|
| 74 |
+
Gs, res = [], []
|
| 75 |
+
for i in range(KMAX):
|
| 76 |
+
fs = [int(u) for u in gfit if kk[u] > i]
|
| 77 |
+
ps = [int(u) for u in gprobe if kk[u] > i]
|
| 78 |
+
a = E_use[torch.tensor(fs, device=DEV)].double().cpu().numpy()
|
| 79 |
+
b = emb[torch.tensor([ids_of[u][i] for u in fs], device=DEV)
|
| 80 |
+
].double().cpu().numpy()
|
| 81 |
+
g, *_ = np.linalg.lstsq(a, b, rcond=None)
|
| 82 |
+
if ps:
|
| 83 |
+
ah = E_use[torch.tensor(ps, device=DEV)
|
| 84 |
+
].double().cpu().numpy()
|
| 85 |
+
bh = emb[torch.tensor([ids_of[u][i] for u in ps],
|
| 86 |
+
device=DEV)].double().cpu().numpy()
|
| 87 |
+
res.append(round(float(np.linalg.norm(ah @ g - bh)
|
| 88 |
+
/ np.linalg.norm(bh)), 4))
|
| 89 |
+
Gs.append(torch.tensor(g, dtype=torch.float32, device=DEV))
|
| 90 |
+
return Gs, res
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
G_byte, res_byte = fit_seq_g(E_C)
|
| 94 |
+
E_rand = F.normalize(torch.randn_like(E_C), dim=-1)
|
| 95 |
+
G_rand, res_rand = fit_seq_g(E_rand)
|
| 96 |
+
print(f"[v02e] held-out residuals byte={res_byte} rand={res_rand}",
|
| 97 |
+
flush=True)
|
| 98 |
+
|
| 99 |
+
lines = open(r"E:\mirel\data\bytelex\codex_v1.txt",
|
| 100 |
+
"rb").read().decode("ascii").split("\n")
|
| 101 |
+
line_tok = {}
|
| 102 |
+
def enc_line(li):
|
| 103 |
+
if li not in line_tok:
|
| 104 |
+
e = tkA(lines[li], return_offsets_mapping=True)
|
| 105 |
+
line_tok[li] = (e["input_ids"], e["offset_mapping"])
|
| 106 |
+
return line_tok[li]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
probe_by_k = {}
|
| 110 |
+
for u in gprobe:
|
| 111 |
+
probe_by_k.setdefault(int(kk[u]), []).append(int(u))
|
| 112 |
+
ev_cand = [k for k in gix["eval"]
|
| 113 |
+
if int(kk[sid[k]]) in probe_by_k
|
| 114 |
+
and len(probe_by_k[int(kk[sid[k]])]) > 1
|
| 115 |
+
and KK[k, 1] == int(kk[sid[k]])]
|
| 116 |
+
rng = np.random.default_rng(SEED + 31)
|
| 117 |
+
ev_cand = rng.permutation(ev_cand)[:1200]
|
| 118 |
+
print(f"[v02e] probe sites: {len(ev_cand)}", flush=True)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def probe(Gs, E_use, tag):
|
| 122 |
+
flips = stuck = n = 0
|
| 123 |
+
div = 0.0
|
| 124 |
+
nb = 0
|
| 125 |
+
rngp = np.random.default_rng(SEED + 37)
|
| 126 |
+
BS = 48
|
| 127 |
+
for i in range(0, len(ev_cand), BS):
|
| 128 |
+
seqs, spans, alts, poss = [], [], [], []
|
| 129 |
+
for k in ev_cand[i:i + BS]:
|
| 130 |
+
li = int(dump["line"][k])
|
| 131 |
+
ids, off = enc_line(li)
|
| 132 |
+
lo, hi = int(dump["lo"][k]), int(dump["hi"][k])
|
| 133 |
+
ix = [j for j, (s, t) in enumerate(off)
|
| 134 |
+
if t > s and s < hi and t > lo]
|
| 135 |
+
u = int(sid[k])
|
| 136 |
+
cand = probe_by_k[int(kk[u])]
|
| 137 |
+
up = cand[int(rngp.integers(0, len(cand)))]
|
| 138 |
+
while up == u:
|
| 139 |
+
up = cand[int(rngp.integers(0, len(cand)))]
|
| 140 |
+
if len(ix) != int(kk[u]):
|
| 141 |
+
continue
|
| 142 |
+
seqs.append(ids)
|
| 143 |
+
spans.append(ix)
|
| 144 |
+
alts.append(up)
|
| 145 |
+
poss.append(ix[0])
|
| 146 |
+
if not seqs:
|
| 147 |
+
continue
|
| 148 |
+
mx = max(len(s) for s in seqs)
|
| 149 |
+
idt = torch.full((len(seqs), mx), tkA.pad_token_id,
|
| 150 |
+
dtype=torch.long)
|
| 151 |
+
att = torch.zeros((len(seqs), mx), dtype=torch.long)
|
| 152 |
+
for j, s in enumerate(seqs):
|
| 153 |
+
idt[j, :len(s)] = torch.tensor(s)
|
| 154 |
+
att[j, :len(s)] = 1
|
| 155 |
+
idt, att = idt.to(DEV), att.to(DEV)
|
| 156 |
+
with torch.no_grad():
|
| 157 |
+
clean = mT(input_ids=idt, attention_mask=att,
|
| 158 |
+
output_hidden_states=True).hidden_states[L_T5]
|
| 159 |
+
x = emb[idt].clone()
|
| 160 |
+
for j, (ix, up) in enumerate(zip(spans, alts)):
|
| 161 |
+
for pi, p in enumerate(ix):
|
| 162 |
+
x[j, p] = E_use[up] @ Gs[pi]
|
| 163 |
+
subh = mT(inputs_embeds=x, attention_mask=att,
|
| 164 |
+
output_hidden_states=True).hidden_states[L_T5]
|
| 165 |
+
div += float((((subh - clean) ** 2).sum(-1) * att).sum()
|
| 166 |
+
/ att.sum() / (clean ** 2).sum(-1).mean())
|
| 167 |
+
nb += 1
|
| 168 |
+
zr = frame_readout(subh[torch.arange(len(seqs)),
|
| 169 |
+
torch.tensor(poss, device=DEV)])
|
| 170 |
+
pred = (zr @ E_Cn.T).argmax(-1).cpu().numpy()
|
| 171 |
+
flips += int((pred == np.array(alts)).sum())
|
| 172 |
+
stuck += int((pred == np.array(
|
| 173 |
+
[sid[k] for k in ev_cand[i:i + BS]][:len(seqs)])).sum())
|
| 174 |
+
n += len(seqs)
|
| 175 |
+
return {"n": n, "flip_to_injected": round(flips / max(n, 1), 4),
|
| 176 |
+
"stuck_on_true": round(stuck / max(n, 1), 4),
|
| 177 |
+
"rel_divergence": round(div / max(nb, 1), 4)}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
res = {"byte_codebook": probe(G_byte, E_C, "byte"),
|
| 181 |
+
"random_codebook_control": probe(G_rand, E_rand, "rand"),
|
| 182 |
+
"heldout_residuals": {"byte": res_byte, "random": res_rand},
|
| 183 |
+
"g_split": {"usable": int(len(usable)), "fit": int(len(gfit)),
|
| 184 |
+
"probe": int(len(gprobe))},
|
| 185 |
+
"_env": {"transformers": transformers.__version__,
|
| 186 |
+
"torch": torch.__version__}}
|
| 187 |
+
with open(rf"{D}\v02_entry_ledger.json", "w", encoding="utf-8") as f:
|
| 188 |
+
json.dump(res, f, indent=1)
|
| 189 |
+
print(json.dumps(res, indent=1), flush=True)
|
| 190 |
+
print("[v02e] SEQUENCE ENTRY COMPLETE", flush=True)
|