Download mind3d_trellis2/code/mapper/pca_tools.py from jamie33/926: direct link, hf CLI and curl.
- Browser
- Download file 2.37 kB
-
https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/pca_tools.py
- Command line
-
hf download hf://datasets/jamie33/926/mind3d_trellis2/code/mapper/pca_tools.py
-
curl -L -o pca_tools.py https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/pca_tools.py
2.37 kB
| """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 | |