compose-audit / code /make_report.py
suchirsalhan's picture
Upload code/make_report.py with huggingface_hub
13aaf2d verified
Raw
History Blame
16.7 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,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. No accuracy benchmark was run inside 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 set4:
L.append("\n## SET 4 · Goldfish monolingual → bilingual merge (the real composition models)\n")
rung_keys = list(set4[0]["rungs"])
hdr = ["pair", "vocab overlap", "floor eng", "floor X"] + [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("**Δ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.
""")
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:
body.append([d[ix["substrate"]], 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", "predictor", "n", "Spearman", "AUROC (held out by seed)",
"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("\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"])
cov.append(["BLiMP / MultiBLiMP accuracy", "0", "**NOT RUN**",
"No benchmark harness was close to wired inside this window. Deliberately not built from scratch. The Δfloor results below therefore 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")