| """Task-vector weight-space columns: the informative version, for a suite with a shared base. |
| |
| F8's weight-space family (`weight_cosine`, `subspace_overlap`, `spectral_overcounting`) was designed |
| for pairs that do NOT share a starting point. Every MergeBench family does share one -- its five |
| experts are fine-tunes of a single pretrained checkpoint -- so those columns sit at their analytic |
| ceiling: weight cosine 1.00000-1.00001, subspace overlap 0.9999-1.0000, spectral over-counting |
| -1.000000 (its exact A==B limit). None of them can carry a correlation. |
| |
| The object every merge operator actually manipulates is the **task vector** tau = theta_expert - |
| theta_base, and task vectors are not saturated. This module recomputes the weight-space family on |
| them: |
| |
| tv_cosine cos(tau_a, tau_b) over every shared floating tensor |
| tv_norm_ratio min(||tau||)/max(||tau||) -- are the two experts equally far from base? |
| tv_qmd_raw ||tau_a - tau_b|| / sqrt(||tau_a|| ||tau_b||); the numerator equals |
| theta_a - theta_b, but the normaliser is the task-vector scale rather |
| than the (near-identical) weight scale, so unlike `qmd_raw` it is not |
| dominated by how big the models are |
| tv_subspace_overlap `metrics.subspace_overlap` on the embedding task vectors |
| tv_spectral_overcounting `metrics.spectral_overcounting` on the embedding task vectors -- this |
| is the column F8 wanted: over-counting between two genuine task |
| directions, not between two copies of the same base |
| |
| Streamed key by key on the GPU straight out of the safetensors, so a 9B family never puts a float32 |
| state dict in host RAM. Deliberately SEPARATE from the measurement sweep and idempotent, so it can |
| be retro-fitted onto families that already ran and had their expert weights deleted. |
| |
| PYTHONPATH=src python -m mergeschool.mergebench.taskvec --families gemma-2-2b |
| bash scripts/run_taskvec.sh # every family with rows on disk |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import gc |
| import json |
| import os |
| import shutil |
| 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"[tv {time.strftime('%H:%M:%S')}]", *a, flush=True) |
|
|
| TV_COLS = ["tv_cosine", "tv_norm_ratio", "tv_qmd_raw", "tv_subspace_overlap", |
| "tv_spectral_overcounting", "tv_norm_a", "tv_norm_b"] |
| ALLOW = ["*.safetensors", "*.json", "tokenizer*", "*.model"] |
|
|
|
|
| def _index(d): |
| """{tensor key -> file} for one checkpoint directory.""" |
| from safetensors import safe_open |
| idx = {} |
| for f in sorted(x for x in os.listdir(d) if x.endswith(".safetensors")): |
| with safe_open(os.path.join(d, f), framework="pt") as fh: |
| for k in fh.keys(): |
| idx[k] = os.path.join(d, f) |
| return idx |
|
|
|
|
| def compute_family(family, device="cuda", local=None, keep=False, doc=None): |
| """{pair_id: {tv_* columns}} for one family. Downloads whatever `local` does not supply.""" |
| from huggingface_hub import snapshot_download |
| from safetensors import safe_open |
| import torch |
|
|
| doc = doc or SU.enumerate_suite() |
| experts = doc["families"][family] |
| parent = SU.FAMILY_PARENT.get(family) |
| if not parent: |
| raise ValueError(f"no pretrained parent recorded for {family}") |
|
|
| |
| |
| |
| |
| need_gb = (SU.family_bytes(family, doc) * 1.2 / 1e9) + 25.0 |
| floor = float(os.environ.get("MB_DISK_FLOOR_GB", "400")) |
| waited = 0 |
| while True: |
| free = shutil.disk_usage("/").free / 1e9 |
| if free - need_gb >= floor: |
| break |
| if waited == 0: |
| log(f" {family}: WAITING for disk -- need ~{need_gb:.0f} GB, free {free:.0f} GB, " |
| f"floor {floor:.0f} GB") |
| if waited > 10800: |
| raise RuntimeError(f"disk never freed for {family}: free {free:.0f} GB, " |
| f"need {need_gb:.0f} GB above a {floor:.0f} GB floor") |
| time.sleep(60) |
| waited += 60 |
| if waited: |
| log(f" {family}: disk free after {waited//60} min wait") |
|
|
| fetched = [] |
| local = dict(local or {}) |
| for dom, repo in sorted(experts.items()): |
| if dom not in local: |
| local[dom] = snapshot_download(repo, allow_patterns=ALLOW, max_workers=4) |
| fetched.append(local[dom]) |
| base_dir = snapshot_download(parent, allow_patterns=ALLOW, max_workers=4) |
| log(f" {family}: base {parent} ready ({shutil.disk_usage('/').free/1e9:.0f} GB free)") |
|
|
| doms = sorted(experts) |
| idx = {d: _index(local[d]) for d in doms} |
| bidx = _index(base_dir) |
| keys = sorted(set(bidx).intersection(*[set(idx[d]) for d in doms])) |
|
|
| dot = {(a, b): 0.0 for i, a in enumerate(doms) for b in doms[i + 1:]} |
| sq = dict(dot) |
| nrm = {d: 0.0 for d in doms} |
| emb = {} |
| nkeys = 0 |
| for k in keys: |
| with safe_open(bidx[k], framework="pt") as fh: |
| tb = fh.get_tensor(k) |
| if not tb.is_floating_point(): |
| continue |
| b = tb.to(device=device, dtype=torch.float32).reshape(-1) |
| tau, ok = {}, True |
| for d in doms: |
| with safe_open(idx[d][k], framework="pt") as fh: |
| t = fh.get_tensor(k) |
| if t.shape != tb.shape: |
| ok = False |
| break |
| tau[d] = t.to(device=device, dtype=torch.float32).reshape(-1) - b |
| if not ok: |
| del b |
| continue |
| nkeys += 1 |
| for d in doms: |
| nrm[d] += float(tau[d].pow(2).sum()) |
| for (a, c) in dot: |
| dot[(a, c)] += float(torch.dot(tau[a], tau[c])) |
| sq[(a, c)] += float((tau[a] - tau[c]).pow(2).sum()) |
| |
| if "embed_tokens" in k or k.endswith("wte.weight"): |
| for d in doms: |
| emb[d] = tau[d].reshape(tb.shape).cpu().numpy() |
| del b, tau |
| torch.cuda.empty_cache() |
| log(f" {family}: task vectors over {nkeys} shared tensors" |
| + (f", embeddings {tuple(next(iter(emb.values())).shape)}" if emb else ", no embedding key")) |
|
|
| from mergeschool.mergebench.sweep import spectral_pair |
| out = {} |
| for i, a in enumerate(doms): |
| for c in doms[i + 1:]: |
| na, nc = nrm[a] ** 0.5, nrm[c] ** 0.5 |
| row = {"tv_norm_a": na, "tv_norm_b": nc, |
| "tv_cosine": float(dot[(a, c)] / (na * nc)) if na * nc > 0 else np.nan, |
| "tv_norm_ratio": float(min(na, nc) / max(na, nc)) if max(na, nc) > 0 else np.nan, |
| "tv_qmd_raw": (float(np.sqrt(sq[(a, c)]) / np.sqrt(na * nc)) |
| if na * nc > 0 else np.nan)} |
| if a in emb and c in emb: |
| try: |
| sp = spectral_pair(emb[a], emb[c], device=device) |
| row["tv_subspace_overlap"] = sp["subspace_overlap"] |
| row["tv_spectral_overcounting"] = sp["spectral_overcounting"] |
| except Exception as e: |
| log(f" {family} {a}-{c}: spectral on task vectors failed " |
| f"({type(e).__name__}: {e})") |
| out[f"{family}__{a}__{c}"] = row |
| emb.clear() |
| gc.collect() |
| if not keep: |
| for d in fetched: |
| shutil.rmtree(os.path.dirname(os.path.dirname(d)), ignore_errors=True) |
| shutil.rmtree(os.path.dirname(os.path.dirname(base_dir)), ignore_errors=True) |
| log(f" {family}: released weights ({shutil.disk_usage('/').free/1e9:.0f} GB free)") |
| return out |
|
|
|
|
| CACHE = OUT / "taskvec_cache.json" |
|
|
|
|
| def cache_write(family, tv): |
| """Persist a family's task-vector columns. |
| |
| Without this the pass is order-dependent in the worst way: it ran ahead of the measurement sweep, |
| found no rows to merge into, and silently discarded 27 minutes of downloads and GPU work for six |
| families. The values depend only on the checkpoints, never on whether the sweep has caught up, |
| so they are written here and merged whenever rows appear. |
| """ |
| doc = {} |
| if CACHE.exists(): |
| try: |
| doc = json.loads(CACHE.read_text()) |
| except Exception: |
| doc = {} |
| doc.update(tv) |
| CACHE.parent.mkdir(parents=True, exist_ok=True) |
| CACHE.write_text(json.dumps(doc, indent=1)) |
| log(f" {family}: cached {len(tv)} pairs -> {CACHE.name} ({len(doc)} total)") |
|
|
|
|
| def merge_cached(): |
| """Merge every cached task-vector row into whichever shard now holds it. Idempotent.""" |
| if not CACHE.exists(): |
| return 0 |
| try: |
| return merge_into_shards(json.loads(CACHE.read_text())) |
| except Exception as e: |
| log(f" cache merge failed: {type(e).__name__}: {e}") |
| return 0 |
|
|
|
|
| def merge_into_shards(tv): |
| """Write the tv_* columns into whichever pairs_w*.csv holds each pair. Idempotent.""" |
| n = 0 |
| for shard in sorted(OUT.glob("pairs_w*.csv")): |
| d = pd.read_csv(shard) |
| if "pair_id" not in d.columns: |
| continue |
| touched = False |
| for col in TV_COLS: |
| if col not in d.columns: |
| d[col] = np.nan |
| for i, pid in enumerate(d.pair_id): |
| if pid in tv: |
| for col, v in tv[pid].items(): |
| d.at[i, col] = v |
| touched = True |
| n += 1 |
| if touched: |
| d.to_csv(shard, index=False) |
| log(f" merged into {shard.name}") |
| return n |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--families", nargs="*", default=None, |
| help="default: every family that already has rows on disk") |
| ap.add_argument("--keep-weights", action="store_true") |
| a = ap.parse_args() |
| import torch |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| doc = SU.enumerate_suite() |
|
|
| fams = a.families |
| if not fams: |
| have = set() |
| for shard in sorted(OUT.glob("pairs_w*.csv")): |
| d = pd.read_csv(shard) |
| have |= set(d.family.dropna().unique()) |
| fams = [f for f in SU.families(doc) if f in have] |
| log(f"task vectors for {fams}") |
| for f in fams: |
| t0 = time.time() |
| try: |
| tv = compute_family(f, device=device, keep=a.keep_weights, doc=doc) |
| cache_write(f, tv) |
| n = merge_into_shards(tv) |
| log(f"FAMILY {f}: {len(tv)} pairs, {n} rows updated in {time.time()-t0:.0f}s") |
| except Exception as e: |
| import traceback |
| log(f"FAMILY {f} FAILED: {type(e).__name__}: {e}") |
| log(traceback.format_exc().splitlines()[-1]) |
| log("done") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|