File size: 4,252 Bytes
7462f1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""Mechanistic diagnostic for the discrete-mode decoders.

Trains one variant on one external task, then decomposes the held-out
prediction into its base and residual parts:

* Spearman of ``s_base`` alone, of ``y_hat``, and of the residual ``y_hat -
  s_base`` against the label.  A residual that carries signal should rank the
  target better than chance; a residual that only adds variance shows |rho| ~ 0.
* The share of the prediction variance that the residual contributes.
* Posterior usage: entropy of the mean posterior, the number of live codes and
  the top code's share, i.e. whether the codebook collapsed.

    PYTHONPATH=src python scripts/mode_diagnose.py --model physmode \
        --study LM_2019 --fold 0 --seed 0
"""

from __future__ import annotations

import argparse

import numpy as np
import torch
from scipy import stats

from lnpbench import data, metrics, paths
from lnpbench.registry import build_model
from lnpbench.store import FeatureStore
from lnpbench.trainer import TrainConfig, build_batch


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="physmode")
    ap.add_argument("--study", default="LM_2019")
    ap.add_argument("--fold", type=int, default=0)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--epochs", type=int, default=30)
    ap.add_argument("--batch-size", type=int, default=256)
    ap.add_argument("--out", default=None)
    args = ap.parse_args()

    store = FeatureStore()
    tasks = data.load_tasks(paths.CACHE_DIR / "tasks.pkl")
    task = next(t for t in tasks if t.name == f"{args.study}_fold{args.fold}")
    model = build_model(args.model)
    cfg = TrainConfig(epochs=args.epochs, batch_size=args.batch_size, seed=args.seed,
                      device="cuda", verbose=True)
    info = model.fit(store, task.train_idx, task.val_idx, cfg)
    mod = model.module.eval()

    parts = {"y_hat": [], "s_base": []}
    pis = []
    for start in range(0, len(task.test_idx), 1024):
        chunk = task.test_idx[start:start + 1024]
        batch = build_batch(store, chunk, model.need(), model.device, model.norm)
        with torch.no_grad():
            out = mod(batch)
        parts["y_hat"].append(out["y_hat"].cpu().numpy())
        parts["s_base"].append(out["s_base"].cpu().numpy())
        if out.get("pi") is not None:
            pis.append(out["pi"].cpu().numpy())
    y = store.y[task.test_idx]
    pred = {k: np.concatenate(v) for k, v in parts.items()}
    res = pred["y_hat"] - pred["s_base"]

    rows = [("y_hat", metrics.spearman(y, pred["y_hat"])),
            ("s_base", metrics.spearman(y, pred["s_base"])),
            ("residual", metrics.spearman(y, res)),
            ("|residual| vs |label resid|", metrics.spearman(np.abs(res), np.abs(y - pred["s_base"])))]
    print(f"\n== {args.model} / {task.name} / seed {args.seed} ==")
    for k, v in rows:
        print(f"  spearman({k:24s}) = {v:+.4f}")
    var_share = float(np.var(res) / max(np.var(pred["y_hat"]), 1e-12))
    print(f"  residual variance share          = {var_share:.3f}")
    print(f"  corr(residual, s_base)           = {float(np.corrcoef(res, pred['s_base'])[0, 1]):+.3f}")

    if pis:
        pi = np.concatenate(pis)
        pi = pi / pi.sum(1, keepdims=True)
        pbar = pi.mean(0)
        ent = float(-(pbar * np.log(pbar + 1e-9)).sum())
        live = int((pbar > 0.01).sum())
        print(f"  posterior: entropy={ent:.3f} (max {np.log(len(pbar)):.3f}), "
              f"live codes={live}/{len(pbar)}, top share={pbar.max():.3f}")
        print("  usage: " + " ".join(f"{v:.2f}" for v in pbar))
        # does the dominant mode line up with anything chemical?
        hard = pi.argmax(1)
        il = store.il_id[task.test_idx]
        cpp = store.il_cpp[il]
        for j, name in enumerate(["CPP_prot", "CPP_neut", "dCPP", "stab"]):
            per = [cpp[hard == k, j].mean() for k in range(len(pbar)) if (hard == k).sum() >= 10]
            if len(per) > 2:
                print(f"  {name:9s} across modes: " + " ".join(f"{v:+.2f}" for v in per))

    if args.out:
        np.savez(args.out, y=y, **pred, **({"pi": np.concatenate(pis)} if pis else {}))
        print("wrote", args.out)


if __name__ == "__main__":
    main()