File size: 28,717 Bytes
92252c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ace30c6
 
 
 
 
 
 
 
 
 
 
92252c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58e7bb7
 
 
 
 
 
 
 
 
92252c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b3ce86
 
 
 
 
 
 
 
92252c2
7b3ce86
 
 
92252c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b3ce86
 
92252c2
 
 
 
 
7b3ce86
 
 
 
 
 
 
 
 
92252c2
 
7b3ce86
 
92252c2
 
7b3ce86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92252c2
7b3ce86
 
92252c2
 
7b3ce86
92252c2
 
 
 
d5c0c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b3ce86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92252c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58e7bb7
92252c2
 
 
 
 
58e7bb7
 
 
92252c2
 
58e7bb7
 
 
 
92252c2
 
 
 
 
d5c0c98
92252c2
 
 
 
 
 
 
 
 
 
58e7bb7
92252c2
58e7bb7
 
 
 
 
 
 
 
 
 
92252c2
58e7bb7
 
92252c2
 
58e7bb7
 
 
92252c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b3ce86
 
ace30c6
7b3ce86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c6b21b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58e7bb7
 
 
9c6b21b
 
58e7bb7
 
9c6b21b
 
 
58e7bb7
 
 
 
 
 
 
 
9c6b21b
 
 
 
 
 
 
 
 
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
"""P0-2: do the PRE-MERGE predictors predict the REALISED rescue?
Held out by seed pair (SET 1) and by language pair (SET 4). Held-out AUROC + permutation null
(seed-cluster permutation, which respects the pair dependence structure) + BH correction."""
import os, sys, json, glob, itertools
sys.path.insert(0, "/root/compose-audit")
from common import *
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

R = "/root/compose-audit/results"
F = "/root/compose-audit/figs"
os.makedirs(F, exist_ok=True)


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 _dedup_sp(rows):
    """Drop duplicate (size, pair) records: a cell may be worked by more than one process."""
    seen, out = set(), []
    for r in rows:
        k = (r.get("size"), tuple(r.get("pair", ())))
        if k[1] and k in seen:
            continue
        seen.add(k); out.append(r)
    return out



# ------------------------------------------------------------------ stats helpers
def auroc(score, label):
    s, y = np.asarray(score, float), np.asarray(label, int)
    ok = np.isfinite(s)
    s, y = s[ok], y[ok]
    if y.sum() == 0 or y.sum() == len(y):
        return float("nan")
    order = np.argsort(s)
    ranks = np.empty(len(s), float); ranks[order] = np.arange(1, len(s) + 1)
    # average ranks for ties
    for v in np.unique(s):
        m = s == v
        if m.sum() > 1:
            ranks[m] = ranks[m].mean()
    n1, n0 = y.sum(), len(y) - y.sum()
    return float((ranks[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))


def spearman(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    ok = np.isfinite(x) & np.isfinite(y)
    if ok.sum() < 3: return float("nan")
    rx = np.argsort(np.argsort(x[ok])).astype(float)
    ry = np.argsort(np.argsort(y[ok])).astype(float)
    return EV.pearson(rx, ry)


def bh(pvals):
    p = np.asarray(pvals, float)
    ok = np.isfinite(p)
    out = np.full(len(p), np.nan)
    idx = np.where(ok)[0]
    o = idx[np.argsort(p[idx])]
    m = len(o)
    prev = 1.0
    for rank in range(m - 1, -1, -1):
        v = min(prev, p[o[rank]] * m / (rank + 1))
        out[o[rank]] = v; prev = v
    return out


def ridge(X, y, lam=1.0):
    Xb = np.hstack([X, np.ones((len(X), 1))])
    A = Xb.T @ Xb + lam * np.eye(Xb.shape[1])
    w = np.linalg.solve(A, Xb.T @ y)
    return w[:-1], w[-1]


# ------------------------------------------------------------------ SET 1 assembly
set1 = load("set1_*.jsonl") + load("set1x_*.jsonl")
_seen = set()
_ded = []
for _r in set1:                     # a size may be worked by more than one worker process
    _k = (_r["size"], tuple(_r["pair"]))
    if _k in _seen:
        continue
    _seen.add(_k); _ded.append(_r)
set1 = _ded
rows1 = []
for r in set1:
    rg = r["rungs"]
    m1 = {k: v for k, v in rg.items() if k.startswith("M1")}
    best = min(m1, key=lambda k: m1[k]["delta_floor"]) if m1 else None
    d0 = rg["M0_naive_avg"]["delta_floor"]
    d1 = m1[best]["delta_floor"] if best else float("nan")
    row = {"set": "SET1_polypythia", "substrate": f"pythia-{r['size']}", "size": r["size"],
           "pair": f"{r['pair'][0]}-{r['pair'][1]}", "a": r["pair"][0], "b": r["pair"][1],
           "floor": r["floor"], "dfloor_M0": d0, "dfloor_M1best": d1, "M1best": best,
           "rescue_nats": d0 - d1, "rescue_frac": (d0 - d1) / d0 if d0 > 0 else float("nan")}
    for k, v in rg.items():
        row[f"nll_{k}"] = v["nll"]; row[f"dfloor_{k}"] = v["delta_floor"]
    for k in ("barrier_naive", "barrier_perm"):
        if k in r: row[k] = r[k]["barrier"]
    row.update({f"p_{k}": v for k, v in r["predictors"].items()})
    row["align_perm_hidden"] = r["align_info"]["perm"].get("hidden", 0)
    row["align_perm_heads"] = r["align_info"]["perm"].get("heads", 0)
    row["align_perm_residual"] = int(bool(r["align_info"]["perm"].get("residual")))
    rows1.append(row)

# ------------------------------------------------------------------ SET 4 assembly
set4 = load("set4_goldfish.jsonl")
rows4 = []
for r in set4:
    rg = r["rungs"]
    # Re-reference the X-language floor to the X parent's OWN tokenizer. The English parent's
    # nats/byte on X text is degenerate wherever the English tokenizer UNK-s the script (46% of
    # Greek tokens), so min(parents) was picking up an artifact rather than a floor.
    px = r["parents"]["x_on_x"]["nats_per_byte"]
    for _k, _v in rg.items():
        _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
    m1 = {k: v for k, v in rg.items() if k.startswith("M1")}
    best = min(m1, key=lambda k: m1[k]["delta_floor_eng"]) if m1 else None
    d0 = rg["M0_naive_avg"]["delta_floor_eng"]
    d1 = m1[best]["delta_floor_eng"] if best else float("nan")
    row = {"set": "SET4_goldfish", "substrate": "goldfish-125M", "pair": f"eng-{r['lang']}",
           "lang": r["lang"], "floor_eng": r["floor_eng"], "floor_x": r["floor_x"],
           "dfloor_M0": d0, "dfloor_M1best": d1, "M1best": best,
           "rescue_nats": d0 - d1, "rescue_frac": (d0 - d1) / d0 if d0 > 0 else float("nan")}
    for k, v in rg.items():
        for f_ in ("delta_floor_eng", "delta_floor_x", "delta_floor_mean"):
            row[f"{f_}_{k}"] = v[f_]
        row[f"npb_eng_{k}"] = v["eng"]["nats_per_byte"]; row[f"npb_x_{k}"] = v["x"]["nats_per_byte"]
    for k in ("barrier_naive", "barrier_perm"):
        if k in r: row[k] = r[k]["barrier"]
    row.update({f"p_{k}": v for k, v in r["predictors"].items()})
    rows4.append(row)


def to_csv(rows, path):
    if not rows: return
    keys = []
    for r in rows:
        for k in r:
            if k not in keys: keys.append(k)
    with open(path, "w") as f:
        f.write(",".join(keys) + "\n")
        for r in rows:
            f.write(",".join("" if r.get(k) is None else str(r.get(k, "")) for k in keys) + "\n")


to_csv(rows1, f"{R}/set1_pairs.csv")
to_csv(rows4, f"{R}/set4_pairs.csv")
print(f"SET1 rows={len(rows1)}  SET4 rows={len(rows4)}")

# ------------------------------------------------------------------ P0-2: held-out prediction, SET 1
PRED_KEYS = ["p_weight_cosine", "p_weight_cosine_bn", "p_d_raw", "p_qmd_perm", "p_coord_share_perm",
             "p_qmd_orth", "p_coord_share_orth", "p_bnd_raw", "p_bnd_perm", "p_bnd_orth",
             "p_coord_share_bnd_perm", "p_coord_share_bnd_orth", "p_cka_mean", "p_cka_last",
             "p_qmd_act_perm", "p_qmd_act_procrustes", "p_qmd_act_ot", "p_task_vector_cosine"]

pred_rows, roc_store = [], {}
OUTCOMES = [("rescue_frac", "fraction of the naive Δfloor that the best M1 rung removes", +1),
            ("dfloor_M1best", "Δfloor of the best M1 rung (how good the ALIGNED merge actually is)", -1)]
for size in sorted({r["size"] for r in rows1}):
    sub = [r for r in rows1 if r["size"] == size]
    if len(sub) < 8:
        continue
    seeds = sorted({r["a"] for r in sub} | {r["b"] for r in sub})
    pair_ix = {(r["a"], r["b"]): i for i, r in enumerate(sub)}
    complete = len(sub) == len(seeds) * (len(seeds) - 1) // 2
    for oname, odesc, osign in OUTCOMES:
        y_cont = osign * np.array([r[oname] for r in sub], float)
        med = np.nanmedian(y_cont)
        y = (y_cont > med).astype(int)
        rng = np.random.default_rng(0)
        # pre-draw the seed-cluster permutations ONCE per outcome so every predictor sees the same null
        perms = []
        for _ in range(2000):
            pi = rng.permutation(seeds)
            m = {sd: pi[i] for i, sd in enumerate(seeds)}
            idx, ok = [], True
            for r in sub:
                u, v = sorted((m[r["a"]], m[r["b"]]))
                if (u, v) not in pair_ix:
                    ok = False; break
                idx.append(pair_ix[(u, v)])
            if ok:
                perms.append(np.asarray(idx))
        for pk in PRED_KEYS:
            x = np.array([r.get(pk, np.nan) for r in sub], float)
            if np.isfinite(x).sum() < 8 or np.nanstd(x) == 0:
                continue
            # HELD OUT BY SEED: fold k = every pair touching seed k, fitted on pairs touching neither,
            # so the predictor's SIGN never sees the held-out pairs.
            oof = np.full(len(sub), np.nan)
            for sd_ in seeds:
                te = np.array([(r["a"] == sd_ or r["b"] == sd_) for r in sub]); tr = ~te
                if tr.sum() < 4 or te.sum() < 1: continue
                sgn = np.sign(spearman(x[tr], y_cont[tr])) or 1.0
                oof[te] = sgn * x[te]
            a_oof = auroc(oof, y)
            a_in = auroc(np.sign(spearman(x, y_cont) or 1.0) * x, y)
            null = np.array([auroc(oof, y[ix]) for ix in perms]) if len(perms) >= 200 else np.array([])
            null = null[np.isfinite(null)]
            pval = float((np.sum(null >= a_oof) + 1) / (len(null) + 1)) if len(null) else float("nan")
            pred_rows.append({"set": "SET1", "substrate": f"pythia-{size}", "outcome": oname,
                              "n_pairs": len(sub), "predictor": pk[2:],
                              "spearman_rescue": spearman(x, y_cont),
                              "auroc_in_sample": a_in, "auroc_heldout_by_seed": a_oof,
                              "perm_null_mean": float(null.mean()) if len(null) else float("nan"),
                              "n_null_draws": int(len(null)), "pairs_complete": int(complete),
                              "perm_null_p": pval})
            if oname == "rescue_frac":
                roc_store[(size, pk)] = (oof, y)
        # multivariate, held out by seed
        X = np.array([[r.get(k, np.nan) for k in PRED_KEYS] for r in sub], float)
        good = np.isfinite(X).all(0) & (np.nanstd(X, 0) > 0)
        Xg = X[:, good]
        Xg = (Xg - Xg.mean(0)) / (Xg.std(0) + 1e-12)
        oof = np.full(len(sub), np.nan)
        for sd_ in seeds:
            te = np.array([(r["a"] == sd_ or r["b"] == sd_) for r in sub]); tr = ~te
            if tr.sum() < 4: continue
            w, b = ridge(Xg[tr], y_cont[tr], lam=2.0)
            oof[te] = Xg[te] @ w + b
        a_oof = auroc(oof, y)
        null = np.array([auroc(oof, y[ix]) for ix in perms]) if len(perms) >= 200 else np.array([])
        null = null[np.isfinite(null)]
        pred_rows.append({"set": "SET1", "substrate": f"pythia-{size}", "outcome": oname,
                          "n_pairs": len(sub), "predictor": "MULTIVARIATE_ridge_all",
                          "spearman_rescue": spearman(oof, y_cont), "auroc_in_sample": float("nan"),
                          "auroc_heldout_by_seed": a_oof,
                          "perm_null_mean": float(null.mean()) if len(null) else float("nan"),
                          "n_null_draws": int(len(null)), "pairs_complete": int(complete),
                          "perm_null_p": float((np.sum(null >= a_oof) + 1) / (len(null) + 1)) if len(null) else float("nan")})

if pred_rows:
    q = bh([r["perm_null_p"] for r in pred_rows])
    for r, qq in zip(pred_rows, q):
        r["bh_q"] = float(qq) if np.isfinite(qq) else ""
    to_csv(pred_rows, f"{R}/predictor_auroc.csv")

# ---------------- P0-2 CONFIRMATORY family: the five predictors the audit brief itself names,
# on the one outcome it asks about. Fixed from the brief, not chosen after seeing the table, and
# BH-corrected within this small family only. Everything else in predictor_auroc.csv is exploratory.
CONFIRMATORY = [("p_weight_cosine", "weight cosine"),
                ("p_coord_share_bnd_perm", "coordinate share (block-normalised / permutation)"),
                ("p_qmd_act_perm", "QMD (quotient_residual / permutation)"),
                ("p_cka_mean", "CKA (mean over layers / unaligned)"),
                ("p_task_vector_cosine", "task-vector cosine")]
conf = []
for r in pred_rows:
    if r["outcome"] != "rescue_frac":
        continue
    for pk, lbl in CONFIRMATORY:
        if r["predictor"] == pk[2:]:
            conf.append({"substrate": r["substrate"], "predictor": lbl, "n_pairs": r["n_pairs"],
                         "spearman": r["spearman_rescue"], "auroc_heldout_by_seed": r["auroc_heldout_by_seed"],
                         "perm_null_mean": r["perm_null_mean"], "perm_p": r["perm_null_p"],
                         "n_null_draws": r["n_null_draws"]})
if conf:
    qq = bh([c["perm_p"] for c in conf])
    for c, q in zip(conf, qq):
        c["bh_q_within_confirmatory_family"] = float(q) if np.isfinite(q) else ""
    to_csv(conf, f"{R}/predictor_confirmatory.csv")

# ---------------- P0-2b: does the predictor transfer ACROSS substrates (leave-one-size-out)?
xfer = []
szs_all = sorted({r["size"] for r in rows1 if len([q for q in rows1 if q["size"] == r["size"]]) >= 8})
if len(szs_all) >= 3:
    pool = [r for r in rows1 if r["size"] in szs_all]
    for oname, osign in (("rescue_frac", +1), ("dfloor_M1best", -1)):
        Y = osign * np.array([r[oname] for r in pool], float)
        SZ = np.array([r["size"] for r in pool])
        X = np.array([[r.get(k, np.nan) for k in PRED_KEYS] for r in pool], float)
        good = np.isfinite(X).all(0) & (np.nanstd(X, 0) > 0)
        Xg = X[:, good].copy()
        # standardise WITHIN size: the raw scales differ across substrates, and a predictor that only
        # works because it encodes "which size is this" is not a transferring predictor.
        for sz in szs_all:
            m = SZ == sz
            Xg[m] = (Xg[m] - Xg[m].mean(0)) / (Xg[m].std(0) + 1e-12)
        oof = np.full(len(pool), np.nan)
        for sz in szs_all:
            te = SZ == sz; tr = ~te
            w, b = ridge(Xg[tr], Y[tr], lam=2.0)
            oof[te] = Xg[te] @ w + b
        rng = np.random.default_rng(1)
        for sz in szs_all:
            te = SZ == sz
            y = (Y[te] > np.median(Y[te])).astype(int)
            a = auroc(oof[te], y)
            null = np.array([auroc(oof[te], y[rng.permutation(len(y))]) for _ in range(2000)])
            null = null[np.isfinite(null)]
            xfer.append({"outcome": oname, "held_out_substrate": f"pythia-{sz}", "n": int(te.sum()),
                         "auroc_transfer": a, "null_mean": float(null.mean()),
                         "perm_p": float((np.sum(null >= a) + 1) / (len(null) + 1))})
        # univariate transfer of the single most-cited predictor family
        for pk in ("p_coord_share_bnd_perm", "p_qmd_act_perm", "p_cka_mean", "p_weight_cosine"):
            if pk not in PRED_KEYS: continue
            j = PRED_KEYS.index(pk)
            if not good[j]: continue
            col = np.where(good)[0].tolist().index(j)
            for sz in szs_all:
                te = SZ == sz; tr = ~te
                sgn = np.sign(spearman(Xg[tr, col], Y[tr])) or 1.0
                y = (Y[te] > np.median(Y[te])).astype(int)
                a = auroc(sgn * Xg[te, col], y)
                null = np.array([auroc(sgn * Xg[te, col], y[rng.permutation(len(y))]) for _ in range(1000)])
                null = null[np.isfinite(null)]
                xfer.append({"outcome": oname, "held_out_substrate": f"pythia-{sz}", "n": int(te.sum()),
                             "predictor": pk[2:], "auroc_transfer": a,
                             "null_mean": float(null.mean()),
                             "perm_p": float((np.sum(null >= a) + 1) / (len(null) + 1))})
    for r in xfer:
        r.setdefault("predictor", "MULTIVARIATE_ridge_all")
    qq = bh([r["perm_p"] for r in xfer])
    for r, q in zip(xfer, qq):
        r["bh_q"] = float(q)
    to_csv(xfer, f"{R}/predictor_transfer_across_size.csv")

# SET 4: leave-one-language-out, n=4 -> report Spearman only, flagged as underpowered
pred4 = []
if len(rows4) >= 3:
    y4 = np.array([r["rescue_frac"] for r in rows4], float)
    for pk in PRED_KEYS + ["p_vocab_overlap", "p_weight_cosine_body"]:
        x = np.array([r.get(pk, np.nan) for r in rows4], float)
        if np.isfinite(x).sum() < 3 or np.nanstd(x) == 0: continue
        pred4.append({"set": "SET4", "substrate": "goldfish-125M", "n_pairs": len(rows4),
                      "predictor": pk[2:], "spearman_rescue": spearman(x, y4),
                      "note": "n=4 language pairs -- UNDERPOWERED, no AUROC/null reported"})
    to_csv(pred4, f"{R}/set4_predictors.csv")

# ------------------------------------------------------------------ figures
plt.rcParams.update({"figure.dpi": 130, "font.size": 9, "axes.grid": True,
                     "grid.alpha": .25, "axes.spines.top": False, "axes.spines.right": False})

# 1. Delta-floor by rung
if rows1:
    sizes = sorted({r["size"] for r in rows1}, key=lambda s: int(s[:-1]))
    rungs = [k[7:] for k in rows1[0] if k.startswith("dfloor_M") and k not in ("dfloor_M0", "dfloor_M1best")]
    fig, axes = plt.subplots(1, len(sizes), figsize=(3.6 * len(sizes), 3.4), squeeze=False)
    for ax, sz in zip(axes[0], sizes):
        sub = [r for r in rows1 if r["size"] == sz]
        data = [[r[f"dfloor_{k}"] for r in sub if np.isfinite(r.get(f"dfloor_{k}", np.nan))] for k in rungs]
        keep = [(k, d) for k, d in zip(rungs, data) if d]
        _lab = {"M0_naive_avg": "M0\nnaive", "M1_perm_avg": "M1\nperm*", "M1_orth_avg": "M1\northo†",
                "M2_task_arith": "M2\ntask-ar†", "M3_ties": "M3\nTIES†"}
        ax.boxplot([d for _, d in keep], tick_labels=[_lab.get(k, k) for k, _ in keep], showfliers=False)
        ax.set_yscale("symlog"); ax.set_title(f"pythia-{sz}  (n={len(sub)} seed pairs)")
        ax.set_ylabel("Δfloor  (nats/token, log)")
        ax.tick_params(axis="x", labelsize=7)
    fig.suptitle("SET 1 · PolyPythia seed merge · Δfloor vs the better parent, by merge rung\n"
                 "* exactly function-preserving   † not function-preserving / no shared base — see the report",
                 fontsize=9)
    fig.tight_layout(); fig.savefig(f"{F}/set1_dfloor_by_rung.png", bbox_inches="tight"); plt.close(fig)

# 2. rescue vs coordinate share
if rows1:
    fig, axes = plt.subplots(1, 2, figsize=(8.4, 3.6))
    for ax, pk, lab in ((axes[0], "p_coord_share_bnd_perm", "coordinate share (block-normalised / permutation)"),
                        (axes[1], "p_cka_mean", "unaligned CKA (mean over layers)")):
        for sz in sorted({r["size"] for r in rows1}, key=lambda s: int(s[:-1])):
            sub = [r for r in rows1 if r["size"] == sz]
            ax.scatter([r.get(pk, np.nan) for r in sub], [r["rescue_frac"] for r in sub],
                       s=18, alpha=.75, label=f"pythia-{sz}")
        ax.set_xlabel(lab); ax.set_ylabel("realised rescue  (frac of naive Δfloor removed)")
        ax.legend(fontsize=7, frameon=False)
    fig.suptitle("SET 1 · does a PRE-MERGE predictor track the REALISED rescue?", fontsize=10)
    fig.tight_layout(); fig.savefig(f"{F}/set1_rescue_vs_predictor.png", bbox_inches="tight"); plt.close(fig)

# 3. ROC of the CONFIRMATORY predictor (coordinate share), one curve per substrate
if roc_store and pred_rows:
    PK = "p_coord_share_bnd_perm"
    au = {(r["substrate"], r["predictor"]): r["auroc_heldout_by_seed"] for r in pred_rows
          if r["outcome"] == "rescue_frac"}
    fig, ax = plt.subplots(figsize=(4.6, 4.2))
    for sz in sorted({k[0] for k in roc_store}, key=lambda x: int(x[:-1])):
        if (sz, PK) not in roc_store:
            continue
        oof, y = roc_store[(sz, PK)]
        ok = np.isfinite(oof)
        o = np.argsort(-oof[ok]); yy = y[ok][o]
        tpr = np.cumsum(yy) / max(1, yy.sum()); fpr = np.cumsum(1 - yy) / max(1, (1 - yy).sum())
        a = au.get((f"pythia-{sz}", PK[2:]), float("nan"))
        ax.plot(np.r_[0, fpr], np.r_[0, tpr], label=f"pythia-{sz}  (AUROC {a:.2f})")
    ax.plot([0, 1], [0, 1], "k--", lw=.8)
    ax.set_xlabel("false positive rate"); ax.set_ylabel("true positive rate")
    ax.set_title("SET 1 · P0-2 confirmatory predictor\ncoordinate share → realised rescue,\n"
                 "held out by seed pair", fontsize=9)
    ax.legend(fontsize=7.5, frameon=False, loc="lower right")
    fig.tight_layout(); fig.savefig(f"{F}/set1_roc.png", bbox_inches="tight"); plt.close(fig)

# 4. SET 4 bars
if rows4:
    rungs = sorted({k[len("delta_floor_mean_"):] for r in rows4 for k in r if k.startswith("delta_floor_mean_M")})
    fig, ax = plt.subplots(figsize=(7.6, 3.6))
    w = 0.8 / len(rungs)
    for i, k in enumerate(rungs):
        ax.bar(np.arange(len(rows4)) + i * w, [r.get(f"delta_floor_mean_{k}", np.nan) for r in rows4],
               width=w, label=k)
    ax.set_xticks(np.arange(len(rows4)) + 0.4 - w / 2)
    ax.set_xticklabels([r["pair"] for r in rows4])
    ax.set_ylabel("Δfloor  (nats/UTF-8 byte)"); ax.legend(fontsize=7, frameon=False, ncol=2)
    ax.set_title("SET 4 · Goldfish eng×X merge · Δfloor vs the better parent (LIKELIHOOD, not accuracy)", fontsize=9)
    fig.tight_layout(); fig.savefig(f"{F}/set4_dfloor.png", bbox_inches="tight"); plt.close(fig)

print("figures + csvs written")

# ------------------------------------------------------------------ 5. BLiMP dissociation
blimp = _dedup_sp(load("blimp_*.jsonl") + load("blimpB_*.jsonl"))
if blimp:
    brows = []
    for b in blimp:
        m1 = {k: v for k, v in b["rungs"].items() if k.startswith("M1")}
        brows.append({"size": b["size"], "pair": tuple(b["pair"]),
                      "ceiling": b["ceiling"], "parent_mean": float(np.mean(list(b["parent_acc"].values()))),
                      "M0": b["rungs"]["M0_naive_avg"]["blimp_acc"],
                      "M1best": max(v["blimp_acc"] for v in m1.values()),
                      **{f"acc_{k}": v["blimp_acc"] for k, v in b["rungs"].items()}})
    to_csv(brows, f"{R}/blimp_pairs.csv")
    s1 = {(r["size"], (r["a"], r["b"])): r for r in rows1}
    sizes_b = sorted({b["size"] for b in brows}, key=lambda x: int(x[:-1]))
    fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))
    for sz in sizes_b:
        sub = [b for b in brows if b["size"] == sz]
        xs, ys = [], []
        for b in sub:
            k = (sz, b["pair"])
            if k in s1 and np.isfinite(s1[k]["rescue_nats"]):
                xs.append(s1[k]["rescue_nats"]); ys.append(b["M1best"] - b["M0"])
        if xs:
            axes[0].scatter(xs, ys, s=20, alpha=.75, label=f"pythia-{sz} (n={len(xs)})")
    axes[0].axhline(0, color="k", lw=.7)
    axes[0].set_xlabel("likelihood rescue from alignment  (nats/token removed)")
    axes[0].set_ylabel("accuracy rescue  (BLiMP, M1best − M0)")
    axes[0].set_title("Rescue in nats does NOT buy rescue in accuracy", fontsize=9)
    axes[0].legend(fontsize=7, frameon=False)
    lab, vals = [], []
    for sz in sizes_b:
        sub = [b for b in brows if b["size"] == sz]
        lab.append(f"pythia-{sz}\n(n={len(sub)})")
        vals.append([np.mean([b["parent_mean"] for b in sub]), np.mean([b["M0"] for b in sub]),
                     np.mean([b["acc_M1_perm_avg"] for b in sub]), np.mean([b["acc_M1_orth_avg"] for b in sub])])
    vals = np.array(vals)
    w = 0.2
    for i, nm in enumerate(["parents", "M0 naive", "M1 permutation", "M1 Procrustes"]):
        axes[1].bar(np.arange(len(lab)) + i * w, vals[:, i], width=w, label=nm)
    axes[1].axhline(0.5, color="k", ls="--", lw=.8)
    axes[1].text(0.02, 0.505, "chance", fontsize=7, transform=axes[1].get_yaxis_transform())
    axes[1].set_xticks(np.arange(len(lab)) + 1.5 * w); axes[1].set_xticklabels(lab, fontsize=7)
    axes[1].set_ylim(0.45, None); axes[1].set_ylabel("BLiMP accuracy")
    axes[1].legend(fontsize=7, frameon=False)
    axes[1].set_title("Parents vs merges", fontsize=9)
    fig.suptitle("SET 1 · likelihood recovery vs grammatical competence", fontsize=10)
    fig.tight_layout(); fig.savefig(f"{F}/set1_blimp_dissociation.png", bbox_inches="tight"); plt.close(fig)

# ------------------------------------------------------------------ 6. scale trend
if rows1:
    szs = sorted({r["size"] for r in rows1}, key=lambda s: int(s[:-1]))
    P = {"14m": 14, "31m": 31, "70m": 70, "160m": 160, "410m": 410}
    x = [P[s] for s in szs]
    naive = [np.mean([r["dfloor_M0_naive_avg"] for r in rows1 if r["size"] == s]) for s in szs]
    resc = [np.mean([1 - min(r["dfloor_M1_perm_avg"], r["dfloor_M1_orth_avg"]) / r["dfloor_M0_naive_avg"]
                     for r in rows1 if r["size"] == s]) * 100 for s in szs]
    fig, ax = plt.subplots(figsize=(4.6, 3.6))
    ax.plot(x, naive, "o-", color="#c0392b", label="naive merge Δfloor (nats/token)")
    ax.set_xscale("log"); ax.set_xticks(x); ax.set_xticklabels(szs)
    ax.set_xlabel("PolyPythia size"); ax.set_ylabel("naive Δfloor (nats/token)", color="#c0392b")
    ax2 = ax.twinx(); ax2.plot(x, resc, "s--", color="#2471a3", label="rescue by alignment (%)")
    ax2.set_ylabel("% of naive Δfloor removed by alignment", color="#2471a3"); ax2.grid(False)
    ax.set_title("Both the obstruction AND alignment's purchase\nshrink with scale", fontsize=9)
    fig.tight_layout(); fig.savefig(f"{F}/set1_scale_trend.png", bbox_inches="tight"); plt.close(fig)
print("extra figures written")

# ------------------------------------------------------------------ 7. B-GPT ceiling
bgc = load("bgpt_ceiling.jsonl")
if bgc:
    arms = list(bgc[0]["arms"])
    nice = {"bgpt_joint_bilingual": "B-GPT\njoint bilingual", "goldfish_eng_parent": "Goldfish\neng parent",
            "goldfish_partner_parent": "Goldfish\npartner parent", "merge_M0_naive": "merge\nM0 naive",
            "merge_M1a_vocab": "merge\nM1a vocab"}
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.9))
    langs = [r["lang"].split("_")[0] for r in bgc]
    w = 0.8 / len(arms)
    for i, a in enumerate(arms):
        axes[0].bar(np.arange(len(bgc)) + i * w, [0.5 * (r["arms"][a]["nats_per_byte_eng"] +
                                                          r["arms"][a]["nats_per_byte_x"]) for r in bgc],
                    width=w, label=nice.get(a, a).replace("\n", " "))
        axes[1].bar(np.arange(len(bgc)) + i * w, [0.5 * (r["arms"][a]["multiblimp_eng"] +
                                                          r["arms"][a]["multiblimp_x"]) for r in bgc],
                    width=w, label=nice.get(a, a).replace("\n", " "))
    for ax, yl, ttl in ((axes[0], "nats / UTF-8 byte (lower better)", "Likelihood"),
                        (axes[1], "MultiBLiMP accuracy (higher better)", "Accuracy")):
        ax.set_xticks(np.arange(len(bgc)) + 0.4 - w / 2)
        ax.set_xticklabels([f"eng–{l}" for l in langs])
        ax.set_ylabel(yl, fontsize=8); ax.set_title(ttl, fontsize=9)
    axes[1].axhline(0.5, color="k", ls="--", lw=.8)
    axes[1].set_ylim(0.0, 1.02)
    axes[0].legend(fontsize=6.5, frameon=False, ncol=2)
    fig.suptitle("SET 4 · what success looks like: a jointly-trained bilingual model vs the merges\n"
                 "(all arms re-scored at a matched 128-token context)", fontsize=9)
    fig.tight_layout(); fig.savefig(f"{F}/set4_joint_ceiling.png", bbox_inches="tight"); plt.close(fig)

# ------------------------------------------------------------------ 8. SET 4 likelihood vs accuracy
mbr = load("set4_multiblimp.jsonl")
if mbr and rows4:
    by_lang = {r["lang"]: r for r in rows4}
    fig, ax = plt.subplots(figsize=(5.4, 4.1))
    _cyc = plt.rcParams["axes.prop_cycle"].by_key()["color"]
    for li, r in enumerate(mbr):
        s4 = by_lang.get(r["lang"])
        if not s4: continue
        col = _cyc[li % len(_cyc)]
        first = True
        for k in r["rungs"]:
            key = f"delta_floor_eng_{k}"
            if key not in s4: continue
            ax.scatter(s4[key], r["rungs"][k]["mb_eng"], s=30, alpha=.85, color=col,
                       marker=("o" if k == "M0_naive_avg" else "^"),
                       label=(r["lang"].split("_")[0] if first else None))
            first = False
    ax.scatter([0], [mbr[0]["parents"]["eng_on_mb_eng"]], marker="*", s=220, color="k",
               label="English parent (Δfloor 0)", zorder=5)
    ax.scatter([], [], marker="o", s=30, color="grey", label="naive merge")
    ax.scatter([], [], marker="^", s=30, color="grey", label="aligned / transported rungs")
    ax.axhline(0.5, color="grey", ls="--", lw=.8)
    ax.text(0.02, 0.505, "chance", fontsize=7, transform=ax.get_yaxis_transform())
    ax.set_xlabel("Δfloor on English text  (nats/byte, LIKELIHOOD)")
    ax.set_ylabel("MultiBLiMP-English  (ACCURACY)")
    ax.set_title("SET 4 · a merge can be destroyed by likelihood\nand still score well above chance",
                 fontsize=9)
    ax.legend(fontsize=7, frameon=False)
    fig.tight_layout(); fig.savefig(f"{F}/set4_likelihood_vs_accuracy.png", bbox_inches="tight"); plt.close(fig)
print("ceiling figures written")