File size: 2,368 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 | """PCA basis of TRELLIS.2 conditioning tokens, fitted on the mapper's fit split only."""
import os
import numpy as np
import torch
import torch.nn.functional as F
FEAT_DIR = "/home/hubin/data/fMRI-Shape/mapper_feats"
TOKEN_DIR = "/home/hubin/data/fMRI-Shape/trellis2_cond/tokens"
TOKEN_FRAMES = [0, 24, 48, 72, 96, 120, 144, 168]
N_TOKENS, TOKEN_DIM = 1029, 1024
PCA_PATH = "/home/hubin/data/fMRI-Shape/mapper_feats/pca_f{frame}_seed{seed}.pt"
def load_tokens(ids, frame=24):
k = TOKEN_FRAMES.index(frame)
return np.stack([np.load(f"{TOKEN_DIR}/{i}.npy", mmap_mode="r")[k] for i in ids])
def split_ids(n_val=100, seed=0):
"""Same fit/val split as train_mapper.py."""
train_ids = open(f"{FEAT_DIR}/train_ids.txt").read().split()
test_ids = open(f"{FEAT_DIR}/test_ids.txt").read().split()
perm = np.random.default_rng(seed).permutation(len(train_ids))
return train_ids, test_ids, np.sort(perm[n_val:]), np.sort(perm[:n_val])
def fit_pca(tokens, max_k=1024):
"""tokens: [N, 1029, 1024] (cuda). Returns mean [D], components [K, D] (orthonormal rows), eigenvalues [K]."""
x = tokens.float().flatten(1)
mean = x.mean(0)
x = x - mean
gram = x @ x.T
evals, evecs = torch.linalg.eigh(gram.double())
order = evals.argsort(descending=True)[:max_k]
evals, evecs = evals[order].clamp_min(1e-8), evecs[:, order]
comps = (evecs.T.float() @ x) / evals.sqrt().float()[:, None]
return mean, comps, evals.float()
def get_pca(frame=24, seed=0, n_val=100):
path = PCA_PATH.format(frame=frame, seed=seed)
if os.path.exists(path):
return torch.load(path, map_location="cuda")
train_ids, _, fit_idx, _ = split_ids(n_val, seed)
tokens = torch.from_numpy(load_tokens([train_ids[i] for i in fit_idx], frame)).cuda()
mean, comps, evals = fit_pca(tokens)
pca = {"mean": mean, "comps": comps.half(), "evals": evals,
"total_var": (tokens.float().flatten(1) - mean).pow(2).sum()}
torch.save(pca, path)
return pca
def project(tokens, pca, k):
x = tokens.float().flatten(1) - pca["mean"]
return x @ pca["comps"][:k].float().T
def reconstruct(coeffs, pca, normalize=True):
k = coeffs.shape[1]
x = pca["mean"] + coeffs.float() @ pca["comps"][:k].float()
x = x.view(-1, N_TOKENS, TOKEN_DIM)
return F.layer_norm(x, (TOKEN_DIM,)) if normalize else x
|