compose-audit / code /make_report.py
suchirsalhan's picture
Upload code/make_report.py with huggingface_hub
f763816 verified
Raw
History Blame
49.5 kB
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,31m,70m,160m,410m}-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; **BLiMP accuracy** on the same merges | Δ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); **MultiBLiMP 1.0 accuracy** on the same merges |
| **What the metric is** | Δfloor is a **likelihood** metric; BLiMP is an **accuracy** metric | Δfloor is a **likelihood** metric; MultiBLiMP is an **accuracy** metric |
> **Δfloor is a likelihood metric, not benchmark accuracy — and here they come apart.** The audit's
> sharpest point is that a likelihood rescue has not been shown to transfer to accuracy. We tested
> that transfer directly, on the same merges, with BLiMP (SET 1) and MultiBLiMP 1.0 (SET 4), and it
> **does not hold in either direction**: in SET 1 a ~70% Δfloor rescue buys ~0.03 BLiMP accuracy over
> the naive merge, and in SET 4 a merge whose Δfloor says it is destroyed still scores 0.68 on
> MultiBLiMP-English. Neither metric may be reported as a proxy for the other. Every table below
> states which one it is.
""")
# ---------------- headline summary (computed, so it cannot drift from the tables)
_bl = load("blimp_*.jsonl"); _rp = load("repair_*.jsonl"); _mb = load("set4_multiblimp.jsonl")
if set1:
hl = []
s14 = [r for r in set1 if r["size"] == sizes[0]]
dd = {}
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])
db = np.array([min(r["rungs"]["M1_perm_avg"]["delta_floor"],
r["rungs"]["M1_orth_avg"]["delta_floor"]) for r in sub])
dd[sz] = (len(sub), d0.mean(), float(np.mean(1 - db / d0) * 100), db.mean())
hl.append(f"1. **Naive averaging of two seed-only-different real LMs is catastrophic, at every "
f"size.** Δfloor {' · '.join(f'{sz}: +{dd[sz][1]:.1f}' for sz in sizes)} nats/token "
f"against parent floors of 3–4.4 nats/token, i.e. above the uniform-over-vocabulary "
f"reference of 10.8 for all but the largest. n = "
f"{' / '.join(str(dd[sz][0]) for sz in sizes)} pairs.")
hl.append(f"2. **Unit alignment removes a large fraction of that gap and still does not produce a "
f"usable model.** Best of permutation / Procrustes removes "
f"{' · '.join(f'{sz}: {dd[sz][2]:.0f}%' for sz in sizes)} — leaving "
f"{' · '.join(f'{dd[sz][3]:.1f}' for sz in sizes)} nats/token above the better parent.")
hl.append(f"3. **The rescue shrinks monotonically with scale** ({sizes[0]}: {dd[sizes[0]][2]:.0f}% "
f"→ {sizes[-1]}: {dd[sizes[-1]][2]:.0f}%) while the naive gap shrinks too — so the "
f"coordinate-removable share of the obstruction is falling in exactly the direction the "
f"field is scaling. (Per-size n is listed in (1); the largest sizes carry the fewest "
f"pairs, so read the trend from the sizes with complete 36-pair grids and treat the "
f"largest as directional.)")
if _bl:
b14 = [b for b in _bl if b["size"] == sorted({x['size'] for x in _bl}, key=lambda x: int(x[:-1]))[0]]
pm = np.mean([np.mean(list(b["parent_acc"].values())) for b in b14])
m0 = np.mean([b["rungs"]["M0_naive_avg"]["blimp_acc"] for b in b14])
m1 = np.mean([max(b["rungs"][k]["blimp_acc"] for k in b["rungs"] if k.startswith("M1")) for b in b14])
hl.append(f"4. **The likelihood rescue does not transfer to accuracy.** On pythia-{b14[0]['size']} "
f"(n={len(b14)}), parents average {pm:.3f} on BLiMP; the naive merge {m0:.3f} and the "
f"aligned merge {m1:.3f}, against chance 0.500. A ~70% Δfloor rescue buys ~"
f"{(m1-m0):.3f} accuracy. Pairwise, the two rescues are uncorrelated.")
if set4:
d0e = np.mean([r["rungs"]["M0_naive_avg"]["delta_floor_eng"] for r in set4])
bst = np.mean([min(r["rungs"][k]["delta_floor_eng"] for k in r["rungs"] if k.startswith("M1")) for r in set4])
hl.append(f"5. **On the real bilingual-composition models the merge fails and alignment does not "
f"rescue it.** Goldfish eng×{{nld,spa,ell,pol}}: naive Δfloor on English text "
f"+{d0e:.2f} nats/byte against a 0.81 floor; the best M1 rung +{bst:.2f}. The binding "
f"constraint is the **vocabulary**, not the coordinate frame — the English tokenizer "
f"UNK-s 45% of Greek and 11% of Polish, and no permutation or rotation can address that.")
if _mb:
hl.append(f"6. **…and the accuracy dissociation runs the other way there.** The same "
f"likelihood-destroyed Goldfish merges retain "
f"{np.mean([r['rungs']['M0_naive_avg']['mb_eng'] for r in _mb]):.2f} on "
f"MultiBLiMP-English (parent {_mb[0]['parents']['eng_on_mb_eng']:.2f}, chance 0.50). "
f"Δfloor and benchmark accuracy dissociate in **both** directions; neither implies the other.")
hl.append("7. **P0-2: the pre-merge predictors do not predict the realised rescue.** Held out by "
"seed pair on a complete 36-pair grid with a seed-cluster permutation null, no predictor "
"survives BH correction. Reported as the negative transfer result it is.")
if _rp:
hl.append("8. **This is not an under-trying artifact.** REPAIR-style statistics correction on "
"top of the alignment — the strongest training-free merge here — improves the "
"likelihood further and still leaves BLiMP near chance.")
L.append("\n## Headline findings\n")
L.append("\n".join(hl) + "\n")
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")
_b = [[f"eng–{r['lang']}"] + [fmt(r["rungs"][k]["delta_floor_eng"]) for k in rung_keys] for r in set4]
_b.append(["**mean of the 4**"] + ["**" + fmt(float(np.mean([r["rungs"][k]["delta_floor_eng"] for r in set4]))) + "**"
for k in rung_keys])
L.append(md_table(["pair"] + rung_keys, _b))
L.append("\nAveraged over the four pairs the best M1 rung removes **"
+ fmt(100 * (1 - min(np.mean([r["rungs"][k]["delta_floor_mean"] for r in set4]) for k in rung_keys if k.startswith("M1"))
/ np.mean([r["rungs"]["M0_naive_avg"]["delta_floor_mean"] for r in set4])), 1)
+ "%** of the naive merge's Δfloor. For contrast, on SET 1 — where the two parents share "
"data, architecture and tokenizer and differ only in seed — the same family of aligners "
"removes 70% at 14M. The Goldfish obstruction is not the kind of obstruction alignment "
"addresses.\n")
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))
# ---------------- REPAIR
rep = load("repair_*.jsonl")
if rep:
L.append("\n## Did we try hard enough? · REPAIR on top of the alignment\n")
L.append("The obvious objection to a negative merging result is that averaging is a weak merge: it "
"halves the variance of every pre-activation, and REPAIR (Jordan et al., ICLR 2023) shows "
"that restoring those statistics recovers most of the remaining barrier on vision nets. "
"This rung adds it, training-free: after the permutation-aligned average, walk the layers "
"in order and affine-correct each Linear's per-unit pre-activation mean and std to the "
"average of the two parents' own statistics on the same corpus. `M5` applies the same "
"correction to the *naive* merge, to separate what alignment contributes from what "
"statistics-repair contributes.\n")
rk = ["M0_naive_avg", "M1_perm_avg", "M4_perm_repair", "M5_naive_repair"]
body = []
for sz in sorted({r["size"] for r in rep}, key=lambda x: int(x[:-1])):
sub = [r for r in rep if r["size"] == sz]
fl = np.mean([r["floor"] for r in sub]); ce = np.mean([r["blimp_ceiling"] for r in sub])
for k in rk:
if k not in sub[0]["rungs"]: continue
d = np.array([r["rungs"][k]["delta_floor"] for r in sub])
a = np.array([r["rungs"][k]["blimp_acc"] for r in sub])
body.append([f"pythia-{sz}", len(sub), k, fmt(d.mean(), 2), fmt(np.median(d), 2),
fmt(a.mean()), fmt((a.mean() - 0.5) / (ce - 0.5) * 100, 1) + "%"])
body.append([f"pythia-{sz}", len(sub), "**parents**", "0.00", "0.00", fmt(ce), "100.0%"])
L.append(md_table(["substrate", "n pairs", "rung", "mean Δfloor (nats/tok)", "median Δfloor",
"BLiMP accuracy", "% of the parents' above-chance margin retained"], body))
L.append("""
REPAIR does help the likelihood — it takes a further bite out of the aligned merge's Δfloor, and it
is the best training-free merge in this report. It does **not** change the conclusion. The repaired
aligned merge is still many nats/token above the better parent, still above the
uniform-over-vocabulary reference at the small sizes, and still close to chance on BLiMP. Applied to
the *naive* merge it barely moves anything, which is the expected pattern: variance repair is only
useful once the units correspond.
So the negative result is not an artifact of using a deliberately weak merge operator. Naive
averaging, unit-aligned averaging, orthogonal alignment, task arithmetic, TIES and REPAIR-corrected
alignment were all tried on the same pairs; the best of them recovers most of the likelihood gap at
14M, a quarter of it at 160M, and grammatical competence in none of them.
""")
# ---------------- SET 4 accuracy arm
mb = load("set4_multiblimp.jsonl")
if mb:
L.append("\n## SET 4 · the accuracy arm (MultiBLiMP 1.0)\n")
L.append("`jumelet/multiblimp` covers exactly the four partner languages plus English. Minimal "
"pairs are `sen` vs `wrong_sen`; correct when the grammatical member gets the higher "
"total log-probability. **Chance = 0.500.** The merged models live in the **English** "
"parent's token-id space, so partner-language items are scored through the English "
"tokenizer — the UNK column says how badly that hurts, and where it is large the "
"partner-language number is a tokenizer artifact, not a competence measurement.\n")
rk = list(mb[0]["rungs"])
body = []
for r in mb:
body.append([f"eng–{r['lang']}", r["n_items_x"], f"{r['unk_rate_eng_tok_on_x_items']:.1%}",
fmt(r["parents"]["eng_on_mb_eng"]), fmt(r["parents"]["x_on_mb_x"]),
fmt(r["parents"]["eng_on_mb_x"])])
L.append("**Parents** (each on its own tokenizer except the last column):\n")
L.append(md_table(["pair", "n items (partner)", "UNK rate, English tok on partner items",
"English parent, MultiBLiMP-eng", "partner parent, MultiBLiMP-partner",
"English parent, MultiBLiMP-partner"], body))
L.append("\n**Merged models, MultiBLiMP-English accuracy** (the clean cell — 0.04% UNK; English "
"parent ceiling in the first column):\n")
L.append(md_table(["pair", "English parent"] + rk,
[[f"eng–{r['lang']}", fmt(r["parents"]["eng_on_mb_eng"])] +
[fmt(r["rungs"][k]["mb_eng"]) for k in rk] for r in mb]))
L.append("\n**Merged models, MultiBLiMP-partner accuracy** (partner parent ceiling in the first "
"column; rows with a high UNK rate are struck through in interpretation, not in the "
"numbers):\n")
L.append(md_table(["pair", "partner parent", "UNK"] + rk,
[[f"eng–{r['lang']}", fmt(r["parents"]["x_on_mb_x"]),
f"{r['unk_rate_eng_tok_on_x_items']:.0%}"] +
[fmt(r["rungs"][k]["mb_x"]) for k in rk] for r in mb]))
L.append("""
**What the accuracy arm adds, and it cuts the other way from SET 1.**
- The English-side accuracy of the naive merge (mean 0.680, parent 0.962) is far below the parent
but **far above chance** — while its Δfloor on the same text is roughly a nat per byte, i.e. by the likelihood
metric the model is destroyed. A merge can look annihilated in nats and still retain a large
fraction of an agreement benchmark.
- The unit-aligned rungs are a **wash** against the naive merge on accuracy. Averaged over the four
pairs the naive merge scores 0.680 on MultiBLiMP-English against 0.645–0.671 for the aligned rungs,
and 0.536 on the partner side (Greek excluded) against 0.527–0.556. Individual cells go both ways —
the vocabulary-transported rungs help Spanish and hurt Dutch — with no consistent direction and a
spread far smaller than the ~0.30 gap to the parents. Nothing in the M1 family recovers
composition; they reshuffle a uniformly bad result.
- Greek is the clean illustration of the tokenizer wall: at a 45% UNK rate the English parent scores
0.03 on MultiBLiMP-Greek — far *below* chance, because `<unk>`-collapsed sentences make the
ungrammatical member the likelier string. Nothing about Greek grammar is being measured there. Any
cross-tokenizer merge that keeps one parent's vocabulary inherits this, and it is a property of the
vocabulary, not of the coordinate frame — no alignment over the permutation or orthogonal group
can touch it.
- Taken with SET 1: **Δfloor and benchmark accuracy dissociate in both directions.** In SET 1 a large
likelihood rescue buys almost no accuracy. In SET 4 a catastrophic likelihood loss leaves a lot of
accuracy standing. Whichever of the two you report, the other does not follow from it.
""")
bgc = load("bgpt_ceiling.jsonl")
if bgc:
L.append("\n## SET 4 · what would SUCCESS look like? The jointly-trained bilingual ceiling\n")
L.append("A merge that fails is only interpretable against what a bilingual model of the same "
"budget actually achieves. B-GPT (Arnett et al.) trains English+X **jointly** with one "
"shared tokenizer — the target the composition literature is trying to reach without "
"joint training. B-GPT's context window is 128 tokens, so **every arm in this table, "
"including the Goldfish parents and merges, is re-scored at a matched 128-token "
"context**; these numbers are therefore not directly comparable to the 512-token SET 4 "
"tables above, only to each other.\n")
arms = list(bgc[0]["arms"])
for metric, lbl in (("nats_per_byte_eng", "nats/byte, English"), ("nats_per_byte_x", "nats/byte, partner"),
("multiblimp_eng", "MultiBLiMP-English"), ("multiblimp_x", "MultiBLiMP-partner")):
L.append(f"\n**{lbl}**" + (" (lower is better)" if "nats" in metric else " (higher is better, chance 0.500)") + "\n")
L.append(md_table(["pair"] + arms,
[[f"eng–{r['lang']}"] + [fmt(r["arms"][a][metric]) for a in arms] for r in bgc]))
L.append("""
This is the cleanest single statement the audit can make about SET 4. A jointly trained bilingual
model of the same parameter budget is **good at both languages at once** — near the monolingual
parents on likelihood and on MultiBLiMP. The merge of two monolingual models is not close, on either
metric, under any rung, in either anchoring direction. The gap is not a coordinate gap that a better
aligner might close; the joint model also has a *shared vocabulary*, which is exactly the axis the
alignment group cannot act on.
""")
rev = load("set4_reverse.jsonl")
if rev:
L.append("\n## SET 4 · reverse direction (the partner language is the anchor)\n")
L.append("Identical rungs, but the merged model lives in the **partner** language's tokenizer and "
"residual basis and English is transported into it. If the failure were an artifact of "
"anchoring on English it would not survive the swap.\n")
rk = list(rev[0]["rungs"])
L.append(md_table(["anchor", "floor (anchor lang)", "floor (English)"] + rk,
[[r["lang"], fmt(r["floor_x"]), fmt(r["floor_eng"])] +
[fmt(r["rungs"][k]["delta_floor_mean"]) for k in rk] for r in rev]))
L.append("\nΔfloor, mean over the two languages, nats/UTF-8 byte. The failure is symmetric: "
"anchoring on the partner language does not make the merge work either.\n")
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)}
def _f(d, k):
try: return float(d[ix[k]])
except Exception: return float("nan")
body = []
for oc in ("rescue_frac", "dfloor_M1best"):
sel = [d for d in dat if d[ix["outcome"]] == oc]
for sub_ in sorted({d[ix["substrate"]] for d in sel}, key=lambda x: int(x.split("-")[1][:-1])):
ss = [d for d in sel if d[ix["substrate"]] == sub_]
mv = [d for d in ss if d[ix["predictor"]].startswith("MULTIV")]
uv = sorted([d for d in ss if not d[ix["predictor"]].startswith("MULTIV")],
key=lambda d: -abs(_f(d, "auroc_heldout_by_seed") - 0.5))[:6]
for d in uv + mv:
body.append([sub_, oc, d[ix["predictor"]], d[ix["n_pairs"]],
fmt(_f(d, "spearman_rescue")), fmt(_f(d, "auroc_heldout_by_seed")),
fmt(_f(d, "perm_null_mean")), fmt(_f(d, "perm_null_p")),
fmt(_f(d, "bh_q"))])
L.append("Showing, per substrate and per outcome, the **six predictors with the largest "
"|AUROC − 0.5|** plus the multivariate ridge. The full table (every predictor, both "
"outcomes, every substrate) is `results/predictor_auroc.csv`; selecting the extremes "
"here is deliberately generous to the positive claim.\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
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.
""")
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("\n## Coverage — what ran and what did not\n")
cov = []
for sz in ["14m", "31m", "70m", "160m", "410m"]:
n = len([r for r in set1 if r["size"] == sz])
tot = 36 if sz != "410m" else 15
cov.append([f"SET 1 Δfloor · pythia-{sz}", f"{n}/{tot} seed pairs",
"complete" if n >= tot else ("partial" if n else "NOT RUN"),
"M0 naive · M1 permutation · M1 Procrustes · M2 task-arithmetic · M3 TIES; LMC barrier for M0 and M1-perm"])
if abl:
for sz in sorted({r["size"] for r in abl}):
cov.append([f"SET 1 control · pythia-{sz}", f"{len([r for r in abl if r['size'] == sz])}/3 pairs",
"complete", "init-seed-only vs data-order-only, same rungs"])
nb = {}
for b in blimp: nb[b["size"]] = nb.get(b["size"], 0) + 1
cov.append(["SET 1 accuracy · BLiMP", ", ".join(f"pythia-{k}: {v}/36" for k, v in sorted(nb.items(), key=lambda kv: int(kv[0][:-1]))) or "0",
"RAN" if blimp else "**NOT RUN**",
"67 paradigms from `nyu-mll/blimp`, minimal-pair sentence-logprob scoring, on the SAME merges"])
nr = {}
for r_ in rep: nr[r_["size"]] = nr.get(r_["size"], 0) + 1
cov.append(["SET 1 · REPAIR rung", ", ".join(f"pythia-{k}: {v}/36" for k, v in sorted(nr.items(), key=lambda kv: int(kv[0][:-1]))) or "0",
"RAN" if rep else "**NOT RUN**", "M4 = permutation-aligned average + pre-activation statistics repair; M5 = naive + repair; Δfloor and BLiMP on the same merges"])
cov.append(["SET 4 Δfloor · English-anchored", f"{len(set4)}/4 language pairs ({', '.join(r['lang'] for r in set4) or '—'})",
"complete" if len(set4) == 4 else ("partial" if set4 else "NOT RUN"),
"M0 naive · M1a vocab-transport · M1b/c vocab+unit-aligned · M1d/e forced-residual · M1f units-only · M1g/h embedding-row Procrustes"])
cov.append(["SET 4 Δfloor · partner-anchored (reverse)", f"{len(rev)}/4 language pairs",
"complete" if len(rev) == 4 else ("partial" if rev else "NOT RUN"), "same rungs, roles swapped"])
cov.append(["SET 4 accuracy · MultiBLiMP 1.0", f"{len(mb)}/4 language pairs",
"RAN" if mb else "**NOT RUN**", "`jumelet/multiblimp`, English + partner, on the SAME merges; UNK rate reported per cell"])
bg = load("bgpt_ceiling.jsonl")
cov.append(["SET 4 · jointly-trained bilingual ceiling", f"{len(bg)}/4 language pairs",
"RAN" if bg else "**NOT RUN**",
"`catherinearnett/B-GPT_en_X_simultaneous` vs the Goldfish parents and merges, all scored at a matched 128-token context"])
cov.append(["SET 4 · task-arithmetic / TIES", "0", "**NOT APPLICABLE**",
"Both operators need a shared ancestor. Two independently trained monolingual Goldfish models have none, and with one parent as a pseudo-base the operators reduce to returning the other parent. Excluded on definition, not on time."])
cov.append(["SET 1 · pythia-410m full grid", f"{len([r for r in set1 if r['size'] == '410m'])}/36 possible pairs", "partial",
"6 seeds only (15 possible pairs) and a reduced eval budget; the per-pair alignment cost is ~9 min at this width. Treat 410m as directional."])
cov.append(["Goldfish other tiers / other languages", "0", "NOT RUN", "Only the 1000mb tier and the four audit languages."])
cov.append(["Any downstream task beyond BLiMP/MultiBLiMP", "0", "NOT RUN",
"Both benchmarks are minimal-pair grammaticality tests. They do not speak to reasoning, generation quality or instruction following."])
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,31m,70m,160m,410m}.jsonl SET 1 per-pair raw records (predictors, rungs, barriers)
results/set1_pairs.csv SET 1 per-pair flat table
results/abl_160m-{weight,data}.jsonl init-seed-only vs data-order-only control
results/blimp_{size}.jsonl, blimp_pairs.csv SET 1 BLiMP accuracy, per pair and per rung
results/repair_{size}.jsonl REPAIR rung (Δfloor + BLiMP on the same merges)
results/set4_goldfish.jsonl, set4_pairs.csv SET 4 Δfloor, English-anchored
results/set4_reverse.jsonl SET 4 Δfloor, partner-language-anchored
results/set4_multiblimp.jsonl SET 4 MultiBLiMP accuracy
results/set4_tokenizer_diag.json UNK rates / bytes-per-token per (tokenizer, language)
results/rung_summary.csv rung x substrate x metric summary
results/predictor_auroc.csv P0-2: held-out-by-seed AUROC, seed-cluster null, BH q
results/predictor_transfer_across_size.csv P0-2: leave-one-substrate-out transfer
results/set4_predictors.csv P0-2 on SET 4 (n=4, descriptive only)
figs/set1_dfloor_by_rung.png Δfloor by rung, per size
figs/set1_scale_trend.png obstruction and rescue vs model size
figs/set1_rescue_vs_predictor.png realised rescue vs coordinate share / CKA
figs/set1_roc.png held-out-by-seed ROC
figs/set1_blimp_dissociation.png likelihood rescue vs accuracy rescue
figs/set4_dfloor.png Δfloor by rung, Goldfish
code/*.py every script that produced the above
```
**Reproducing.** `common.py` holds the corpora and evaluation; `gpt2_align.py` holds the GPT-2
(Conv1D) symmetry factors that `mergeschool.core.alignment`'s row-major aligners do not cover; the
`set1_*`/`set4_*` scripts are the drivers, each with a resumable JSONL ledger; `analyze.py` builds
the tables and figures and `make_report.py` writes this document. Merge operators, aligners, quotient
metrics and the barrier are imported unmodified from `mergeschool.core`.
""")
open("/root/compose-audit/RESULTS_COMPOSE_AUDIT.md", "w").write("\n".join(L) + "\n")
if rung_rows:
keys = []
for r in rung_rows:
for k in r:
if k not in keys: keys.append(k)
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")