suchirsalhan commited on
Commit
e87a0a7
·
verified ·
1 Parent(s): 1c22b92

Upload code/set4_goldfish.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/set4_goldfish.py +223 -0
code/set4_goldfish.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SET 4: Goldfish monolingual -> bilingual merge on the REAL composition models.
2
+ goldfish-models/eng_latn_1000mb x goldfish-models/{nld,spa,ell,pol}_*_1000mb (GPT-2, 125M each,
3
+ SEPARATE monolingual tokenizers). Rungs: M0 naive average (the merge the manuscript reports as
4
+ failing) vs M1 vocab-remapped + unit-aligned (permutation / Procrustes on the residual basis,
5
+ free MLP axis, attention heads).
6
+
7
+ METRIC: Delta-floor in NATS PER UTF-8 BYTE on FLORES-200 devtest. Bytes, not tokens: the two
8
+ parents use different tokenizers, so nats/token is not comparable across them. This is a
9
+ LIKELIHOOD metric, not benchmark accuracy."""
10
+ import os, sys, json, time, argparse, gc
11
+ sys.path.insert(0, "/root/compose-audit")
12
+ from common import *
13
+ import gpt2_align as G2
14
+ from mergeschool.core.models import load_hf
15
+
16
+ ap = argparse.ArgumentParser()
17
+ ap.add_argument("--pairs", default="nld_Latn:nld_latn,spa_Latn:spa_latn,ell_Grek:ell_grek,pol_Latn:pol_latn")
18
+ ap.add_argument("--n_sent", type=int, default=500)
19
+ ap.add_argument("--bs", type=int, default=8)
20
+ ap.add_argument("--barrier_n", type=int, default=7)
21
+ A = ap.parse_args()
22
+ OUT = "/root/compose-audit/results/set4_goldfish.jsonl"
23
+ DEV = "cuda"
24
+ ENG_REPO = "goldfish-models/eng_latn_1000mb"
25
+
26
+
27
+ def log(*a):
28
+ print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True)
29
+
30
+
31
+ # ------------------------------------------------------------------ tokenizer-invariant eval
32
+ def build_blocks(tok, text, block=512, max_blocks=64):
33
+ ids = tok(text)["input_ids"]
34
+ n = max(1, min(max_blocks, len(ids) // block))
35
+ ids = ids[: n * block]
36
+ arr = torch.from_numpy(np.asarray(ids, dtype=np.int64).reshape(n, block))
37
+ nbytes = sum(len(tok.decode(list(arr[i, 1:].numpy())).encode("utf-8")) for i in range(n))
38
+ return arr, nbytes
39
+
40
+
41
+ @torch.no_grad()
42
+ def nll_total(model, blocks, dev, bs=8):
43
+ tot, ntok = 0.0, 0
44
+ for i in range(0, blocks.shape[0], bs):
45
+ x = blocks[i:i + bs].to(dev)
46
+ lp = torch.log_softmax(model(x).logits.float()[:, :-1], -1)
47
+ tgt = x[:, 1:]
48
+ tot += (-lp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1)).sum().item()
49
+ ntok += tgt.numel()
50
+ return tot, ntok
51
+
52
+
53
+ @torch.no_grad()
54
+ def sent_acts(model, tok, lines, dev, bs=16, maxlen=128):
55
+ """Mean-pooled per-sentence residual activations, {layer: (n_sent, d)} -- rows are matched
56
+ ACROSS LANGUAGES by FLORES sentence id, which is what makes a cross-lingual basis map fittable."""
57
+ outs = None
58
+ for i in range(0, len(lines), bs):
59
+ enc = tok(lines[i:i + bs], return_tensors="pt", padding=True, truncation=True, max_length=maxlen)
60
+ ids = enc["input_ids"].to(dev); am = enc["attention_mask"].to(dev).float()
61
+ hs = model(ids, attention_mask=enc["attention_mask"].to(dev), output_hidden_states=True).hidden_states
62
+ if outs is None:
63
+ outs = [[] for _ in hs]
64
+ w = am / am.sum(1, keepdim=True).clamp(min=1)
65
+ for j, h in enumerate(hs):
66
+ outs[j].append((h.float() * w.unsqueeze(-1)).sum(1).cpu())
67
+ return {j: torch.cat(o).numpy().astype(np.float64) for j, o in enumerate(outs)}
68
+
69
+
70
+ # ------------------------------------------------------------------ load English parent
71
+ log("loading eng parent")
72
+ m_e, tok_e = load_hf(ENG_REPO, dtype=torch.float32, device=DEV)
73
+ m_e.eval()
74
+ cfg = m_e.config
75
+ D, NH, NL, V = cfg.n_embd, cfg.n_head, cfg.n_layer, cfg.vocab_size
76
+ SD_E = sd_np(m_e)
77
+ log(f"gpt2 d={D} heads={NH} layers={NL} vocab={V}")
78
+
79
+ eng_lines = flores_lines("eng_Latn")[: A.n_sent]
80
+ eng_text = "\n".join(eng_lines)
81
+ bl_e_e, by_e_e = build_blocks(tok_e, eng_text) # eng text, eng tokenizer
82
+ acts_e = sent_acts(m_e, tok_e, eng_lines, DEV)
83
+ shell = m_e # reuse as the eval shell (eng tokenizer space)
84
+
85
+
86
+ def ev_np(sd, blocks):
87
+ sd_load(shell, sd, DEV)
88
+ t, n = nll_total(shell, blocks, DEV, bs=A.bs)
89
+ return t, n
90
+
91
+
92
+ nll_e_eng_t, nll_e_eng_n = nll_total(m_e, bl_e_e, DEV, bs=A.bs)
93
+ PARENT_ENG = {"nats_per_byte": nll_e_eng_t / by_e_e, "nats_per_token": nll_e_eng_t / nll_e_eng_n}
94
+ log(f"eng parent on eng: {PARENT_ENG}")
95
+
96
+ done = set()
97
+ if os.path.exists(OUT):
98
+ for line in open(OUT):
99
+ try: done.add(json.loads(line)["lang"])
100
+ except Exception: pass
101
+ fh = open(OUT, "a")
102
+
103
+ for spec in A.pairs.split(","):
104
+ fcode, gcode = spec.split(":")
105
+ if fcode in done:
106
+ log("skip", fcode); continue
107
+ t0 = time.time()
108
+ repo = f"goldfish-models/{gcode}_1000mb"
109
+ log(f"=== {fcode} <- {repo}")
110
+ m_x, tok_x = load_hf(repo, dtype=torch.float32, device=DEV); m_x.eval()
111
+ SD_X = sd_np(m_x)
112
+ x_lines = flores_lines(fcode)[: A.n_sent]
113
+ x_text = "\n".join(x_lines)
114
+ bl_x_x, by_x_x = build_blocks(tok_x, x_text) # X text, X tokenizer (X parent's own floor)
115
+ bl_x_e, by_x_e = build_blocks(tok_e, x_text) # X text, ENG tokenizer (merged model's space)
116
+ acts_x = sent_acts(m_x, tok_x, x_lines, DEV)
117
+ tx, nx = nll_total(m_x, bl_x_x, DEV, bs=A.bs)
118
+ parent_x = {"nats_per_byte": tx / by_x_x, "nats_per_token": tx / nx}
119
+ del m_x; torch.cuda.empty_cache()
120
+ te, ne = ev_np(SD_E, bl_x_e) # eng parent on X text
121
+ eng_on_x = {"nats_per_byte": te / by_x_e, "nats_per_token": te / ne}
122
+ log(f" parents: eng/eng={PARENT_ENG['nats_per_byte']:.4f} x/x={parent_x['nats_per_byte']:.4f} "
123
+ f"eng-on-x={eng_on_x['nats_per_byte']:.4f} nats/byte")
124
+
125
+ # ------------- vocabulary transport (the OTHER axis: token ids, not the residual basis)
126
+ vkeys = [k for k in SD_X if k.endswith("wte.weight") or k.endswith("lm_head.weight")]
127
+ SD_X_V, cov = AL.remap_vocab_rows(SD_X, tok_e, tok_x, V, keys=vkeys)
128
+ for k in vkeys:
129
+ W = np.asarray(SD_X_V[k], float)
130
+ bad = ~np.isfinite(W).all(axis=1) if W.shape[0] == V else ~np.isfinite(W).all(axis=0)
131
+ if W.shape[0] == V:
132
+ W[bad] = np.asarray(SD_E[k], float)[bad] # unshared ids: keep English's row (no-op merge)
133
+ SD_X_V[k] = W
134
+ anchors = AL.vocab_anchors(tok_e, tok_x)
135
+ log(f" vocab anchors={len(anchors)} ({len(anchors)/V:.1%} of English ids)")
136
+
137
+ BODY = [k for k in SD_E if not (k.endswith("wte.weight") or k.endswith("lm_head.weight"))]
138
+
139
+ # ------------- alignments (fitted BEFORE merging)
140
+ sdp, ip = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "permutation", body_keys=BODY)
141
+ sdo, io = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY)
142
+ sdpf, ipf = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "permutation", body_keys=BODY, accept_each=False)
143
+ sdof, iof = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY, accept_each=False)
144
+ log(f" align perm={ip} orth={io}")
145
+
146
+ # ------------- predictors (pre-merge)
147
+ KEYS = shared_keys(SD_E, SD_X)
148
+ fa, fb = flat(SD_E, KEYS), flat(SD_X, KEYS)
149
+ p = {"weight_cosine": float(fa @ fb / (np.linalg.norm(fa) * np.linalg.norm(fb))),
150
+ "vocab_overlap": len(anchors) / V}
151
+ p["weight_cosine_body"] = float(np.mean([
152
+ float(np.asarray(SD_E[k], float).ravel() @ np.asarray(SD_X[k], float).ravel() /
153
+ (np.linalg.norm(SD_E[k]) * np.linalg.norm(SD_X[k]) + 1e-12)) for k in BODY]))
154
+ q_p = MT.quotient_weight_distance(SD_E, SD_X_V, sdp, BODY)
155
+ q_o = MT.quotient_weight_distance(SD_E, SD_X_V, sdo, BODY)
156
+ p.update({"d_raw": q_p["d_raw"], "qmd_perm": q_p["qmd"], "coord_share_perm": q_p["coord_fraction"],
157
+ "qmd_orth": q_o["qmd"], "coord_share_orth": q_o["coord_fraction"]})
158
+ b_raw = AL.block_normalised_distance(SD_E, SD_X_V, BODY)
159
+ b_p = AL.block_normalised_distance(SD_E, sdp, BODY)
160
+ b_o = AL.block_normalised_distance(SD_E, sdo, BODY)
161
+ p.update({"bnd_raw": b_raw, "bnd_perm": b_p, "bnd_orth": b_o,
162
+ "coord_share_bnd_perm": float((b_raw - b_p) / b_raw),
163
+ "coord_share_bnd_orth": float((b_raw - b_o) / b_raw)})
164
+ ck, ckby = mean_cka(acts_e, acts_x)
165
+ p["cka_mean"] = ck; p["cka_last"] = ckby[max(ckby)]
166
+ for g in ("perm", "procrustes", "ot"):
167
+ try:
168
+ qr = MT.quotient_residual(acts_e[NL // 2], acts_x[NL // 2], group=g)
169
+ p[f"qmd_act_{g}"] = qr["distance"]; p[f"aligned_cka_{g}"] = qr["aligned_cka"]
170
+ except Exception:
171
+ p[f"qmd_act_{g}"] = float("nan")
172
+
173
+ # ------------- merge rungs
174
+ rungs = {"M0_naive_avg": MG.average([SD_E, SD_X]),
175
+ "M1a_vocab_avg": MG.average([SD_E, SD_X_V]),
176
+ "M1b_vocab_perm_avg": MG.average([SD_E, sdp]),
177
+ "M1c_vocab_orth_avg": MG.average([SD_E, sdo]),
178
+ "M1d_vocab_perm_forced": MG.average([SD_E, sdpf]),
179
+ "M1e_vocab_orth_forced": MG.average([SD_E, sdof]),
180
+ "M1f_perm_novocab": MG.average([SD_E, G2.align_full(SD_E, SD_X, D, NH, acts_e, acts_x, "permutation", body_keys=BODY)[0]])}
181
+ res = {}
182
+ for name, sd in rungs.items():
183
+ t_e, n_e = ev_np(sd, bl_e_e)
184
+ t_x, n_x = ev_np(sd, bl_x_e)
185
+ res[name] = {
186
+ "eng": {"nats_per_byte": t_e / by_e_e, "nats_per_token": t_e / n_e},
187
+ "x": {"nats_per_byte": t_x / by_x_e, "nats_per_token": t_x / n_x},
188
+ "delta_floor_eng": t_e / by_e_e - PARENT_ENG["nats_per_byte"],
189
+ "delta_floor_x": t_x / by_x_e - min(parent_x["nats_per_byte"], eng_on_x["nats_per_byte"]),
190
+ }
191
+ res[name]["delta_floor_mean"] = 0.5 * (res[name]["delta_floor_eng"] + res[name]["delta_floor_x"])
192
+ for name in res:
193
+ res[name]["delta_vs_naive_mean"] = res[name]["delta_floor_mean"] - res["M0_naive_avg"]["delta_floor_mean"]
194
+
195
+ r = {"set": "set4_goldfish", "lang": fcode, "repo_a": ENG_REPO, "repo_b": repo,
196
+ "corpus": "flores200_devtest", "n_sent": A.n_sent,
197
+ "metric": "nats_per_utf8_byte (likelihood, NOT benchmark accuracy)",
198
+ "parents": {"eng_on_eng": PARENT_ENG, "x_on_x": parent_x, "eng_on_x": eng_on_x},
199
+ "floor_eng": PARENT_ENG["nats_per_byte"],
200
+ "floor_x": min(parent_x["nats_per_byte"], eng_on_x["nats_per_byte"]),
201
+ "align_info": {"perm": ip, "orth": io, "perm_forced": ipf, "orth_forced": iof}, "predictors": p, "rungs": res}
202
+
203
+ # ------------- barriers on the mean nats/byte
204
+ def ev_mean(sd):
205
+ t_e, _ = ev_np(sd, bl_e_e); t_x, _ = ev_np(sd, bl_x_e)
206
+ return 0.5 * (t_e / by_e_e + t_x / by_x_e)
207
+ try:
208
+ bn = EV.merge_barrier(SD_E, SD_X, ev_mean, n=A.barrier_n)
209
+ r["barrier_naive"] = {"barrier": bn["barrier"], "losses": list(map(float, bn["losses"]))}
210
+ bp = EV.merge_barrier(SD_E, sdp, ev_mean, n=A.barrier_n)
211
+ r["barrier_perm"] = {"barrier": bp["barrier"], "losses": list(map(float, bp["losses"]))}
212
+ except Exception as e:
213
+ log("barrier failed", e)
214
+
215
+ r["secs"] = time.time() - t0
216
+ fh.write(json.dumps(r) + "\n"); fh.flush()
217
+ log(f" {fcode}: M0 dfloor_mean={res['M0_naive_avg']['delta_floor_mean']:+.4f} "
218
+ f"M1a={res['M1a_vocab_avg']['delta_floor_mean']:+.4f} "
219
+ f"M1b_perm={res['M1b_vocab_perm_avg']['delta_floor_mean']:+.4f} "
220
+ f"M1c_orth={res['M1c_vocab_orth_avg']['delta_floor_mean']:+.4f} ({r['secs']:.0f}s)")
221
+ del rungs, sdp, sdo, sdpf, sdof, SD_X, SD_X_V; gc.collect()
222
+ fh.close()
223
+ log("DONE set4")