LamTNguyen's picture
set5: phase 5 (random labels, MLP probes, 224 px check, SPair-71k), final analysis, conclusions, reproduce notebook
1777460 verified
Raw History Blame Contribute Delete
9.93 kB
"""Set 5, phase 5 (optional item): SPair-71k keypoint matching, training-free, PCK@0.1 (bbox).
Images are resized (whole image, bicubic) to the model input (256 px; 224 for DINOv2/14) -> 16x16 token grid. For
every source keypoint, the source feature is sampled bilinearly from the L2-normalised token grid; its cosine
similarity with every target token is upsampled bilinearly to 256x256 and the arg-max pixel, mapped back to the
original target image, is the prediction. Correct when within 0.1 * max(target bbox w, h) (SPair convention).
Every block of B models (every second block of L models), every noise level for SiT/JiT (same noise bank, split id 6).
Block and s are chosen on the SPair val pairs; test PCK reported with a 95% bootstrap over test pairs.
python spair5.py [model,model,...]
"""
from __future__ import annotations
import csv
import json
import os
import sys
import tarfile
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
CODE = Path(__file__).resolve().parent
sys.path.insert(0, str(CODE))
import data5 as D # noqa: E402
import models5 as M # noqa: E402
import probes5 as PR # noqa: E402
from common5 import DATA, OUT_LOCAL, is_done, log, mark_done, sha256, write_json # noqa: E402
SPAIR_URL = "https://cvlab.postech.ac.kr/research/SPair-71k/data/SPair-71k.tar.gz"
OUT = OUT_LOCAL / "p5"
PER = OUT_LOCAL / "perimage" / "p5"
S_GRID = [0.05, 0.1, 0.3, 0.5, 0.7]
D.SPLIT_ID.setdefault("spair", 6)
CTOR = {"sit_b": lambda: M.SiTSource("B"), "jit_b": lambda: M.JiTSource("B"),
"sit_l": lambda: M.SiTSource("L"), "jit_l": lambda: M.JiTSource("L")}
MODELS = ["sit_b", "jit_b", "mae_b", "mocov3_b", "dino_b", "ibot_b", "deit3_b", "dinov2_b",
"sit_l", "jit_l", "mae_l", "mocov3_l", "ibot_l", "deit3_l"]
def prepare_spair():
c = D.CACHE
if (c / "spair.done").exists():
return
d = DATA / "spair"
d.mkdir(parents=True, exist_ok=True)
tgz = D._curl(SPAIR_URL, str(d / "SPair-71k.tar.gz"), min_bytes=200_000_000)
root = d / "SPair-71k"
if not root.exists():
with tarfile.open(tgz) as tf:
tf.extractall(d, filter="data")
pairs = {}
for split in ("val", "test"):
pairs[split] = [json.loads(p.read_text()) for p in sorted((root / "PairAnnotation" / split).glob("*.json"))]
names = sorted({(p["category"], p[k]) for sp in pairs.values() for p in sp for k in ("src_imname", "trg_imname")})
index = {n: i for i, n in enumerate(names)}
imgs = np.zeros((len(names), 256, 256, 3), np.uint8)
for i, (cat, nm) in enumerate(names):
imgs[i] = np.asarray(Image.open(root / "JPEGImages" / cat / nm).convert("RGB").resize((256, 256), Image.BICUBIC))
np.save(c / "spair_img.npy", imgs)
for split, ps in pairs.items():
K = max(len(p["src_kps"]) for p in ps)
n = len(ps)
arr = {"src": np.zeros(n, np.int64), "trg": np.zeros(n, np.int64), "skp": np.zeros((n, K, 2), np.float32),
"tkp": np.zeros((n, K, 2), np.float32), "kmask": np.zeros((n, K), bool), "tsize": np.zeros((n, 2), np.float32),
"thr": np.zeros(n, np.float32), "cat": np.array([p["category"] for p in ps])}
for j, p in enumerate(ps):
arr["src"][j] = index[(p["category"], p["src_imname"])]
arr["trg"][j] = index[(p["category"], p["trg_imname"])]
sw, sh = p["src_imsize"][:2]
k = len(p["src_kps"])
arr["skp"][j, :k] = np.asarray(p["src_kps"], np.float32) * np.array([256 / sw, 256 / sh], np.float32)
arr["tkp"][j, :k] = np.asarray(p["trg_kps"], np.float32)
arr["kmask"][j, :k] = True
arr["tsize"][j] = p["trg_imsize"][:2]
x1, y1, x2, y2 = p["trg_bndbox"]
arr["thr"][j] = 0.1 * max(x2 - x1, y2 - y1)
np.savez(c / f"spair_{split}.npz", **arr)
write_json(c / "spair_meta.json", {"url": SPAIR_URL, "tgz_bytes": os.path.getsize(tgz), "tgz_sha256": sha256(tgz),
"images": len(names), "val_pairs": len(pairs["val"]), "test_pairs": len(pairs["test"])})
log(f"[spair] {len(names)} images, {len(pairs['val'])} val / {len(pairs['test'])} test pairs")
(c / "spair.done").touch()
@torch.no_grad()
def grid_feats(src, s, blocks, imgs, lat, bs=64):
"""All blocks' token grids for all SPair images, L2-normalised per token: list over blocks of [N, g, g, D] fp16."""
n = len(imgs)
out = None
for i0 in range(0, n, bs):
idx = np.arange(i0, min(n, i0 + bs))
if src.kind == "latent":
f = src.tokens(torch.from_numpy(lat[idx]).cuda(), torch.from_numpy(D.noise("spair", idx, "lat")).cuda(), s, blocks)
elif src.kind == "pixel":
x = torch.from_numpy(np.ascontiguousarray(imgs[idx])).cuda().permute(0, 3, 1, 2).float() / 127.5 - 1
f = src.tokens(x, torch.from_numpy(D.noise("spair", idx, "pix")).cuda(), s, blocks)
else:
f = src.tokens(imgs[idx], blocks)
g = int(round(f[0].shape[1] ** 0.5))
if out is None:
out = [torch.empty(n, g, g, f[0].shape[-1], dtype=torch.float16, device="cuda") for _ in blocks]
for l, t in enumerate(f):
out[l][i0:i0 + len(idx)] = F.normalize(t.float(), dim=-1).reshape(len(idx), g, g, -1).half()
return out
@torch.no_grad()
def pck_counts(Fg, P, bs=256):
"""Fg [N, g, g, D] normalised; P pair arrays -> per pair (correct, total) keypoints."""
n = len(P["src"])
correct, total = np.zeros(n), P["kmask"].sum(1).astype(np.float64)
g = Fg.shape[1]
for i0 in range(0, n, bs):
sl = slice(i0, min(n, i0 + bs))
fs = Fg[torch.from_numpy(P["src"][sl]).cuda()].permute(0, 3, 1, 2).float() # [b, D, g, g]
ft = Fg[torch.from_numpy(P["trg"][sl]).cuda()].reshape(-1, g * g, Fg.shape[-1]).float() # [b, g*g, D]
skp = torch.from_numpy(P["skp"][sl]).cuda() # 256-px coords
grid = (skp / 256.0) * 2 - 1 # align_corners=False
q = F.grid_sample(fs, grid[:, :, None, :], mode="bilinear", align_corners=False)[..., 0].permute(0, 2, 1)
q = F.normalize(q, dim=-1) # [b, K, D]
sim = torch.bmm(q, ft.transpose(1, 2)).reshape(-1, 1, g, g) # [b*K, 1, g, g]
up = F.interpolate(sim, size=(256, 256), mode="bilinear", align_corners=False).reshape(sim.shape[0], -1)
am = up.argmax(1)
py, px = (am // 256).float() + 0.5, (am % 256).float() + 0.5
b, K = skp.shape[:2]
ts = torch.from_numpy(P["tsize"][sl]).cuda()
pred = torch.stack([px.reshape(b, K) * ts[:, None, 0] / 256, py.reshape(b, K) * ts[:, None, 1] / 256], -1)
dist = (pred - torch.from_numpy(P["tkp"][sl]).cuda()).norm(dim=-1)
ok = (dist <= torch.from_numpy(P["thr"][sl]).cuda()[:, None]) & torch.from_numpy(P["kmask"][sl]).cuda()
correct[sl] = ok.sum(1).cpu().numpy()
return correct, total
def run_model(name, ctx):
tag = f"spair_{name}"
if is_done(f"p5/{tag}.done"):
return None
t0 = time.time()
src = CTOR[name]() if name in CTOR else M.EncoderSource(name)
n = src.n_blocks
blocks = list(range(1, n + 1)) if n <= 12 else list(range(2, n + 1, 2))
svals = S_GRID if name in CTOR else [None]
rows, per = [], {}
for s in svals:
Fs = grid_feats(src, s, blocks, ctx["img"], ctx["lat"])
for l, b in enumerate(blocks):
for split in ("val", "test"):
c, tot = pck_counts(Fs[l], ctx[split])
pck = float(c.sum() / tot.sum())
lo = hi = ""
if split == "test":
Wb = PR.boot_weights(len(c), n_boot=2000, seed=3)
bs_ = (Wb @ c) / (Wb @ tot)
lo, hi = (float(x) for x in np.percentile(bs_, [2.5, 97.5]))
per[f"s{'clean' if s is None else s}_b{b}"] = c.astype(np.int16)
rows.append(dict(layer=b, s="clean" if s is None else s, task="spair_pck", metric="pck@0.1_bbox",
mean=pck, std="", n=1, split=split, ci_lo=lo, ci_hi=hi,
depth_rel=round(b / n, 4)))
del Fs
torch.cuda.empty_cache()
size = "L" if name.endswith("_l") else "B"
with open(OUT / f"{tag}_rows.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=PR.FIELDS)
w.writeheader()
for r in rows:
w.writerow({**{k: "" for k in PR.FIELDS}, "model": name, "size": size, **r})
np.savez_compressed(PER / f"{tag}.npz", total=ctx["test"]["kmask"].sum(1).astype(np.int16), **per)
best = max((r for r in rows if r["split"] == "val"), key=lambda r: r["mean"])
tb = [r for r in rows if r["split"] == "test" and r["layer"] == best["layer"] and r["s"] == best["s"]][0]
log(f"[{tag}] {time.time() - t0:.0f}s; val-best block {best['layer']} s={best['s']}: test PCK {tb['mean']:.4f}")
mark_done(f"p5/{tag}.done")
path = src.path
src.close()
return path
def main():
M.no_tf32()
prepare_spair()
imgs = np.load(D.CACHE / "spair_img.npy")
vae = {}
def get_vae():
vae.setdefault("v", M.VAE())
return vae["v"]
ctx = {"img": imgs, "lat": M.latents("spair", imgs, get_vae, D.CACHE),
"val": dict(np.load(D.CACHE / "spair_val.npz")), "test": dict(np.load(D.CACHE / "spair_test.npz"))}
vae.clear()
torch.cuda.empty_cache()
only = sys.argv[1].split(",") if len(sys.argv) > 1 else MODELS
for name in only:
p = run_model(name, ctx)
if p and Path(p).is_file():
os.remove(p)
log(f"[{name}] checkpoint deleted")
log("SPAIR FINISHED")
if __name__ == "__main__":
main()