File size: 4,499 Bytes
aaba844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# MIT License, Bryan Cheng, 2026.
"""E1 on a wild population: relatedness structure from weights alone (RESEARCH_PLAN 5.4).

  python src/analysis/e1_wild.py --geno data/processed/qwen05 --index data/raw/hf_index/<base>.adapter.jsonl
         --out results/e1/wild_qwen05.json
"""
import argparse
import json
import os
from collections import Counter

import numpy as np
from scipy.sparse.csgraph import connected_components
from sklearn.metrics import adjusted_rand_score


def law(r1, r2, d):
    return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))


def q(x):
    return {str(p): float(np.quantile(x, p / 100)) for p in (1, 5, 25, 50, 75, 95, 99, 99.9)}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--geno", required=True)
    ap.add_argument("--index", required=True)
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    A = json.load(open(os.path.join(a.geno, "adapters.json")))
    names, info = A["names"], A["info"]
    K = np.load(os.path.join(a.geno, "K.npz"))
    Kd, Kf = K["K_desc"], K["K_func"]
    n = len(names)
    iu = np.triu_indices(n, 1)
    rmax = np.array([max(info[x]["ranks"]) for x in names], float)
    thr = 3 * law(rmax[:, None], rmax[None, :], 896)
    adj = (Kd > thr) & ~np.eye(n, dtype=bool)
    nf, fam = connected_components(adj, directed=False)
    sizes = Counter(fam)
    meta = {json.loads(l)["id"].replace("/", "__"): json.loads(l) for l in open(a.index)}
    authors = [x.split("__")[0] for x in names]
    dsets = [",".join(sorted(t for t in (meta.get(x, {}).get("tags") or []) if t.startswith("dataset:"))) or f"none{i}"
             for i, x in enumerate(names)]
    multi = np.array([sizes[f] > 1 for f in fam])
    ev_d = np.sort(np.linalg.eigvalsh(Kd))[::-1]
    ev_f = np.sort(np.linalg.eigvalsh(Kf))[::-1]
    fails = {k: v for k, v in info.items() if v.get("status") != "ok"}
    out = {
        "n_genotyped": n, "n_failed_load": len(fails),
        "fail_reasons": Counter(v["error"].split(":")[0] + ":" + v["error"].split(":")[1][:40] for v in fails.values()),
        "n_dora": int(sum(info[x]["flags"].get("dora", False) for x in names)),
        "n_modules_to_save": int(sum(info[x]["flags"].get("modules_to_save", False) for x in names)),
        "rank_counts": Counter(int(r) for r in rmax), "K_desc_offdiag": q(Kd[iu]), "K_func_offdiag": q(Kf[iu]),
        "corr_Kdesc_Kfunc_offdiag": float(np.corrcoef(Kd[iu], Kf[iu])[0, 1]),
        "pairs_Kdesc_gt": {str(t): int((Kd[iu] > t).sum()) for t in (0.01, 0.1, 0.5, 0.9, 0.999)},
        "pairs_related_by_law_rule": int(adj[iu].sum()),
        "n_descent_families": int(nf), "family_size_counts": Counter(int(s) for s in sizes.values()),
        "largest_families": sorted(sizes.values(), reverse=True)[:10],
        "share_with_relative": float(multi.mean()),
        "n_eff_desc": float(np.trace(Kd) ** 2 / np.sum(Kd * Kd)), "n_eff_func": float(np.trace(Kf) ** 2 / np.sum(Kf * Kf)),
        "top_eig_desc": ev_d[:10].tolist(), "top_eig_func": ev_f[:10].tolist(),
        "ARI_family_vs_author": float(adjusted_rand_score(authors, fam)),
        "ARI_family_vs_dataset_tags": float(adjusted_rand_score(dsets, fam)),
        "share_families_single_author": float(np.mean([len(set(np.array(authors)[fam == f])) == 1
                                                       for f in sizes if sizes[f] > 1])) if (multi.any()) else None,
        "same_author_pairs_related": float(adj[iu][np.array(authors)[iu[0]] == np.array(authors)[iu[1]]].mean()),
        "diff_author_pairs_related": float(adj[iu][np.array(authors)[iu[0]] != np.array(authors)[iu[1]]].mean()),
    }
    os.makedirs(os.path.dirname(a.out), exist_ok=True)
    json.dump(out, open(a.out, "w"), indent=1, default=lambda o: dict(o) if isinstance(o, Counter) else str(o))
    print(json.dumps({k: out[k] for k in ("n_genotyped", "n_dora", "n_descent_families", "share_with_relative",
                                          "n_eff_desc", "n_eff_func", "ARI_family_vs_author",
                                          "corr_Kdesc_Kfunc_offdiag", "pairs_related_by_law_rule")}, indent=0))
    print("K_desc q:", {k: round(v, 5) for k, v in out["K_desc_offdiag"].items()})
    print("K_func q:", {k: round(v, 4) for k, v in out["K_func_offdiag"].items()})
    print("largest families", out["largest_families"], "same/diff author related", round(out["same_author_pairs_related"], 3),
          round(out["diff_author_pairs_related"], 5))


if __name__ == "__main__":
    main()