Download mind3d_trellis2/code/mapper/valsel_preds.py from jamie33/926: direct link, hf CLI and curl.
- Browser
- Download file 7.23 kB
-
https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/valsel_preds.py
- Command line
-
hf download hf://datasets/jamie33/926/mind3d_trellis2/code/mapper/valsel_preds.py
-
curl -L -o valsel_preds.py https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/valsel_preds.py
7.23 kB
| """Validation-set predictions for every candidate token variant (fit on the 1200 fit objects, predict the 100 held-out | |
| val objects), so CFG / output variant / kNN k can be chosen without touching the test set.""" | |
| 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 cls_first import solve | |
| from train_mapper import token_metrics | |
| from train_mapper_v2 import MapperV2, FRAMES | |
| O = "/home/hubin/trellis_work/outputs" | |
| LAMBDAS = (0.01, 0.1, 1, 10, 100, 1000) | |
| def kernel_fit(sub_id, kind, fit_t, val_t): | |
| feats = np.load(f"{FEAT_DIR}/sub{sub_id}_train_feats.npy", mmap_mode="r") | |
| test = np.load(f"{FEAT_DIR}/sub{sub_id}_test_feats.npy", mmap_mode="r") | |
| x_tr = make_features(torch.from_numpy(np.ascontiguousarray(feats)).cuda(), kind) | |
| x_te = make_features(torch.from_numpy(np.ascontiguousarray(test)).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 main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--sub_id", default="0001") | |
| p.add_argument("--out_dir", default=f"{O}/valsel") | |
| p.add_argument("--ridge_kind", default="concat") | |
| p.add_argument("--ridge_lambda", type=float, default=0.01) | |
| p.add_argument("--resid_kind", default="mean") | |
| p.add_argument("--resid_lambda", type=float, default=10.0) | |
| p.add_argument("--v2_runs", nargs="*", default=[f"{O}/v2/nce_ce_k64"] + [f"{O}/v2/nce_ce_k64_s{s}" for s in range(1, 5)]) | |
| p.add_argument("--k", type=int, default=64) | |
| p.add_argument("--auto_lambda", action="store_true", help="pick both ridge lambdas by val MSE (new subjects)") | |
| args = p.parse_args() | |
| train_ids, test_ids, fit_idx, val_idx = split_ids() | |
| fit_ids, val_ids = [train_ids[i] for i in fit_idx], [train_ids[i] for i in val_idx] | |
| fit_t, val_t = torch.from_numpy(fit_idx).cuda(), torch.from_numpy(val_idx).cuda() | |
| pca = get_pca() | |
| train_tok = torch.from_numpy(load_tokens(train_ids)).cuda() | |
| val_tok = train_tok[val_t].float() | |
| coef = project(train_tok, pca, args.k) | |
| 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) | |
| y_fit, y_val = y[fit_t], y[val_t] | |
| cat_coef = torch.stack([coef[fit_t][y_fit == c].mean(0) for c in range(len(cats))]) | |
| report = {"sub_id": args.sub_id, "val_ids": val_ids, "token_metrics": {}, "val_acc": {}, "test_acc": {}} | |
| val_out, test_out = {}, {} | |
| def pick_lambda(k_fit, k_val, y_fit_, y_val_): | |
| err = {lam: ((k_val @ solve(k_fit, y_fit_, lam) - y_val_) ** 2).mean().item() for lam in LAMBDAS} | |
| return min(err, key=err.get) | |
| k_fit, k_val, k_te = kernel_fit(args.sub_id, args.ridge_kind, fit_t, val_t) | |
| if args.auto_lambda: | |
| args.ridge_lambda = pick_lambda(k_fit, k_val, coef[fit_t], coef[val_t]) | |
| a = solve(k_fit, coef[fit_t], args.ridge_lambda) | |
| p_fit, p_val, p_te = k_fit @ a, k_val @ a, k_te @ a | |
| scale = coef[fit_t].std(0) / (p_fit.std(0) + 1e-8) | |
| val_out["ridge_k64_rescaled"], test_out["ridge_k64_rescaled"] = p_val * scale, p_te * scale | |
| del k_fit, k_val, k_te | |
| knn_vote = lambda c, k: F.one_hot(y_fit[(F.normalize(c, dim=1) @ F.normalize(coef[fit_t], dim=1).T) | |
| .topk(k, 1).indices], len(cats)).sum(1).argmax(1) | |
| for k in (1, 5, 15): | |
| report["val_acc"][f"knn{k}"] = (knn_vote(val_out["ridge_k64_rescaled"], k) == y_val).float().mean().item() | |
| best_k = max((1, 5, 15), key=lambda k: report["val_acc"][f"knn{k}"]) | |
| report["chosen_knn_k"] = best_k | |
| k_fit, k_val, k_te = kernel_fit(args.sub_id, args.resid_kind, fit_t, val_t) | |
| if args.auto_lambda: | |
| args.resid_lambda = pick_lambda(k_fit, k_val, coef[fit_t] - cat_coef[y_fit], coef[val_t] - cat_coef[y_val]) | |
| report["lambdas"] = {"ridge": args.ridge_lambda, "resid": args.resid_lambda} | |
| a = solve(k_fit, coef[fit_t] - cat_coef[y_fit], args.resid_lambda) | |
| r_fit, r_val, r_te = k_fit @ a, k_val @ a, k_te @ a | |
| r_scale = (coef[fit_t] - cat_coef[y_fit]).std(0) / (r_fit.std(0) + 1e-8) | |
| del k_fit, k_val, k_te | |
| pv, pt = knn_vote(val_out["ridge_k64_rescaled"], best_k), knn_vote(test_out["ridge_k64_rescaled"], best_k) | |
| report["test_acc"][f"knn{best_k}"] = (pt == y_test).float().mean().item() | |
| name = f"clsfirst_knn{best_k}_resid_k64_rescaled" | |
| val_out[name], test_out[name] = cat_coef[pv] + r_val * r_scale, cat_coef[pt] + r_te * r_scale | |
| if args.v2_runs: | |
| load = lambda split: torch.from_numpy(np.ascontiguousarray( | |
| np.load(f"{FEAT_DIR}/sub{args.sub_id}_{split}_feats.npy", mmap_mode="r")[:, FRAMES])).cuda() | |
| feats, test_feats = load("train"), load("test") | |
| probs_v, probs_t, c_v, c_t, c_f = 0, 0, 0, 0, 0 | |
| n = len(args.v2_runs) | |
| for run in args.v2_runs: | |
| ra = json.load(open(f"{run}/result.json"))["args"] | |
| model = MapperV2(ra["k"], len(cats), d=ra["d"], depth=ra["depth"]).cuda().eval() | |
| model.load_state_dict(torch.load(f"{run}/best.pt")) | |
| with torch.no_grad(): | |
| pred = lambda x: [torch.cat(o) for o in zip(*[model(x[i:i + 128]) for i in range(0, len(x), 128)])] | |
| cv, lv, _ = pred(feats[val_t]) | |
| ct, lt, _ = pred(test_feats) | |
| probs_v, probs_t = probs_v + lv.softmax(1) / n, probs_t + lt.softmax(1) / n | |
| c_v, c_t, c_f = c_v + cv / n, c_t + ct / n, c_f + pred(feats[fit_t])[0] / n | |
| s = coef[fit_t].std(0) / (c_f.std(0) + 1e-8) | |
| cls_v, cls_t = probs_v.argmax(1), probs_t.argmax(1) | |
| report["val_acc"]["v2ens5_cls"] = (cls_v == y_val).float().mean().item() | |
| report["test_acc"]["v2ens5_cls"] = (cls_t == y_test).float().mean().item() | |
| val_out["v2ens5_coef_rescaled"], test_out["v2ens5_coef_rescaled"] = c_v * s, c_t * s | |
| val_out["v2ens5_clsmean_resid"] = cat_coef[cls_v] + (c_v - c_f.mean(0)) * s | |
| test_out["v2ens5_clsmean_resid"] = cat_coef[cls_t] + (c_t - c_f.mean(0)) * s | |
| val_out["v2ens5_clsmean"], test_out["v2ens5_clsmean"] = cat_coef[cls_v], cat_coef[cls_t] | |
| os.makedirs(args.out_dir, exist_ok=True) | |
| with open(f"{args.out_dir}/val_ids.txt", "w") as f: | |
| f.write("\n".join(val_ids)) | |
| for name in val_out: | |
| for split, cc in [("val", val_out[name]), ("test", test_out[name])]: | |
| d = f"{args.out_dir}/{split}/{name}" | |
| os.makedirs(d, exist_ok=True) | |
| tok = reconstruct(cc, pca) | |
| np.save(f"{d}/tokens.npy", tok.half().cpu().numpy()) | |
| if split == "val": | |
| report["token_metrics"][name] = token_metrics(tok.float(), val_tok) | |
| print(json.dumps({k: v for k, v in report.items() if k != "val_ids"}, indent=1)) | |
| json.dump(report, open(f"{args.out_dir}/report.json", "w"), indent=1) | |
| if __name__ == "__main__": | |
| main() | |