File size: 14,391 Bytes
7c61ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""Unfrozen fMRI side: MinD-3D fMRI ViT-L (init from sub-01 weights) with per-subject patch embeddings, the last
n blocks trainable, + MapperV2 head -> k PCA coefficients. Trains on one or several subjects (same object split)."""
import os
import copy
import json
import math
import argparse

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from timm.models.vision_transformer import Block

from pca_tools import FEAT_DIR, load_tokens, split_ids, get_pca, fit_pca, project, reconstruct
from train_mapper import token_metrics
from train_mapper_v2 import MapperV2, view_avg_cls

ROOT = "/home/hubin/data/fMRI-Shape"
CKPT = "/home/hubin/MinD-3D/ckpt/mind3d_sub01.pt"
TEST_START = 2
N_FRAMES = 6


class Encoder(nn.Module):
    """fMRI_Encoder.forward_encoder_wo_pred of MinD-3D, with one patch embedding per subject."""

    def __init__(self, subjects, n_train_blocks, train_patch, grad_ckpt=True, dim=1024, depth=24, heads=16):
        super().__init__()
        patch = nn.Conv2d(1, dim, 16, 16)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, 257, dim), requires_grad=False)
        self.blocks = nn.ModuleList([Block(dim, heads, mlp_ratio=4.0, qkv_bias=True, proj_drop=0.01, attn_drop=0.01,
                                           drop_path=0.01) for _ in range(depth)])
        self.norm = nn.LayerNorm(dim)
        state = torch.load(CKPT, map_location="cpu", mmap=True, weights_only=False)
        state = state.get("model", state)
        enc = {k[len("fmri_encoder."):]: v for k, v in state.items() if k.startswith("fmri_encoder.")}
        patch.load_state_dict({"weight": enc["patch_embed.proj.weight"], "bias": enc["patch_embed.proj.bias"]})
        missing, unexpected = self.load_state_dict({k: v for k, v in enc.items() if not k.startswith(("patch_embed", "pred"))},
                                                   strict=False)
        assert not missing and not unexpected, (missing, unexpected)
        self.patch = nn.ModuleDict({s: copy.deepcopy(patch) for s in subjects})
        self.n_frozen = depth - n_train_blocks
        self.train_patch = train_patch
        self.grad_ckpt = grad_ckpt
        for p in self.parameters():
            p.requires_grad = False
        for blk in self.blocks[self.n_frozen:]:
            for p in blk.parameters():
                p.requires_grad = True
        if n_train_blocks:
            for p in self.norm.parameters():
                p.requires_grad = True
        if train_patch:
            for p in self.patch.parameters():
                p.requires_grad = True

    def forward(self, x, subj):  # x [N, 256, 256] (frames flattened into batch); subj [N] subject keys
        tok = torch.empty(len(x), 256, 1024, device=x.device, dtype=x.dtype)
        for s in set(subj):
            m = torch.tensor([t == s for t in subj], device=x.device)
            with torch.set_grad_enabled(self.train_patch and torch.is_grad_enabled()):
                tok[m] = self.patch[s](x[m][:, None]).flatten(2).transpose(1, 2).to(x.dtype)
        tok = tok + self.pos_embed[:, 1:]
        tok = torch.cat([(self.cls_token + self.pos_embed[:, :1]).expand(len(x), -1, -1).to(tok.dtype), tok], 1)
        need_grad = self.train_patch and torch.is_grad_enabled()
        for i, blk in enumerate(self.blocks):
            if i < self.n_frozen and not need_grad:
                with torch.no_grad():
                    tok = blk(tok)
            elif self.grad_ckpt and torch.is_grad_enabled():
                tok = checkpoint(blk, tok, use_reentrant=False)
            else:
                tok = blk(tok)
        return self.norm(tok)


class Model(nn.Module):
    def __init__(self, args, n_cls):
        super().__init__()
        self.enc = Encoder(args.subjects, args.n_train_blocks, not args.freeze_patch)
        self.head = MapperV2(args.k, n_cls, d=args.d, depth=args.depth)

    def forward(self, x, subj):  # x [B, F, 256, 256]
        b, f = x.shape[:2]
        with torch.autocast("cuda", dtype=torch.bfloat16):
            feats = self.enc(x.flatten(0, 1), [s for s in subj for _ in range(f)])
        return self.head(feats.float().view(b, f, 257, 1024))


def load_fmri(sub, ids):
    return torch.from_numpy(np.stack([np.load(f"{ROOT}/sub-{sub}/npy_data/{o}.npy") for o in ids])).half().cuda()


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--out_dir", required=True)
    p.add_argument("--subjects", nargs="+", default=["0001"])
    p.add_argument("--k", type=int, default=16)
    p.add_argument("--n_train_blocks", type=int, default=4)
    p.add_argument("--freeze_patch", action="store_true")
    p.add_argument("--w_nce", type=float, default=0.5)
    p.add_argument("--w_ce", type=float, default=0.0, help=">0 uses category labels")
    p.add_argument("--tau", type=float, default=0.05)
    p.add_argument("--noise", type=float, default=0.1)
    p.add_argument("--jitter", type=int, default=1, help="train window start in [2-j, 2+j]")
    p.add_argument("--steps", type=int, default=3000)
    p.add_argument("--eval_every", type=int, default=250)
    p.add_argument("--bs", type=int, default=32)
    p.add_argument("--lr", type=float, default=3e-4)
    p.add_argument("--enc_lr", type=float, default=3e-5)
    p.add_argument("--wd", type=float, default=0.05)
    p.add_argument("--d", type=int, default=512)
    p.add_argument("--depth", type=int, default=4)
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--eval_only", action="store_true", help="skip training, export from <out_dir>/best.pt")
    p.add_argument("--fold", type=int, default=-1, help=">=0: hold out this fold of the fit split, export its "
                   "out-of-fold predictions to <out_dir>/oof.npz instead of val/test tokens")
    p.add_argument("--n_folds", type=int, default=5)
    p.add_argument("--select", default="knn_mse", choices=["knn_mse", "mse"],
                   help="checkpoint score on val: kNN acc - coef MSE (uses train labels), or -coef MSE only")
    p.add_argument("--holdout_cats", default="", help="comma-separated synsets removed from fit/val and the PCA basis")
    args = p.parse_args()
    os.makedirs(args.out_dir, exist_ok=True)
    torch.manual_seed(args.seed)

    train_ids, test_ids, fit_idx, val_idx = split_ids()
    if args.fold >= 0:
        held = np.sort(np.array_split(np.random.default_rng(0).permutation(fit_idx), args.n_folds)[args.fold])
        fit_idx = np.setdiff1d(fit_idx, held)
    held_cats = [c for c in args.holdout_cats.split(",") if c]
    if held_cats:
        seen = lambda idx: np.array([i for i in idx if train_ids[i].split("/")[0] not in held_cats])
        fit_idx, val_idx = seen(fit_idx), seen(val_idx)
        print(f"holdout {held_cats}: fit {len(fit_idx)}, val {len(val_idx)}", flush=True)
    fit_t, val_t = torch.from_numpy(fit_idx).cuda(), torch.from_numpy(val_idx).cuda()
    train_tok = torch.from_numpy(load_tokens(train_ids)).cuda()
    if held_cats:
        mean, comps, evals = fit_pca(train_tok[fit_t], max_k=64)
        pca = {"mean": mean, "comps": comps.half(), "evals": evals}
        torch.save(pca, f"{args.out_dir}/pca.pt")
    else:
        pca = get_pca()
    test_tok = torch.from_numpy(load_tokens(test_ids)).cuda().float()
    coef = project(train_tok, pca, args.k)
    coef_test = project(test_tok, pca, args.k)
    cls_t = F.normalize(view_avg_cls(train_ids).cuda(), dim=1)
    cats = sorted({i.split("/")[0] for i in train_ids})
    lab = lambda ids: torch.tensor([cats.index(i.split("/")[0]) for i in ids], device="cuda")
    y, y_test = lab(train_ids), lab(test_ids)
    total_var = coef[fit_t].var(0).sum()

    data, scale_in = {}, {}
    for s in args.subjects:
        data[s] = (load_fmri(s, train_ids), load_fmri(s, test_ids))
        scale_in[s] = data[s][0][fit_t[:200]].float().std().item()
    ref = scale_in.get("0001", scale_in[args.subjects[0]])
    print("input std per subject", scale_in, flush=True)

    model = Model(args, len(cats)).cuda()
    enc_params = [q for q in model.enc.parameters() if q.requires_grad]
    print("trainable encoder params %.1fM, head %.1fM" % (sum(q.numel() for q in enc_params) / 1e6,
                                                         sum(q.numel() for q in model.head.parameters()) / 1e6), flush=True)
    opt = torch.optim.AdamW([{"params": model.head.parameters(), "lr": args.lr},
                             {"params": enc_params, "lr": args.enc_lr}], weight_decay=args.wd)
    sched = torch.optim.lr_scheduler.LambdaLR(
        opt, lambda st: min(1, st / 200) * 0.5 * (1 + math.cos(math.pi * min(st, args.steps) / args.steps)))

    def frames(x, s, start):
        return x[:, start:start + N_FRAMES].float() * (ref / scale_in[s])

    @torch.no_grad()
    def predict(s, x):
        model.eval()
        outs = [model(frames(x[i:i + 16], s, TEST_START), [s] * len(x[i:i + 16])) for i in range(0, len(x), 16)]
        model.train()
        return [torch.cat(o) for o in zip(*outs)]

    def evaluate(s, x, idx_y, target):
        c, logits, _ = predict(s, x)
        sim = F.normalize(c, dim=1) @ F.normalize(coef[fit_t], dim=1).T
        knn = F.one_hot(y[fit_t][sim.topk(5, 1).indices], len(cats)).sum(1).argmax(1)
        return {"knn_acc": (knn == idx_y).float().mean().item(), "cls_acc": (logits.argmax(1) == idx_y).float().mean().item(),
                "coef_mse": ((c - target) ** 2).sum(1).mean().item() / total_var.item()}, c, logits

    best, log = None, []
    for step in range(1, 0 if args.eval_only else args.steps + 1):
        subj = [args.subjects[i] for i in torch.randint(len(args.subjects), (args.bs,)).tolist()]
        b = fit_t[torch.randint(len(fit_t), (args.bs,), device="cuda")]
        start = TEST_START + int(torch.randint(-args.jitter, args.jitter + 1, (1,)))
        x = torch.stack([frames(data[s][0][i:i + 1], s, start)[0] for s, i in zip(subj, b.tolist())])
        x = x + args.noise * ref * torch.randn_like(x)
        c, logits, z = model(x, subj)
        l_coef = ((c - coef[b]) ** 2).sum(1).mean() / total_var
        l_nce = F.cross_entropy(F.normalize(z, dim=1) @ cls_t[fit_t].T / args.tau, torch.searchsorted(fit_t, b))
        l_ce = F.cross_entropy(logits, y[b], label_smoothing=0.1)
        loss = l_coef + args.w_nce * l_nce + args.w_ce * l_ce
        opt.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_([q for g in opt.param_groups for q in g["params"]], 1.0)
        opt.step()
        sched.step()
        if step % args.eval_every == 0:
            val = {s: evaluate(s, data[s][0][val_t], y[val_t], coef[val_t])[0] for s in args.subjects}
            score = float(np.mean([(v["knn_acc"] if args.select == "knn_mse" else 0) - v["coef_mse"]
                                   for v in val.values()]))
            log.append({"step": step, "loss": loss.item(), "l_coef": l_coef.item(), "l_nce": l_nce.item(),
                        "l_ce": l_ce.item(), "val": val, "score": score})
            print(json.dumps(log[-1]), flush=True)
            if best is None or score > best["score"]:
                best = log[-1]
                torch.save({k: v for k, v in model.state_dict().items()
                            if not k.startswith("enc.") or any(k.startswith(f"enc.{n}") for n in
                            ["patch", "norm"] + [f"blocks.{i}." for i in range(model.enc.n_frozen, 24)])},
                           f"{args.out_dir}/best.pt")

    model.load_state_dict(torch.load(f"{args.out_dir}/best.pt"), strict=False)
    if args.fold >= 0:
        s = args.subjects[0]
        x_tr = data[s][0]
        held_t = torch.from_numpy(held).cuda()
        model.eval()
        with torch.no_grad():
            oof = [torch.cat([model(frames(x_tr[held_t[i:i + 16]], s, start), [s] * len(held_t[i:i + 16]))[0]
                              for i in range(0, len(held), 16)]) for start in range(TEST_START - args.jitter,
                                                                                    TEST_START + args.jitter + 1)]
        c_fit = predict(s, x_tr[fit_t])[0]
        scale = coef[fit_t].std(0) / (c_fit.std(0) + 1e-8)
        oof = torch.stack(oof)
        mse = ((oof[args.jitter] - coef[held_t]) ** 2).sum(1).mean().item() / total_var.item()
        np.savez(f"{args.out_dir}/oof.npz", idx=held, coef=oof.cpu().numpy(), scale=scale.cpu().numpy())
        json.dump({"args": vars(args), "best": best, "log": log, "oof_coef_mse": mse},
                  open(f"{args.out_dir}/result.json", "w"), indent=1)
        print("OOF", s, json.dumps({"n": len(held), "coef_mse": mse}), flush=True)
        return
    summary = {"args": vars(args), "best": best, "log": log, "subjects": {}}
    for s in args.subjects:
        x_tr, x_te = data[s]
        m_val, c_val, _ = evaluate(s, x_tr[val_t], y[val_t], coef[val_t])
        m_test, c_te, _ = evaluate(s, x_te, y_test, coef_test)
        c_fit = predict(s, x_tr[fit_t])[0]
        scale = coef[fit_t].std(0) / (c_fit.std(0) + 1e-8)
        model.eval()
        with torch.no_grad():
            win = lambda x: np.stack([torch.cat([model(frames(x[i:i + 16], s, st), [s] * len(x[i:i + 16]))[0]
                                                 for i in range(0, len(x), 16)]).cpu().numpy()
                                      for st in range(TEST_START - args.jitter, TEST_START + args.jitter + 1)])
            np.savez(f"{args.out_dir}/sub{s}_coefs.npz", val=win(x_tr[val_t]), test=win(x_te), fit=c_fit.cpu().numpy(),
                     scale=scale.cpu().numpy())
        res = {"val": m_val, "test": m_test, "token_metrics": {}}
        for split, cc, gt in [("val", c_val, train_tok[val_t].float()), ("test", c_te, test_tok)]:
            for name, v in [("coef", cc), ("coef_rescaled", cc * scale)]:
                tok = reconstruct(v, pca)
                d = f"{args.out_dir}/sub{s}/{split}/{name}"
                os.makedirs(d, exist_ok=True)
                np.save(f"{d}/tokens.npy", tok.half().cpu().numpy())
                res["token_metrics"][f"{split}/{name}"] = token_metrics(tok.float(), gt)
        summary["subjects"][s] = res
        print("SUB", s, json.dumps({"val": m_val, "test": m_test}), flush=True)
    json.dump(summary, open(f"{args.out_dir}/result.json", "w"), indent=1)


if __name__ == "__main__":
    main()