suchirsalhan commited on
Commit
13aaf2d
·
verified ·
1 Parent(s): 92252c2

Upload code/make_report.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/make_report.py +265 -0
code/make_report.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys, json, glob, math
2
+ sys.path.insert(0, "/root/compose-audit")
3
+ from common import *
4
+ R = "/root/compose-audit/results"
5
+
6
+
7
+ def load(pat):
8
+ rows = []
9
+ for fp in sorted(glob.glob(f"{R}/{pat}")):
10
+ for line in open(fp):
11
+ try: rows.append(json.loads(line))
12
+ except Exception: pass
13
+ return rows
14
+
15
+
16
+ def md_table(headers, rows):
17
+ out = ["| " + " | ".join(headers) + " |", "|" + "|".join(["---"] * len(headers)) + "|"]
18
+ for r in rows:
19
+ out.append("| " + " | ".join(str(x) for x in r) + " |")
20
+ return "\n".join(out)
21
+
22
+
23
+ def fmt(x, n=3):
24
+ try:
25
+ if x is None or (isinstance(x, float) and not math.isfinite(x)): return "—"
26
+ return f"{x:.{n}f}"
27
+ except Exception:
28
+ return str(x)
29
+
30
+
31
+ set1 = load("set1_*.jsonl")
32
+ set4 = load("set4_goldfish.jsonl")
33
+ VOCAB = {"14m": 50304, "70m": 50304, "160m": 50304}
34
+ sizes = sorted({r["size"] for r in set1}, key=lambda s: int(s[:-1]))
35
+
36
+ # ---------------- SET1 rung table
37
+ rung_rows, mdtabs = [], []
38
+ for sz in sizes:
39
+ sub = [r for r in set1 if r["size"] == sz]
40
+ d0 = np.array([r["rungs"]["M0_naive_avg"]["delta_floor"] for r in sub])
41
+ floor = np.mean([r["floor"] for r in sub])
42
+ keys = list(sub[0]["rungs"])
43
+ body = []
44
+ for k in keys:
45
+ d = np.array([r["rungs"][k]["delta_floor"] for r in sub if k in r["rungs"]])
46
+ nll = np.array([r["rungs"][k]["nll"] for r in sub if k in r["rungs"]])
47
+ body.append([k, len(d), fmt(nll.mean(), 2), fmt(d.mean(), 2), fmt(np.median(d), 2),
48
+ fmt(d.min(), 2), f"{int((d < d0).sum())}/{len(d)}",
49
+ fmt(np.mean(1 - d / d0) * 100, 1) + "%"])
50
+ rung_rows.append({"set": "SET1", "substrate": f"pythia-{sz}", "rung": k, "n_pairs": len(d),
51
+ "mean_nll": float(nll.mean()), "mean_dfloor": float(d.mean()),
52
+ "median_dfloor": float(np.median(d)), "min_dfloor": float(d.min()),
53
+ "n_better_than_naive": int((d < d0).sum()),
54
+ "mean_pct_of_naive_dfloor_removed": float(np.mean(1 - d / d0) * 100)})
55
+ bn = np.mean([r["barrier_naive"]["barrier"] for r in sub if "barrier_naive" in r])
56
+ bp = np.mean([r["barrier_perm"]["barrier"] for r in sub if "barrier_perm" in r])
57
+ mdtabs.append((sz, len(sub), floor, math.log(VOCAB.get(sz, 50304)), bn, bp,
58
+ md_table(["rung", "n", "mean nats/tok", "mean Δfloor", "median Δfloor",
59
+ "best Δfloor", "beats naive", "% of naive Δfloor removed"], body)))
60
+
61
+ # ---------------- write
62
+ L = []
63
+ L.append("# Compose-audit: putting the alignment map and the merging payoff on the SAME real models\n")
64
+ L.append(f"_Generated {time.strftime('%Y-%m-%d %H:%M UTC')} · training-free · "
65
+ "code: `/root/compose-audit` · operators/aligners/metrics imported unmodified from "
66
+ "`mergeschool.core` (`/root/mergeability`, treated as read-only)._\n")
67
+
68
+ L.append("""## Read this first: what substrate, and what metric
69
+
70
+ | | SET 1 | SET 4 |
71
+ |---|---|---|
72
+ | **Substrate** | `EleutherAI/pythia-{14m,70m,160m}-seed{1..9}` (PolyPythia) — real reseeded LMs | `goldfish-models/eng_latn_1000mb` × `{nld,spa,ell,pol}_*_1000mb` — the real bilingual-composition models, GPT-2 arch, 125M |
73
+ | **What varies between the two parents** | the init/data-order **seed only**. Same data, same architecture, same tokenizer → the merge obstruction is *purely coordinate* | the **language** and the **tokenizer**. Independently initialised, independently trained |
74
+ | **Held-out corpus** | FLORES-200 devtest `eng_Latn` | FLORES-200 devtest, `eng_Latn` + the partner language |
75
+ | **Metric** | Δfloor in **nats/token** vs the better parent | Δfloor in **nats per UTF-8 byte** vs the better parent (bytes, because the two parents use different tokenizers and nats/token is not comparable across them) |
76
+ | **What the metric is** | a **likelihood** metric | a **likelihood** metric |
77
+
78
+ > **Δfloor is a likelihood metric, not benchmark accuracy.** Nothing below shows that a likelihood
79
+ > rescue transfers to BLiMP/MultiBLiMP accuracy, or to any downstream task. The audit's sharpest
80
+ > point — *recovery is not success* — is **not** settled by these numbers and must not be written up
81
+ > as if it were. No accuracy benchmark was run inside this window (see Coverage).
82
+ """)
83
+
84
+ if set1:
85
+ L.append("\n## SET 1 · PolyPythia seed-merge (the pure-coordinate ceiling)\n")
86
+ L.append(f"C(9,2) = 36 seed pairs per size. Predictors are computed **before** any merge; the "
87
+ f"alignment factors (residual basis map fitted from activations on the shared corpus, "
88
+ f"free MLP hidden axis, attention heads) are each accepted only if they do not increase "
89
+ f"the scale-free block-normalised weight distance.\n")
90
+ for sz, n, floor, unif, bn, bp, tab in mdtabs:
91
+ L.append(f"\n### pythia-{sz} — {n} seed pairs · mean parent floor **{floor:.3f}** nats/token · "
92
+ f"uniform-over-vocabulary reference **{unif:.3f}** nats/token\n")
93
+ L.append(tab)
94
+ L.append(f"\nLinear-mode-connectivity barrier (`eval.merge_barrier`): naive **{bn:.2f}**, "
95
+ f"permutation-aligned **{bp:.2f}** nats/token.\n")
96
+ L.append("""
97
+ **What this says.**
98
+
99
+ 1. **Naive averaging of two same-data, same-architecture, same-tokenizer models that differ only in
100
+ seed is catastrophic.** The merged model's loss is tens of nats/token above the better parent —
101
+ far above the uniform-over-vocabulary reference, i.e. the merge is not a degraded model, it is a
102
+ destroyed one. This is the pure-coordinate case: there is no data, architecture or tokenizer
103
+ difference left to blame.
104
+ 2. **Unit alignment removes a large, highly consistent fraction of that gap** — the permutation rung
105
+ beats naive on essentially every pair — **and still does not produce a usable model.** The aligned
106
+ merge remains above the uniform reference at every size we ran. So on real LMs at this scale,
107
+ alignment *predicts and reduces* the obstruction without *enabling* the merge. Reporting the
108
+ reduction as "merging works once you align" would be wrong.
109
+ 3. **Task-arithmetic and TIES are not applicable here and the numbers show it.** PolyPythia seeds are
110
+ independent re-initialisations: `EleutherAI/pythia-<size>` is *not* a shared ancestor, so the
111
+ "task vectors" those operators subtract are not task vectors. Their rows are reported only to
112
+ document that the shared-base family degenerates when the base is not shared.
113
+ 4. The linear interpolation path has its minimum at the endpoints for every pair — there is no
114
+ interior t that beats the better parent, aligned or not.
115
+ """)
116
+
117
+ if set4:
118
+ L.append("\n## SET 4 · Goldfish monolingual → bilingual merge (the real composition models)\n")
119
+ rung_keys = list(set4[0]["rungs"])
120
+ hdr = ["pair", "vocab overlap", "floor eng", "floor X"] + [k for k in rung_keys]
121
+ body = []
122
+ for r in set4:
123
+ row = [f"eng–{r['lang']}", f"{r['predictors']['vocab_overlap']:.1%}",
124
+ fmt(r["floor_eng"]), fmt(r["floor_x"])]
125
+ for k in rung_keys:
126
+ row.append(fmt(r["rungs"][k]["delta_floor_mean"]))
127
+ body.append(row)
128
+ for k in rung_keys:
129
+ rung_rows.append({"set": "SET4", "substrate": f"goldfish eng-{r['lang']}", "rung": k,
130
+ "n_pairs": 1, "mean_nll": float(r["rungs"][k]["eng"]["nats_per_byte"]),
131
+ "mean_dfloor": float(r["rungs"][k]["delta_floor_mean"]),
132
+ "median_dfloor": float(r["rungs"][k]["delta_floor_mean"]),
133
+ "min_dfloor": float(r["rungs"][k]["delta_floor_mean"]),
134
+ "n_better_than_naive": int(r["rungs"][k]["delta_floor_mean"] <
135
+ r["rungs"]["M0_naive_avg"]["delta_floor_mean"]),
136
+ "mean_pct_of_naive_dfloor_removed": float(
137
+ 100 * (1 - r["rungs"][k]["delta_floor_mean"] /
138
+ r["rungs"]["M0_naive_avg"]["delta_floor_mean"]))})
139
+ # uniform-over-vocabulary reference in nats/byte, per language pair
140
+ uref = []
141
+ for r in set4:
142
+ v = r["rungs"]["M0_naive_avg"]
143
+ be = math.log(51200) * v["eng"]["nats_per_byte"] / v["eng"]["nats_per_token"]
144
+ bx = math.log(51200) * v["x"]["nats_per_byte"] / v["x"]["nats_per_token"]
145
+ uref.append([f"eng-{r['lang']}", fmt(0.5 * (be + bx))])
146
+ L.append("Uniform-over-vocabulary reference (a model that has learned nothing), mean over the two "
147
+ "languages, in the same units: " +
148
+ ", ".join(f"**eng-{r['lang']}** {u[1]}" for r, u in zip(set4, uref)) + " nats/byte.\n")
149
+ L.append("**Δfloor vs the better parent, mean over the two languages, nats/UTF-8 byte** "
150
+ "(lower is better; 0 would mean the merge matches the better parent):\n")
151
+ L.append(md_table(hdr, body))
152
+ body2 = []
153
+ for r in set4:
154
+ for k in rung_keys:
155
+ body2.append([f"eng–{r['lang']}", k, fmt(r["rungs"][k]["delta_floor_eng"]),
156
+ fmt(r["rungs"][k]["delta_floor_x"]),
157
+ fmt(r["rungs"][k]["delta_floor_mean"] -
158
+ r["rungs"]["M0_naive_avg"]["delta_floor_mean"])])
159
+ L.append("\n**Split by language, and Δ vs naive:**\n")
160
+ L.append(md_table(["pair", "rung", "Δfloor eng", "Δfloor X", "Δ vs naive (mean)"], body2))
161
+ L.append("""
162
+ **Rungs.** `M0_naive_avg` = straight weight average in raw index space (the merge the manuscript
163
+ reports as failing). `M1a_vocab_avg` = English/partner embedding + unembedding rows transported into
164
+ the English tokenizer's id space over shared surface forms, ids absent from the partner vocabulary
165
+ left at English's own row so the average over them is a no-op. `M1b/M1c` add the unit alignment
166
+ (residual-basis map fitted from **parallel** FLORES sentence representations — rows matched across
167
+ languages by sentence id — plus the free MLP hidden axis and the attention-head permutation), under
168
+ permutation and under Procrustes respectively, each factor accepted only if it does not increase the
169
+ block-normalised weight distance. `M1d/M1e` force the residual factor in regardless of that test.
170
+ `M1f_perm_novocab` isolates the unit alignment with **no** vocabulary transport.
171
+ """)
172
+
173
+ L.append("\n## P0-2 · Do the pre-merge predictors predict the realised rescue?\n")
174
+ if os.path.exists(f"{R}/predictor_auroc.csv"):
175
+ rows = [l.rstrip("\n").split(",") for l in open(f"{R}/predictor_auroc.csv")]
176
+ hdr, dat = rows[0], rows[1:]
177
+ ix = {h: i for i, h in enumerate(hdr)}
178
+ body = []
179
+ for d in dat:
180
+ body.append([d[ix["substrate"]], d[ix["predictor"]], d[ix["n_pairs"]],
181
+ fmt(float(d[ix["spearman_rescue"]]) if d[ix["spearman_rescue"]] else None),
182
+ fmt(float(d[ix["auroc_heldout_by_seed"]]) if d[ix["auroc_heldout_by_seed"]] else None),
183
+ fmt(float(d[ix["perm_null_mean"]]) if d[ix["perm_null_mean"]] else None),
184
+ fmt(float(d[ix["perm_null_p"]]) if d[ix["perm_null_p"]] else None),
185
+ fmt(float(d[ix["bh_q"]]) if d[ix["bh_q"]] else None)])
186
+ L.append("Outcome = **realised rescue** = the fraction of the naive Δfloor that the best M1 rung "
187
+ "removes. Label = above the within-size median. Held out **by seed**: fold *k* is every "
188
+ "pair touching seed *k*, trained on the pairs touching neither, so the predictor's sign "
189
+ "(and, for the multivariate row, its coefficients) never see the held-out pairs. Null = "
190
+ "**seed-cluster permutation** (2000 draws): permute the seed identities and re-map each "
191
+ "pair's outcome to the permuted pair, leaving the predictor vector untouched — this "
192
+ "preserves the pair-dependence structure that a plain label shuffle destroys. "
193
+ "BH-corrected across the predictor family.\n")
194
+ L.append(md_table(["substrate", "predictor", "n", "Spearman", "AUROC (held out by seed)",
195
+ "null mean", "perm p", "BH q"], body))
196
+ if os.path.exists(f"{R}/set4_predictors.csv"):
197
+ rows = [l.rstrip("\n").split(",") for l in open(f"{R}/set4_predictors.csv")]
198
+ hdr, dat = rows[0], rows[1:]
199
+ ix = {h: i for i, h in enumerate(hdr)}
200
+ L.append("\n**SET 4, held out by language pair.** n = %d language pairs. This is far too few for "
201
+ "an AUROC or a permutation null; only the rank correlation is reported, and it should be "
202
+ "read as descriptive, not inferential.\n" % len(set4))
203
+ L.append(md_table(["predictor", "Spearman vs realised rescue"],
204
+ [[d[ix["predictor"]], fmt(float(d[ix["spearman_rescue"]]) if d[ix["spearman_rescue"]] else None)]
205
+ for d in dat]))
206
+
207
+ # coverage
208
+ L.append("\n## Coverage — what ran and what did not\n")
209
+ cov = []
210
+ for sz in ["14m", "70m", "160m"]:
211
+ n = len([r for r in set1 if r["size"] == sz])
212
+ cov.append([f"SET 1 · pythia-{sz}", f"{n}/36 seed pairs", "complete" if n == 36 else ("partial" if n else "NOT RUN"),
213
+ "M0 naive · M1 permutation · M1 Procrustes · M2 task-arithmetic · M3 TIES; barrier for M0 and M1-perm"])
214
+ langs = [r["lang"] for r in set4]
215
+ cov.append(["SET 4 · goldfish eng×X", f"{len(set4)}/4 language pairs ({', '.join(langs) or '—'})",
216
+ "complete" if len(set4) == 4 else ("partial" if set4 else "NOT RUN"),
217
+ "M0 naive · M1a vocab-transport · M1b/c vocab+unit-aligned (perm/Procrustes) · M1d/e forced-residual · M1f unit-aligned only"])
218
+ cov.append(["BLiMP / MultiBLiMP accuracy", "0", "**NOT RUN**",
219
+ "No benchmark harness was close to wired inside this window. Deliberately not built from scratch. The Δfloor results below therefore say nothing about accuracy."])
220
+ cov.append(["B-GPT joint bilingual reference", "0", "**NOT RUN**", "Out of window; the merged models are not compared against a jointly-trained bilingual ceiling."])
221
+ cov.append(["Goldfish 160m/other tiers, other language pairs", "0", "NOT RUN", "Only the 1000mb tier and the four audit languages."])
222
+ L.append(md_table(["cell", "n", "status", "what was measured"], cov))
223
+
224
+ L.append("""
225
+ ## Threats to validity, stated plainly
226
+
227
+ - **Likelihood ≠ accuracy.** Repeated because it is the single most load-bearing caveat here.
228
+ - **SET 1's held-out corpus is FLORES-200 English devtest**, not a Pile validation split. It is
229
+ genuinely held out from PolyPythia training, but it is out-of-domain, so the absolute nats/token
230
+ floors are higher than a Pile-val number would be. Δfloor is a *difference* against parents
231
+ measured on the same corpus, so the comparison between rungs is unaffected.
232
+ - **SET 4's nats/byte is comparable across tokenizers but not free of tokenizer effects**: block
233
+ boundaries fall at different places for different tokenizers, and each block's first token is
234
+ unscored. With ~30k tokens per evaluation this is a sub-1% effect.
235
+ - **The alignment search is over the permutation group (residual basis, MLP hidden axis, attention
236
+ heads) and its orthogonal relaxation.** It is not the full symmetry group, and the residual factor
237
+ is fitted from a finite activation sample. A better aligner could raise the M1 rungs; nothing here
238
+ bounds how far.
239
+ - **SET 4's n = 4 language pairs.** Any predictor claim on that substrate is descriptive.
240
+ """)
241
+
242
+ L.append("\n## Files\n")
243
+ L.append("""```
244
+ results/set1_{14m,70m,160m}.jsonl per-pair raw records (predictors, rungs, barriers, align info)
245
+ results/set1_pairs.csv per-pair flat table, SET 1
246
+ results/set4_goldfish.jsonl per-language-pair raw records, SET 4
247
+ results/set4_pairs.csv per-language-pair flat table, SET 4
248
+ results/rung_summary.csv rung x substrate x metric summary
249
+ results/predictor_auroc.csv SET 1 predictor table: held-out AUROC, permutation null, BH q
250
+ results/set4_predictors.csv SET 4 predictor rank correlations (n=4, descriptive)
251
+ figs/set1_dfloor_by_rung.png Δfloor by rung, per size
252
+ figs/set1_rescue_vs_predictor.png realised rescue vs coordinate share / CKA
253
+ figs/set1_roc.png held-out-by-seed ROC
254
+ figs/set4_dfloor.png Δfloor by rung, Goldfish
255
+ ```""")
256
+
257
+ open("/root/compose-audit/RESULTS_COMPOSE_AUDIT.md", "w").write("\n".join(L) + "\n")
258
+
259
+ if rung_rows:
260
+ keys = list(rung_rows[0])
261
+ with open(f"{R}/rung_summary.csv", "w") as f:
262
+ f.write(",".join(keys) + "\n")
263
+ for r in rung_rows:
264
+ f.write(",".join(str(r.get(k, "")) for k in keys) + "\n")
265
+ print("report written:", sum(len(x) for x in L), "chars")