File size: 10,441 Bytes
9b789e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""926/C — the attribution fingerprint on more than one decoder.

Validation-safe EEG encoders (objects 00-05 train, 06-07 epoch selection), five
training seeds (0-2 existing, 3-4 trained for 926 with the same script). Test:
held-out objects 08-09, EEG repetitions averaged (test_mean), 12 subjects.

Inputs, all fed through the same encoder (wrong = (c + 1) mod 72):
  paired               4-trial mean of the object
  same_category_swap   4-trial mean of the other held-out object of the category
  target_mean          mean of the 16 train trials (objects 00-07) of the target category, same subject
  wrong_mean           same for the wrong category

Three small decoders on top of the frozen encoder:
  classify_medoid      MAP category -> its train medoid (results/p0_category_geometry)
  latent_regression    ridge from encoder features to the existing CLIP point embedding
                       (data/EEG-3D/clip_feature.pth, fit on train objects 00-05),
                       decoded as the train object (00-05) nearest in that embedding
  retrieval            train object (00-05) whose EEG feature is nearest (cosine)
Geometry: same as 926/A (512 points, centred, unit sphere, Chamfer-L2, F@0.1, EMD-256).
Readout per seed: top-1/5/10, MRR, NLL on paired input, single subject and 12-subject pooled.
"""
import argparse
import csv
import json
import sys
from pathlib import Path

import numpy as np
import torch

sys.path.insert(0, str(Path(__file__).parent))
from a_sets import REFS, chamfer_matrix, emd_matrix, load_obj  # noqa: E402

sys.path.insert(0, str(REFS / "third_party" / "neuro-3D"))
SUBJECTS = [f"sub{i:02d}" for i in range(1, 13)]
ENC = {0: REFS / "results/encoder_validation_safe", 1: REFS / "results/encoder_validation_safe_seed1",
       2: REFS / "results/encoder_validation_safe_seed2", 3: Path("/home/hubin/926/encoders/seed3"),
       4: Path("/home/hubin/926/encoders/seed4")}
CONDS = ["paired", "same_category_swap", "target_mean", "wrong_mean"]
DECODERS = ["classify_medoid", "latent_regression", "retrieval"]


def raw(subject, split):
    d = REFS / "data/EEG-3D/EEGdata" / subject
    return (np.load(d / f"{subject}_{split}_data_6s_100Hz.npy").astype(np.float32),
            np.load(d / f"{subject}_{split}_data_1s_250Hz.npy").astype(np.float32))


def inputs(subject):
    tr, te = raw(subject, "train"), raw(subject, "test")
    c = np.repeat(np.arange(72), 2)
    o = np.tile([0, 1], 72)
    x = {"paired": tuple(a.mean(2)[c, o] for a in te),
         "same_category_swap": tuple(a.mean(2)[c, 1 - o] for a in te)}
    cm = tuple(a.mean((1, 2)) for a in tr)
    x["target_mean"] = tuple(m[c] for m in cm)
    x["wrong_mean"] = tuple(m[(c + 1) % 72] for m in cm)
    gallery = tuple(a[:, :6].mean(2).reshape(72 * 6, 64, -1) for a in tr)
    return x, gallery


@torch.inference_mode()
def encode(model, long_, short, device):
    P, F = [], []
    for i in range(0, len(long_), 72):
        f1, logits, _, _ = model(torch.from_numpy(long_[i:i + 72]).to(device), torch.from_numpy(short[i:i + 72]).to(device))
        P.append(logits.float().softmax(-1).cpu().numpy()); F.append(f1.float().cpu().numpy())
    return np.concatenate(P).astype(np.float64), np.concatenate(F).astype(np.float64)


def readout(P, y):
    rank = (P > P[np.arange(len(y)), y][:, None]).sum(1)
    return {"top1": float((rank < 1).mean()), "top5": float((rank < 5).mean()), "top10": float((rank < 10).mean()),
            "mrr": float((1.0 / (rank + 1)).mean()), "nll": float(-np.log(np.clip(P[np.arange(len(y)), y], 1e-12, 1)).mean())}


def geometry(work):
    p = work / "c_gallery_geometry.npz"
    if p.exists():
        return dict(np.load(p))
    g = np.load(work / "geometry.npz", allow_pickle=True)
    names = [f"{n.rsplit('_', 1)[0]}_{j:02d}" for n in g["names"][::2] for j in range(6)]
    gal = np.stack([load_obj(n) for n in names])
    tgt = np.stack([load_obj(n) for n in g["names"]])
    ch, f = chamfer_matrix(tgt, gal)
    out = {"gal_ch": ch, "gal_f": f, "gal_emd": emd_matrix(tgt, gal), "gal_names": np.array(names)}
    np.savez(p, **out)
    return out


def subject_ci(x, n_boot, rng):
    idx = rng.integers(0, len(x), (n_boot, len(x)))
    d = x[idx].mean(1)
    return float(x.mean()), [float(np.quantile(d, 0.025)), float(np.quantile(d, 0.975))]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="/home/hubin/926/results/C")
    ap.add_argument("--seeds", default="0,1,2,3,4")
    ap.add_argument("--ridge", type=float, default=10.0)
    ap.add_argument("--bootstrap", type=int, default=10000)
    ap.add_argument("--seed", type=int, default=20260722)
    a = ap.parse_args()
    out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
    work = Path("/home/hubin/926/cache")
    g = np.load(work / "geometry.npz", allow_pickle=True)
    gg = geometry(work)
    y = g["true"]
    clip = torch.load(REFS / "data/EEG-3D/clip_feature.pth", map_location="cpu", weights_only=False)
    Z = np.stack([clip[str(n).split("_", 1)[1]]["point"].float().numpy() for n in gg["gal_names"]]).astype(np.float64)
    Zn = Z / np.linalg.norm(Z, axis=1, keepdims=True)
    from eeg_data_process.extract_eeg_feature import VideoImageEEGClassifyColor3
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    seeds = [int(s) for s in a.seeds.split(",")]

    rows, seed_rows, pooled_P = [], [], {s: [] for s in seeds}
    for seed in seeds:
        for si, subj in enumerate(SUBJECTS):
            ck = torch.load(ENC[seed] / subj / "best_validation.pt", map_location="cpu", weights_only=False)
            model = VideoImageEEGClassifyColor3(num_channels=64, sequence_length=600, sequence_length2=250,
                                                num_latents=1024, cls_num=72)
            model.load_state_dict(ck["model"]); model.eval().to(device)
            x, gal = inputs(subj)
            _, Fg = encode(model, *gal, device)
            Fgn = Fg / np.linalg.norm(Fg, axis=1, keepdims=True)
            mu, sd = Fg.mean(0), Fg.std(0) + 1e-6
            Xs = (Fg - mu) / sd
            W = np.linalg.solve(Xs.T @ Xs + a.ridge * np.eye(Xs.shape[1]), Xs.T @ (Z - Z.mean(0)))
            for cond in CONDS:
                P, F = encode(model, *x[cond], device)
                if cond == "paired":
                    seed_rows.append({"seed": seed, "subject": subj, "pool": "single", **readout(P, y)})
                    pooled_P[seed].append(P)
                zhat = ((F - mu) / sd) @ W + Z.mean(0)
                pick = {"classify_medoid": P.argmax(1),
                        "latent_regression": (zhat / np.linalg.norm(zhat, axis=1, keepdims=True) @ Zn.T).argmax(1),
                        "retrieval": ((F / np.linalg.norm(F, axis=1, keepdims=True)) @ Fgn.T).argmax(1)}
                for dec, k in pick.items():
                    src = ("target_ch", "target_f", "target_emd") if dec == "classify_medoid" else ("gal_ch", "gal_f", "gal_emd")
                    M = g if dec == "classify_medoid" else gg
                    cat = k if dec == "classify_medoid" else k // 6
                    for i in range(144):
                        rows.append({"seed": seed, "subject": subj, "decoder": dec, "condition": cond,
                                     "object": str(g["names"][i]), "category": int(y[i]),
                                     "decoded_category": int(cat[i]), "category_hit": int(cat[i] == y[i]),
                                     "chamfer_l2": float(M[src[0]][i, k[i]]), "f01": float(M[src[1]][i, k[i]]),
                                     "emd_256": float(M[src[2]][i, k[i]])})
            print(f"C seed={seed} {subj} top5={seed_rows[-1]['top5']:.3f}", flush=True)
            del model
        seed_rows.append({"seed": seed, "subject": "pooled12", "pool": "pooled", **readout(np.mean(pooled_P[seed], 0), y)})

    with open(out / "seeds.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(seed_rows[0])); w.writeheader(); w.writerows(seed_rows)
    with open(out / "per_object.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)

    rng = np.random.default_rng(a.seed)
    import pandas as pd
    df = pd.DataFrame(rows)
    fingerprint = {}
    for dec in DECODERS:
        fingerprint[dec] = {}
        base = df[(df.decoder == dec) & (df.condition == "paired")].groupby("subject")[["chamfer_l2", "f01", "emd_256", "category_hit"]].mean()
        for cond in CONDS:
            cur = df[(df.decoder == dec) & (df.condition == cond)].groupby("subject")[["chamfer_l2", "f01", "emd_256", "category_hit"]].mean()
            e = {"mean": {k: float(cur[k].mean()) for k in cur}}
            if cond != "paired":
                for k in ("chamfer_l2", "f01", "emd_256"):
                    d = (cur[k] - base[k]).values
                    m, ci = subject_ci(d, a.bootstrap, rng)
                    worse = int((d > 0).sum()) if k != "f01" else int((d < 0).sum())
                    e[f"delta_{k}"] = {"delta": m, "ci95_subject": ci, "subjects_worse": worse}
            fingerprint[dec][cond] = e
    sr = pd.DataFrame(seed_rows)
    single = sr[sr["pool"] == "single"].groupby("seed")[["top1", "top5", "top10", "mrr", "nll"]].mean()
    pooled = sr[sr["pool"] == "pooled"].set_index("seed")[["top1", "top5", "top10", "mrr", "nll"]]
    readouts = {"single_subject_mean_per_seed": single.to_dict("index"),
                "single_subject_mean_std_over_seeds": {k: [float(single[k].mean()), float(single[k].std(ddof=1))] for k in single},
                "pooled12_per_seed": pooled.to_dict("index"),
                "pooled12_mean_std_over_seeds": {k: [float(pooled[k].mean()), float(pooled[k].std(ddof=1))] for k in pooled},
                "chance": {"top1": 1 / 72, "top5": 5 / 72, "top10": 10 / 72, "nll": float(np.log(72))}}
    res = {"experiment": "926_C_decoders", "seeds": seeds, "decoders": DECODERS, "conditions": CONDS,
           "fingerprint_seed_mean": fingerprint, "readout": readouts,
           "note": "subject = unit; per-subject values are means over the 5 encoder seeds and 144 objects; "
                   "delta = condition - paired (positive Chamfer/EMD = worse); CI resamples subjects",
           "ridge": a.ridge, "bootstrap": a.bootstrap}
    json.dump(res, open(out / "results.json", "w"), indent=1, default=float)
    print("C done", flush=True)


if __name__ == "__main__":
    main()