Download mind3d_trellis2/code/mapper/ens_v2.py from jamie33/926: direct link, hf CLI and curl.
- Browser
- Download file 3.18 kB
-
https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/ens_v2.py
- Command line
-
hf download hf://datasets/jamie33/926/mind3d_trellis2/code/mapper/ens_v2.py
-
curl -L -o ens_v2.py https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/ens_v2.py
3.18 kB
| """Ensemble several MapperV2 runs: average class probabilities and PCA coefficients, then build token variants.""" | |
| import os | |
| import json | |
| import argparse | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from pca_tools import FEAT_DIR, load_tokens, split_ids, get_pca, project, reconstruct | |
| from train_mapper import token_metrics | |
| from train_mapper_v2 import MapperV2, FRAMES | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--runs", nargs="+", required=True) | |
| p.add_argument("--out_dir", required=True) | |
| args = p.parse_args() | |
| train_ids, test_ids, fit_idx, _ = split_ids() | |
| fit_ids = [train_ids[i] for i in fit_idx] | |
| load = lambda split: torch.from_numpy(np.ascontiguousarray( | |
| np.load(f"{FEAT_DIR}/sub0001_{split}_feats.npy", mmap_mode="r")[:, FRAMES])).cuda() | |
| feats, test_feats = load("train"), load("test") | |
| pca = get_pca() | |
| test_tok = torch.from_numpy(load_tokens(test_ids)).cuda().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_fit, y_test = lab(fit_ids), lab(test_ids) | |
| fit_t = torch.from_numpy(fit_idx).cuda() | |
| probs, c_te, c_fit = 0, 0, 0 | |
| for run in args.runs: | |
| a = json.load(open(f"{run}/result.json"))["args"] | |
| model = MapperV2(a["k"], len(cats), d=a["d"], depth=a["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)])] | |
| c, logits, _ = pred(test_feats) | |
| probs, c_te = probs + logits.softmax(1) / len(args.runs), c_te + c / len(args.runs) | |
| c_fit = c_fit + pred(feats[fit_t])[0] / len(args.runs) | |
| k = c_te.shape[1] | |
| coef_fit = project(torch.from_numpy(load_tokens(fit_ids)).cuda(), pca, k) | |
| cat_coef = torch.stack([coef_fit[y_fit == c].mean(0) for c in range(len(cats))]) | |
| scale = coef_fit.std(0) / (c_fit.std(0) + 1e-8) | |
| pred_cls = probs.argmax(1) | |
| sim = F.normalize(c_te, dim=1) @ F.normalize(coef_fit, dim=1).T | |
| knn = F.one_hot(y_fit[sim.topk(5, 1).indices], len(cats)).sum(1).argmax(1) | |
| res = {"runs": args.runs, "test_cls_acc": (pred_cls == y_test).float().mean().item(), | |
| "test_top3": (probs.topk(3, 1).indices == y_test[:, None]).any(1).float().mean().item(), | |
| "test_knn_acc": (knn == y_test).float().mean().item(), "token_metrics": {}} | |
| variants = {"coef_rescaled": c_te * scale, | |
| "clsmean_resid": cat_coef[pred_cls] + (c_te - c_fit.mean(0)) * scale, | |
| "clsmean": cat_coef[pred_cls]} | |
| for name, cc in variants.items(): | |
| tok = reconstruct(cc, pca) | |
| os.makedirs(f"{args.out_dir}/{name}", exist_ok=True) | |
| np.save(f"{args.out_dir}/{name}/tokens.npy", tok.half().cpu().numpy()) | |
| res["token_metrics"][name] = token_metrics(tok.float(), test_tok) | |
| print(json.dumps({k: v for k, v in res.items() if k != "token_metrics"}), flush=True) | |
| json.dump(res, open(f"{args.out_dir}/result.json", "w"), indent=1) | |
| if __name__ == "__main__": | |
| main() | |