File size: 6,695 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 | """Classify-then-generate: fMRI -> category (kernel ridge classifier), then category-mean tokens (+ ridge residual)."""
import os
import json
import argparse
import numpy as np
import torch
import torch.nn.functional as F
from pca_tools import FEAT_DIR, TOKEN_DIM, load_tokens, split_ids, get_pca, project, reconstruct
from ridge_pca import make_features
from train_mapper import token_metrics
def kernels(train_feats, test_feats, kind, fit_t, val_t):
x_tr = make_features(torch.from_numpy(np.ascontiguousarray(train_feats)).cuda(), kind)
x_te = make_features(torch.from_numpy(np.ascontiguousarray(test_feats)).cuda(), kind)
mu, sd = x_tr[fit_t].mean(0), x_tr[fit_t].std(0) + 1e-6
x_tr, x_te = (x_tr - mu) / sd, (x_te - mu) / sd
x_fit = x_tr[fit_t]
out = x_fit @ x_fit.T, x_tr[val_t] @ x_fit.T, x_te @ x_fit.T
del x_tr, x_te, x_fit
torch.cuda.empty_cache()
return out
def solve(k_fit, y, lam):
eye = torch.eye(len(k_fit), device="cuda")
return torch.linalg.solve((k_fit + lam * k_fit.diag().mean() * eye).double(), y.double()).float()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--sub_id", default="0001")
parser.add_argument("--out_dir", default="/home/hubin/trellis_work/outputs/clsfirst")
parser.add_argument("--features", default="cls,mean,concat")
parser.add_argument("--lambdas", default="0.01,0.1,1,10,100,1000")
parser.add_argument("--k", type=int, default=64)
parser.add_argument("--ridge_tokens", default="/home/hubin/trellis_work/outputs/ridge/ridge_k64_rescaled/tokens.npy",
help="ridge-predicted test tokens; kNN-5 over their PCA coeffs gives the second classifier")
args = parser.parse_args()
os.makedirs(args.out_dir, exist_ok=True)
lambdas = [float(l) for l in args.lambdas.split(",")]
train_ids, test_ids, fit_idx, val_idx = split_ids()
train_feats = np.load(f"{FEAT_DIR}/sub{args.sub_id}_train_feats.npy", mmap_mode="r")
test_feats = np.load(f"{FEAT_DIR}/sub{args.sub_id}_test_feats.npy", mmap_mode="r")
train_tok = torch.from_numpy(load_tokens(train_ids)).cuda()
test_tok = torch.from_numpy(load_tokens(test_ids)).cuda().float()
pca = get_pca()
fit_t, val_t = torch.from_numpy(fit_idx).cuda(), torch.from_numpy(val_idx).cuda()
val_tok = train_tok[val_t].float()
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_train, y_test = lab(train_ids), lab(test_ids)
onehot = F.one_hot(y_train[fit_t], len(cats)).float()
coef = project(train_tok, pca, args.k)
cat_tok = torch.stack([F.layer_norm(train_tok[fit_t][y_train[fit_t] == c].float().mean(0), (TOKEN_DIM,))
for c in range(len(cats))])
cat_coef = torch.stack([coef[fit_t][y_train[fit_t] == c].mean(0) for c in range(len(cats))])
resid = coef[fit_t] - cat_coef[y_train[fit_t]]
log, best_cls, best_res = [], None, None
for kind in args.features.split(","):
k_fit, k_val, k_te = kernels(train_feats, test_feats, kind, fit_t, val_t)
for lam in lambdas:
a = solve(k_fit, onehot, lam)
s_val, s_te = k_val @ a, k_te @ a
acc = (s_val.argmax(1) == y_train[val_t]).float().mean().item()
top3 = (s_val.topk(3, 1).indices == y_train[val_t, None]).any(1).float().mean().item()
log.append({"task": "cls", "features": kind, "lambda": lam, "val_acc": acc, "val_top3": top3})
if best_cls is None or acc > best_cls["val_acc"]:
best_cls = {**log[-1], "test_scores": s_te}
a = solve(k_fit, resid, lam)
r_fit, r_val, r_te = k_fit @ a, k_val @ a, k_te @ a
mse = token_metrics(reconstruct(cat_coef[y_train[val_t]] + r_val, pca), val_tok)["mse"]
log.append({"task": "resid", "features": kind, "lambda": lam, "val_mse_oracle_cat": mse})
if best_res is None or mse < best_res["val_mse_oracle_cat"]:
best_res = {**log[-1], "test_resid": r_te,
"scale": resid.std(0) / (r_fit.std(0) + 1e-8)}
print(json.dumps(log[-2]), json.dumps(log[-1]), flush=True)
del k_fit, k_val, k_te
torch.cuda.empty_cache()
pred = best_cls["test_scores"].argmax(1)
test_acc = (pred == y_test).float().mean().item()
test_top3 = (best_cls["test_scores"].topk(3, 1).indices == y_test[:, None]).any(1).float().mean().item()
confusion = torch.zeros(len(cats), len(cats), dtype=torch.long)
for t, p in zip(y_test.tolist(), pred.tolist()):
confusion[t, p] += 1
per_cat = {c: confusion[i, i].item() / max(confusion[i].sum().item(), 1) for i, c in enumerate(cats)}
ridge_coef = project(torch.from_numpy(np.load(args.ridge_tokens)).cuda(), pca, args.k)
sim = F.normalize(ridge_coef, dim=1) @ F.normalize(coef[fit_t], dim=1).T
pred_knn = F.one_hot(y_train[fit_t][sim.topk(5, 1).indices], len(cats)).sum(1).argmax(1)
knn_acc = (pred_knn == y_test).float().mean().item()
r_te, scale = best_res["test_resid"], best_res["scale"]
variants = {f"oraclecls_resid_k{args.k}": reconstruct(cat_coef[y_test] + r_te, pca)}
for tag, p in [("krr", pred), ("knn", pred_knn)]:
variants[f"clsfirst_{tag}_mean"] = cat_tok[p]
variants[f"clsfirst_{tag}_resid_k{args.k}"] = reconstruct(cat_coef[p] + r_te, pca)
variants[f"clsfirst_{tag}_resid_k{args.k}_rescaled"] = reconstruct(cat_coef[p] + r_te * scale, pca)
summary = {"categories": cats, "test_acc": test_acc, "test_top3": test_top3, "per_category_acc": per_cat,
"knn5_on_ridge_test_acc": knn_acc, "pred_knn": [cats[p] for p in pred_knn.tolist()],
"confusion": confusion.tolist(), "pred": [cats[p] for p in pred.tolist()],
"best_cls": {k: v for k, v in best_cls.items() if k != "test_scores"},
"best_resid": {k: v for k, v in best_res.items() if k not in ("test_resid", "scale")},
"token_metrics": {}, "log": log}
for name, tok in variants.items():
os.makedirs(f"{args.out_dir}/{name}", exist_ok=True)
np.save(f"{args.out_dir}/{name}/tokens.npy", tok.half().cpu().numpy())
summary["token_metrics"][name] = token_metrics(tok.float(), test_tok)
print(json.dumps({k: summary[k] for k in ("test_acc", "knn5_on_ridge_test_acc", "test_top3", "best_cls",
"best_resid", "token_metrics")}, indent=1), flush=True)
with open(f"{args.out_dir}/summary.json", "w") as f:
json.dump(summary, f, indent=1)
if __name__ == "__main__":
main()
|