File size: 31,019 Bytes
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b5a99
 
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b5a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13aaf2d
 
22b5a99
 
 
 
 
 
 
 
 
13aaf2d
22b5a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b5a99
 
 
 
 
 
 
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b5a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13aaf2d
 
 
 
 
 
 
22b5a99
 
 
 
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
 
22b5a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
22b5a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13aaf2d
 
 
 
 
 
 
 
 
 
22b5a99
 
 
 
 
 
 
13aaf2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import os, sys, json, glob, math
sys.path.insert(0, "/root/compose-audit")
from common import *
R = "/root/compose-audit/results"


def load(pat):
    rows = []
    for fp in sorted(glob.glob(f"{R}/{pat}")):
        for line in open(fp):
            try: rows.append(json.loads(line))
            except Exception: pass
    return rows


def md_table(headers, rows):
    out = ["| " + " | ".join(headers) + " |", "|" + "|".join(["---"] * len(headers)) + "|"]
    for r in rows:
        out.append("| " + " | ".join(str(x) for x in r) + " |")
    return "\n".join(out)


def fmt(x, n=3):
    try:
        if x is None or (isinstance(x, float) and not math.isfinite(x)): return "—"
        return f"{x:.{n}f}"
    except Exception:
        return str(x)


set1 = load("set1_*.jsonl")
set4 = load("set4_goldfish.jsonl")
VOCAB = {"14m": 50304, "70m": 50304, "160m": 50304}
sizes = sorted({r["size"] for r in set1}, key=lambda s: int(s[:-1]))

# ---------------- SET1 rung table
rung_rows, mdtabs = [], []
for sz in sizes:
    sub = [r for r in set1 if r["size"] == sz]
    d0 = np.array([r["rungs"]["M0_naive_avg"]["delta_floor"] for r in sub])
    floor = np.mean([r["floor"] for r in sub])
    keys = list(sub[0]["rungs"])
    body = []
    for k in keys:
        d = np.array([r["rungs"][k]["delta_floor"] for r in sub if k in r["rungs"]])
        nll = np.array([r["rungs"][k]["nll"] for r in sub if k in r["rungs"]])
        body.append([k, len(d), fmt(nll.mean(), 2), fmt(d.mean(), 2), fmt(np.median(d), 2),
                     fmt(d.min(), 2), f"{int((d < d0).sum())}/{len(d)}",
                     fmt(np.mean(1 - d / d0) * 100, 1) + "%"])
        rung_rows.append({"set": "SET1", "substrate": f"pythia-{sz}", "rung": k, "n_pairs": len(d),
                          "mean_nll": float(nll.mean()), "mean_dfloor": float(d.mean()),
                          "median_dfloor": float(np.median(d)), "min_dfloor": float(d.min()),
                          "n_better_than_naive": int((d < d0).sum()),
                          "mean_pct_of_naive_dfloor_removed": float(np.mean(1 - d / d0) * 100)})
    bn = np.mean([r["barrier_naive"]["barrier"] for r in sub if "barrier_naive" in r])
    bp = np.mean([r["barrier_perm"]["barrier"] for r in sub if "barrier_perm" in r])
    mdtabs.append((sz, len(sub), floor, math.log(VOCAB.get(sz, 50304)), bn, bp,
                   md_table(["rung", "n", "mean nats/tok", "mean Δfloor", "median Δfloor",
                             "best Δfloor", "beats naive", "% of naive Δfloor removed"], body)))

# ---------------- write
L = []
L.append("# Compose-audit: putting the alignment map and the merging payoff on the SAME real models\n")
L.append(f"_Generated {time.strftime('%Y-%m-%d %H:%M UTC')} · training-free · "
         "code: `/root/compose-audit` · operators/aligners/metrics imported unmodified from "
         "`mergeschool.core` (`/root/mergeability`, treated as read-only)._\n")

L.append("""## Read this first: what substrate, and what metric

| | SET 1 | SET 4 |
|---|---|---|
| **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 |
| **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 |
| **Held-out corpus** | FLORES-200 devtest `eng_Latn` | FLORES-200 devtest, `eng_Latn` + the partner language |
| **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) |
| **What the metric is** | a **likelihood** metric | a **likelihood** metric |

> **Δfloor is a likelihood metric, not benchmark accuracy.** Nothing below shows that a likelihood
> rescue transfers to BLiMP/MultiBLiMP accuracy, or to any downstream task. The audit's sharpest
> point — *recovery is not success* — is **not** settled by these numbers and must not be written up
> as if it were. **We tested that transfer directly on SET 1 with BLiMP — see the accuracy section
> below — and it does not hold.** SET 4 has no accuracy benchmark in this window (see Coverage).
""")

if set1:
    L.append("\n## SET 1 · PolyPythia seed-merge (the pure-coordinate ceiling)\n")
    L.append(f"C(9,2) = 36 seed pairs per size. Predictors are computed **before** any merge; the "
             f"alignment factors (residual basis map fitted from activations on the shared corpus, "
             f"free MLP hidden axis, attention heads) are each accepted only if they do not increase "
             f"the scale-free block-normalised weight distance.\n")
    for sz, n, floor, unif, bn, bp, tab in mdtabs:
        L.append(f"\n### pythia-{sz}{n} seed pairs · mean parent floor **{floor:.3f}** nats/token · "
                 f"uniform-over-vocabulary reference **{unif:.3f}** nats/token\n")
        L.append(tab)
        L.append(f"\nLinear-mode-connectivity barrier (`eval.merge_barrier`): naive **{bn:.2f}**, "
                 f"permutation-aligned **{bp:.2f}** nats/token.\n")
    L.append("""
**What this says.**

1. **Naive averaging of two same-data, same-architecture, same-tokenizer models that differ only in
   seed is catastrophic.** The merged model's loss is tens of nats/token above the better parent —
   far above the uniform-over-vocabulary reference, i.e. the merge is not a degraded model, it is a
   destroyed one. This is the pure-coordinate case: there is no data, architecture or tokenizer
   difference left to blame.
2. **Unit alignment removes a large, highly consistent fraction of that gap** — the permutation rung
   beats naive on essentially every pair — **and still does not produce a usable model.** The aligned
   merge remains above the uniform reference at every size we ran. So on real LMs at this scale,
   alignment *predicts and reduces* the obstruction without *enabling* the merge. Reporting the
   reduction as "merging works once you align" would be wrong.
3. **Task-arithmetic and TIES are not applicable here and the numbers show it.** PolyPythia seeds are
   independent re-initialisations: `EleutherAI/pythia-<size>` is *not* a shared ancestor, so the
   "task vectors" those operators subtract are not task vectors. Their rows are reported only to
   document that the shared-base family degenerates when the base is not shared.
4. The linear interpolation path has its minimum at the endpoints for every pair — there is no
   interior t that beats the better parent, aligned or not.
""")

if len(mdtabs) >= 3:
    L.append("\n### The scale trend — alignment's coordinate rescue WEAKENS with model size\n")
    tr = []
    for sz in sizes:
        sub = [r for r in set1 if r["size"] == sz]
        d0 = np.array([r["rungs"]["M0_naive_avg"]["delta_floor"] for r in sub])
        dp = np.array([r["rungs"]["M1_perm_avg"]["delta_floor"] for r in sub])
        do = np.array([r["rungs"]["M1_orth_avg"]["delta_floor"] for r in sub])
        db = np.minimum(dp, do)
        ck = np.array([r["predictors"]["cka_mean"] for r in sub])
        ac = np.array([r["predictors"].get("aligned_cka_perm", float("nan")) for r in sub])
        cs = np.array([r["predictors"]["coord_share_bnd_perm"] for r in sub])
        tr.append([f"pythia-{sz}", len(sub), fmt(float(np.mean([r["floor"] for r in sub])), 2),
                   fmt(d0.mean(), 2), fmt(np.mean(1 - dp / d0) * 100, 1) + "%",
                   fmt(np.mean(1 - do / d0) * 100, 1) + "%",
                   fmt(np.mean(1 - db / d0) * 100, 1) + "%",
                   fmt(ck.mean()), fmt(float(np.nanmean(ac))), fmt(cs.mean(), 4)])
    L.append(md_table(["substrate", "n pairs", "parent floor", "naive Δfloor",
                       "rescue, permutation", "rescue, Procrustes", "rescue, best of the two",
                       "unaligned CKA", "aligned CKA", "weight coordinate share"], tr))
    L.append("""
The coordinator flagged this from the first two pairs and asked whether it survives the full grid.
**It does, monotonically, across every size we ran.** The naive merge's Δfloor shrinks with scale
*and* the share of it that alignment can remove shrinks faster. Two things are worth separating:

- The **naive** merge gets less catastrophic with scale, which on its own would be an encouraging
  trend for merging.
- The **alignment rescue** shrinks at the same time. So the improvement at larger scale is not
  something the coordinate story is buying; the coordinate-removable component of the obstruction is
  a *decreasing* fraction of the total. Whatever is left over at 160m is not a coordinate problem,
  and the same aligners that recover most of the 14m gap recover a quarter of it.

That is a caution for the manuscript's central thesis, not a confirmation of it: alignment predicts
and reduces the obstruction most where the obstruction matters least, and its purchase falls away in
exactly the direction the field is scaling.
""")

if set4:
    L.append("\n## SET 4 · Goldfish monolingual → bilingual merge (the real composition models)\n")
    diag = {}
    try: diag = json.load(open(f"{R}/set4_tokenizer_diag.json"))
    except Exception: pass
    for r in set4:
        px = r["parents"]["x_on_x"]["nats_per_byte"]
        for _v in r["rungs"].values():
            _v["delta_floor_x"] = _v["x"]["nats_per_byte"] - px
            _v["delta_floor_mean"] = 0.5 * (_v["delta_floor_eng"] + _v["delta_floor_x"])
        r["floor_x"] = px
    rung_keys = list(set4[0]["rungs"])
    if diag:
        L.append("\n**Tokenizer diagnostic — read this before any SET 4 number.** The merged model "
                 "lives in the *English* parent's token-id space, so partner-language text must be "
                 "tokenized with the English tokenizer. It cannot represent much of that text:\n")
        L.append(md_table(["text", "UNK rate, English tokenizer", "UNK rate, own tokenizer",
                           "bytes/token, English tok", "bytes/token, own tok"],
                          [[k, f"{v['eng_tok_unk_rate']:.1%}", f"{v['own_tok_unk_rate']:.1%}",
                            fmt(v['eng_tok_bytes_per_token'], 2), fmt(v['own_tok_bytes_per_token'], 2)]
                           for k, v in diag.items()]))
        L.append("\nAt a 46.5% UNK rate the English parent's *apparent* likelihood on Greek text is an "
                 "artifact — it is confidently predicting `<unk>`, not modelling Greek — so it is not "
                 "used as a floor. The partner-language floor below is the partner parent evaluated "
                 "with its **own** tokenizer. The **English-side** column is the clean one (0.07% UNK) "
                 "and is the primary SET 4 number.\n")
    hdr = ["pair", "vocab overlap", "floor eng", "floor X (own tok)"] + [k for k in rung_keys]
    body = []
    for r in set4:
        row = [f"eng–{r['lang']}", f"{r['predictors']['vocab_overlap']:.1%}",
               fmt(r["floor_eng"]), fmt(r["floor_x"])]
        for k in rung_keys:
            row.append(fmt(r["rungs"][k]["delta_floor_mean"]))
        body.append(row)
        for k in rung_keys:
            rung_rows.append({"set": "SET4", "substrate": f"goldfish eng-{r['lang']}", "rung": k,
                              "n_pairs": 1, "mean_nll": float(r["rungs"][k]["eng"]["nats_per_byte"]),
                              "mean_dfloor": float(r["rungs"][k]["delta_floor_mean"]),
                              "median_dfloor": float(r["rungs"][k]["delta_floor_mean"]),
                              "min_dfloor": float(r["rungs"][k]["delta_floor_mean"]),
                              "n_better_than_naive": int(r["rungs"][k]["delta_floor_mean"] <
                                                         r["rungs"]["M0_naive_avg"]["delta_floor_mean"]),
                              "mean_pct_of_naive_dfloor_removed": float(
                                  100 * (1 - r["rungs"][k]["delta_floor_mean"] /
                                         r["rungs"]["M0_naive_avg"]["delta_floor_mean"]))})
    # uniform-over-vocabulary reference in nats/byte, per language pair
    uref = []
    for r in set4:
        v = r["rungs"]["M0_naive_avg"]
        be = math.log(51200) * v["eng"]["nats_per_byte"] / v["eng"]["nats_per_token"]
        bx = math.log(51200) * v["x"]["nats_per_byte"] / v["x"]["nats_per_token"]
        uref.append([f"eng-{r['lang']}", fmt(0.5 * (be + bx))])
    L.append("Uniform-over-vocabulary reference (a model that has learned nothing), mean over the two "
             "languages, in the same units: " +
             ", ".join(f"**eng-{r['lang']}** {u[1]}" for r, u in zip(set4, uref)) + " nats/byte.\n")
    L.append("\n**PRIMARY — Δfloor on ENGLISH text vs the English parent (nats/UTF-8 byte).** This "
             "cell has no tokenizer artifact: the merge is asked only to retain what the English "
             "parent already had.\n")
    L.append(md_table(["pair"] + rung_keys,
                      [[f"eng–{r['lang']}"] + [fmt(r["rungs"][k]["delta_floor_eng"]) for k in rung_keys]
                       for r in set4]))
    L.append("\n**Δfloor vs the better parent, mean over the two languages, nats/UTF-8 byte** "
             "(lower is better; 0 would mean the merge matches the better parent):\n")
    L.append(md_table(hdr, body))
    body2 = []
    for r in set4:
        for k in rung_keys:
            body2.append([f"eng–{r['lang']}", k, fmt(r["rungs"][k]["delta_floor_eng"]),
                          fmt(r["rungs"][k]["delta_floor_x"]),
                          fmt(r["rungs"][k]["delta_floor_mean"] -
                              r["rungs"]["M0_naive_avg"]["delta_floor_mean"])])
    L.append("\n**Split by language, and Δ vs naive:**\n")
    L.append(md_table(["pair", "rung", "Δfloor eng", "Δfloor X", "Δ vs naive (mean)"], body2))
    L.append("""
**Rungs.** `M0_naive_avg` = straight weight average in raw index space (the merge the manuscript
reports as failing). `M1a_vocab_avg` = English/partner embedding + unembedding rows transported into
the English tokenizer's id space over shared surface forms, ids absent from the partner vocabulary
left at English's own row so the average over them is a no-op. `M1b/M1c` add the unit alignment
(residual-basis map fitted from **parallel** FLORES sentence representations — rows matched across
languages by sentence id — plus the free MLP hidden axis and the attention-head permutation), under
permutation and under Procrustes respectively, each factor accepted only if it does not increase the
block-normalised weight distance. `M1d/M1e` force the residual factor in regardless of that test.
`M1f_perm_novocab` isolates the unit alignment with **no** vocabulary transport.
""")

# ---------------- BLiMP: accuracy, not likelihood
blimp = load("blimp_*.jsonl")
if blimp:
    L.append("\n## The accuracy test · does the likelihood rescue transfer? (BLiMP, SET 1)\n")
    L.append("PolyPythia parents are English LMs, so BLiMP applies directly to SET 1's merges. "
             "Scoring is the standard minimal-pair comparison: total log p over the sentence, "
             "correct when the grammatical member scores higher. **Chance = 0.500.** Same merges, "
             "same alignment, same pairs as the Δfloor tables above.\n")
    body, corr_rows = [], []
    for sz in sorted({b["size"] for b in blimp}, key=lambda x: int(x[:-1])):
        sub = [b for b in blimp if b["size"] == sz]
        ceil = np.mean([b["ceiling"] for b in sub])
        pmean = np.mean([np.mean(list(b["parent_acc"].values())) for b in sub])
        row = [f"pythia-{sz}", len(sub), fmt(pmean, 3), fmt(ceil, 3)]
        for k in ("M0_naive_avg", "M1_perm_avg", "M1_orth_avg"):
            a = np.array([b["rungs"][k]["blimp_acc"] for b in sub])
            row.append(f"{a.mean():.3f}")
        best = np.array([min(b["rungs"][k]["blimp_acc"] for k in b["rungs"]) for b in sub])
        bestm = np.array([max(b["rungs"][k]["blimp_acc"] for k in b["rungs"]) for b in sub])
        row.append(fmt(np.mean((bestm - 0.5) / (ceil - 0.5)) * 100, 1) + "%")
        body.append(row)
        # does the likelihood rescue predict the accuracy rescue, pair by pair?
        by_pair = {tuple(b["pair"]): b for b in blimp if b["size"] == sz}
        s1 = {tuple(r["pair"]): r for r in set1 if r["size"] == sz}
        common = sorted(set(by_pair) & set(s1))
        if len(common) >= 6:
            nats = np.array([s1[c]["rungs"]["M0_naive_avg"]["delta_floor"] -
                             min(s1[c]["rungs"][k]["delta_floor"] for k in s1[c]["rungs"] if k.startswith("M1"))
                             for c in common])
            acc = np.array([max(by_pair[c]["rungs"][k]["blimp_acc"] for k in by_pair[c]["rungs"] if k.startswith("M1")) -
                            by_pair[c]["rungs"]["M0_naive_avg"]["blimp_acc"] for c in common])
            rx = np.argsort(np.argsort(nats)).astype(float); ry = np.argsort(np.argsort(acc)).astype(float)
            corr_rows.append([f"pythia-{sz}", len(common), fmt(EV.pearson(rx, ry)),
                              fmt(float(nats.mean()), 2), fmt(float(acc.mean()), 4)])
    L.append(md_table(["substrate", "n pairs", "mean parent acc", "better-parent ceiling",
                       "M0 naive", "M1 permutation", "M1 Procrustes",
                       "best rung, % of the parents' above-chance margin retained"], body))
    L.append("""
**This is the result the audit asked for, and it is negative.** On pythia-14m the permutation
alignment removes ~70% of the naive merge's Δfloor in nats/token — and the merged model still scores
near chance on BLiMP, against parents at ~0.66-0.69. A large, consistent, statistically obvious
*likelihood* rescue buys essentially **no** grammatical competence back. "Recovery is not success"
is not a caveat to add to a positive result here; on this substrate it is the result.
""")
    if corr_rows:
        L.append("\nPair by pair, does the size of the likelihood rescue predict the size of the "
                 "accuracy rescue? (Spearman, over seed pairs within a size.)\n")
        L.append(md_table(["substrate", "n", "Spearman(Δfloor rescue, BLiMP rescue)",
                           "mean Δfloor rescue (nats/tok)", "mean BLiMP rescue (acc)"], corr_rows))

L.append("\n## P0-2 · Do the pre-merge predictors predict the realised rescue?\n")
if os.path.exists(f"{R}/predictor_auroc.csv"):
    rows = [l.rstrip("\n").split(",") for l in open(f"{R}/predictor_auroc.csv")]
    hdr, dat = rows[0], rows[1:]
    ix = {h: i for i, h in enumerate(hdr)}
    body = []
    for d in dat:
        if d[ix.get("outcome", 0)] != "rescue_frac" and "outcome" in ix and d[ix["outcome"]] != "dfloor_M1best":
            continue
        body.append([d[ix["substrate"]], d[ix["outcome"]] if "outcome" in ix else "rescue_frac",
                     d[ix["predictor"]], d[ix["n_pairs"]],
                     fmt(float(d[ix["spearman_rescue"]]) if d[ix["spearman_rescue"]] else None),
                     fmt(float(d[ix["auroc_heldout_by_seed"]]) if d[ix["auroc_heldout_by_seed"]] else None),
                     fmt(float(d[ix["perm_null_mean"]]) if d[ix["perm_null_mean"]] else None),
                     fmt(float(d[ix["perm_null_p"]]) if d[ix["perm_null_p"]] else None),
                     fmt(float(d[ix["bh_q"]]) if d[ix["bh_q"]] else None)])
    L.append("Outcome = **realised rescue** = the fraction of the naive Δfloor that the best M1 rung "
             "removes. Label = above the within-size median. Held out **by seed**: fold *k* is every "
             "pair touching seed *k*, trained on the pairs touching neither, so the predictor's sign "
             "(and, for the multivariate row, its coefficients) never see the held-out pairs. Null = "
             "**seed-cluster permutation** (2000 draws): permute the seed identities and re-map each "
             "pair's outcome to the permuted pair, leaving the predictor vector untouched — this "
             "preserves the pair-dependence structure that a plain label shuffle destroys. "
             "BH-corrected across the predictor family.\n")
    L.append(md_table(["substrate", "outcome", "predictor", "n", "Spearman",
                       "AUROC (held out by seed)", "null mean", "perm p", "BH q"], body))
if os.path.exists(f"{R}/predictor_transfer_across_size.csv"):
    rows = [l.rstrip("\n").split(",") for l in open(f"{R}/predictor_transfer_across_size.csv")]
    hdr, dat = rows[0], rows[1:]
    ix = {h: i for i, h in enumerate(hdr)}
    L.append("\n### Does a predictor fitted on one substrate transfer to another?\n")
    L.append("Leave-one-**size**-out. Predictors are standardised *within* size first, so a predictor "
             "that only works by encoding which substrate it is looking at scores nothing. The sign "
             "(and the ridge coefficients) come from the other sizes only. Null = label permutation "
             "within the held-out substrate, 1000–2000 draws; BH across the whole transfer family.\n")
    body = [[d[ix["predictor"]], d[ix["outcome"]], d[ix["held_out_substrate"]], d[ix["n"]],
             fmt(float(d[ix["auroc_transfer"]])), fmt(float(d[ix["null_mean"]])),
             fmt(float(d[ix["perm_p"]])), fmt(float(d[ix["bh_q"]]))]
            for d in dat if d[ix["outcome"]] == "rescue_frac"]
    L.append(md_table(["predictor", "outcome", "held-out substrate", "n", "AUROC", "null mean",
                       "perm p", "BH q"], body))

if os.path.exists(f"{R}/set4_predictors.csv"):
    rows = [l.rstrip("\n").split(",") for l in open(f"{R}/set4_predictors.csv")]
    hdr, dat = rows[0], rows[1:]
    ix = {h: i for i, h in enumerate(hdr)}
    L.append("\n**SET 4, held out by language pair.** n = %d language pairs. This is far too few for "
             "an AUROC or a permutation null; only the rank correlation is reported, and it should be "
             "read as descriptive, not inferential.\n" % len(set4))
    L.append(md_table(["predictor", "Spearman vs realised rescue"],
                      [[d[ix["predictor"]], fmt(float(d[ix["spearman_rescue"]]) if d[ix["spearman_rescue"]] else None)]
                       for d in dat]))

# coverage
abl = load("abl_*.jsonl")
if abl:
    L.append("\n## Control · is the obstruction the INIT seed or the DATA order?\n")
    L.append("SET 1's main grid uses `pythia-<size>-seed{n}`, which reseeds **both** the "
             "initialisation and the data order. `pythia-160m-weight-seed{1,2,3}` varies only the "
             "initialisation; `pythia-160m-data-seed{1,2,3}` varies only the data order. Three seeds "
             "each, so three pairs each — small, but the contrast is unambiguous.\n")
    body = []
    for sz in sorted({r["size"] for r in abl}):
        sub = [r for r in abl if r["size"] == sz]
        d0 = np.array([r["rungs"]["M0_naive_avg"]["delta_floor"] for r in sub])
        dp = np.array([r["rungs"]["M1_perm_avg"]["delta_floor"] for r in sub])
        do = np.array([r["rungs"]["M1_orth_avg"]["delta_floor"] for r in sub])
        cs = np.array([r["predictors"]["coord_share_bnd_perm"] for r in sub])
        body.append([sz, len(sub), fmt(float(np.mean([r["floor"] for r in sub])), 2), fmt(d0.mean(), 2),
                     fmt(dp.mean(), 2), fmt(do.mean(), 2),
                     fmt(np.mean(1 - np.minimum(dp, do) / d0) * 100, 1) + "%", fmt(cs.mean(), 4)])
    main160 = [r for r in set1 if r["size"] == "160m"]
    if main160:
        d0 = np.array([r["rungs"]["M0_naive_avg"]["delta_floor"] for r in main160])
        dp = np.array([r["rungs"]["M1_perm_avg"]["delta_floor"] for r in main160])
        do = np.array([r["rungs"]["M1_orth_avg"]["delta_floor"] for r in main160])
        cs = np.array([r["predictors"]["coord_share_bnd_perm"] for r in main160])
        body.append(["160m (init+data, main grid)", len(main160),
                     fmt(float(np.mean([r["floor"] for r in main160])), 2), fmt(d0.mean(), 2),
                     fmt(dp.mean(), 2), fmt(do.mean(), 2),
                     fmt(np.mean(1 - np.minimum(dp, do) / d0) * 100, 1) + "%", fmt(cs.mean(), 4)])
    L.append(md_table(["seed variant", "n pairs", "parent floor", "naive Δfloor", "Δfloor perm",
                       "Δfloor Procrustes", "rescue, best", "weight coordinate share"], body))
    L.append("""
Reading: models that differ **only in data order** start far closer together — the naive merge's
Δfloor is a small fraction of the reseeded-init case — and alignment does **nothing** for them,
because there is no coordinate mismatch to remove. Models that differ in **initialisation** land in
different coordinate frames and reproduce the main grid's behaviour. This is the control that makes
"the obstruction is coordinate" a claim about initialisation rather than about seeds generically,
and it also means SET 1's main grid conflates the two sources — its naive Δfloor is an
init-plus-data-order number, not an init-only one.
""")

L.append("""
### What P0-2 comes to

**Within a single substrate, nothing predicts the realised rescue.** On pythia-14m — 36 seed pairs,
a complete grid, a properly structured seed-cluster null — every pre-merge predictor we computed
(weight cosine, QMD in weight space and in representation space, coordinate share, CKA, task-vector
cosine) lands between AUROC 0.30 and 0.68 held out by seed, and **not one survives BH correction**.
The multivariate ridge over all of them does no better. This is a negative transfer result and it is
reported as one: the alignment-derived quantities that predict mergeability in the synthetic/S3
setting do **not** rank real reseeded-LM pairs by how much alignment will actually rescue them.

**Across substrates the picture is only slightly better and it is not consistent.** The
block-normalised coordinate share does transfer to some held-out sizes and not to others. Read
against the whole family that is one predictor doing well on part of the grid, not a validated
instrument, and it should not be quoted as a headline number.

Two honest caveats in the other direction. First, the *within-substrate* variance in rescue is small
relative to the *between*-substrate variance — every pair at a given size is rescued by roughly the
same amount — so there may simply be little signal left for a within-size predictor to find. Second,
the seed-cluster null is conservative by construction. Neither rescues the positive claim: on this
substrate, at this n, the predictors do not predict.
""")

L.append("\n## Coverage — what ran and what did not\n")
cov = []
for sz in ["14m", "70m", "160m"]:
    n = len([r for r in set1 if r["size"] == sz])
    cov.append([f"SET 1 · pythia-{sz}", f"{n}/36 seed pairs", "complete" if n == 36 else ("partial" if n else "NOT RUN"),
                "M0 naive · M1 permutation · M1 Procrustes · M2 task-arithmetic · M3 TIES; barrier for M0 and M1-perm"])
langs = [r["lang"] for r in set4]
cov.append(["SET 4 · goldfish eng×X", f"{len(set4)}/4 language pairs ({', '.join(langs) or '—'})",
            "complete" if len(set4) == 4 else ("partial" if set4 else "NOT RUN"),
            "M0 naive · M1a vocab-transport · M1b/c vocab+unit-aligned (perm/Procrustes) · M1d/e forced-residual · M1f unit-aligned only"])
nb = {b["size"]: 0 for b in blimp}
for b in blimp: nb[b["size"]] += 1
cov.append(["BLiMP accuracy · SET 1 (English)", ", ".join(f"pythia-{k}: {v}/36 pairs" for k, v in sorted(nb.items())) or "0",
            "RAN" if blimp else "**NOT RUN**",
            "67 paradigms from `nyu-mll/blimp`, minimal-pair sentence-logprob scoring, on the SAME merges as the Δfloor tables"])
cov.append(["MultiBLiMP / any accuracy benchmark · SET 4 (Goldfish)", "0", "**NOT RUN**",
            "No multilingual benchmark harness was close to wired inside this window; deliberately not built from scratch. SET 4's numbers are likelihood only and say nothing about accuracy."])
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."])
cov.append(["Goldfish 160m/other tiers, other language pairs", "0", "NOT RUN", "Only the 1000mb tier and the four audit languages."])
L.append(md_table(["cell", "n", "status", "what was measured"], cov))

L.append("""
## Threats to validity, stated plainly

- **Likelihood ≠ accuracy.** Repeated because it is the single most load-bearing caveat here.
- **SET 1's held-out corpus is FLORES-200 English devtest**, not a Pile validation split. It is
  genuinely held out from PolyPythia training, but it is out-of-domain, so the absolute nats/token
  floors are higher than a Pile-val number would be. Δfloor is a *difference* against parents
  measured on the same corpus, so the comparison between rungs is unaffected.
- **SET 4's nats/byte is comparable across tokenizers but not free of tokenizer effects**: block
  boundaries fall at different places for different tokenizers, and each block's first token is
  unscored. With ~30k tokens per evaluation this is a sub-1% effect.
- **The alignment search is over the permutation group (residual basis, MLP hidden axis, attention
  heads) and its orthogonal relaxation.** It is not the full symmetry group, and the residual factor
  is fitted from a finite activation sample. A better aligner could raise the M1 rungs; nothing here
  bounds how far.
- **SET 4's n = 4 language pairs.** Any predictor claim on that substrate is descriptive.
""")

L.append("\n## Files\n")
L.append("""```
results/set1_{14m,70m,160m}.jsonl   per-pair raw records (predictors, rungs, barriers, align info)
results/set1_pairs.csv              per-pair flat table, SET 1
results/set4_goldfish.jsonl         per-language-pair raw records, SET 4
results/set4_pairs.csv              per-language-pair flat table, SET 4
results/rung_summary.csv            rung x substrate x metric summary
results/predictor_auroc.csv         SET 1 predictor table: held-out AUROC, permutation null, BH q
results/set4_predictors.csv         SET 4 predictor rank correlations (n=4, descriptive)
figs/set1_dfloor_by_rung.png        Δfloor by rung, per size
figs/set1_rescue_vs_predictor.png   realised rescue vs coordinate share / CKA
figs/set1_roc.png                   held-out-by-seed ROC
figs/set4_dfloor.png                Δfloor by rung, Goldfish
```""")

open("/root/compose-audit/RESULTS_COMPOSE_AUDIT.md", "w").write("\n".join(L) + "\n")

if rung_rows:
    keys = list(rung_rows[0])
    with open(f"{R}/rung_summary.csv", "w") as f:
        f.write(",".join(keys) + "\n")
        for r in rung_rows:
            f.write(",".join(str(r.get(k, "")) for k in keys) + "\n")
print("report written:", sum(len(x) for x in L), "chars")