File size: 3,957 Bytes
bdc469b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shape checks on the final scenes of the leaderboard episodes (medium effort), from held-out silhouettes.

  uv run python scripts/shape_checks.py          -> results/shape_checks.json

* Mirror test (build tasks): silhouette IoU of the final scene on the 8 held-out views, as built and after mirroring
  the Gaussian centers front to back (y -> -y), plus three other axis changes. A build that follows the object's real
  layout loses overlap when mirrored; a rough blob fits the mirrored object about as well as the real one, and no
  model gains from an axis change (no systematic axis error).
* Size (all tasks): area ratio = rendered pixels with alpha > 0.5 over true silhouette pixels, summed over the
  held-out views. 1 = right size, below 1 = too small or too transparent.
"""
import argparse
import json
import statistics as st
from collections import defaultdict
from pathlib import Path

import pyarrow.parquet as pq
import torch

from splatbench.render import render
from splatbench.scene import Scene

ap = argparse.ArgumentParser()
ap.add_argument("--data", default="data")
ap.add_argument("--out", default="results/shape_checks.json")
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
a = ap.parse_args()
dev = a.device

TRANSFORMS = {"as_built": torch.eye(3), "mirror_x": torch.diag(torch.tensor([-1.0, 1, 1])),
              "mirror_y": torch.diag(torch.tensor([1.0, -1, 1])), "rotate_180_z": torch.diag(torch.tensor([-1.0, -1, 1])),
              "swap_xy": torch.tensor([[0.0, 1, 0], [1, 0, 0], [0, 0, 1]])}
rows = pq.read_table(Path(a.data) / "episodes" / "medium_effort.parquet",
                     columns=["episode_id", "model", "model_name", "task_id", "kind", "final_gaussians"]).to_pylist()
scenes = {}
iou, area = defaultdict(lambda: defaultdict(list)), defaultdict(list)
for e in rows:
    G = e["final_gaussians"]
    scene = e["task_id"].split("__")[0]
    if scene not in scenes:
        scenes[scene] = Scene.load(Path(a.data) / "bench" / "scenes" / scene)
    if not G:
        continue
    cams, _, masks = scenes[scene].torch_views("test", dev)
    f = lambda k: torch.tensor([g[k] for g in G], dtype=torch.float32, device=dev)
    gs = dict(means=f("pos"), scales=f("scale"), quats=f("quat"), colors=f("color"), opacities=f("opacity"))
    mine = truth = 0.0
    for cam, m in zip(cams, masks):
        with torch.no_grad():
            al = render(gs, cam)["alpha"]
        mine += float((al > 0.5).sum())
        truth += float((m > 0.5).sum())
    area[e["model"]].append(mine / max(truth, 1.0))
    if e["kind"] != "build":
        continue
    for name, M in TRANSFORMS.items():
        g2 = dict(gs, means=gs["means"] @ M.to(dev).T)
        inter = union = 0.0
        for cam, m in zip(cams, masks):
            with torch.no_grad():
                al = render(g2, cam)["alpha"] > 0.5
            b = m > 0.5
            inter += float((al & b).sum())
            union += float((al | b).sum())
        iou[e["model"]][name].append(inter / max(union, 1.0))

names = {e["model"]: e["model_name"] for e in rows}
out = {}
for m in sorted(iou, key=lambda m: -st.mean(iou[m]["as_built"])):
    r = area[m]
    out[m] = dict(
        heldout_iou={k: round(st.mean(v), 3) for k, v in iou[m].items()},
        mirror_drop_points=round(100 * (st.mean(iou[m]["as_built"]) - st.mean(iou[m]["mirror_y"])), 1),
        median_area_ratio=round(st.median(r), 2), share_too_small=round(sum(x < 0.7 for x in r) / len(r), 2),
        share_too_big=round(sum(x > 1.3 for x in r) / len(r), 2))
    o = out[m]
    print(f"{names[m]:18s} IoU as built {o['heldout_iou']['as_built']:.3f}, mirrored {o['heldout_iou']['mirror_y']:.3f} "
          f"(drop {o['mirror_drop_points']:.1f} points) | median area ratio {o['median_area_ratio']:.2f}, "
          f"too small {o['share_too_small']:.0%}")
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(out, indent=1))