# MIT License, Bryan Cheng, 2026. """Cross-hardware concordance of phenotypes (D-019/D-027). The same adapters measured on H200 (population run) and re-measured on B200 (results/phenotypes/qwen05_concord). Per trait, on the raw scale divided by the population robust SD (MAD x 1.4826 over all ok records): shift mean paired difference B200 - H200 (SD units) with a t-based 95% CI sd_diff SD of the paired differences r, ccc Pearson and Lin concordance correlation between the two measurements item_se median per-adapter item-sampling SE of the full measure, sqrt(((h_A - h_B)/2)^2) in SD units (split halves) ratio sd_diff / item_se: < 1 means hardware disagreement is smaller than the item-sampling noise already modelled base_diff B200 base in the population run minus B200 base in the concordance run (same hardware: determinism check) group_smd population-level H200 vs B200 standardized mean difference (shards interleave adapters, so it estimates the hardware offset plus sampling noise) with Welch p python src/analysis/concordance.py --pop results/phenotypes/qwen05 --rep results/phenotypes/qwen05_concord \ --primary results/scans/qwen05/primary_traits.json --out results/phenotypes/concordance_qwen05.json """ import argparse import glob import json import os import numpy as np from scipy import stats def load(d): out = {} for f in sorted(glob.glob(os.path.join(d, "*.json"))): r = json.load(open(f)) if r.get("status") == "ok" or os.path.basename(f) == "__base__.json": out[os.path.basename(f)[:-5]] = r return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--pop", required=True) ap.add_argument("--rep", required=True) ap.add_argument("--primary") ap.add_argument("--out", required=True) a = ap.parse_args() pop, rep = load(a.pop), load(a.rep) pb, rb = pop.pop("__base__", None), rep.pop("__base__", None) pairs = [n for n in rep if n in pop] gpus = {n: pop[n].get("gpu", "?") for n in pairs} prim = json.load(open(a.primary))["primary"] if a.primary and os.path.exists(a.primary) else None traits = sorted(set().union(*[set(r["traits"]) for r in pop.values()])) res = {} for t in traits: y = np.array([r["traits"][t][0] for r in pop.values() if r["traits"].get(t)], float) y = y[np.isfinite(y)] if len(y) < 50: continue sd = 1.4826 * np.median(np.abs(y - np.median(y))) if not sd > 0: sd = np.std(y) if not sd > 0: continue P = np.array([pop[n]["traits"].get(t, [np.nan] * 3) for n in pairs], float) / sd R = np.array([rep[n]["traits"].get(t, [np.nan] * 3) for n in pairs], float) / sd ok = np.isfinite(P[:, 0]) & np.isfinite(R[:, 0]) if ok.sum() < 5: continue x, z = P[ok, 0], R[ok, 0] d = z - x m, s = float(d.mean()), float(d.std(ddof=1)) h = stats.t.ppf(0.975, len(d) - 1) * s / np.sqrt(len(d)) r = float(np.corrcoef(x, z)[0, 1]) if np.std(x) > 0 and np.std(z) > 0 else None ccc = float(2 * np.cov(x, z, ddof=0)[0, 1] / (x.var() + z.var() + (x.mean() - z.mean()) ** 2)) se_item = np.abs(P[ok, 1] - P[ok, 2]) / 2 item_se = float(np.nanmedian(se_item)) bd = None if pb and rb and pb["traits"].get(t) and rb["traits"].get(t): bd = float((pb["traits"][t][0] - rb["traits"][t][0]) / sd) gh = np.array([r["traits"][t][0] for r in pop.values() if r["traits"].get(t) and r.get("gpu") == "NVIDIA H200"], float) gb = np.array([r["traits"][t][0] for r in pop.values() if r["traits"].get(t) and r.get("gpu") == "NVIDIA B200"], float) gh, gb = gh[np.isfinite(gh)] / sd, gb[np.isfinite(gb)] / sd smd, pw = None, None if len(gh) > 10 and len(gb) > 10: smd = float(gb.mean() - gh.mean()) pw = float(stats.ttest_ind(gb, gh, equal_var=False).pvalue) res[t] = {"n_pairs": int(ok.sum()), "sd_pop": float(sd), "shift": m, "shift_ci95": [m - h, m + h], "sd_diff": s, "max_abs_diff": float(np.abs(d).max()), "r": r, "ccc": ccc, "item_se": item_se, "ratio": float(s / item_se) if item_se > 0 else None, "base_diff_same_hw": bd, "group_smd": smd, "group_p": pw, "primary": (t in prim) if prim else None} keys = [t for t in res if (res[t]["primary"] if prim else True)] summ = {"n_pairs": len(pairs), "pair_gpus": sorted(set(gpus.values())), "n_traits": len(res), "summary_over": "primary" if prim else "all", "median_ccc": float(np.median([res[t]["ccc"] for t in keys])), "min_ccc": float(np.min([res[t]["ccc"] for t in keys])), "median_ratio": float(np.nanmedian([res[t]["ratio"] or np.nan for t in keys])), "n_shift_ci_excludes_0": int(sum(res[t]["shift_ci95"][0] > 0 or res[t]["shift_ci95"][1] < 0 for t in keys)), "max_abs_shift": float(np.max([abs(res[t]["shift"]) for t in keys])), "max_abs_base_diff_same_hw": float(np.nanmax([abs(res[t]["base_diff_same_hw"]) if res[t]["base_diff_same_hw"] is not None else np.nan for t in keys]))} print(json.dumps(summ, indent=1)) for t in keys: v = res[t] print(f"{t:55s} shift {v['shift']:+.3f} [{v['shift_ci95'][0]:+.3f},{v['shift_ci95'][1]:+.3f}] sd_diff {v['sd_diff']:.3f}" f" item_se {v['item_se']:.3f} ccc {v['ccc']:.3f} base_same_hw {v['base_diff_same_hw']}" f" group_smd {v['group_smd']} p {v['group_p']}") os.makedirs(os.path.dirname(a.out), exist_ok=True) json.dump({"summary": summ, "per_trait": res, "pairs": pairs}, open(a.out, "w"), indent=1) if __name__ == "__main__": main()