extrinsic-evaluations / build_extrinsic.py
suchirsalhan's picture
Upload build_extrinsic.py with huggingface_hub
d5f728f verified
Raw
History Blame Contribute Delete
40.7 kB
#!/usr/bin/env python3
"""
Build Mergeability-2/extrinsic-evaluations: one tidy long-format table of every
EXTRINSIC (downstream / task-level) evaluation produced across the 2026-08-26 workstreams.
Re-runnable and idempotent. Sources that are not yet published on the Hub are skipped
with a recorded status, so re-running once the in-progress agents publish will pick
them up without any code change.
Usage:
source /root/.ms_hf_env
python3 build_extrinsic.py # build only
python3 build_extrinsic.py --push # build and push to the Hub
"""
import argparse, csv, json, math, os, sys, datetime
from pathlib import Path
ROOT = Path("/root/extrinsic-eval")
CACHE = ROOT / "cache"
OUT = ROOT / "out"
TARGET_REPO = "Mergeability-2/extrinsic-evaluations"
# ---------------------------------------------------------------- source registry
SOURCES = {
"merge-accuracy": dict(repo="Mergeability-2/merge-accuracy", status="complete"),
"compose-audit": dict(repo="Mergeability-2/compose-audit", status="complete"),
"crossarch-1b": dict(repo="Mergeability-2/crossarch-1b-diagnostics", status="complete"),
"mergebench": dict(repo="Mergeability-2/mergebench-property-sweep", status="complete"),
"aim": dict(repo="Mergeability-2/aim-activation-informed-merging",status="complete"),
"goldfish": dict(repo="suchirsalhan/goldfish-crosslingual-cka", status="complete"),
"beetle": dict(repo="Mergeability-2/beetle-merge-eval", status="in_progress"),
"crossarch-acc": dict(repo="Mergeability-2/crossarch-accuracy", status="in_progress"),
}
# ---------------------------------------------------------------- metric dictionary
# metric -> (metric_kind, unit). metric_kind is the coarse grouping that must never be
# mixed: accuracy | benchmark_score | likelihood | likelihood_delta | other
METRICS = {
"accuracy": ("accuracy", "proportion_0_1"),
"accuracy_pct": ("accuracy", "percent_0_100"),
"delta_accuracy": ("accuracy_delta", "proportion_0_1"),
"benchmark_score_pct": ("benchmark_score", "percent_0_100"),
"benchmark_score_norm_pct": ("benchmark_score", "percent_0_100_normalised"),
"benchmark_mean_accuracy": ("benchmark_score", "proportion_0_1"),
"nats_per_token": ("likelihood", "nats/token"),
"nats_per_utf8_byte": ("likelihood", "nats/utf8_byte"),
"delta_floor_nats_per_token": ("likelihood_delta", "nats/token"),
"delta_floor_nats_per_byte": ("likelihood_delta", "nats/utf8_byte"),
"lmc_barrier_nats_per_token": ("likelihood_delta", "nats/token"),
"harmfulness_score": ("other", "score_0_1"),
"bliss_score": ("other", "BLiSS sub-score"),
}
# chance levels for single-benchmark accuracy rows
CHANCE = {
"belebele": 0.25, "arc_easy": 0.25, "sciq": 0.25, "piqa": 0.5,
"lambada": 0.0, "ifeval": 0.0, "blimp": 0.5, "multiblimp": 0.5,
"mmlu": 25.0, "humaneval": 0.0, "mbpp": 0.0, "math": 0.0, "gsm8k": 0.0,
}
rows = []
NCOLS = ["model_id","model_role","provenance_family","parents","rung","operator","experiment",
"benchmark","metric","value","chance","n","source_dataset","notes","metric_kind","unit"]
def emit(model_id, model_role, provenance_family, parents, rung, operator, experiment,
benchmark, metric, value, chance=None, n=None, source_dataset=None, notes=""):
if value is None: return
try:
v = float(value)
except (TypeError, ValueError):
return
if math.isnan(v) or math.isinf(v): return
kind, unit = METRICS[metric]
if kind == "accuracy" and chance is None:
raise AssertionError(f"accuracy row without chance: {model_id} {benchmark} {metric}")
rows.append(dict(model_id=model_id, model_role=model_role, provenance_family=provenance_family,
parents=parents or "", rung=rung or "", operator=operator or "", experiment=experiment,
benchmark=benchmark, metric=metric, value=v,
chance=("" if chance is None else float(chance)), n=("" if n is None else int(n)),
source_dataset=source_dataset, notes=notes, metric_kind=kind, unit=unit))
def rd(p):
return list(csv.DictReader(open(p)))
def jl(p):
return [json.loads(l) for l in open(p) if l.strip()]
def f(x):
if x in (None, "", "NA", "nan", "NaN"): return None
try:
v = float(x)
return None if math.isnan(v) else v
except (TypeError, ValueError):
return None
# =================================================================== 1. merge-accuracy
def build_merge_accuracy(d, ds):
"""Chat-vector / Llama-3.1-8B fork accuracies + the pythia x Zh-Pythia cross-group pair."""
BENCH_CHANCE = {"arc_easy": 0.25, "belebele_eng_Latn": 0.25, "belebele_ind_Latn": 0.25,
"belebele_jpn_Jpan": 0.25, "belebele_tha_Thai": 0.25,
"ifeval_inst": 0.0, "ifeval_prompt": 0.0}
ROLE = {"reference": "reference", "control": "control", "fork": "parent", "merge": "merged"}
for r in jl(d / "results/chatvec.jsonl"):
acc = r.get("acc")
if not acc: # 'diag' records carry no evaluation
continue
kind, fork, arm = r["kind"], r.get("fork"), r.get("arm")
lam = r.get("lam")
role = ROLE.get(kind, "merged")
model = r.get("model")
if kind in ("reference", "fork"):
# each real fork has its own repo, so the repo id is a unique model id
mid = model
elif kind == "control":
# every PERM control shares the underlying fork's repo but is a DIFFERENT model
# (that fork acted on by a random element of its own symmetry group), so the
# permutation fraction and arm must be part of the identity.
mid = f"chatvec-control:{fork}|{arm}" + (f"|lam{lam}" if lam is not None else "")
else:
mid = f"chatvec-merge:{fork}|{arm}|lam{lam}"
parents = ""
operator = ""
if kind == "merge" or (kind == "control" and arm in ("naive", "aligned")):
base_fork = (fork or "").split("_PERM")[0]
parents = "|".join(filter(None, [
"meta-llama/Llama-3.1-8B-Instruct", "meta-llama/Llama-3.1-8B",
{"swallow_ja": "tokyotech-llm/Llama-3.1-Swallow-8B-v0.1",
"swallow_ja_v02": "tokyotech-llm/Llama-3.1-Swallow-8B-v0.2",
"sealion_id": "aisingapore/llama3.1-8b-cpt-sea-lionv3-base",
"typhoon2_th": "scb10x/llama3.1-typhoon2-8b"}.get(base_fork, f"fork:{fork}")]))
operator = f"chat_vector_{arm}"
note = r.get("note", "")
if kind == "control":
note = (note + f" | ground-truth control: {fork} = the fork acted on by a random element "
f"of its own symmetry group (functionally identical, differently parameterised); "
f"frac_layers_permuted={r.get('frac_layers_permuted')}; "
f"underlying repo {model or 'n/a (constructed merge)'}").strip(" |")
for b, v in acc.items():
if b == "mean":
emit(mid, role, "Llama-3.1-8B", parents, (f"lambda={lam}" if lam is not None else ""),
operator, "chat_vector_llama31", "mean_of_benchmarks", "benchmark_mean_accuracy",
v, None, None, ds, (note + " | unweighted mean over the row's benchmarks; "
"not a single-benchmark accuracy, so no chance level").strip(" |"))
continue
ch = BENCH_CHANCE.get(b)
if ch is None:
ch = 0.25 if b.startswith("belebele") else 0.0
emit(mid, role, "Llama-3.1-8B", parents, (f"lambda={lam}" if lam is not None else ""),
operator, "chat_vector_llama31", b, "accuracy", v, ch, None, ds, note)
# cross-group direct merge: pythia-1.4b x Zh-Pythia-1.4B
LED_CHANCE = {"sciq": 0.25, "sciq_norm": 0.25, "piqa": 0.5, "piqa_norm": 0.5,
"arc_easy": 0.25, "arc_easy_norm": 0.25, "lambada": 0.0, "lambada_norm": 0.0}
for r in jl(d / "results/ledger.jsonl"):
acc = r.get("acc")
if not acc: continue
arm = r["arm"]
role = "parent" if arm in ("parentA", "parentB") else "merged"
model = r.get("model")
alpha = r.get("alpha")
mid = model if role == "parent" else f"crossgroup-merge:{r['pair']}|{arm}|alpha{alpha}"
parents = "" if role == "parent" else "EleutherAI/pythia-1.4b|SJTU-CL/Zh-Pythia-1.4B"
for b, v in acc.items():
if b == "mean":
emit(mid, role, "pythia-1.4b x Zh-Pythia-1.4B", parents,
(f"alpha={alpha}" if alpha is not None else ""), arm if role=="merged" else "",
"crossgroup_direct_merge", "mean_of_benchmarks", "benchmark_mean_accuracy", v,
None, None, ds, "R4_cross_group; unweighted mean over sciq/piqa/arc_easy/lambada "
"(acc and acc_norm), not a single-benchmark accuracy")
continue
emit(mid, role, "pythia-1.4b x Zh-Pythia-1.4B", parents,
(f"alpha={alpha}" if alpha is not None else ""), arm if role=="merged" else "",
"crossgroup_direct_merge", b, "accuracy", v, LED_CHANCE.get(b, 0.25), None, ds,
"R4_cross_group; two independently pretrained 1.4B models, different vocabularies")
# =================================================================== 2. compose-audit
def build_compose_audit(d, ds):
R = d / "results"
# ---- SET 1: BLiMP accuracy on PolyPythia seed merges
for p in sorted(R.glob("blimp*.jsonl")):
size_tag = p.stem.replace("blimpB_", "").replace("blimp_", "")
for r in jl(p):
size = r.get("size", size_tag)
pair = r["pair"]; pid = f"pythia-{size}-seed{pair[0]}|pythia-{size}-seed{pair[1]}"
npar = r.get("n_per_paradigm"); npara = r.get("n_paradigms")
n = (npar * npara) if (npar and npara) else None
fam = f"PolyPythia-{size}"
for side, k in (("a", 0), ("b", 1)):
emit(f"EleutherAI/pythia-{size}-seed{pair[k]}", "parent", fam, "", "parent", "",
"polypythia_seed_merge", "BLiMP", "accuracy", r["parent_acc"][side], 0.5, n, ds,
"SET 1 parent; seed-only difference")
for rung, vals in r["rungs"].items():
mid = f"compose-audit:polypythia_seed_merge|{size}|seed{pair[0]}x{pair[1]}|{rung}"
emit(mid, "merged", fam, pid,
rung, rung.split("_", 1)[1], "polypythia_seed_merge", "BLiMP", "accuracy",
vals.get("blimp_acc"), 0.5, n, ds,
"SET 1 merged; BLiMP is ACCURACY -- do not read as the likelihood rescue")
emit(mid, "merged", fam, pid,
rung, rung.split("_", 1)[1], "polypythia_seed_merge", "BLiMP", "delta_accuracy",
vals.get("delta_vs_best_parent"), None, n, ds, "vs. the better parent")
# ---- SET 1: nats/token (Delta-floor) on the same merges
# NOTE: set1 / set1x / slerp / repair are four resumable ledgers over the SAME merges.
# They re-report identical M0_naive_avg / M1_perm_avg baselines, and set1x re-measures
# three 410m pairs already in set1. A canonical merge id + the global dedupe below
# collapses those repeats so no merge is counted more than once.
for pat, exp in (("set1_*.jsonl", "polypythia_seed_merge"), ("set1x_*.jsonl", "polypythia_seed_merge"),
("slerp_*.jsonl", "polypythia_seed_merge"),
("repair_*.jsonl", "polypythia_seed_merge"),
("abl_*.jsonl", "polypythia_ablation")):
for p in sorted(R.glob(pat)):
if p.name.endswith("_pairs.csv"): continue
for r in jl(p):
size = r.get("size", p.stem.split("_", 1)[1])
pair = r["pair"]; pid = f"pythia-{size}-seed{pair[0]}|pythia-{size}-seed{pair[1]}"
fam = f"PolyPythia-{size}"
corpus = r.get("corpus", "flores200_devtest_eng_Latn")
pn = r.get("parent_nll") or {}
for side, k in (("a", 0), ("b", 1)):
if side in pn:
emit(f"EleutherAI/pythia-{size}-seed{pair[k]}", "parent", fam, "", "parent", "",
exp, corpus, "nats_per_token", pn[side], None, None, ds, "SET 1 parent floor")
for rung, vals in r["rungs"].items():
mid = f"compose-audit:{exp}|{size}|seed{pair[0]}x{pair[1]}|{rung}"
op = rung.split("_", 1)[1]
emit(mid, "merged", fam, pid, rung, op, exp, corpus, "nats_per_token",
vals.get("nll"), None, None, ds, "LIKELIHOOD, not accuracy")
emit(mid, "merged", fam, pid, rung, op, exp, corpus,
"delta_floor_nats_per_token", vals.get("delta_floor"), None, None, ds,
"Delta vs. the better parent's floor; LIKELIHOOD, not accuracy")
if "blimp_acc" in vals:
emit(mid, "merged", fam, pid, rung, op, exp, "BLiMP", "accuracy",
vals["blimp_acc"], 0.5, None, ds,
"same merge as the nats/token rows -- the two rescues are uncorrelated")
for key, lbl in (("barrier_naive", "naive"), ("barrier_perm", "perm_avg")):
if key in r:
emit(f"compose-audit:{exp}|{size}|seed{pair[0]}x{pair[1]}|{lbl}", "merged", fam, pid,
lbl, lbl, exp, corpus, "lmc_barrier_nats_per_token",
r[key].get("barrier"), None, None, ds, "linear-mode-connectivity barrier")
# ---- SET 1: corpus robustness -- the same merges scored on three held-out corpora
for p in sorted(R.glob("corpus_*.jsonl")):
for r in jl(p):
size = r["size"]; pair = r["pair"]
pid = f"pythia-{size}-seed{pair[0]}|pythia-{size}-seed{pair[1]}"
fam = f"PolyPythia-{size}"
for side, k in (("a", 0), ("b", 1)):
for corpus, v in (r.get("parent_nll") or {}).get(side, {}).items():
emit(f"EleutherAI/pythia-{size}-seed{pair[k]}", "parent", fam, "", "parent", "",
"polypythia_corpus_robustness", corpus, "nats_per_token", v, None, None, ds,
"SET 1 parent floor on an alternative held-out corpus")
for rung, per_corpus in r["rungs"].items():
mid = f"compose-audit:corpus|{size}|seed{pair[0]}x{pair[1]}|{rung}"
op = rung.split("_", 1)[1]
for corpus, vals in per_corpus.items():
emit(mid, "merged", fam, pid, rung, op, "polypythia_corpus_robustness",
corpus, "nats_per_token", vals.get("nll"), None, None, ds,
"robustness check: same merge, different held-out corpus; LIKELIHOOD")
emit(mid, "merged", fam, pid, rung, op, "polypythia_corpus_robustness",
corpus, "delta_floor_nats_per_token", vals.get("delta_floor"), None, None,
ds, "Delta vs. the better parent's floor on that corpus; LIKELIHOOD")
# ---- SET 4: Goldfish bilingual composition (nats / UTF-8 byte)
for name, exp in (("set4_goldfish.jsonl", "goldfish_bilingual_merge"),
("set4_reverse.jsonl", "goldfish_bilingual_merge_reverse")):
p = R / name
if not p.exists(): continue
for r in jl(p):
lang = r["lang"]; ra, rb = r.get("repo_a"), r.get("repo_b")
pid = "|".join(x for x in (ra, rb) if x); fam = f"Goldfish eng x {lang}"
for pk, pv in (r.get("parents") or {}).items():
if isinstance(pv, dict) and "nats_per_byte" in pv:
emit(f"goldfish-parent:{pid}|{pk}", "parent", fam, "", "parent", "", exp,
f"flores200_devtest[{pk}]", "nats_per_utf8_byte", pv["nats_per_byte"],
None, r.get("n_sent"), ds, "SET 4 parent floor; LIKELIHOOD")
for rung, vals in r["rungs"].items():
mid = f"compose-audit:{r['set']}|{lang}|{rung}"; op = rung.split("_", 1)[1]
for sub in ("eng", "x"):
if isinstance(vals.get(sub), dict):
emit(mid, "merged", fam, pid, rung, op, exp, f"flores200_devtest[{sub}]",
"nats_per_utf8_byte", vals[sub].get("nats_per_byte"), None,
r.get("n_sent"), ds, "LIKELIHOOD, not accuracy")
for k, sub in (("delta_floor_eng", "eng"), ("delta_floor_x", "x"),
("delta_floor_mean", "mean")):
emit(mid, "merged", fam, pid, rung, op, exp, f"flores200_devtest[{sub}]",
"delta_floor_nats_per_byte", vals.get(k), None, r.get("n_sent"), ds,
"Delta vs. parent floor; LIKELIHOOD, not accuracy")
# ---- SET 4: MultiBLiMP accuracy on the same Goldfish merges
p = R / "set4_multiblimp.jsonl"
if p.exists():
for r in jl(p):
lang = r["lang"]; rb = r.get("repo_b"); fam = f"Goldfish eng x {lang}"
pid = f"goldfish-models/eng_latn_1000mb|{rb}"
ne, nx = r.get("n_items_eng"), r.get("n_items_x")
for pk, pv in (r.get("parents") or {}).items():
emit(f"goldfish-parent:{pid}|{pk}", "parent", fam, "", "parent", "",
"goldfish_bilingual_merge", f"MultiBLiMP1.0[{pk}]", "accuracy", pv, 0.5,
ne if "eng" in pk else nx, ds, "SET 4 parent")
for rung, vals in r["rungs"].items():
mid = f"compose-audit:set4_goldfish|{lang}|{rung}"; op = rung.split("_", 1)[1]
for k, sub, n in (("mb_eng", "eng", ne), ("mb_x", "x", nx)):
emit(mid, "merged", fam, pid, rung, op, "goldfish_bilingual_merge",
f"MultiBLiMP1.0[{sub}]", "accuracy", vals.get(k), 0.5, n, ds,
"ACCURACY on the same merge whose Delta-floor says it is destroyed")
for k, sub, n in (("delta_eng_vs_eng_parent", "eng", ne),
("delta_x_vs_x_parent", "x", nx)):
emit(mid, "merged", fam, pid, rung, op, "goldfish_bilingual_merge",
f"MultiBLiMP1.0[{sub}]", "delta_accuracy", vals.get(k), None, n, ds,
"vs. that language's parent")
# ---- B-GPT: bilingual x bilingual merge (shared vocabulary) + joint-training ceiling
p = R / "bgpt_merge.jsonl"
if p.exists():
for r in jl(p):
lang = r["lang"]; ra, rb = r.get("repo_a"), r.get("repo_b")
pid = f"{ra}|{rb}"; fam = f"B-GPT en-{lang} ({r.get('variant')})"
for pk, pv in (r.get("parents") or {}).items():
mid = {"A": ra, "B": rb}.get(pk, f"bgpt-parent:{pk}")
for k, sub in (("nats_per_byte_eng", "eng"), ("nats_per_byte_x", "x")):
emit(mid, "parent", fam, "", "parent", "", "bgpt_bilingual_merge",
f"flores200_devtest[{sub}]", "nats_per_utf8_byte", pv.get(k), None, None, ds,
"B-GPT parent; LIKELIHOOD")
for k, sub in (("multiblimp_eng", "eng"), ("multiblimp_x", "x")):
emit(mid, "parent", fam, "", "parent", "", "bgpt_bilingual_merge",
f"MultiBLiMP1.0[{sub}]", "accuracy", pv.get(k), 0.5, None, ds, "B-GPT parent")
for rung, vals in r["rungs"].items():
mid = f"compose-audit:bgpt_merge|{lang}|{rung}"; op = rung.split("_", 1)[1]
for k, sub in (("nats_per_byte_eng", "eng"), ("nats_per_byte_x", "x")):
emit(mid, "merged", fam, pid, rung, op, "bgpt_bilingual_merge",
f"flores200_devtest[{sub}]", "nats_per_utf8_byte", vals.get(k), None, None, ds,
"LIKELIHOOD, not accuracy")
for k, sub in (("delta_floor_eng", "eng"), ("delta_floor_x", "x"),
("delta_floor_mean", "mean")):
emit(mid, "merged", fam, pid, rung, op, "bgpt_bilingual_merge",
f"flores200_devtest[{sub}]", "delta_floor_nats_per_byte", vals.get(k),
None, None, ds, "LIKELIHOOD, not accuracy")
for k, sub in (("multiblimp_eng", "eng"), ("multiblimp_x", "x")):
emit(mid, "merged", fam, pid, rung, op, "bgpt_bilingual_merge",
f"MultiBLiMP1.0[{sub}]", "accuracy", vals.get(k), 0.5, None, ds,
"ACCURACY on the same merge")
p = R / "bgpt_ceiling.jsonl"
if p.exists():
for r in jl(p):
lang = r["lang"]; fam = f"B-GPT en-{lang} ({r.get('variant')})"
ne, nx = r.get("n_items_eng"), r.get("n_items_x")
ROLE = {"bgpt_joint_bilingual": "jointly_trained", "goldfish_eng_parent": "parent",
"goldfish_partner_parent": "parent", "merge_M0_naive": "merged",
"merge_M1a_vocab": "merged"}
for arm, vals in r["arms"].items():
role = ROLE.get(arm, "reference")
mid = r.get("repo") if arm == "bgpt_joint_bilingual" else f"compose-audit:bgpt_ceiling|{lang}|{arm}"
note = ("jointly trained bilingual model -- the ceiling any merge is compared against"
if role == "jointly_trained" else "")
for k, sub, n in (("nats_per_byte_eng", "eng", ne), ("nats_per_byte_x", "x", nx)):
emit(mid, role, fam, "", arm, "", "bgpt_joint_vs_merge",
f"flores200_devtest[{sub}]", "nats_per_utf8_byte", vals.get(k), None, n, ds,
(note + " | LIKELIHOOD").strip(" |"))
for k, sub, n in (("multiblimp_eng", "eng", ne), ("multiblimp_x", "x", nx)):
emit(mid, role, fam, "", arm, "", "bgpt_joint_vs_merge",
f"MultiBLiMP1.0[{sub}]", "accuracy", vals.get(k), 0.5, n, ds, note)
# =================================================================== 3. crossarch 1B
CODE2REPO = {"EN_pythia": "EleutherAI/pythia-1.4b", "ZH_pythia": "SJTU-CL/Zh-Pythia-1.4B",
"PT_tucano": "TucanoBR/Tucano-1b1", "PL_bielik": "speakleash/Bielik-1.5B-v3",
"IT_minerva": "sapienzanlp/Minerva-1B-base-v1.0",
"pythia": "EleutherAI/pythia-1.4b", "zhpythia": "SJTU-CL/Zh-Pythia-1.4B",
"EN": "EleutherAI/pythia-1.4b", "ZH": "SJTU-CL/Zh-Pythia-1.4B",
"PT": "TucanoBR/Tucano-1b1", "PL": "speakleash/Bielik-1.5B-v3",
"IT": "sapienzanlp/Minerva-1B-base-v1.0"}
def build_crossarch(d, ds):
R = d / "results"
# per-model reference quality (nats/token)
mq = R / "model_quality.json"
if mq.exists():
roster = {}
tr = R / "table_model_roster.csv"
if tr.exists():
for x in rd(tr):
roster[x["model"].replace("-", "_").replace(".", "")] = x.get("HF repo id", "")
for k, v in json.load(open(mq)).items():
emit(CODE2REPO.get(k, k), "reference", "crossarch-1B", "", "endpoint", "",
"crossarch_1b_native", "held_out_corpus", "nats_per_token", v.get("tok_nll"),
None, None, ds, f"single-model reference quality (source code '{k}'); LIKELIHOOD")
# checkpoint merges within one training run
for p in sorted(R.glob("ckpt_*_shard*.jsonl")):
for r in jl(p):
fam = r["family"]; repo = CODE2REPO.get(fam, fam)
pid = f"{repo}@step{r['step_a']}|{repo}@step{r['step_b']}"
base = f"crossarch:{fam}|{r['step_a']}x{r['step_b']}"
for side, st in (("a", r["step_a"]), ("b", r["step_b"])):
emit(f"{repo}@step{st}", "parent", fam, "", "checkpoint", "",
"crossarch_checkpoint_merge", "held_out_corpus", "nats_per_token",
r.get(f"nll_{side}"), None, None, ds, "checkpoint endpoint; LIKELIHOOD")
for k, op in (("nll_avg", "weight_avg"), ("nll_lerp_0.25", "lerp_a0.25"),
("nll_lerp_0.75", "lerp_a0.75"), ("nll_ties", "ties"),
("nll_task_arith", "task_arithmetic"), ("nll_dare", "dare")):
emit(f"{base}|{op}", "merged", fam, pid, op, op, "crossarch_checkpoint_merge",
"held_out_corpus", "nats_per_token", r.get(k), None, None, ds,
"LIKELIHOOD, not accuracy")
emit(f"{base}|lmc", "merged", fam, pid, "lmc", "weight_avg",
"crossarch_checkpoint_merge", "held_out_corpus", "lmc_barrier_nats_per_token",
r.get("barrier"), None, None, ds,
"linear-mode-connectivity barrier; negative = merge beats the endpoint average")
# cross-architecture optimal-transport transport merges
p = R / "transport_merge.csv"
if p.exists():
for r in rd(p):
tgt, don, a = r["target"], r["donor"], r["alpha"]
pid = f"{CODE2REPO.get(tgt, tgt)}|{CODE2REPO.get(don, don)}"
mid = f"crossarch-transport:{tgt}<-{don}|alpha{a}"
n = int(f(r.get("n_probe")) or 0) or None
for k, lbl, op in (("nll", f"held_out[{r['target_lang']}]", "transport_ot"),
("nll_donor_lang", f"held_out[{r['donor_lang']}]", "transport_ot"),
("nll_randplan", f"held_out[{r['target_lang']}]", "transport_random_plan"),
("nll_donor_lang_randplan", f"held_out[{r['donor_lang']}]", "transport_random_plan")):
emit(f"{mid}|{op}", "merged" if "random" not in op else "control", "crossarch-1B",
pid, f"alpha={a}", op, "crossarch_transport_merge", lbl, "nats_per_token",
r.get(k), None, n, ds,
"random-plan arm is the control for the OT plan" if "random" in op
else "cross-architecture transport merge; LIKELIHOOD")
# native cross-model merges (no transport)
p = R / "crossmodel_native_merge_summary.csv"
if p.exists():
for r in rd(p):
host, op = r["host"], r["operator"]
emit(CODE2REPO.get(host, host), "parent", "crossarch-1B", "", "host_only",
"", "crossarch_native_merge", f"held_out[{host}]", "nats_per_token",
r.get("nll_host_only"), None, None, ds, "host model alone; LIKELIHOOD")
for k, rung in (("nll_donor_blocks", "donor_blocks"), ("nll_half", "half")):
emit(f"crossarch-native:{host}|{op}|{rung}", "merged", "crossarch-1B", "", rung, op,
"crossarch_native_merge", f"held_out[{host}]", "nats_per_token", r.get(k),
None, None, ds, "LIKELIHOOD, not accuracy")
emit(f"crossarch-native:{host}|{op}|half", "merged", "crossarch-1B", "", "half", op,
"crossarch_native_merge", f"held_out[{host}]", "lmc_barrier_nats_per_token",
r.get("barrier"), None, None, ds, "LMC barrier")
# =================================================================== 4. MergeBench
def build_mergebench(d, ds):
p = d / "mergebench_published_scores.csv"
if not p.exists(): return
NORM = {"Avg. Norm", "Avg. Norm (Table 8)"}
for r in rd(p):
fam = r["family"]
fam_c = {"Gemma-2-2b": "gemma-2-2b", "Gemma-2-2b-it": "gemma-2-2b-it",
"Gemma-2-9b": "gemma-2-9b", "Gemma-2-9b-it": "gemma-2-9b-it"}.get(fam, fam)
task = r["task"]
metric = "benchmark_score_norm_pct" if task in NORM else "benchmark_score_pct"
arity = int(f(r.get("merge_arity")) or 5)
emit(f"mergebench:{fam_c}|{r['method']}", "merged", fam_c,
f"{fam_c}: all {arity} domain experts", f"{arity}-expert merge", r["method"],
"mergebench_published_outcomes", task, metric, r.get("score"), None, None, ds,
f"published by MergeBench ({r.get('source','')}); every released score is a "
f"{arity}-expert merge, so no pair-level outcome exists. Suite aggregate over "
"heterogeneous tasks -- NOT a single-benchmark accuracy, so no chance level is defined.")
# =================================================================== 5. AIM
def build_aim(d, ds):
p = d / "results/published_scores.csv"
if not p.exists(): return
B = {"HumanEval": ("accuracy_pct", 0.0), "MBPP": ("accuracy_pct", 0.0),
"MMLU": ("accuracy_pct", 25.0), "MATH": ("accuracy_pct", 0.0),
"GSM8K": ("accuracy_pct", 0.0), "IFEval": ("accuracy_pct", 0.0),
"HV": ("harmfulness_score", None)}
for r in rd(p):
op, combo, aim = r["operator"], r["combo"], r["aim"]
is_base = op == "_base"
role = "reference" if is_base else "merged"
mid = r.get("repo_id") or f"aim:{op}|{combo}|aim{aim}"
note = ("base / single-expert reference checkpoint" if is_base else
("with AIM (activation-informed merging applied post hoc)" if aim == "1"
else "without AIM (baseline merge)"))
parents = "" if is_base else f"Llama-2 experts: {combo.replace('-', ' + ')}"
for b, (metric, ch) in B.items():
emit(mid, role, "Llama-2-7B (AIM release)", parents, f"aim={aim}",
"" if is_base else op, "aim_published_outcomes", b, metric, r.get(b), ch, None, ds,
note + (" | HV is a harmfulness score, not an accuracy" if b == "HV" else ""))
# =================================================================== 6. Goldfish CKA/NLL
def build_goldfish(d, ds):
"""Only the NLL columns are extrinsic evaluations; CKA is an intrinsic
representation-similarity diagnostic and is deliberately excluded."""
p = d / "results/cka_lastlayer.csv"
if not p.exists(): return
seen = set()
for r in rd(p):
mid = r["model"]
if mid in seen: continue # one row per model; the file repeats it per pooling
seen.add(mid)
arm = r.get("arm") or "reference"
role = {"merged": "merged", "trained": "jointly_trained"}.get(arm, "reference")
pair = r["pair"]; cfg = r["config"]
parents = "" if role != "merged" else f"goldfish[{pair.split('_')[0]}]|goldfish[{pair.split('_')[1]}]"
n = int(f(r.get("n")) or 0) or None
note = (f"config={cfg}; arm={arm}. NLL only -- the CKA columns in the source are an "
"intrinsic representation-similarity diagnostic and are not extrinsic evaluations.")
if role == "jointly_trained":
note += " 'trained' = a model trained directly on the mixture, the merge's comparator."
for k, lbl in (("nll_a", f"held_out[{pair.split('_')[0]}]"),
("nll_b", f"held_out[{pair.split('_')[1]}]"),
("nll_mean", f"held_out[{pair}] mean")):
emit(mid, role, f"Goldfish {pair}", parents,
f"alpha={r.get('alpha')},topk={r.get('topk')}", arm if role == "merged" else "",
"goldfish_crosslingual", lbl, "nats_per_token", r.get(k), None, n, ds,
note + " | LIKELIHOOD, not accuracy")
# =================================================================== 7. Beetle merges
def build_beetle(d, ds):
"""Beetle merge evaluations. The source already ships a long-format table whose
columns line up almost exactly with this schema, so this is mostly a relabelling."""
p = d / "beetle_merge_eval_long.csv"
if not p.exists(): return
src = rd(p)
# a released model that some merge names as its ceiling is a jointly-trained comparator;
# one named as a parent is a parent. Everything else is a plain reference.
ceilings = {r["ceiling"] for r in src if r.get("ceiling")}
parents_set = {r[k] for r in src for k in ("parent_a", "parent_b") if r.get(k)}
for r in src:
kind = r.get("kind")
mid_base = r["merge_id"]
rung, op, arm = r.get("rung", ""), r.get("operator", ""), r.get("arm", "")
if kind == "merge":
role = "merged"
mid = f"{mid_base}#{rung}" if rung else mid_base
parents = "|".join(x for x in (r.get("parent_a"), r.get("parent_b")) if x)
note = (f"Beetle merge; arm={arm}; jointly-trained ceiling for this pair is "
f"{r.get('ceiling') or 'n/a'}; eval langs {r.get('eval_langs') or 'n/a'}")
else:
mid, parents = mid_base, ""
if mid_base in ceilings:
role, note = "jointly_trained", ("released bilingual model trained directly on the "
"pair -- the ceiling a Beetle merge is judged against")
elif mid_base in parents_set:
role, note = "parent", "Beetle merge parent, evaluated alone"
else:
role, note = "reference", "Beetle reference model"
bench, metric_in = r["benchmark"], r.get("metric")
ch = f(r.get("chance"))
if metric_in == "accuracy":
# BLiSS accuracy is reported on 0-100, everything else on 0-1
metric = "accuracy_pct" if (ch is not None and ch > 1) else "accuracy"
else:
bench, metric = f"{bench}:{metric_in}", "bliss_score"
note += f" | BLiSS sub-score '{metric_in}', not an accuracy"
emit(mid, role, r.get("provenance_family") or "beetle", parents, rung, op,
"beetle_merge_eval", bench, metric, r.get("value"),
ch if metric.startswith("accuracy") else ch, f(r.get("n")), ds, note)
# =================================================================== driver
BUILDERS = {"merge-accuracy": build_merge_accuracy, "compose-audit": build_compose_audit,
"crossarch-1b": build_crossarch, "mergebench": build_mergebench,
"aim": build_aim, "goldfish": build_goldfish, "beetle": build_beetle}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--push", action="store_true")
ap.add_argument("--no-fetch", action="store_true")
a = ap.parse_args()
from huggingface_hub import snapshot_download
from huggingface_hub.errors import RepositoryNotFoundError
tok = os.environ.get("HF_TOKEN")
OUT.mkdir(parents=True, exist_ok=True)
manifest = {"built_utc": datetime.datetime.now(datetime.timezone.utc)
.strftime("%Y-%m-%dT%H:%M:%SZ"), "sources": {}}
for key, meta in SOURCES.items():
repo = meta["repo"]; local = CACHE / key
entry = {"repo": repo, "declared_status": meta["status"]}
if not a.no_fetch:
try:
snapshot_download(repo, repo_type="dataset", local_dir=str(local), token=tok,
allow_patterns=["*.csv", "*.json", "*.jsonl", "*.md"])
entry["fetch"] = "ok"
except RepositoryNotFoundError:
entry["fetch"] = "not_published_yet"
print(f"[skip] {repo} is not published yet", file=sys.stderr)
except Exception as e:
entry["fetch"] = f"error: {type(e).__name__}"
print(f"[warn] {repo}: {e}", file=sys.stderr)
else:
entry["fetch"] = "ok" if local.exists() else "not_present"
before = len(rows)
fn = BUILDERS.get(key)
if fn and entry["fetch"] == "ok" and local.exists():
fn(local, repo)
elif entry["fetch"] == "ok" and local.exists():
data = [q for q in local.rglob("*")
if q.is_file() and q.suffix in (".csv", ".json", ".jsonl")
and ".cache" not in q.parts]
if not data:
print(f"[note] {repo} exists but ships no result files yet", file=sys.stderr)
entry["note"] = "repo created but empty; re-run once it has results"
else:
print(f"[note] {repo} has {len(data)} result file(s) but no extractor -- "
f"add one and re-run", file=sys.stderr)
entry["note"] = f"published with {len(data)} result file(s) but no extractor yet"
entry["rows"] = len(rows) - before
manifest["sources"][key] = entry
# in-progress provenance flag in notes
inprog = {SOURCES[k]["repo"] for k in SOURCES if SOURCES[k]["status"] == "in_progress"}
for r in rows:
if r["source_dataset"] in inprog:
r["notes"] = ("IN PROGRESS -- this source dataset was still being written when this "
"file was built; treat as provisional. | " + r["notes"]).strip(" |")
# ---- global dedupe: the same measurement on the same model must appear exactly once.
# Several sources are resumable ledgers that re-report shared baseline rungs.
seen, deduped, conflicts = {}, [], []
KEY = ("source_dataset", "experiment", "model_id", "model_role", "rung", "operator",
"benchmark", "metric")
for r in rows:
k = tuple(r[c] for c in KEY)
if k in seen:
# tolerate re-measurement jitter (different ledgers re-run the same eval and can
# differ in the ~8th significant figure); flag only genuine disagreements
if not math.isclose(seen[k]["value"], r["value"], rel_tol=1e-6, abs_tol=1e-9):
conflicts.append({"key": list(k), "kept": seen[k]["value"], "dropped": r["value"]})
continue
seen[k] = r
deduped.append(r)
n_dropped = len(rows) - len(deduped)
rows[:] = deduped
print(f"dedupe: dropped {n_dropped} repeated measurements, {len(conflicts)} value conflicts")
rows.sort(key=lambda r: (r["source_dataset"], r["experiment"], r["metric_kind"],
r["benchmark"], r["model_id"], r["metric"]))
csv_p = OUT / "extrinsic_evaluations.csv"
with open(csv_p, "w", newline="") as fh:
w = csv.DictWriter(fh, fieldnames=NCOLS); w.writeheader(); w.writerows(rows)
print(f"wrote {csv_p} rows={len(rows)}")
try:
import pandas as pd
df = pd.DataFrame(rows, columns=NCOLS)
df["chance"] = pd.to_numeric(df["chance"], errors="coerce")
df["n"] = pd.to_numeric(df["n"], errors="coerce").astype("Int64")
df.to_parquet(OUT / "extrinsic_evaluations.parquet", index=False)
print("wrote parquet")
except Exception as e:
print(f"[warn] parquet skipped: {e}", file=sys.stderr)
from collections import Counter
manifest["n_rows"] = len(rows)
manifest["n_duplicate_measurements_dropped"] = n_dropped
manifest["n_value_conflicts"] = len(conflicts)
manifest["value_conflicts"] = conflicts[:200]
manifest["by_experiment"] = dict(Counter(r["experiment"] for r in rows).most_common())
manifest["by_metric_kind"] = dict(Counter(r["metric_kind"] for r in rows).most_common())
manifest["by_metric"] = dict(Counter(r["metric"] for r in rows).most_common())
manifest["by_source"] = dict(Counter(r["source_dataset"] for r in rows).most_common())
manifest["by_role"] = dict(Counter(r["model_role"] for r in rows).most_common())
manifest["accuracy_rows_missing_chance"] = sum(
1 for r in rows if r["metric_kind"] == "accuracy" and r["chance"] == "")
json.dump(manifest, open(OUT / "build_manifest.json", "w"), indent=2)
print(json.dumps({k: manifest[k] for k in
("n_rows", "by_metric_kind", "accuracy_rows_missing_chance")}, indent=2))
if a.push:
from huggingface_hub import HfApi
api = HfApi(token=tok)
api.create_repo(TARGET_REPO, repo_type="dataset", exist_ok=True)
for fn_ in ("extrinsic_evaluations.csv", "extrinsic_evaluations.parquet",
"build_manifest.json", "README.md"):
fp = OUT / fn_
if fp.exists():
api.upload_file(path_or_fileobj=str(fp), path_in_repo=fn_,
repo_id=TARGET_REPO, repo_type="dataset")
print("uploaded", fn_)
api.upload_file(path_or_fileobj=__file__, path_in_repo="build_extrinsic.py",
repo_id=TARGET_REPO, repo_type="dataset")
print("uploaded build_extrinsic.py")
if __name__ == "__main__":
main()