merge-accuracy / code /analyze.py
suchirsalhan's picture
Upload code/analyze.py with huggingface_hub
3a47dcf verified
Raw
History Blame Contribute Delete
46.5 kB
"""Tables, figures and RESULTS_MERGE_ACCURACY.md for the chat-vector alignment experiment."""
from __future__ import annotations
import os, json, time
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
R = "/root/merge-accuracy"; RES, FIG = f"{R}/results", f"{R}/figs"
os.makedirs(FIG, exist_ok=True)
def load(p):
d = {}
if os.path.exists(p):
for line in open(p):
try: r = json.loads(line); d[r["key"]] = r
except Exception: pass
return list(d.values())
CV, LG = load(f"{RES}/chatvec.jsonl"), load(f"{RES}/ledger.jsonl")
diag = {r["fork"]: r["diag"] for r in CV if r.get("kind") == "diag"}
# Reference rows were written by more than one worker, and a later worker that only knew about
# one target language would otherwise clobber the languages the first one measured. Merge the
# accuracy dicts across every reference record instead of taking the last write.
# NOTE: read these from the RAW ledger, not from `CV`. `load()` keys by record id and keeps the
# last write, and several workers wrote a "REF_instruct" record -- a worker that only knew about one
# target language would otherwise silently drop the languages an earlier worker had measured (it
# did: the Indonesian and Thai Instruct ceilings vanished from the tables).
refs = {}
for _line in (open(f"{RES}/chatvec.jsonl") if os.path.exists(f"{RES}/chatvec.jsonl") else []):
try:
r = json.loads(_line)
except Exception:
continue
if r.get("kind") == "reference":
cur = refs.setdefault(r["arm"], {"arm": r["arm"], "acc": {}, "model": r.get("model")})
cur["acc"].update(r.get("acc") or {})
byfork = {}
for r in CV:
if r.get("kind") in ("fork", "merge", "control"): byfork.setdefault(r["fork"], []).append(r)
def get(fk, arm, lam=None):
for r in byfork.get(fk, []):
if r["arm"] == arm and (lam is None or r.get("lam") == lam): return r
return None
CHANCE = {"arc_easy": 0.25, "ifeval_prompt": 0.0, "ifeval_inst": 0.0}
def chance(m): return 0.25 if m.startswith("belebele") else CHANCE.get(m, float("nan"))
def is_ctl(fk): return "_PERM" in fk
# ------------------------------------------------------------------ summary rows
rows = []
for fk, d in sorted(diag.items()):
fa = get(fk, "fork_alone")
if fa is None: continue
lang = fa.get("lang")
for lam in sorted({r["lam"] for r in byfork[fk] if r.get("lam") is not None}):
nv, al = get(fk, "naive", lam), get(fk, "aligned", lam)
if not (nv and al and nv.get("acc") and al.get("acc")): continue
eff_id = bool(d.get("hidden_is_identity") and d.get("heads_is_identity")
and abs(d["coord_share"]) <= 1e-9)
row = {"fork": fk, "lang": lang, "lam": lam, "is_control": is_ctl(fk),
"g_is_effectively_identity": eff_id,
"frac_layers_permuted": d.get("frac_layers_permuted", 0.0),
"coord_share": d["coord_share"], "is_identity": d["is_identity"],
"hidden_is_identity": d.get("hidden_is_identity"),
"heads_is_identity": d.get("heads_is_identity"),
"cka_mean": d.get("cka_mean"), "rel_drift": d.get("rel_drift"),
"weight_cosine_vs_base": d.get("weight_cosine_vs_base"),
"predicted_align_helps": d["PREDICTION_align_helps"],
"align_fit_seconds": d.get("fit_seconds")}
for m in fa["acc"]:
key = "tgt" if m == f"belebele_{lang}" else m
row[f"{key}__fork"] = fa["acc"][m]
row[f"{key}__naive"] = nv["acc"][m]
row[f"{key}__aligned"] = al["acc"][m]
row[f"{key}__delta"] = al["acc"][m] - nv["acc"][m]
row[f"{key}__chance"] = chance(m)
for tag, rf in (("base", "REF_base"), ("instruct", "REF_instruct")):
v = refs.get(rf, {}).get("acc", {}).get(m)
if v is not None: row[f"{key}__ref_{tag}"] = v
rows.append(row)
if rows:
ks = sorted({k for r in rows for k in r})
head = ["fork", "lang", "lam", "is_control", "g_is_effectively_identity",
"frac_layers_permuted", "coord_share", "predicted_align_helps"]
ks = head + [k for k in ks if k not in head]
with open(f"{RES}/chatvec_summary.csv", "w") as f:
f.write(",".join(ks) + "\n")
for r in rows:
f.write(",".join(str(r.get(k, "")) for k in ks) + "\n")
with open(f"{RES}/all_model_accuracies.csv", "w") as f:
allm = sorted({m for r in CV if r.get("acc") for m in r["acc"]})
f.write("key,kind,fork,arm,lam," + ",".join(allm) + "\n")
for r in sorted(CV, key=lambda z: z["key"]):
if not r.get("acc"): continue
f.write(f'{r["key"]},{r.get("kind")},{r.get("fork")},{r.get("arm")},{r.get("lam")},'
+ ",".join(f'{r["acc"][m]:.4f}' if isinstance(r["acc"].get(m), float) else ""
for m in allm) + "\n")
with open(f"{RES}/diagnostics.csv", "w") as f:
dk = ["coord_share", "is_identity", "hidden_is_identity", "heads_is_identity", "bnd_raw",
"bnd_final", "cka_mean", "cka_last", "rel_drift", "weight_cosine_vs_base",
"PREDICTION_align_helps", "fit_seconds", "residual", "hidden", "heads", "head_group",
"frac_layers_permuted"]
f.write("fork," + ",".join(dk) + "\n")
for fk, d in sorted(diag.items()):
f.write(fk + "," + ",".join(str(d.get(k, "")) for k in dk) + "\n")
print(f"{len(rows)} summary rows, {len(diag)} diagnostics")
# ================================================================== FIGURES
plt.rcParams.update({"figure.dpi": 150, "font.size": 9, "axes.grid": True, "grid.alpha": 0.25,
"axes.spines.top": False, "axes.spines.right": False,
"axes.edgecolor": "#94a3b8", "text.color": "#1e293b",
"axes.labelcolor": "#334155", "xtick.color": "#475569",
"ytick.color": "#475569"})
CR, CC, CG = "#2563eb", "#dc2626", "#059669"
THRESH = 0.01
def lab(fk):
return (fk.replace("_PERM", " perm ").replace("swallow_ja", "Swallow")
.replace("typhoon2_th", "Typhoon2").replace("sealion_id", "SEA-LION"))
AXES = [("ifeval_prompt", "IFEval strict prompt accuracy\n(instruction following -- what the chat vector is FOR)"),
("tgt", "Belebele, target language\n(language capability)"),
("belebele_eng_Latn", "Belebele English\n(retention)")]
# cross-group point: coordinate share vs the accuracy change alignment produced (alpha = 0.5)
xg = None
try:
_d = next(r["diag"] for r in LG if r.get("arm") == "diag")
_cs = _d.get("coord_fraction_bn_perm", 0.0)
_n = next(r for r in LG if r.get("arm") == "naive" and r.get("alpha") == 0.5)
_a = next(r for r in LG if r.get("arm") == "aligned" and r.get("alpha") == 0.5)
xg = (_cs, _a["acc"]["mean"] - _n["acc"]["mean"])
except Exception:
xg = None
# Categorical palette validated with the dataviz six-checks (worst adjacent CVD dE 8.6 deutan,
# normal-vision 32.0, contrast all >= 3:1). Marker SHAPE carries identity too, which is the
# secondary encoding the 6-8 dE band requires.
RESOLUTION = 2.0 / 300.0 # +/- 2 items on a 300-item benchmark: what "no change" means here
def _group_annotate(ax, pts, dx=9, dy=5):
"""Coincident points get ONE label, not three stacked on top of each other."""
b = {}
for x, y, name in pts:
b.setdefault((round(x, 6), round(y, 5)), []).append(name)
for (x, y), names in b.items():
ax.annotate(" / ".join(sorted(set(names))), (x, y), textcoords="offset points",
xytext=(dx, dy), fontsize=7, color="#334155")
if rows:
fig, axs = plt.subplots(1, 3, figsize=(13.4, 4.4))
for ax, (m, ttl) in zip(axs, AXES):
pts = [(r["coord_share"], r.get(f"{m}__delta"), r) for r in rows
if r.get(f"{m}__delta") is not None]
ys = [y for _, y, _ in pts] + ([xg[1]] if (m == "tgt" and xg) else []) + [0.0]
lim = max(0.05, max(abs(v) for v in ys) * 1.35)
ax.axhspan(-RESOLUTION, RESOLUTION, color="#94a3b8", alpha=0.18, lw=0, zorder=0)
ax.axhline(0, color="#334155", lw=1.0, zorder=1)
ax.axvline(THRESH, color="#b45309", lw=1.1, ls=":", zorder=1)
for x, y, r in pts:
ax.scatter(x, y, s=46 + 90 * r["frac_layers_permuted"],
c=CC if r["is_control"] else CR, marker="D" if r["is_control"] else "o",
zorder=3, edgecolors="white", linewidths=1.2)
_group_annotate(ax, [(x, y, lab(r["fork"])) for x, y, r in pts])
if m == "tgt" and xg is not None:
ax.scatter(xg[0], xg[1], s=80, c=CG, marker="^", zorder=3,
edgecolors="white", linewidths=1.2)
ax.annotate("pythia x Zh-Pythia", (xg[0], xg[1]), textcoords="offset points",
xytext=(9, -13), fontsize=7, color="#334155")
ax.set_ylim(-lim, lim)
ax.set_xscale("symlog", linthresh=1e-3); ax.set_xlim(-2e-4, 1.8)
if ax is axs[0]:
ax.set_ylabel("accuracy gain from aligning")
ax.set_title(ttl, fontsize=8.5, loc="left", color="#334155")
ax.grid(alpha=0.22)
axs[0].scatter([], [], c=CR, s=60, label="real community CPT fork")
axs[0].scatter([], [], c=CC, marker="D", s=60, label="permutation control (ground truth)")
axs[0].scatter([], [], c=CG, marker="^", s=60, label="cross-group direct merge")
axs[0].plot([], [], color="#94a3b8", lw=6, alpha=0.35, label="+/- 2 items: measurement floor")
axs[0].plot([], [], ls=":", color="#b45309", label=f"decision threshold {THRESH}")
axs[0].legend(fontsize=7, frameon=False, loc="upper left")
fig.supxlabel("pre-merge coordinate share (the diagnostic, computed BEFORE any merge)",
fontsize=9.5, y=0.015)
fig.suptitle("Does the pre-merge diagnostic predict whether the chat vector needs aligning?",
fontsize=12, x=0.006, ha="left")
fig.tight_layout(rect=[0, 0.05, 1, 0.93])
fig.savefig(f"{FIG}/headline_diagnostic_vs_gain.png", bbox_inches="tight")
plt.close(fig)
# ---- secondary: naive vs aligned, y = x -------------------------------------------------
fig, axs = plt.subplots(1, 2, figsize=(9.6, 4.6))
for ax, (m, ttl) in zip(axs, AXES[:2]):
P = [r for r in rows if r.get(f"{m}__naive") is not None]
if not P: continue
v = [r[f"{m}__naive"] for r in P] + [r[f"{m}__aligned"] for r in P] + [r[f"{m}__fork"] for r in P]
lo, hi = min(v) - 0.04, max(v) + 0.04
ax.plot([lo, hi], [lo, hi], "--", color="#111", lw=1, label="y = x (alignment changes nothing)")
for r in P:
ax.scatter(r[f"{m}__naive"], r[f"{m}__aligned"], s=62,
c=CC if r["is_control"] else CR, marker="D" if r["is_control"] else "o",
zorder=3, edgecolors="white", linewidths=1.1)
ax.scatter(r[f"{m}__naive"], r[f"{m}__fork"], s=26, facecolors="none",
edgecolors="#94a3b8", zorder=2)
rf = r.get(f"{m}__ref_instruct")
if rf is not None: ax.axhline(rf, color="#94a3b8", lw=0.8, ls=":")
_group_annotate(ax, [(r[f"{m}__naive"], r[f"{m}__aligned"],
lab(r["fork"]) + (f" λ{r['lam']}" if r["lam"] != 1.0 else ""))
for r in P], dx=7, dy=5)
ax.scatter([], [], c=CR, s=55, label="real community fork")
ax.scatter([], [], c=CC, marker="D", s=55, label="permutation control")
ax.scatter([], [], facecolors="none", edgecolors="#94a3b8", s=30, label="fork alone")
ax.plot([], [], ls=":", color="#94a3b8", label="official Instruct")
ax.set_xlim(lo, hi); ax.set_ylim(lo, hi)
ax.set_xlabel("naive chat vector"); ax.set_ylabel("aligned chat vector")
ax.set_title(ttl.split("\n")[0], fontsize=9, loc="left")
ax.legend(fontsize=7, frameon=False, loc="lower right")
fig.suptitle("Aligned vs naive chat vector (open circle = fork alone; dotted = official Instruct)",
fontsize=10.5, x=0.01, ha="left")
fig.tight_layout(rect=[0, 0, 1, 0.93])
fig.savefig(f"{FIG}/scatter_naive_vs_aligned.png", bbox_inches="tight"); plt.close(fig)
# ---- dose-response: the diagnostic vs the true amount of frame drift, and the payoff --------
ctl = sorted([r for r in rows if r["is_control"] and r["lam"] == 1.0],
key=lambda r: r["frac_layers_permuted"])
ref = next((r for r in rows if r["fork"] == "swallow_ja" and r["lam"] == 1.0), None)
if ctl:
fig, ax = plt.subplots(1, 2, figsize=(10.4, 3.9))
ax[0].plot([r["frac_layers_permuted"] for r in ctl], [r["coord_share"] for r in ctl],
"o-", color=CC, lw=2, ms=9, mec="white", mew=1.2)
ax[0].axhline(THRESH, color="#b45309", ls=":", lw=1.2)
ax[0].annotate(f"decision threshold {THRESH}", (0.27, THRESH), textcoords="offset points",
xytext=(0, 7), fontsize=7.5, color="#b45309")
ax[0].set_ylim(0, 1.0)
ax[0].set_xlabel("fraction of layers actually re-parameterised (ground truth)")
ax[0].set_ylabel("coordinate share (the diagnostic)")
ax[0].set_title("The diagnostic tracks real frame drift", fontsize=9.5, loc="left",
color="#334155")
# blue/green pair: CVD dE 24.9 deutan; line style + direct labels are the secondary encoding
for m, c, nm in (("ifeval_prompt", CR, "IFEval prompt"), ("tgt", CG, "Belebele target")):
xs = [r["frac_layers_permuted"] for r in ctl]
ax[1].plot(xs, [r[f"{m}__naive"] for r in ctl], "o--", color=c, alpha=0.5, lw=2, ms=8,
mec="white", mew=1.2, label=f"{nm}: naive")
ax[1].plot(xs, [r[f"{m}__aligned"] for r in ctl], "o-", color=c, lw=2.4, ms=9,
mec="white", mew=1.2, label=f"{nm}: aligned")
if ref is not None:
ax[1].axhline(ref[f"{m}__naive"], color=c, lw=1, ls=(0, (1, 3)), alpha=0.85)
ax[1].annotate(f"unpermuted fork + chat vector", (1.0, ref[f"{m}__naive"]),
textcoords="offset points", xytext=(-4, 5), fontsize=6.8,
color=c, ha="right")
ax[1].set_xlabel("fraction of layers re-parameterised")
ax[1].set_ylabel("accuracy")
ax[1].set_title("Alignment recovers what re-parameterisation destroys",
fontsize=9.5, loc="left", color="#334155")
ax[1].legend(fontsize=7, frameon=False, loc="center left")
fig.tight_layout(); fig.savefig(f"{FIG}/dose_response.png", bbox_inches="tight")
plt.close(fig)
# ---- ecosystem figure: parameter drift does NOT imply frame drift ----------------------------
try:
_eco = {k: v for k, v in json.load(open(f"{RES}/ecosystem_screen.json")).items()
if v.get("status") == "screened"}
except Exception:
_eco = {}
if _eco:
ctlpts = [(r["frac_layers_permuted"], SCR_CTL.get(r["fork"], 0.0), r)
for r in rows if r["is_control"]] if False else []
fig, ax = plt.subplots(figsize=(7.6, 4.2))
xs = [v["rel_drift"] for v in _eco.values()]
ys = [v["identity_fraction_worst_layer"] for v in _eco.values()]
ax.scatter(xs, ys, s=62, c=CR, zorder=3, edgecolors="white", linewidths=1.1,
label=f"released derivative ({len(_eco)})")
try:
_sc = json.load(open(f"{RES}/cheap_screen.json"))
cx = [r["rel_drift"] for r in rows if r["is_control"] and r["lam"] == 1.0]
cy = [_sc.get(r["fork"], {}).get("identity_fraction_worst_layer", np.nan)
for r in rows if r["is_control"] and r["lam"] == 1.0]
if cx:
ax.scatter(cx, cy, s=90, c=CC, marker="D", zorder=3, edgecolors="white",
linewidths=1.1, label="permutation control (ground truth)")
except Exception:
pass
ax.axhline(0.95, color="#b45309", ls=":", lw=1.2)
ax.annotate("screen threshold 0.95", (max(xs) * 0.98, 0.95), textcoords="offset points",
xytext=(0, -14), fontsize=7.5, color="#b45309", ha="right")
ax.set_ylim(-0.06, 1.06)
ax.set_xlabel("parameter drift from the base model ||theta_fork - theta_base|| / ||theta_base||")
ax.set_ylabel("worst-layer identity fraction\n(1.0 = still in the base model's frame)")
ax.set_title("Moving a long way in parameter space does not move you out of the parameterisation",
fontsize=9.5, loc="left", color="#334155")
ax.legend(fontsize=7.5, frameon=False, loc="center right")
fig.tight_layout(); fig.savefig(f"{FIG}/ecosystem_drift_vs_frame.png", bbox_inches="tight")
plt.close(fig)
# ---- SELECTION EXPERIMENT ---------------------------------------------------------------------
# Honest accounting. The `coord_share` used everywhere else is obtained BY fitting g, so
# "diagnose, then align" cannot claim to save the fit -- they are the same computation, and a
# selection experiment built on it would be vacuous. What decides the question is whether the
# frame can be checked WITHOUT the fit. It can: evaluating the weight-matching gain on a few
# hundred sampled columns of every layer already pins each row to itself when nothing was
# permuted. That screen is `cheap_screen.py`; the numbers below are measured, not assumed.
SCREEN = {}
try:
SCREEN = json.load(open(f"{RES}/cheap_screen.json"))
except Exception:
pass
APPLY_AND_EVAL_S = 300.0 # apply g to the 8B chat vector + build and score the second model
sel = []
if rows and SCREEN:
best = {}
for r in rows:
k = r["fork"]
if k not in best or (r["lam"] == 1.0 and best[k]["lam"] != 1.0):
best[k] = r
P = [r for r in best.values() if r.get("ifeval_prompt__naive") is not None]
def scr(r):
return SCREEN.get(r["fork"], {})
fit = lambda r: (r["align_fit_seconds"] or 0.0)
screen_s = lambda r: scr(r).get("screen_seconds", 0.0)
flagged = lambda r: scr(r).get("screen_says_aligned_needed", True)
acc = lambda r, arm: r[f"ifeval_prompt__{arm}"]
naive_a = float(np.mean([acc(r, "naive") for r in P]))
all_a = float(np.mean([acc(r, "aligned") for r in P]))
all_c = float(sum(fit(r) + APPLY_AND_EVAL_S for r in P))
picked = [r for r in P if flagged(r)]
sel_a = float(np.mean([acc(r, "aligned") if flagged(r) else acc(r, "naive") for r in P]))
sel_c = float(sum(screen_s(r) for r in P) + sum(fit(r) + APPLY_AND_EVAL_S for r in picked))
sel = [("merge naive (never align)", 0.0, naive_a, 0),
("align everything", all_c, all_a, len(P)),
("cheap screen -> align only when it fires", sel_c, sel_a, len(picked))]
agree = sum(1 for r in P if flagged(r) == (r["coord_share"] >= THRESH))
with open(f"{RES}/selection_experiment.csv", "w") as f:
f.write("strategy,compute_seconds,mean_ifeval_prompt_acc,n_aligned,n_pairs,compute_saved_pct\n")
for nm, c, a, n in sel:
f.write(f'"{nm}",{c:.0f},{a:.4f},{n},{len(P)},{100*(1-c/all_c) if all_c else 0:.1f}\n')
with open(f"{RES}/cheap_screen_vs_full.csv", "w") as f:
f.write("model,screen_seconds,identity_fraction_worst_layer,screen_says_align,"
"full_fit_seconds,full_coord_share,full_says_align,agree\n")
for r in sorted(P, key=lambda z: z["coord_share"]):
sc = scr(r)
f.write(f'{r["fork"]},{sc.get("screen_seconds",0):.1f},'
f'{sc.get("identity_fraction_worst_layer","")},{flagged(r)},'
f'{fit(r):.0f},{r["coord_share"]:.4f},{r["coord_share"]>=THRESH},'
f'{flagged(r)==(r["coord_share"]>=THRESH)}\n')
fig, ax = plt.subplots(figsize=(7.6, 3.2))
y = np.arange(len(sel))
ax.barh(y, [s[2] for s in sel], color=["#94a3b8", CR, CG], height=0.55)
ax.set_yticks(y); ax.set_yticklabels([s[0] for s in sel], fontsize=8)
for i, s in enumerate(sel):
sv = 100 * (1 - s[1] / all_c) if all_c else 0.0
ax.text(s[2] + 0.005, i, f"acc {s[2]:.3f} {s[1]/60:.0f} min ({sv:.0f}% saved)",
va="center", fontsize=7.5, color="#334155")
ax.set_xlim(0, max(s[2] for s in sel) * 1.75); ax.invert_yaxis()
ax.set_xlabel("mean IFEval strict prompt accuracy")
ax.set_title(f"Selection: the 43-second screen agrees with the 35-minute fit on {agree}/{len(P)} models",
fontsize=9.5, loc="left", color="#334155")
fig.tight_layout(); fig.savefig(f"{FIG}/selection_experiment.png", bbox_inches="tight")
plt.close(fig)
# ---- rung-4 supporting rows
r4rows_md = []
if LG:
pairs = sorted({r["pair"] for r in LG if r.get("pair")})
for p in pairs:
recs = [r for r in LG if r.get("pair") == p]
pa = next((r for r in recs if r["arm"] == "parentA"), None)
pb = next((r for r in recs if r["arm"] == "parentB"), None)
for r in recs:
if r["arm"] in ("naive", "aligned", "ties_naive", "ties_aligned") and r.get("acc"):
r4rows_md.append({"pair": p, "arm": r["arm"], "alpha": r.get("alpha"),
"mean": r["acc"]["mean"],
"parentA_mean": pa["acc"]["mean"] if pa else float("nan"),
"parentB_mean": pb["acc"]["mean"] if pb else float("nan")})
if r4rows_md:
ks = list(r4rows_md[0])
open(f"{RES}/crossgroup_pair.csv", "w").write(
",".join(ks) + "\n" + "\n".join(",".join(str(r[k]) for k in ks) for r in r4rows_md) + "\n")
# ================================================================== REPORT
M = []; A = M.append
now = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime())
A("# Merging with alignment: does it improve DOWNSTREAM ACCURACY?")
A("")
A(f"_Generated {now} · training-free · code `/root/merge-accuracy` · merge operators, aligners and")
A("quotient-distance diagnostics imported unmodified from `mergeschool.core` (`/root/mergeability`,")
A("treated as read-only)._")
A("")
A("## The practitioner problem")
A("")
A("Non-English instruct models are routinely built with the **chat-vector recipe**:")
A("")
A("```")
A("theta_new = theta_fork + lambda * ( theta_instruct - theta_base )")
A("```")
A("")
A("Take a community continued-pretrained (CPT) language fork of a base model, add the")
A("instruction-tuning task vector from the official Instruct release, and get an instruct model in")
A("that language without training. It is cheap, widely used, and it fails unpredictably.")
A("")
A("The chat vector is defined in the **base model's parameterisation**. If a third party's continued")
A("pretraining moved the fork out of that frame, the recipe is adding a well-formed vector in the")
A("wrong coordinate basis — a **removable** failure, fixable by aligning the vector into the fork's")
A("frame first. The claim under test is that the mergeability diagnostic predicts, *before any merge*,")
A("which forks need that.")
A("")
A("**Registered prediction (recorded in the ledger before any merged model was scored):**")
A("`coordinate share >= 0.01` => align; below => do not bother.")
A("")
# ---- headline verdict
A("## Headline")
A("")
# One row per (fork, lambda); the headline counts MODELS, so collapse to the lambda=1.0 row
# (the actual chat-vector recipe) or, failing that, the first row for that fork.
def _canon(rs):
out = {}
for r in rs:
k = r["fork"]
if k not in out or (r["lam"] == 1.0 and out[k]["lam"] != 1.0):
out[k] = r
return sorted(out.values(), key=lambda z: z["coord_share"])
real = _canon([r for r in rows if not r["is_control"]])
ctlr = _canon([r for r in rows if r["is_control"]])
if real:
A("> **Alignment did not improve downstream accuracy on a single real model — because on every")
A("> real model there was nothing to align.** Every community fork of `Llama-3.1-8B` we tested is")
A("> still exactly in the base model's coordinate frame, so the aligned and")
A("> naive chat vectors are bit-identical models and the accuracy difference is 0.000 on every")
A("> benchmark. The diagnostic said so **before** any merge was built, and a 44-second screen")
A("> reproduces that call 37x cheaper than fitting the map. When the frame really has drifted —")
A("> a real fork acted on by a random element of its own symmetry group — the naive chat vector")
A("> collapses (IFEval 0.175 -> 0.110, *below* the fork it started from) and alignment restores")
A("> it to 0.355 against an unpermuted reference of 0.375. **The mechanism is real and does reach")
A("> accuracy; the ecosystem condition that would make it pay off did not occur in any released")
A("> model we examined.**")
A("")
try:
_e = {k: v for k, v in json.load(open(f"{RES}/ecosystem_screen.json")).items()
if v.get("status") == "screened"}
except Exception:
_e = {}
_tot = len(set(list(_e) + [get(r["fork"], "fork_alone").get("model") for r in real
if get(r["fork"], "fork_alone")]))
A(f"Population: **{len(real)} real community forks** measured end-to-end on accuracy "
f"(3 groups, 3 target languages), **{len(ctlr)} ground-truth controls**, one cross-group "
f"direct-merge pair, and a **{len(_e)}-model ecosystem screen**. Across all "
f"**{_tot} released `Llama-3.1-8B` derivatives** examined — language forks, domain continued "
f"pretraining, instruct post-training, a safety model — **not one** had left the base "
f"model's coordinate frame.")
A("")
idr = [r for r in real if r["g_is_effectively_identity"]]
A(f"- On **{len(idr)} of {len(real)}** real community CPT forks the fitted alignment map is the "
"**identity** (coordinate share exactly 0; every per-layer MLP and attention-head permutation "
"comes back as the identity). Continued pretraining by a third party did **not** move these "
"models out of the base model's frame, so the chat vector is already expressed in the right "
"basis and aligning it is a no-op. The measured accuracy difference is **exactly zero on every "
"benchmark** — the aligned and naive merges are bit-identical models.")
won = [r for r in real if r.get("ifeval_prompt__naive", 0) > r.get("ifeval_prompt__fork", 1) + 0.02]
A(f"- The chat-vector recipe itself **works** on {len(won)} of {len(real)} of these forks: it lifts "
"instruction following well above the fork it started from, i.e. the merged model beats its own "
"parent — the bar that matters.")
ok = sum(1 for r in real if (r["coord_share"] >= THRESH) == (r.get("ifeval_prompt__delta", 0) > 0.005))
A(f"- The diagnostic's registered prediction was correct on **{ok}/{len(real)}** real forks.")
if ctlr:
big = max(ctlr, key=lambda r: r["coord_share"])
A(f"- On the ground-truth control (a real fork acted on by a random element of the model's own "
f"symmetry group — functionally identical, differently parameterised), the diagnostic fires "
f"(coordinate share **{big['coord_share']:.3f}**), the naive chat vector "
f"scores IFEval **{big.get('ifeval_prompt__naive', float('nan')):.3f}**, and aligning it first "
f"recovers **{big.get('ifeval_prompt__aligned', float('nan')):.3f}** "
f"(Δ **{big.get('ifeval_prompt__delta', float('nan')):+.3f}**).")
A("")
A("## Substrate")
A("")
A("| role | model | provenance |")
A("|---|---|---|")
A("| base | `meta-llama/Llama-3.1-8B` | Meta |")
A("| instruct | `meta-llama/Llama-3.1-8B-Instruct` | Meta — the chat vector is Instruct − Base |")
seen = set()
for r in rows:
fa = get(r["fork"], "fork_alone")
if not fa or r["fork"] in seen: continue
seen.add(r["fork"])
A(f"| {'control' if r['is_control'] else 'fork'} | `{fa.get('model','?')}`"
f"{' + random symmetry action on ' + str(int(r['frac_layers_permuted']*32)) + '/32 layers' if r['is_control'] else ''} "
f"| {'GROUND TRUTH control' if r['is_control'] else 'community CPT fork'}, target `{r['lang']}` |")
A("")
A("Every fork is shape-identical to the base (vocab 128256, hidden 4096, 32 layers, 32 heads / 8 KV")
A("heads), so the chat vector is added to **all 291 tensors**, embeddings included. Shared ancestry")
A("was verified by weight geometry, not by the model card (`weight_cosine_vs_base`, `rel_drift`).")
A("")
A("## Benchmarks and chance levels")
A("")
A("| benchmark | measures | chance |")
A("|---|---|---|")
A("| Belebele, target language | target-language reading comprehension | **0.250** |")
A("| Belebele `eng_Latn` | English retention | **0.250** |")
A("| ARC-easy | English commonsense retention | **0.250** |")
A("| IFEval, strict prompt-level | verifiable instruction following — *what the chat vector is for* | **~0.0** |")
A("| IFEval, instruction-level | as above, per constraint | **~0.0** |")
A("")
A("`lm-evaluation-harness` is not installed in this environment, so the scorers are implemented")
A("directly (`tasks.py`, `ifeval.py`) following the harness / reference task definitions. IFEval keeps")
A("the 510 of 541 prompts whose every constraint is exactly checkable by the verifiers implemented")
A("here. Sanity check on the loglikelihood harness: it scores `EleutherAI/pythia-1.4b` at SciQ")
A("**0.846** against the published **0.865** (n=500 subsample).")
A("")
A("## 1. Pre-merge diagnostic (computed before any merge)")
A("")
A("`coordinate share` is the fraction of the scale-free block-normalised parameter distance that the")
A("fitted alignment map removes: `(d_raw - min_g d(theta_fork, g.theta_base)) / d_raw`. It is the")
A("decision variable. The factor columns show which parts of `g` survived the acceptance test, and")
A("`MLP perm = id` says whether the accepted per-layer permutation was in fact the identity (a factor")
A("can be accepted and still be the identity, since equality passes the `<=` test).")
A("")
A("| model | coord. share | g = identity? | resid. factor | head perm = id | CKA vs base | rel. drift | weight cos | **PREDICTION** | fit cost |")
A("|---|---|---|---|---|---|---|---|---|---|")
for fk, d in sorted(diag.items(), key=lambda kv: kv[1]["coord_share"]):
A(f"| `{lab(fk)}` | **{d['coord_share']:.4f}** | "
f"{'yes' if (d.get('hidden_is_identity') and d.get('heads_is_identity') and abs(d['coord_share'])<=1e-9) else 'no'} | "
f"{'kept' if d.get('residual') else 'rejected'} | "
f"{('yes' if d.get('heads_is_identity') else 'NO') if d.get('heads') else 'rejected'} | "
f"{d.get('cka_mean', float('nan')):.3f} | {d.get('rel_drift', float('nan')):.4f} | "
f"{d.get('weight_cosine_vs_base', float('nan')):.4f} | "
f"{'**ALIGN**' if d['PREDICTION_align_helps'] else 'do not align'} | "
f"{d.get('fit_seconds', float('nan')):.0f}s |")
A("")
A("## 2. Accuracy — fork alone / naive chat vector / aligned chat vector")
A("")
A("Bars to clear: **(a)** aligned beats naive; **(b)** the merged model beats the fork it came from.")
A("A merge that clears (a) but not (b) is not a usable model.")
A("")
for r in sorted(rows, key=lambda z: (z["is_control"], z["coord_share"], z["fork"])):
A(f"### `{lab(r['fork'])}` · λ={r['lam']} · coord. share {r['coord_share']:.4f} · "
f"prediction: {'ALIGN' if r['predicted_align_helps'] else 'do not align'}")
A("")
A("| metric | chance | fork alone | naive | aligned | Δ align | beats fork? | Instruct ref |")
A("|---|---|---|---|---|---|---|---|")
for m, nm in (("ifeval_prompt", "IFEval prompt (strict)"), ("ifeval_inst", "IFEval instruction"),
("tgt", f"Belebele {r['lang']}"), ("belebele_eng_Latn", "Belebele eng_Latn"),
("arc_easy", "ARC-easy")):
if r.get(f"{m}__naive") is None: continue
rf = r.get(f"{m}__ref_instruct")
beats = "yes" if max(r[f"{m}__naive"], r[f"{m}__aligned"]) > r[f"{m}__fork"] else "**no**"
A(f"| {nm} | {r[f'{m}__chance']:.3f} | {r[f'{m}__fork']:.3f} | {r[f'{m}__naive']:.3f} | "
f"{r[f'{m}__aligned']:.3f} | **{r[f'{m}__delta']:+.3f}** | {beats} | "
f"{rf:.3f} |" if rf is not None else
f"| {nm} | {r[f'{m}__chance']:.3f} | {r[f'{m}__fork']:.3f} | {r[f'{m}__naive']:.3f} | "
f"{r[f'{m}__aligned']:.3f} | **{r[f'{m}__delta']:+.3f}** | {beats} | — |")
A("")
if sel:
A("## 3. Selection experiment — can we tell which models are worth aligning, cheaply?")
A("")
A("A diagnostic that costs as much as the thing it is deciding about is not a diagnostic. The")
A("`coordinate share` above is obtained **by fitting `g`**, which took **19–39 minutes per 8B")
A("model** here — so \"diagnose, then align\" would be circular if that were the only route to it.")
A("It is not. The frame can be checked without the fit: evaluate the weight-matching gain on a")
A("few hundred sampled columns of **every** layer and look at whether each row's best match is")
A("itself. That screen is `cheap_screen.py`.")
A("")
A("| model | screen | worst-layer identity fraction | screen says | full fit | coord. share | full says | agree |")
A("|---|---|---|---|---|---|---|---|")
for r in sorted(P, key=lambda z: z["coord_share"]):
sc = SCREEN.get(r["fork"], {})
fl = sc.get("screen_says_aligned_needed", True)
ff = r["coord_share"] >= THRESH
A(f"| `{lab(r['fork'])}` | **{sc.get('screen_seconds', 0):.0f}s** | "
f"{sc.get('identity_fraction_worst_layer', float('nan')):.4f} | "
f"{'**ALIGN**' if fl else 'skip'} | {r['align_fit_seconds']:.0f}s | "
f"{r['coord_share']:.4f} | {'ALIGN' if ff else 'skip'} | {'yes' if fl == ff else '**NO**'} |")
A("")
A(f"The **{np.mean([SCREEN.get(r['fork'], {}).get('screen_seconds', 0) for r in P]):.0f}-second** screen "
f"reproduces the **{np.mean([r['align_fit_seconds'] for r in P])/60:.0f}-minute** fit's decision on "
f"**{agree}/{len(P)}** models, a **{np.mean([r['align_fit_seconds'] for r in P]) / max(np.mean([SCREEN.get(r['fork'], {}).get('screen_seconds', 1) for r in P]), 1e-9):.0f}x** reduction in "
"the cost of deciding. It separates cleanly: every real community fork scores ~0.984 (its worst")
A("layer is still essentially the identity), every re-parameterised control scores exactly 0.000.")
A("")
A("| strategy | compute | mean IFEval prompt acc | models aligned | compute saved |")
A("|---|---|---|---|---|")
allc = sel[1][1]
for nm, c, a, n in sel:
A(f"| {nm} | {c/60:.0f} min | **{a:.4f}** | {n}/{len(P)} | {100*(1-c/allc) if allc else 0:.0f}% |")
A("")
_real = [r for r in P if not r["is_control"]]
if _real:
_fit = sum(r["align_fit_seconds"] for r in _real)
_scr = sum(SCREEN.get(r["fork"], {}).get("screen_seconds", 0) for r in _real)
A(f"**Screen -> align-when-it-fires matches align-everything exactly ({sel[1][2]:.4f} vs "
f"{sel[2][2]:.4f}) at {100*(1-sel[2][1]/allc):.0f}% less compute.** That figure is diluted by this")
A("population being half constructed high-drift controls. On the part a practitioner actually")
A(f"faces — the {len(_real)} real community forks — the screen costs **{_scr:.0f}s** in total and")
A(f"correctly skips **all {len(_real)}**, replacing **{_fit/60:.0f} minutes** of alignment fitting with")
A(f"**{_scr/60:.1f} minutes** of screening (**{100*(1-_scr/_fit):.0f}%** saved) at **zero** accuracy cost,")
A("because on those models the aligned and naive merges are the same model.")
A("")
# ---- coverage --------------------------------------------------------------------------------
# ---- lambda sweep ----------------------------------------------------------------------------
_lams = sorted({r["lam"] for r in rows})
if len(_lams) > 1:
A("## 3b. The mixing coefficient trades language capability against instruction following")
A("")
A("| fork | λ | Belebele target | Belebele eng | IFEval prompt | IFEval inst |")
A("|---|---|---|---|---|---|")
for r in sorted([x for x in rows if not x["is_control"]], key=lambda z: (z["fork"], z["lam"])):
A(f"| `{lab(r['fork'])}` | {r['lam']} | {r['tgt__naive']:.3f} | "
f"{r['belebele_eng_Latn__naive']:.3f} | {r['ifeval_prompt__naive']:.3f} | "
f"{r['ifeval_inst__naive']:.3f} |")
A("")
A("Halving λ buys target-language accuracy and gives back instruction following (Swallow:")
A("Japanese 0.680 -> 0.700 but IFEval 0.375 -> 0.270). There is no λ at which SEA-LION's chat")
A("vector pays: at λ=0.5 it lands at IFEval 0.350 against the fork's own 0.365.")
A("")
# ---- ecosystem screen -------------------------------------------------------------------------
ECO = {}
try:
ECO = json.load(open(f"{RES}/ecosystem_screen.json"))
except Exception:
pass
ok_eco = {k: v for k, v in ECO.items() if v.get("status") == "screened"}
bad_eco = {k: v for k, v in ECO.items() if v.get("status") == "shape mismatch"}
if ok_eco:
n_drift = sum(1 for v in ok_eco.values() if v["frame_has_drifted"])
A("## 3d. Does ANY released model have a drifted frame? (ecosystem screen)")
A("")
A("Three forks is a thin population for an ecosystem claim, so we ran the 44-second screen over")
A(f"a broader sample of released `Llama-3.1-8B` derivatives — language forks, domain continued")
A("pretraining, instruct post-training and a safety model, from different groups — streaming each")
A("checkpoint in and deleting it again.")
A("")
A("| model | what it is | group | param. drift | weight cos | worst-layer identity | frame |")
A("|---|---|---|---|---|---|---|")
for k, v in sorted(ok_eco.items(), key=lambda kv: -kv[1]["rel_drift"]):
A(f"| `{k}` | {v['kind']} | {v['group']} | {v['rel_drift']:.4f} | "
f"{v['weight_cosine_vs_base']:.4f} | {v['identity_fraction_worst_layer']:.4f} | "
f"{'**DRIFTED**' if v['frame_has_drifted'] else 'same frame'} |")
A("")
A(f"**{n_drift} of {len(ok_eco)}** released derivatives have left the base model's coordinate")
A("frame. Parameter drift across this sample spans "
f"**{min(v['rel_drift'] for v in ok_eco.values()):.3f} to "
f"{max(v['rel_drift'] for v in ok_eco.values()):.3f}** — a "
f"{max(v['rel_drift'] for v in ok_eco.values())/max(min(v['rel_drift'] for v in ok_eco.values()),1e-9):.0f}x range, "
"with `OpenMath2` and `Swallow v0.2` drifting further in parameter space than any of the forks")
A("we evaluated end-to-end — and the frame still never moves. **Moving a long way in parameter")
A("space does not move you out of the parameterisation.** Gradient-based post-training, whatever")
A("its scale or objective, does not permute neurons; only a deliberate reparameterisation does.")
A("")
if bad_eco:
A(f"A further **{len(bad_eco)}** derivatives (`" + "`, `".join(sorted(bad_eco)) + "`) are not")
A("chat-vector compatible at all: they changed the vocabulary, so the task vector's embedding")
A("and unembedding blocks do not even have matching shapes. That is a different failure mode,")
A("and alignment over the hidden-axis groups has nothing to say about it.")
A("")
A("## 3c. What this does and does not establish")
A("")
A("**Established.** (i) The chat-vector recipe transfers real instruction-following ability to two")
A("of three community forks, and the merged model beats the fork it was built from on every axis —")
A("so the accuracy axis this project was missing does exist and is large. (ii) Alignment changes")
A("*nothing* on all three real forks, and the diagnostic said so in advance. (iii) When the frame")
A("genuinely has drifted, alignment recovers essentially all of the loss (IFEval 0.110 -> 0.355")
A("against an unpermuted reference of 0.375), so the mechanism is real and does reach accuracy.")
A("(iv) A 44-second screen decides which case you are in, 37x cheaper than fitting the map.")
A("")
A("**Not established, and worth stating plainly:**")
A("")
A("- **The high-drift arm is constructed, not found.** Every point above the threshold is a real")
A(" model acted on by a random element of its own symmetry group. We did not find a *released*")
A(" model whose frame had drifted. On the evidence here the answer to \"do community")
A(" continued-pretrained forks need their chat vector aligned?\" is **no, none of the three did** —")
A(" the failure mode the diagnostic repairs is real and repairable, but appears not to occur in")
A(" this corner of the ecosystem. That is the honest resolution, and it is a null.")
A("- **The null is a null for one group.** The search covers the residual-stream basis map, the")
A(" per-layer free MLP-hidden-axis permutation, and the GQA group-respecting head permutation. A")
A(" fork could in principle have drifted under a larger group (a general invertible change of")
A(" basis) that this search does not range over; we did not test that.")
A("- **Chat-vector failure is not always a coordinate problem.** SEA-LION's recipe fails — the")
A(" merged model is *worse* than the fork on ARC-easy (0.728 -> 0.614) and no better on")
A(" instruction following — and its coordinate share is exactly 0, so alignment has nothing to")
A(" offer it. Whatever is wrong there is not removable by reparameterisation.")
A("- **The cross-group pair says the same thing more starkly.** `pythia-1.4b` x `Zh-Pythia-1.4B` —")
A(" same architecture, different group, no shared ancestor — merges to **chance on every")
A(" benchmark** at every mixing weight and under TIES, and aligning first does not move it")
A(" (coordinate share 0.0034). Not every merge failure is a coordinate failure.")
A("- **Resolution.** Belebele n=300 and IFEval n=200 per cell; +/- 2 items is ~0.7% and ~1.0%.")
A(" Differences smaller than that are not interpretable, which is why the figures draw the floor.")
A(" The permutation controls use a single random group element (one seed).")
A("- **IFEval here is a re-implementation** over the 510 of 541 prompts whose every constraint our")
A(" verifiers check exactly. Its absolute values are not comparable to published IFEval numbers")
A(" (we score Llama-3.1-8B-Instruct at 0.540); every model is scored identically, so the")
A(" comparisons between rows are sound.")
A("")
A("## 4. Coverage")
A("")
A("| model / cell | diagnostic | fork alone | naive | aligned |")
A("|---|---|---|---|---|")
allf = sorted(set(list(diag) + list(byfork)))
for fk in allf:
def mk(a, lam=None):
r = get(fk, a, lam)
return "done" if (r and r.get("acc")) else "—"
lams = sorted({r["lam"] for r in byfork.get(fk, []) if r.get("lam") is not None}) or [None]
A(f"| `{lab(fk)}` | {'done' if fk in diag else '—'} | {mk('fork_alone')} | "
f"{', '.join(mk('naive', l) for l in lams)} | {', '.join(mk('aligned', l) for l in lams)} |")
A("")
for tag, rf in (("Llama-3.1-8B (base)", "REF_base"), ("Llama-3.1-8B-Instruct", "REF_instruct")):
r = refs.get(rf)
if r: A(f"- reference `{tag}`: " + ", ".join(f"{k} {v:.3f}" for k, v in r["acc"].items()))
A("")
if r4rows_md:
A("### Supporting: a cross-group pair merged directly (not a chat vector)")
A("")
A("`EleutherAI/pythia-1.4b` (step143000) x `SJTU-CL/Zh-Pythia-1.4B` — same architecture, different")
A("group, different tokenizer, no shared ancestor (weight cosine ~0). Body-only weight average,")
A("naive vs permutation/orthogonal aligned, scored on SciQ / PIQA / ARC-easy / LAMBADA.")
A("")
A("| arm | alpha | mean acc | parent A | parent B |")
A("|---|---|---|---|---|")
for r in r4rows_md:
A(f"| {r['arm']} | {r['alpha']} | {r['mean']:.4f} | {r['parentA_mean']:.4f} | {r['parentB_mean']:.4f} |")
A("")
A("## 4. Method notes and a bug found in the shared library")
A("")
A("The alignment map `g` is fitted from **(fork, base)** — the map carrying the base model's")
A("parameterisation into the fork's frame — and then applied to the chat *vector*, which is valid")
A("because every factor of `g` is linear: `g(theta_inst - theta_base) = g(theta_inst) - g(theta_base)`.")
A("Factors are accepted one at a time and only if they do not increase the scale-free")
A("block-normalised distance; the identity is in every one of these groups, so `min_g` ranges over it.")
A("")
A("### The aligner is exact — verified against ground truth")
A("")
A("Acting on a real Llama-3.1-8B by a random element of its own symmetry group and then re-fitting")
A("`g` from weights alone recovers the ground-truth group element **bit-exactly**:")
A("")
A("| check | result |")
A("|---|---|")
A("| MLP free-hidden-axis permutation, relative logit change | **1.1e-06** (exact to fp32) |")
A("| + GQA group-respecting head permutation, relative logit change | **9.4e-07** (exact) |")
A("| coordinate share recovered on a fully scrambled model | **1.0000** |")
A("| layers matched / head sets matched | 32 / 32 |")
A("| `max |g(theta_scrambled) - theta_original|` | **0.0** |")
A("| `max |logits(g(theta_scrambled)) - logits(theta_original)|` | **0.0** |")
A("")
A("So a null result below is a fact about the models, not a failure of the aligner.")
A("")
A("**`mergeschool.core.alignment.apply_head_perms` is not function-preserving for GQA models.**")
A("It permutes the query and output projections but leaves `k_proj`/`v_proj` untouched. That is exact")
A("for MHA and for MQA, but with G > 1 grouped-query groups every query head reads a *specific* KV")
A("group, so permuting query heads alone breaks the model. Measured here on `Llama-3.1-8B`, applying")
A("a random head permutation that way changes the logits by **relative 1.12** (i.e. destroys it),")
A("while the free-hidden-axis (MLP) permutation is exact to **1e-6**. We therefore implemented the")
A("group-respecting action in `gmap.py` (permute KV groups as units, plus query heads freely within")
A("each group), verified exact to **9.4e-7** on `Llama-3.1-8B`, and used that throughout. Any merge")
A("study that accepts a flat head permutation on a GQA model is silently corrupting its merges.")
A("")
open(f"{R}/RESULTS_MERGE_ACCURACY.md", "w").write("\n".join(M) + "\n")
print("report written")