LamTNguyen's picture
REPA representation probing: report, results, analysis, code
aaa6483 verified
Raw History Blame Contribute Delete
14.2 kB
"""Dataset preparation (idempotent). Produces fixed uint8 image caches, VAE latents,
a fixed noise bank and fold assignments shared by every model.
Splits
inet_train : 50 images / class from ImageNet-1k train (timm/imagenet-1k-wds shards, in shard order)
inet_eval : 10 images / class from ImageNet val (fixed, seed 0) -> classification test, latent test,
first 5 / class of it (5,000 images) -> CKNNA and effective rank
inet_latfit: 5 more images / class from ImageNet val, disjoint from inet_eval -> latent-probe fit
nyu : NYU Depth v2 labeled (795 train / 654 test, official splits)
"""
from __future__ import annotations
import io
import os
import shutil
import subprocess
import tarfile
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import torch
from PIL import Image
from .common import ASSETS, CACHE, DATA, IREPA_REPO, PRETRAINED, ROOT, log, write_json
N_CLASSES = 1000
TRAIN_PER_CLASS = 50
EVAL_PER_CLASS = 10
LATFIT_PER_CLASS = 5
SUB_PER_CLASS = 5 # CKNNA / rank subset (inside inet_eval)
N_FOLDS = 10
NYU_URL = "https://horatio.cs.nyu.edu/mit/silberman/nyu_depth_v2/nyu_depth_v2_labeled.mat"
NYU_SPLITS_URL = "http://horatio.cs.nyu.edu/mit/silberman/indoor_seg_sup/splits.mat"
NYU_CROP_COLS = (80, 560) # center 480x480 of the 480x640 frame; input = this crop resized to 256
DINOV3_COMMIT = "94a96ac83c2446f15f9bdcfae23cad3c6a9d4988"
def center_crop_arr(arr: np.ndarray, image_size: int = 256) -> np.ndarray:
"""ADM center crop (identical to iREPA/REPA preprocessing)."""
pil = Image.fromarray(arr)
while min(*pil.size) >= 2 * image_size:
pil = pil.resize(tuple(x // 2 for x in pil.size), resample=Image.BOX)
scale = image_size / min(*pil.size)
pil = pil.resize(tuple(round(x * scale) for x in pil.size), resample=Image.BICUBIC)
a = np.array(pil)
cy = (a.shape[0] - image_size) // 2
cx = (a.shape[1] - image_size) // 2
return a[cy:cy + image_size, cx:cx + image_size]
def _hf_download(repo_id, filename, repo_type="model", local_dir=None, token=None):
from huggingface_hub import hf_hub_download
return hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type,
local_dir=str(local_dir) if local_dir else None, token=token)
def _curl(url, out, min_bytes=0):
if os.path.exists(out) and os.path.getsize(out) >= max(min_bytes, 1):
return out
tmp = out + ".part"
subprocess.run(["curl", "-fL", "--retry", "20", "--retry-delay", "5", "-C", "-", "-o", tmp, url], check=True)
os.replace(tmp, out)
return out
# ----------------------------------------------------------------------------- assets
def ensure_assets(teachers: list[str]):
PRETRAINED.mkdir(parents=True, exist_ok=True)
need = ["pretrained_models/sdvae-ft-mse-f8d4.pt", "pretrained_models/sdvae-ft-mse-f8d4-latents-stats.pt"]
for t in teachers:
if t == "dinov3-vit-b16":
need.append("pretrained_models/dinov3_vitb16_pretrain_lvd1689m-73cec8be.pth")
if t == "dinov3-vit-h16plus":
need.append("pretrained_models/dinov3_vith16plus_pretrain_lvd1689m-7c1da9a5.pth")
if t == "mocov3-vit-b":
need.append("pretrained_models/mocov3_vitb.pth")
for f in need:
if not (ASSETS / f).exists():
log(f"[assets] downloading {f}")
_hf_download(IREPA_REPO, f, local_dir=ASSETS)
if any(t.startswith("dinov3") for t in teachers):
d = ASSETS / "dinov3"
if not (d / "hubconf.py").exists():
if d.exists():
shutil.rmtree(d)
subprocess.run(["git", "clone", "-q", "https://github.com/facebookresearch/dinov3.git", str(d)], check=True)
subprocess.run(["git", "-C", str(d), "checkout", "-q", DINOV3_COMMIT], check=True)
# ----------------------------------------------------------------------------- ImageNet val (iREPA arrow copy)
def _read_arrow_rows(path):
import pyarrow as pa
with pa.memory_map(str(path)) as src:
reader = pa.ipc.open_stream(src)
for batch in reader:
ids = batch.column("id").to_pylist() if "id" in batch.schema.names else [None] * batch.num_rows
labels = batch.column("label").to_pylist()
imgs = batch.column("image")
img_bytes = imgs.field("bytes").to_pylist()
for i in range(batch.num_rows):
yield ids[i], labels[i], img_bytes[i]
def _decode256(b: bytes) -> np.ndarray:
im = Image.open(io.BytesIO(b)).convert("RGB")
a = np.array(im)
if a.shape[:2] != (256, 256):
a = center_crop_arr(a, 256)
return a
def prepare_imagenet_val():
done = CACHE / "inet_val.done"
if done.exists():
return
from huggingface_hub import HfApi
files = sorted(f.path for f in HfApi().list_repo_tree(IREPA_REPO, path_in_repo="data/imagenet-latents-images/val")
if f.path.endswith(".arrow"))
log(f"[inet-val] {len(files)} arrow shards")
rows = [] # (shard_path, row_in_file, id, label)
raw_dir = DATA / "imagenet_val_irepa"
paths = []
for f in files:
p = _hf_download(IREPA_REPO, f, local_dir=raw_dir)
paths.append(p)
labels_all, ids_all, loc = [], [], []
for si, p in enumerate(paths):
for ri, (iid, lab, _b) in enumerate(_read_arrow_rows(p)):
labels_all.append(lab)
ids_all.append(iid if iid is not None else len(ids_all))
loc.append((si, ri))
labels_all = np.asarray(labels_all)
log(f"[inet-val] {len(labels_all)} images, {len(np.unique(labels_all))} classes")
assert len(labels_all) == 50000 and len(np.unique(labels_all)) == N_CLASSES
rng = np.random.default_rng(0)
eval_idx, lat_idx = [], []
for c in range(N_CLASSES):
idx = np.flatnonzero(labels_all == c)
idx = idx[rng.permutation(len(idx))]
eval_idx += list(idx[:EVAL_PER_CLASS])
lat_idx += list(idx[EVAL_PER_CLASS:EVAL_PER_CLASS + LATFIT_PER_CLASS])
eval_idx, lat_idx = np.asarray(eval_idx), np.asarray(lat_idx)
want = {int(i): None for i in np.concatenate([eval_idx, lat_idx])}
gi = 0
for si, p in enumerate(paths):
for ri, (iid, lab, b) in enumerate(_read_arrow_rows(p)):
if gi in want:
want[gi] = _decode256(b)
gi += 1
for name, idx in (("inet_eval", eval_idx), ("inet_latfit", lat_idx)):
imgs = np.stack([want[int(i)] for i in idx])
np.save(CACHE / f"{name}_img.npy", imgs)
np.save(CACHE / f"{name}_lbl.npy", labels_all[idx].astype(np.int64))
np.save(CACHE / f"{name}_srcidx.npy", idx)
log(f"[inet-val] {name}: {imgs.shape}")
# CKNNA / rank subset: first SUB_PER_CLASS of each class inside inet_eval (eval is class-major)
sub = np.concatenate([np.arange(c * EVAL_PER_CLASS, c * EVAL_PER_CLASS + SUB_PER_CLASS) for c in range(N_CLASSES)])
np.save(CACHE / "inet_eval_sub5k.npy", sub)
done.touch()
# ----------------------------------------------------------------------------- ImageNet train (timm wds)
def hf_token():
"""Token for gated ImageNet: a private file on the VM (outside the repo) wins over the environment."""
p = ROOT / ".hf_token"
if p.exists():
return p.read_text().strip()
return os.environ.get("HF_TOKEN")
def prepare_imagenet_train(max_shards: int = 300):
done = CACHE / "inet_train.done"
if done.exists():
return
token = hf_token()
repo = "timm/imagenet-1k-wds"
tmp_dir = DATA / "imagenet_train_wds"
tmp_dir.mkdir(parents=True, exist_ok=True)
counts = np.zeros(N_CLASSES, dtype=np.int64)
imgs = np.zeros((N_CLASSES * TRAIN_PER_CLASS, 256, 256, 3), dtype=np.uint8)
lbls = np.full(N_CLASSES * TRAIN_PER_CLASS, -1, dtype=np.int64)
keys = [None] * (N_CLASSES * TRAIN_PER_CLASS)
nxt = 0
def dl(i):
fn = f"imagenet1k-train-{i:04d}.tar"
return i, _hf_download(repo, fn, repo_type="dataset", local_dir=tmp_dir, token=token)
shards_used = 0
with ThreadPoolExecutor(4) as ex:
futs = {i: ex.submit(dl, i) for i in range(min(8, max_shards))}
i = 0
while counts.min() < TRAIN_PER_CLASS:
if i >= max_shards:
raise RuntimeError(f"ImageNet train: still short after {max_shards} shards (min count {counts.min()})")
_, path = futs.pop(i).result()
if i + 8 < max_shards:
futs[i + 8] = ex.submit(dl, i + 8)
members = {}
with tarfile.open(path) as tf:
for m in tf:
if not m.isfile():
continue
key, ext = m.name.rsplit(".", 1)
members.setdefault(key, {})[ext] = tf.extractfile(m).read()
for key in members: # tar order
d = members[key]
c = int(d["cls"].decode().strip())
if counts[c] >= TRAIN_PER_CLASS:
continue
img = d.get("jpg") or d.get("jpeg") or d.get("png")
a = np.array(Image.open(io.BytesIO(img)).convert("RGB"))
imgs[nxt] = center_crop_arr(a, 256)
lbls[nxt] = c
keys[nxt] = key
counts[c] += 1
nxt += 1
os.remove(path)
shards_used = i + 1
if i % 10 == 0:
log(f"[inet-train] shard {i}: filled {nxt}/{len(lbls)} min/class {counts.min()}")
i += 1
for f in futs.values():
f.cancel()
# sort class-major for readability
order = np.lexsort((np.arange(len(lbls)), lbls))
np.save(CACHE / "inet_train_img.npy", imgs[order])
np.save(CACHE / "inet_train_lbl.npy", lbls[order])
with open(CACHE / "inet_train_keys.txt", "w") as f:
f.write("\n".join(keys[j] for j in order))
write_json(CACHE / "inet_train_meta.json", {"source": repo, "shards_used": shards_used, "per_class": TRAIN_PER_CLASS})
shutil.rmtree(tmp_dir, ignore_errors=True)
log(f"[inet-train] done with {shards_used} shards")
done.touch()
# ----------------------------------------------------------------------------- NYU depth v2
def prepare_nyu():
done = CACHE / "nyu.done"
if done.exists():
return
import h5py
import scipy.io
d = DATA / "nyu"
d.mkdir(parents=True, exist_ok=True)
mat = _curl(NYU_URL, str(d / "nyu_depth_v2_labeled.mat"), min_bytes=2_000_000_000)
spl = _curl(NYU_SPLITS_URL, str(d / "splits.mat"))
s = scipy.io.loadmat(spl)
train = s["trainNdxs"].ravel().astype(int) - 1
test = s["testNdxs"].ravel().astype(int) - 1
assert len(train) == 795 and len(test) == 654, (len(train), len(test))
c0, c1 = NYU_CROP_COLS
with h5py.File(mat, "r") as f:
images = f["images"] # (1449, 3, 640, 480)
depths = f["depths"] # (1449, 640, 480)
n = images.shape[0]
out_img = np.zeros((n, 256, 256, 3), np.uint8)
out_dep = np.zeros((n, 480, 480), np.float32)
for i in range(n):
im = np.asarray(images[i]).transpose(2, 1, 0)[:, c0:c1] # (480, 480, 3)
dp = np.asarray(depths[i]).transpose(1, 0)[:, c0:c1] # (480, 480)
out_img[i] = np.array(Image.fromarray(im).resize((256, 256), resample=Image.BICUBIC))
out_dep[i] = dp
split = np.full(n, -1, np.int64)
split[train] = 0
split[test] = 1
np.save(CACHE / "nyu_img.npy", out_img)
np.save(CACHE / "nyu_depth.npy", out_dep)
np.save(CACHE / "nyu_split.npy", split)
log(f"[nyu] images {out_img.shape}, depth range {out_dep.min():.3f}-{out_dep.max():.3f}")
done.touch()
# ----------------------------------------------------------------------------- latents, noise, folds
SPLITS = ["inet_train", "inet_eval", "inet_latfit", "nyu"]
def load_images(split):
return np.load(CACHE / f"{split}_img.npy", mmap_mode="r")
def build_vae(device):
from models.autoencoder import VAE_F8D4
vae = VAE_F8D4().to(device).eval()
sd = torch.load(PRETRAINED / "sdvae-ft-mse-f8d4.pt", map_location="cpu", weights_only=False)
vae.load_state_dict(sd, strict=True)
st = torch.load(PRETRAINED / "sdvae-ft-mse-f8d4-latents-stats.pt", map_location="cpu", weights_only=False)
scale = st["latents_scale"].to(device).view(1, -1, 1, 1).float()
bias = st["latents_bias"].to(device).view(1, -1, 1, 1).float()
return vae, scale, bias
@torch.no_grad()
def prepare_latents_noise_folds(device="cuda"):
vae = None
for si, split in enumerate(SPLITS):
if not (CACHE / f"{split}_img.npy").exists():
continue
lat_p = CACHE / f"{split}_lat.npy"
if not lat_p.exists():
if vae is None:
vae, scale, bias = build_vae(device)
imgs = load_images(split)
out = np.zeros((len(imgs), 4, 32, 32), np.float32)
for b0 in range(0, len(imgs), 64):
x = torch.from_numpy(np.ascontiguousarray(imgs[b0:b0 + 64])).to(device).permute(0, 3, 1, 2).float()
x = x / 127.5 - 1.0
mean = vae.encode(x).mean # posterior mean (deterministic)
out[b0:b0 + 64] = ((mean - bias) * scale).cpu().numpy()
np.save(lat_p, out)
log(f"[latents] {split}: {out.shape} mean {out.mean():.3f} std {out.std():.3f}")
eps_p = CACHE / f"{split}_eps.npy"
if not eps_p.exists():
n = len(np.load(lat_p, mmap_mode="r"))
rng = np.random.default_rng(1000 + si)
np.save(eps_p, rng.standard_normal((n, 4, 32, 32), dtype=np.float32))
fold_p = CACHE / f"{split}_fold.npy"
if not fold_p.exists():
n = len(np.load(lat_p, mmap_mode="r"))
rng = np.random.default_rng(2000 + si)
np.save(fold_p, (rng.permutation(n) % N_FOLDS).astype(np.int64))
if vae is not None:
del vae
torch.cuda.empty_cache()
def prepare_all(teachers, need_train=True):
ensure_assets(teachers)
prepare_imagenet_val()
prepare_nyu()
if need_train:
prepare_imagenet_train()
prepare_latents_noise_folds()