926 / mind3d_trellis2 /code /mapper /bottleneck.py
jamie33's picture
Restore mind3d_trellis2 (docs, code, results, renders, paper)
7c61ee6 verified
Raw History Blame Contribute Delete
4.13 kB
"""Where does our error come from? Per-object test CD of the best method split by whether its predicted
coefficients land in the right category (kNN-5 over fit objects; category used for this diagnosis only), vs. the
GT-16-dim / GT-category-mean / oracle references; per-category table; correlation with coefficient error;
sampling-variance share on val (4 samples of the same tokens)."""
import os
import json
import numpy as np
import torch
from scipy.stats import spearmanr
from pca_tools import load_tokens, split_ids, get_pca, project
P = "/home/hubin/trellis_work/outputs"
H = "/home/hubin/hf_upload/mind3d-trellis2/results/metrics"
REFS = {"ours": "ft_frozen_sub01_k16_cfg50", "gt_pca16": "diag_pca16", "gt_pca64": "diag_pca64",
"gt_category_mean": "diag_category_mean", "oracle": "oracle_gt_image", "train_mean": "diag_train_mean",
"mind3d": "mind3d_official"}
def rows(path):
return {r["id"]: r["cd"] * 1e3 for r in json.load(open(path))["rows"]}
def main():
tr, te, fi, va = split_ids()
pca = get_pca()
fitc = project(torch.from_numpy(load_tokens([tr[i] for i in fi])).cuda(), pca, 16).cpu().numpy()
sd, tv = fitc.std(0), fitc.var(0).sum()
fity = np.array([tr[i].split("/")[0] for i in fi])
def knn(c):
a, b = c / sd, fitc / sd
s = (a / np.linalg.norm(a, axis=1, keepdims=True)) @ (b / np.linalg.norm(b, axis=1, keepdims=True)).T
return np.array([max(sorted(set(fity[t])), key=list(fity[t]).count) for t in np.argsort(-s, 1)[:, :5]])
z = np.load(f"{P}/ft/frozen_0001/sub0001_coefs.npz")
gtc = project(torch.from_numpy(load_tokens(te)).cuda().float(), pca, 16).cpu().numpy()
err = ((z["test"][1] * z["scale"] - gtc) ** 2).sum(1) / tv
ok = knn(z["test"][1]) == np.array([t.split("/")[0] for t in te])
R = {k: rows(f"{H}/{v}.json") for k, v in REFS.items()}
ids = [t for t in te if all(t in r for r in R.values())]
ix = [te.index(t) for t in ids]
okk, e = ok[ix], err[ix]
V = {k: np.array([r[t] for t in ids]) for k, r in R.items()}
out = {"n": len(ids), "category_correct_rate": float(okk.mean()), "methods": {}}
for k, v in V.items():
out["methods"][k] = {"all": float(v.mean()), "category_correct": float(v[okk].mean()),
"category_wrong": float(v[~okk].mean()), "median": float(np.median(v))}
o, p16 = V["ours"], V["gt_pca16"]
out["share_of_our_cd_from_category_wrong"] = float(o[~okk].sum() / o.sum())
out["share_of_gap_to_gt16_from_category_wrong"] = float((o - p16)[~okk].sum() / (o - p16).sum())
out["counterfactual_wrong_set_to_gt16"] = float(np.where(okk, o, p16).mean())
out["coef_err"] = {"category_correct": float(e[okk].mean()), "category_wrong": float(e[~okk].mean())}
out["spearman"] = {"cd_vs_coef_err": float(spearmanr(o, e)[0]), "cd_vs_gt16_cd": float(spearmanr(o, p16)[0]),
"cd_vs_oracle_cd": float(spearmanr(o, V["oracle"])[0])}
y = np.array([t.split("/")[0] for t in ids])
out["per_category"] = {c: {**{k: float(V[k][y == c].mean()) for k in ("ours", "gt_pca16", "gt_category_mean",
"oracle")},
"n": int((y == c).sum()), "category_correct_rate": float(okk[y == c].mean())}
for c in sorted(set(y))}
vids = open(f"{P}/valsel/val_ids.txt").read().split()
S = [rows(f"{P}/opt/val/single_c/metrics_s{j}.json") for j in range(4)]
vi = [t for t in vids if all(t in s for s in S)]
cd = np.array([[s[t] for s in S] for t in vi])
out["val_sampling"] = {"within_object_variance_share": float(cd.var(1, ddof=1).mean() / cd.reshape(-1).var()),
"per_object_sample_std": float(cd.std(1, ddof=1).mean()),
"between_object_std": float(cd.mean(1).std())}
os.makedirs(f"{P}/analysis", exist_ok=True)
json.dump(out, open(f"{P}/analysis/bottleneck.json", "w"), indent=1)
print(json.dumps({k: v for k, v in out.items() if k != "per_category"}, indent=1))
if __name__ == "__main__":
main()