Download code/scripts/make_fig_mergebench_scale.py from Cross-Mergeability/mergebench-property-sweep: direct link, hf CLI and curl.
- Browser
- Download file 6.95 kB
-
https://huggingface.co/datasets/Cross-Mergeability/mergebench-property-sweep/resolve/main/code/scripts/make_fig_mergebench_scale.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/mergebench-property-sweep/code/scripts/make_fig_mergebench_scale.py
-
curl -L -o make_fig_mergebench_scale.py https://huggingface.co/datasets/Cross-Mergeability/mergebench-property-sweep/resolve/main/code/scripts/make_fig_mergebench_scale.py
6.95 kB
| """`fig_mergebench_scale.png` -- MergeBench at scale, all eight base families. | |
| Two heatmaps, families x domains: | |
| (a) the published five-expert (Model soup / Weight Avg) merge score -- MergeBench's number, not | |
| ours; every published MergeBench score is a five-expert merge, which is why the outcome unit | |
| is the family and not the pair. | |
| (b) mean qmd_raw over the four within-family pairs that CONTAIN each domain, x10^3 -- ours. | |
| Design is pinned to the version already in the manuscript so a regenerated file drops in unchanged: | |
| viridis for (a) with a 0-90 scale, magma_r for (b), value annotations, `n/a` in italic grey for any | |
| cell without data, two-line suptitle, row labels `family\\n(params)`. | |
| PYTHONPATH=src python scripts/make_fig_mergebench_scale.py | |
| """ | |
| from __future__ import annotations | |
| import glob | |
| import os | |
| import sys | |
| import numpy as np | |
| import pandas as pd | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from mergeschool import paths | |
| RESULTS = paths.RESULTS / "mergebench" | |
| OUT_DIRS = [paths.ROOT / "paper" / "overleaf_iclr", paths.FIGURES / "mergebench"] | |
| NAME = "fig_mergebench_scale" | |
| FAMILIES = [("gemma-2-2b", "2.6B"), ("gemma-2-2b-it", "2.6B"), | |
| ("Llama-3.2-3B", "3.2B"), ("Llama-3.2-3B-Instruct", "3.2B"), | |
| ("Llama-3.1-8B", "8.0B"), ("Llama-3.1-8B-Instruct", "8.0B"), | |
| ("gemma-2-9b", "9.2B"), ("gemma-2-9b-it", "9.2B")] | |
| # figure column order, and the task label each maps to in MergeBench's published table | |
| DOMAINS = [("math", "Math"), ("safety", "Safety"), ("coding", "Coding"), | |
| ("multilingual", "Multilingual"), ("instruction", "Instruction following")] | |
| METHOD = "Model soup" | |
| def load(): | |
| pairs = pd.concat([pd.read_csv(f) for f in glob.glob(str(RESULTS / "pairs_w*.csv"))], | |
| ignore_index=True).drop_duplicates("pair_id") | |
| pub = pd.read_csv(RESULTS / "mergebench_published_scores.csv") | |
| pub = pub[pub.method == METHOD] | |
| S = np.full((len(FAMILIES), len(DOMAINS)), np.nan) # published merge score | |
| Q = np.full((len(FAMILIES), len(DOMAINS)), np.nan) # mean qmd_raw x10^3 | |
| for i, (fam, _p) in enumerate(FAMILIES): | |
| sub = pub[pub.family == fam] | |
| g = pairs[pairs.family == fam] | |
| for j, (dom, task) in enumerate(DOMAINS): | |
| v = sub[sub.task == task]["score"] | |
| if len(v): | |
| S[i, j] = float(v.iloc[0]) | |
| # the four pairs of this family that contain this domain | |
| m = g[(g.domain_a == dom) | (g.domain_b == dom)]["qmd_raw"].dropna() | |
| if len(m): | |
| Q[i, j] = float(m.mean()) * 1e3 | |
| return S, Q, pairs | |
| def panel(ax, M, cmap, title, cbar_label, vmin=None, vmax=None, log=False): | |
| # LOG COLOUR SCALE for the quotient-distance panel, forced by the data rather than chosen for | |
| # looks. With all eight families present qmd_raw spans 9.65 to 70.3 -- the 8B/9B experts drift | |
| # 3-5x further from each other than the 2B/3B ones -- so on a linear scale the four small | |
| # families all sit in the bottom tenth of the range and render as one flat pale block, losing | |
| # exactly the within-family structure the original figure showed. A log scale keeps both reads: | |
| # the cross-scale growth AND the ordering inside each family. | |
| norm = matplotlib.colors.LogNorm(vmin=np.nanmin(M), vmax=np.nanmax(M)) if log else None | |
| im = ax.imshow(np.ma.masked_invalid(M), cmap=cmap, aspect="auto", | |
| norm=norm, **({} if log else {"vmin": vmin, "vmax": vmax})) | |
| im.cmap.set_bad("white") | |
| ax.set_xticks(range(len(DOMAINS))) | |
| ax.set_xticklabels([d for d, _t in DOMAINS], rotation=35, ha="right", rotation_mode="anchor") | |
| ax.set_yticks(range(len(FAMILIES))) | |
| ax.set_yticklabels([f"{f}\n({p})" for f, p in FAMILIES], fontsize=9) | |
| ax.set_title(title, fontsize=11, pad=10) | |
| lo, hi = np.nanmin(M), np.nanmax(M) | |
| for i in range(M.shape[0]): | |
| for j in range(M.shape[1]): | |
| v = M[i, j] | |
| if not np.isfinite(v): | |
| ax.text(j, i, "n/a", ha="center", va="center", fontsize=9, | |
| style="italic", color="#9A9A9A") | |
| continue | |
| # white on dark cells, black on light -- judged against this panel's own range | |
| frac = ((np.log(v) - np.log(lo)) / max(np.log(hi) - np.log(lo), 1e-12)) if log \ | |
| else (v - lo) / max(hi - lo, 1e-12) | |
| dark = frac > 0.55 if cmap.endswith("_r") else frac < 0.55 | |
| ax.text(j, i, f"{v:.1f}" if cmap == "viridis" else f"{v:.2f}", | |
| ha="center", va="center", fontsize=9, | |
| color="white" if dark else "#1A1A1A") | |
| cb = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.03) | |
| cb.set_label(cbar_label, fontsize=9) | |
| cb.ax.tick_params(labelsize=8) | |
| if log: | |
| # matplotlib's default log locator adds 6x10^1-style minor labels that collide with the | |
| # round ticks the reader wants; silence both locators and set the ticks explicitly. | |
| cb.ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator()) | |
| cb.ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter()) | |
| ticks = [t for t in (10, 15, 20, 30, 50, 70) if np.nanmin(M) <= t <= np.nanmax(M)] | |
| cb.set_ticks(ticks) | |
| cb.ax.yaxis.set_major_formatter(matplotlib.ticker.FixedFormatter([str(t) for t in ticks])) | |
| return im | |
| def main(): | |
| S, Q, pairs = load() | |
| n_fam = int(np.isfinite(S).any(axis=1).sum()) | |
| n_pairs = int(len(pairs)) | |
| missing = [f for i, (f, _p) in enumerate(FAMILIES) if not np.isfinite(Q[i]).any()] | |
| fig, axes = plt.subplots(1, 2, figsize=(20, 8)) | |
| panel(axes[0], S, "viridis", "(a) Published 5-expert merge score (Model soup)", | |
| "norm. task score", vmin=0, vmax=90) | |
| panel(axes[1], Q, "magma_r", | |
| "(b) Mean quotient dist. qmd$_\\mathrm{raw}$ ($\\times10^{3}$, log scale)", | |
| "qmd$_\\mathrm{raw}$ $\\times$ 10$^{3}$ (log)", log=True) | |
| sub = (f"(all {n_fam} families measured, {n_pairs}/80 pairs; " | |
| f"MergeBench publishes only 5-expert merges, n={n_fam} families)" | |
| if not missing else | |
| f"({n_fam}/8 families measured; {', '.join(missing)} pending, n/a; " | |
| f"MergeBench publishes only 5-expert merges)") | |
| fig.suptitle("MergeBench at scale — 8 base families (2.6B / 3.2B / 8.0B / 9.2B) × 5 domains\n" | |
| + sub, fontsize=13) | |
| fig.tight_layout(rect=(0, 0, 1, 0.94)) | |
| for d in OUT_DIRS: | |
| d.mkdir(parents=True, exist_ok=True) | |
| for ext in ("png", "pdf"): | |
| fig.savefig(d / f"{NAME}.{ext}", dpi=200, bbox_inches="tight") | |
| print(f" wrote {d / (NAME + '.png')}") | |
| plt.close(fig) | |
| print(f" families with data: {n_fam}/8 | pairs: {n_pairs}/80 | " | |
| f"pending: {missing or 'none'}") | |
| return S, Q | |
| if __name__ == "__main__": | |
| main() | |