File size: 12,095 Bytes
d04bc2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""926/B — is the category-mean gain just a better input?

Frozen released 200k point-diffusion generator (encoder + PVN), 200 denoising
steps, batch 48, sampling seed fixed per batch start, so every condition of an
object shares its initial noise. Targets: held-out objects 08-09 (144).

Conditions (wrong category = (c + 1) mod 72 everywhere):
  paired_4avg            mean of the 4 test trials of the object (the standard `real` input)
  paired_single          first test trial of the object
  same_category_swap     4-trial mean of the other held-out object of the same category
  samecat_rand4          mean of 4 random train trials of the target category
  wrongcat_rand4         mean of 4 random train trials of the wrong category
  target_trialmatched4   mean of 4 train trials of the target category, 4 different train objects
  wrong_trialmatched4    same for the wrong category
  target_within          mean of all 16 train trials of the target category, same subject
  wrong_within           same for the wrong category
  target_cross           target-category mean pooled over all 12 subjects
  wrong_cross            same for the wrong category
  target_loso            target-category mean over the 11 other subjects
  wrong_loso             same for the wrong category
  paired_match_varnorm   paired_4avg with per-channel mean/std and Frobenius norm set to target_within
  paired_match_spectrum  paired_4avg with per-channel amplitude spectrum of target_within (phase kept)
  paired_match_cov       paired_4avg whitened and re-coloured to the channel covariance of target_within
  target_latent          encoder outputs replaced by the mean encoder output over the 16 train trials
                         of the target category (same subject)
  wrong_latent           same for the wrong category
"""
import argparse
import json
import os
import sys
import tempfile
import time
from pathlib import Path

import numpy as np
import torch

REFS = Path(os.environ.get("BB3D_REFS", "/home/hubin/workspace/July/brain3d_refs"))
sys.path.insert(0, str(REFS / "third_party" / "neuro-3D"))
sys.path.insert(0, str(REFS / "scripts"))
import evaluate_shape_diffusion_controls as ev  # noqa: E402

ev.ROOT, ev.REPO, ev.DATA = REFS, REFS / "third_party" / "neuro-3D", REFS / "data" / "EEG-3D"
DATA = ev.DATA
SUBJECTS = [f"sub{i:02d}" for i in range(1, 13)]
CONDITIONS = ["paired_4avg", "paired_single", "same_category_swap", "samecat_rand4", "wrongcat_rand4",
              "target_trialmatched4", "wrong_trialmatched4", "target_within", "wrong_within",
              "target_cross", "wrong_cross", "target_loso", "wrong_loso",
              "paired_match_varnorm", "paired_match_spectrum", "paired_match_cov",
              "target_latent", "wrong_latent"]


def raw(subject, split):
    d = DATA / "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 category_means(cache):
    """Per-subject train category means (72, 64, T) for both EEG streams, cached."""
    cache.mkdir(parents=True, exist_ok=True)
    out = {}
    for s in SUBJECTS:
        p = cache / f"catmean_{s}.npz"
        if not p.exists():
            a, b = raw(s, "train")
            np.savez(p, dyn=a.mean((1, 2)), sta=b.mean((1, 2)))
        z = np.load(p)
        out[s] = (z["dyn"], z["sta"])
    return out


def match_varnorm(x, m):
    y = (x - x.mean(-1, keepdims=True)) / (x.std(-1, keepdims=True) + 1e-8) * m.std(-1, keepdims=True) \
        + m.mean(-1, keepdims=True)
    return y * (np.linalg.norm(m) / (np.linalg.norm(y) + 1e-8))


def match_spectrum(x, m):
    X, M = np.fft.rfft(x, axis=-1), np.fft.rfft(m, axis=-1)
    return np.fft.irfft(np.abs(M) * np.exp(1j * np.angle(X)), n=x.shape[-1], axis=-1).astype(np.float32)


def _sqrtm(c, inv=False):
    w, v = np.linalg.eigh(c)
    w = np.clip(w, 1e-8 * w.max(), None)
    return (v * (w ** (-0.5 if inv else 0.5))) @ v.T


def match_cov(x, m):
    xc, mc = x - x.mean(-1, keepdims=True), m - m.mean(-1, keepdims=True)
    cx, cm = xc @ xc.T / x.shape[-1], mc @ mc.T / m.shape[-1]
    eps = 1e-6 * np.trace(cx) / len(cx)
    return (_sqrtm(cm + eps * np.eye(len(cm))) @ _sqrtm(cx + eps * np.eye(len(cx)), inv=True) @ xc
            + m.mean(-1, keepdims=True)).astype(np.float32)


class Inputs:
    def __init__(self, subject, means, seed):
        self.s = subject
        self.tr = raw(subject, "train")          # (72, 8, 2, 64, T)
        self.te = raw(subject, "test")           # (72, 2, 4, 64, T)
        self.own = means[subject]
        self.cross = tuple(np.mean([means[s][k] for s in SUBJECTS], 0) for k in (0, 1))
        self.loso = tuple(np.mean([means[s][k] for s in SUBJECTS if s != subject], 0) for k in (0, 1))
        self.seed = seed

    def _rng(self, cond, c, o):
        return np.random.default_rng([self.seed, SUBJECTS.index(self.s), 1 + CONDITIONS.index(cond), c, o])

    def get(self, cond, c, o):
        """EEG (dynamic, static) for test object o (0/1) of category c."""
        w = (c + 1) % 72
        if cond in ("paired_4avg", "target_latent", "wrong_latent"):
            return tuple(a[c, o].mean(0) for a in self.te)
        if cond == "paired_single":
            return tuple(a[c, o, 0] for a in self.te)
        if cond == "same_category_swap":
            return tuple(a[c, 1 - o].mean(0) for a in self.te)
        if cond in ("samecat_rand4", "wrongcat_rand4"):
            k = c if cond == "samecat_rand4" else w
            pick = self._rng(cond, c, o).choice(16, 4, replace=False)
            return tuple(a[k].reshape(16, *a.shape[3:])[pick].mean(0) for a in self.tr)
        if cond in ("target_trialmatched4", "wrong_trialmatched4"):
            k = c if cond.startswith("target") else w
            r = self._rng(cond, c, o)
            objs, trials = r.choice(8, 4, replace=False), r.integers(0, 2, 4)
            return tuple(a[k, objs, trials].mean(0) for a in self.tr)
        for tag, src in (("within", self.own), ("cross", self.cross), ("loso", self.loso)):
            if cond in (f"target_{tag}", f"wrong_{tag}"):
                k = c if cond.startswith("target") else w
                return src[0][k], src[1][k]
        if cond.startswith("paired_match_"):
            fn = {"varnorm": match_varnorm, "spectrum": match_spectrum, "cov": match_cov}[cond.split("_")[-1]]
            x = tuple(a[c, o].mean(0) for a in self.te)
            return tuple(fn(xi, mi[c]).astype(np.float32) for xi, mi in zip(x, self.own))
        raise ValueError(cond)


def atomic_json(path, payload):
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=path.name, suffix=".tmp", delete=False) as h:
        json.dump(payload, h)
        tmp = Path(h.name)
    os.replace(tmp, path)


def build_model(subject, device):
    ckpt = DATA / "model" / "point_generate" / "shape" / subject / "resumable_200000steps" / "checkpoint-200000.pth"
    state = torch.load(ckpt, map_location="cpu", weights_only=False)
    model = ev.EEGTo3DDiffusionModel(
        beta_start=1e-5, beta_end=8e-3, beta_schedule="linear", sub=subject, generate_type="shape",
        retri_pretrain_model=f"{DATA}/model/retraival/{subject}/{ev.encoder_name(int(subject[3:]))}/",
        point_cloud_model_embed_dim=64, in_channels=1027, out_channels=3)
    model.load_state_dict(state["model"])
    return model.eval().to(device), str(ckpt), int(state.get("step", -1))


def latent_means(model, inp, device):
    """Mean encoder outputs over the 16 train trials of each category (same subject)."""
    outs = []
    with torch.inference_mode():
        for c in range(72):
            a = torch.from_numpy(inp.tr[0][c].reshape(16, 64, -1)).to(device)
            b = torch.from_numpy(inp.tr[1][c].reshape(16, 64, -1)).to(device)
            o = model.meta_eeg_video(a, b)
            outs.append([t.float().mean(0) for t in o])
    return [torch.stack([outs[c][i] for c in range(72)]) for i in range(len(outs[0]))]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--subject", required=True)
    ap.add_argument("--conditions", default=",".join(CONDITIONS))
    ap.add_argument("--steps", type=int, default=200)
    ap.add_argument("--batch-size", type=int, default=48)
    ap.add_argument("--seed", type=int, default=20260722)
    ap.add_argument("--cache", default="/home/hubin/926/cache")
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    device = torch.device("cuda")
    model, ckpt, step = build_model(a.subject, device)
    means = category_means(Path(a.cache))
    inp = Inputs(a.subject, means, a.seed)
    test = ev.AllDataFeatureTwoEEG(f"{DATA}/", sub_list=[a.subject], train=False, test_mean=True,
                                   aug_data=False, load_point_cloud=True)
    items = [test[i] for i in range(len(test))]
    names = [str(it["name"]) for it in items]
    cats = [int(it["cls_label"]) for it in items]
    obj = [0 if n.endswith("_08") else 1 for n in names]
    assert all(n.endswith(("_08", "_09")) for n in names)
    all_pf = test.color_point_features[:, 0].float().to(device)
    all_vf = test.color_video_features[:, 0].float().to(device)

    override = {"value": None}
    model.meta_eeg_video.register_forward_hook(
        lambda mod, args, out: tuple(override["value"]) if override["value"] is not None else out)
    lat = None

    out = Path(a.out)
    rows = json.loads(out.read_text())["rows"] if out.exists() else []
    done = {(r["condition"], r["name"]) for r in rows}
    for cond in a.conditions.split(","):
        if all((cond, n) for n in names) and all((cond, n) in done for n in names):
            continue
        t0 = time.time()
        if cond.endswith("_latent") and lat is None:
            lat = latent_means(model, inp, device)
        for start in range(0, len(items), a.batch_size):
            idx = list(range(start, min(start + a.batch_size, len(items))))
            if all((cond, names[i]) in done for i in idx):
                continue
            batch = ev.default_collate([items[i] for i in idx])
            eeg = [inp.get(cond, cats[i], obj[i]) for i in idx]
            dyn = torch.from_numpy(np.stack([e[0] for e in eeg])).float().to(device)
            sta = torch.from_numpy(np.stack([e[1] for e in eeg])).float().to(device)
            if cond.endswith("_latent"):
                lab = torch.tensor([c if cond.startswith("target") else (c + 1) % 72 for c in (cats[i] for i in idx)])
                override["value"] = [t[lab.to(device)] for t in lat]
            torch.manual_seed(a.seed + start)
            torch.cuda.manual_seed_all(a.seed + start)
            pc = batch["point_cloud"].float()[:, :, :3].to(device)
            feats = {"point_features": batch["color_point_fea"].float().to(device),
                     "video_features": batch["color_video_fea"].float().to(device),
                     "point_features_all": all_pf, "video_features_all": all_vf}
            with torch.inference_mode():
                pred, _ = model(pc, dyn, sta, mode="sample", shape_c=None, fea_list=feats,
                                labels=batch["cls_label"].to(device), return_sample_every_n_steps=-1,
                                num_inference_steps=a.steps, disable_tqdm=True)
            override["value"] = None
            p, t = pred.float().cpu().numpy(), pc.cpu().numpy()
            for j, i in enumerate(idx):
                rows.append({"subject": a.subject, "condition": cond, "name": names[i], "category": cats[i],
                             **ev.metrics(p[j], t[j])})
                done.add((cond, names[i]))
            atomic_json(out, {"subject": a.subject, "checkpoint": ckpt, "checkpoint_step": step,
                              "inference_steps": a.steps, "batch_size": a.batch_size, "seed": a.seed,
                              "rows": rows})
        print(f"B subject={a.subject} condition={cond} done in {time.time() - t0:.0f}s", flush=True)


if __name__ == "__main__":
    main()