Download scripts/analyze_correlations.py from Cross-Mergeability/crossarch-1b-diagnostics: direct link, hf CLI and curl.
- Browser
- Download file 4.29 kB
-
https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/analyze_correlations.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/crossarch-1b-diagnostics/scripts/analyze_correlations.py
-
curl -L -o analyze_correlations.py https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/analyze_correlations.py
4.29 kB
| """Diagnostic x diagnostic Spearman correlation tables, with a permutation null. | |
| Two arms, reported separately and never pooled: | |
| * checkpoint arm -- within-run Pythia / Zh-Pythia checkpoint pairs. Native weight-space | |
| merging, so the full weight-space family is defined. n is adequate. | |
| * cross-model arm -- the 10 independently trained 1B models. Representation-level only. | |
| n=10 is badly underpowered; the permutation null is the honest read. | |
| """ | |
| import glob, itertools, json, os, sys | |
| import numpy as np, pandas as pd | |
| from scipy import stats | |
| ROOT = "/root/crossarch-diagnostics" | |
| NPERM = 20000 | |
| RNG = np.random.default_rng(0) | |
| CKPT_COLS = ["log10_step_ratio", "log10_step_b", "w_cos", "w_cos_blocks", "w_l2_rel", | |
| "tau_cos", "tau_norm_ratio", "sign_agree", "barrier", "barrier_half", | |
| "nll_avg", "gain_avg", "gain_ties", "gain_task_arith", "gain_dare", "gain_best", | |
| "cka", "cka_delta", "procrustes", "svcca", "p_at_1", "mean_endpoint_nll"] | |
| XM_COLS = ["cka", "cka_shuf", "procrustes", "svcca", "p_at_1", | |
| "uriel_syntactic", "uriel_genetic", "uriel_featural", "mean_tok_nll"] | |
| def spearman_perm(x, y, nperm=NPERM, rng=RNG): | |
| """Spearman rho, its asymptotic p, and a permutation p on |rho|.""" | |
| m = np.isfinite(x) & np.isfinite(y) | |
| x, y = np.asarray(x, float)[m], np.asarray(y, float)[m] | |
| n = len(x) | |
| if n < 4 or np.std(x) == 0 or np.std(y) == 0: | |
| return np.nan, np.nan, np.nan, n | |
| rho, p = stats.spearmanr(x, y) | |
| rx = stats.rankdata(x); ry = stats.rankdata(y) | |
| rx = (rx - rx.mean()) / rx.std(); ry = (ry - ry.mean()) / ry.std() | |
| idx = np.argsort(rng.random((nperm, n)), axis=1) | |
| null = np.abs((rx[idx] * ry).mean(1)) | |
| pperm = float((null >= abs(rho) - 1e-12).mean()) | |
| return float(rho), float(p), pperm, int(n) | |
| def corr_table(df, cols, tag): | |
| cols = [c for c in cols if c in df.columns and df[c].notna().sum() >= 4] | |
| rows = [] | |
| for a, b in itertools.combinations(cols, 2): | |
| rho, p, pp, n = spearman_perm(df[a].values, df[b].values) | |
| rows.append(dict(arm=tag, diag_a=a, diag_b=b, spearman_rho=rho, p_asymptotic=p, | |
| p_permutation=pp, n_pairs=n)) | |
| out = pd.DataFrame(rows) | |
| if len(out): | |
| # Benjamini-Hochberg across the whole table | |
| o = out.p_permutation.rank(method="first") | |
| out["q_bh"] = (out.p_permutation * len(out) / o).clip(upper=1.0) | |
| out = out.sort_values("p_permutation") | |
| return out, cols | |
| def matrix_form(ct, cols): | |
| m = pd.DataFrame(np.eye(len(cols)), index=cols, columns=cols) | |
| for _, r in ct.iterrows(): | |
| m.loc[r.diag_a, r.diag_b] = r.spearman_rho | |
| m.loc[r.diag_b, r.diag_a] = r.spearman_rho | |
| return m | |
| def main(): | |
| # ---- checkpoint arm ---- | |
| rows = [] | |
| for f in glob.glob(f"{ROOT}/results/ckpt_*_shard*.jsonl"): | |
| rows += [json.loads(l) for l in open(f)] | |
| ck = pd.DataFrame(rows).drop_duplicates(subset=["family", "pair"]).reset_index(drop=True) | |
| if len(ck): | |
| ck["mean_endpoint_nll"] = 0.5 * (ck.nll_a + ck.nll_b) | |
| ck["min_endpoint_nll"] = ck[["nll_a", "nll_b"]].min(1) | |
| ck.to_csv(f"{ROOT}/results/checkpoint_pairs.csv", index=False) | |
| for fam, g in list(ck.groupby("family")) + [("ALL", ck)]: | |
| ct, cols = corr_table(g, CKPT_COLS, f"checkpoint:{fam}") | |
| ct.to_csv(f"{ROOT}/results/corr_checkpoint_{fam}.csv", index=False) | |
| matrix_form(ct, cols).to_csv(f"{ROOT}/results/corrmat_checkpoint_{fam}.csv") | |
| print(f"== checkpoint arm [{fam}] n={len(g)} pairs, {len(cols)} diagnostics") | |
| print(ct.head(12).to_string(index=False)) | |
| # ---- cross-model arm ---- | |
| xm = pd.read_csv(f"{ROOT}/results/crossmodel_pairs.csv") | |
| ct, cols = corr_table(xm, XM_COLS, "crossmodel") | |
| ct.to_csv(f"{ROOT}/results/corr_crossmodel.csv", index=False) | |
| matrix_form(ct, cols).to_csv(f"{ROOT}/results/corrmat_crossmodel.csv") | |
| print(f"\n== cross-model arm n={len(xm)} pairs (UNDERPOWERED)") | |
| print(ct.head(15).to_string(index=False)) | |
| json.dump(dict(n_perm=NPERM, ckpt_pairs=int(len(ck)), xmodel_pairs=int(len(xm))), | |
| open(f"{ROOT}/results/corr_provenance.json", "w"), indent=2) | |
| if __name__ == "__main__": | |
| main() | |