File size: 6,472 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""Semantic N-way top-1 accuracy following MinD-3D tools/get_acc_shape.py: an ImageNet ViT-H/14 classifies the GT image
(argmax = gt class) and the prediction's render; success if the prediction's probability of the gt class beats N-1
random other ImageNet classes (100 trials). Pred views use get_acc_shape's 6 cameras (azimuth 30..330, elevation
20/-10). We have no GT meshes, so GT images are 6 evenly spaced frames of the stimulus video (renders of the GT object);
both sides are grey-on-white and cropped to the object's bounding box."""
import os
import sys
import glob
import json
import argparse
from concurrent.futures import ThreadPoolExecutor

import numpy as np
import torch
import imageio.v3 as iio
import nvdiffrast.torch as dr
from PIL import Image
from torchvision.models import vit_h_14, ViT_H_14_Weights

from render_compare import load_mesh, render_mesh, look_at, perspective

O = "/home/hubin/trellis_work/outputs"
STIM = "/home/hubin/data/fMRI-Shape/stimuli_test/stimuli"
VIT_CKPT = "/home/hubin/trellis_work/weights/vit_h_14_swag-80465313.pth"
AZIMUTHS = [30, 90, 150, 210, 270, 330]
ELEVATIONS = [20, -10, 20, -10, 20, -10]
RES = 512


def cameras():
    out = []
    for az, el in zip(np.deg2rad(AZIMUTHS), np.deg2rad(ELEVATIONS)):
        eye = 2.0 * np.array([np.cos(el) * np.sin(az), np.sin(el), np.cos(el) * np.cos(az)])
        light = eye / np.linalg.norm(eye) + np.array([0.3, 0.6, 0.0])
        out.append((torch.tensor(perspective(32) @ look_at(eye), dtype=torch.float32, device="cuda"),
                    torch.tensor(light / np.linalg.norm(light), dtype=torch.float32, device="cuda")))
    return out


def crop(img, margin=0.1):
    a = np.asarray(img.convert("RGB"))
    ys, xs = np.nonzero((a < 245).any(-1))
    if len(ys) == 0:
        return img.convert("RGB")
    cy, cx = (ys.min() + ys.max()) / 2, (xs.min() + xs.max()) / 2
    half = max(ys.max() - ys.min(), xs.max() - xs.min()) / 2 * (1 + margin) + 1
    return img.convert("RGB").crop((int(cx - half), int(cy - half), int(cx + half), int(cy + half))).resize((256, 256))


def gt_frames(obj):
    cat, uid = obj.split("/")
    frames = iio.imread(f"{STIM}/{cat}/{uid}.mp4")
    return [crop(Image.fromarray(frames[i])) for i in np.linspace(0, len(frames), 6, endpoint=False).astype(int)]


class Classifier:
    def __init__(self):
        self.model = vit_h_14(weights=None, image_size=518).cuda().eval()
        self.model.load_state_dict(torch.load(VIT_CKPT))
        self.prep = ViT_H_14_Weights.DEFAULT.transforms()

    @torch.no_grad()
    def probs(self, imgs, bs=24):
        out = []
        for i in range(0, len(imgs), bs):
            x = torch.stack([self.prep(im) for im in imgs[i:i + bs]]).cuda()
            with torch.autocast("cuda", dtype=torch.bfloat16):
                out.append(self.model(x).float().softmax(1).cpu())
        return torch.cat(out).numpy()


def n_way(pred_probs, gt_cls, n, trials=100, seed=0):
    rng = np.random.default_rng(seed)
    accs = []
    for p, c in zip(pred_probs, gt_cls):
        others = np.delete(np.arange(len(p)), c)
        picks = np.stack([rng.choice(others, n - 1, replace=False) for _ in range(trials)])
        accs.append(np.mean(p[c] > p[picks].max(1)))
    return float(np.mean(accs)), accs


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--methods", nargs="*", help="name=src (dir under outputs/ holding meshes/ + metrics.json)")
    p.add_argument("--out_dir", default=f"{O}/sem")
    args = p.parse_args()
    if args.methods:
        methods = [m.split("=", 1) for m in args.methods]
    else:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "mapper"))
        from pack_hf import VARIANTS
        methods = [(n, src) for n, src, *_ in VARIANTS]
    os.makedirs(args.out_dir, exist_ok=True)
    clf = Classifier()

    gt_cache = f"{args.out_dir}/gt_probs.npz"
    ids = sorted(json.load(open(f"{O}/mind3d_sub01/metrics.json"))["rows"], key=lambda r: r["id"])
    ids = [r["id"] for r in ids]
    if os.path.exists(gt_cache):
        gt_probs = np.load(gt_cache)["probs"]
    else:
        with ThreadPoolExecutor(8) as pool:
            frames = list(pool.map(gt_frames, ids))
        os.makedirs(f"{args.out_dir}/gt_views", exist_ok=True)
        for obj, fs in zip(ids, frames):
            for i, im in enumerate(fs):
                im.save(f"{args.out_dir}/gt_views/{obj.replace('/', '_')}_{i}.png")
        gt_probs = clf.probs([im for fs in frames for im in fs]).reshape(len(ids), 6, -1)
        np.savez_compressed(gt_cache, probs=gt_probs, ids=np.array(ids))
    gt_cls = gt_probs.argmax(-1)

    ctx = dr.RasterizeCudaContext()
    cams = cameras()
    summary = json.load(open(f"{args.out_dir}/summary.json")) if os.path.exists(f"{args.out_dir}/summary.json") else {}
    for name, src in methods:
        if name in summary:
            continue
        rows = {r["id"]: r for r in json.load(open(f"{O}/{src}/metrics.json"))["rows"]}
        paths = {o: [q for q in glob.glob(f"{O}/{src}/meshes/{o.replace('/', '_')}.*") if q.endswith((".ply", ".obj"))]
                 for o in ids}
        if not all(paths.values()) or not all(o in rows for o in ids):
            print(f"skip {name}", flush=True)
            continue
        view_dir = f"{args.out_dir}/views/{name}"
        os.makedirs(view_dir, exist_ok=True)
        with ThreadPoolExecutor(6) as pool:
            meshes = pool.map(lambda o: load_mesh(paths[o][0], rows[o]["up"], rows[o]["azimuth"]), ids)
            imgs = []
            for o, (v, f) in zip(ids, meshes):
                for i, (mvp, light) in enumerate(cams):
                    im = crop(render_mesh(ctx, v, f, res=RES, mvp=mvp, light=light, base=(0.8, 0.8, 0.8)))
                    im.save(f"{view_dir}/{o.replace('/', '_')}_{i}.png")
                    imgs.append(im)
        probs = clf.probs(imgs).reshape(len(ids), 6, -1)
        pp, gg = probs.reshape(-1, probs.shape[-1]), gt_cls.reshape(-1)
        acc2, per2 = n_way(pp, gg, 2)
        acc10, _ = n_way(pp, gg, 10)
        summary[name] = {"n_objects": len(ids), "2way": acc2, "10way": acc10,
                         "top1_same_class": float((pp.argmax(1) == gg).mean())}
        np.save(f"{view_dir}/probs_top5.npy", np.argsort(-probs, -1)[..., :5])
        print(f"{name:45s} 2-way {acc2:.3f}  10-way {acc10:.3f}", flush=True)
        json.dump(summary, open(f"{args.out_dir}/summary.json", "w"), indent=1)


if __name__ == "__main__":
    main()