"""Per-pair parameter coverage, from config files alone -- and the vocabulary mismatch it exposes. `MergeBench/Llama-3.2-3B_math` declares `vocab_size = 128320`; its four siblings declare 128256. The math expert added 64 tokens during fine-tuning. That is not a curiosity, it is a mergeability fact: * `embed_tokens` (and `lm_head`, when untied) have DIFFERENT SHAPES from every sibling, so no elementwise merge operator is defined on them. A merge of that pair either drops the embedding or needs the vocabulary handling the Beetle project's `transport` arm exists for. * the behaviour family is undefined for those pairs -- the two models emit logits over different vocabularies, so a KL or a top-k overlap between them compares incomparable things. The sweep's `behaviour_block` correctly returns nothing; this module records WHY. * `param_coverage` for those pairs is NOT 1.0, and the sweep's hardcoded 1.0 was wrong. Everything here is derived from `config.json` -- a few kB per model -- because the only dimension that actually differs is the vocabulary, and the tensors it governs are exactly `embed_tokens` and `lm_head`. So this runs in seconds, needs no weights, and can be applied retroactively to families whose checkpoints were deleted long ago. PYTHONPATH=src python -m mergeschool.mergebench.coverage """ from __future__ import annotations import json import time import numpy as np import pandas as pd from mergeschool import paths from mergeschool.mergebench import suite as SU OUT = paths.RESULTS / "mergebench" log = lambda *a: print(f"[cov {time.strftime('%H:%M:%S')}]", *a, flush=True) # noqa: E731 COLS = ["vocab_a", "vocab_b", "vocab_match", "n_params_est", "n_params_vocab_governed", "param_coverage_cfg", "behaviour_defined", "coverage_note"] def model_config(repo): from huggingface_hub import hf_hub_download with open(hf_hub_download(repo, "config.json")) as fh: return json.load(fh) def _shape_facts(c): V = int(c.get("vocab_size") or 0) d = int(c.get("hidden_size") or c.get("d_model") or c.get("n_embd") or 0) L = int(c.get("num_hidden_layers") or c.get("n_layers") or c.get("n_layer") or 0) inter = int(c.get("intermediate_size") or 4 * d) tied = bool(c.get("tie_word_embeddings", False)) kv = int(c.get("num_key_value_heads") or c.get("num_attention_heads") or 1) heads = int(c.get("num_attention_heads") or 1) hd = d // heads if heads else 0 attn = d * d + 2 * (d * kv * hd) + d * d # q, k, v, o mlp = 3 * d * inter # gate, up, down (SwiGLU) body = L * (attn + mlp) vocab_governed = V * d * (1 if tied else 2) return {"V": V, "d": d, "tied": tied, "body": body, "vocab_governed": vocab_governed, "total": body + vocab_governed} def compute(doc=None): doc = doc or SU.enumerate_suite() rows = [] for fam in SU.families(doc): experts = doc["families"][fam] facts = {} for dom, repo in sorted(experts.items()): try: facts[dom] = _shape_facts(model_config(repo)) except Exception as e: log(f" {repo}: config unavailable ({type(e).__name__}: {e})") doms = sorted(facts) vs = {d: facts[d]["V"] for d in doms} odd = {d: v for d, v in vs.items() if v != max(set(vs.values()), key=list(vs.values()).count)} if odd: log(f" {fam}: VOCAB MISMATCH {odd} vs {sorted(set(vs.values()))}") for i, a in enumerate(doms): for b in doms[i + 1:]: fa, fb = facts[a], facts[b] match = fa["V"] == fb["V"] # A merge is spliced over the BASE model's tensors, so coverage is measured against # parent A -- the same convention `emit_lm._shared_params` uses. gov = fa["vocab_governed"] cov = 1.0 if match else float((fa["total"] - gov) / fa["total"]) note = ("" if match else f"vocab {fa['V']} vs {fb['V']}: embed_tokens" + ("" if fa["tied"] else " and lm_head") + " differ in shape, so no elementwise merge operator is defined on them " "and the behaviour family compares different vocabularies. " f"{gov/fa['total']:.1%} of parameter mass is affected.") rows.append({"pair_id": f"{fam}__{a}__{b}", "family": fam, "vocab_a": fa["V"], "vocab_b": fb["V"], "vocab_match": bool(match), "n_params_est": int(fa["total"]), "n_params_vocab_governed": int(gov), "param_coverage_cfg": cov, "behaviour_defined": bool(match), "coverage_note": note}) d = pd.DataFrame(rows) OUT.mkdir(parents=True, exist_ok=True) d.to_csv(OUT / "table_param_coverage.csv", index=False) return d def merge_into_shards(d): n = 0 by = d.set_index("pair_id") for shard in sorted(OUT.glob("pairs_w*.csv")): t = pd.read_csv(shard) if "pair_id" not in t.columns: continue for c in COLS: if c not in t.columns: # dtype chosen up front: assigning a bool or a string into a float64 column is # deprecated in pandas and would become an error. t[c] = pd.Series([pd.NA] * len(t), dtype="object") \ if c in ("vocab_match", "behaviour_defined", "coverage_note") else np.nan touched = False for i, pid in enumerate(t.pair_id): if pid in by.index: r = by.loc[pid] for c in COLS: t.at[i, c] = r[c] # the sweep hardcoded 1.0; replace it with the measured value t.at[i, "param_coverage"] = r["param_coverage_cfg"] touched = True n += 1 if touched: t.to_csv(shard, index=False) log(f" merged into {shard.name}") return n def main(): d = compute() bad = d[~d.vocab_match] log(f"{len(d)} pairs; {len(bad)} with a vocabulary mismatch") for _, r in bad.iterrows(): log(f" {r.pair_id}: vocab {r.vocab_a} vs {r.vocab_b}, " f"param_coverage {r.param_coverage_cfg:.4f}") log(f"merged into {merge_into_shards(d)} rows") if __name__ == "__main__": main()