"""Set 5 data (VM). Same selection and preprocessing as sets 1-2 (repa-probe/probe/data.py), set-5 paths. nyu : NYU Depth v2 labeled, official 795 train / 654 test; centre 480x480 crop -> 256 px input; depth at 480x480 inet_eval : ImageNet val, 10 / class (iREPA arrow copy, per-class rng seed 0; same images as sets 1-2) inet_train : ImageNet train, 50 / class from timm/imagenet-1k-wds in shard order (gated: HF token on the VM) nyu normals: FAIR self-supervision benchmark normals (Ladicky et al., as Probe3D) for the same 1449 frames, same crop ade_train : ADE20K (SceneParsing 2016) train subset, 5,000 of 20,210 images (rng 4000), shorter side -> 256 + centre crop; labels 0 = ignore, 1..150 classes (nearest resize, same geometry) ade_val : ADE20K val, all 2,000 images, same preprocessing (evaluation on the 256 px centre crop) Folds (10 per split, rng 2000 + split id, as sets 1-2) pick the validation fold of each seed. Noise bank: one fixed standard-normal draw per (split, image, kind), seeded by (base, split id, image index), shared by every task, model and noise level s. kind 'lat' is 4x32x32 (SiT latent), 'pix' is 3x256x256 (JiT pixels). """ from __future__ import annotations import io import os import shutil import subprocess import sys import tarfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parent)) from common5 import DATA, log, write_json # noqa: E402 CACHE = DATA / "cache" CACHE.mkdir(parents=True, exist_ok=True) N_CLASSES, TRAIN_PER_CLASS, EVAL_PER_CLASS, N_FOLDS = 1000, 50, 10, 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) IREPA_REPO = "REPA-E/iREPA-collections" SPLIT_ID = {"inet_train": 0, "inet_eval": 1, "nyu": 3, "ade_train": 4, "ade_val": 5} # 0-3: sets 1-2 numbering NORMALS_URL = "https://dl.fbaipublicfiles.com/fair_self_supervision_benchmark/nyuv2_surfacenormal_metadata.zip" ADE_URL = "https://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip" ADE_TRAIN_SUBSET, ADE_CLASSES = 5000, 150 NOISE_BASE = {"lat": 1000, "pix": 3000} NOISE_SHAPE = {"lat": (4, 32, 32), "pix": (3, 256, 256)} def center_crop_arr(arr, image_size=256): """ADM centre crop (as iREPA / REPA / sets 1-2).""" 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, cx = (a.shape[0] - image_size) // 2, (a.shape[1] - image_size) // 2 return a[cy:cy + image_size, cx:cx + image_size] def _curl(url, out, min_bytes=1): if os.path.exists(out) and os.path.getsize(out) >= min_bytes: return out tmp = out + ".part" subprocess.run(["curl", "-sSfL", "--retry", "20", "--retry-delay", "5", "-C", "-", "-o", tmp, url], check=True) os.replace(tmp, out) return out def _folds(split, n): p = CACHE / f"{split}_fold.npy" if not p.exists(): rng = np.random.default_rng(2000 + SPLIT_ID[split]) np.save(p, (rng.permutation(n) % N_FOLDS).astype(np.int64)) return np.load(p) def noise(split, idx, kind): """Fixed noise for images idx of split: float32 [len(idx), *shape].""" out = np.empty((len(idx), *NOISE_SHAPE[kind]), np.float32) for j, i in enumerate(idx): out[j] = np.random.default_rng((NOISE_BASE[kind], SPLIT_ID[split], int(i))).standard_normal( NOISE_SHAPE[kind], dtype=np.float32) return out def random_labels(split, idx, true=None): """Phase-5 side test: one fixed random ImageNet class per image (seeded by split and index), never the true label.""" out = np.empty(len(idx), np.int64) for j, i in enumerate(idx): r = np.random.default_rng((9000, SPLIT_ID[split], int(i))) if true is None: out[j] = r.integers(0, N_CLASSES) else: v = int(r.integers(0, N_CLASSES - 1)) out[j] = v + 1 if v >= int(true[j]) else v return out # ----------------------------------------------------------------------------- NYU def prepare_nyu(): if (CACHE / "nyu.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, test = s["trainNdxs"].ravel().astype(int) - 1, 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, depths = f["images"], f["depths"] 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] out_img[i] = np.array(Image.fromarray(im).resize((256, 256), resample=Image.BICUBIC)) out_dep[i] = np.asarray(depths[i]).transpose(1, 0)[:, c0:c1] split = np.full(n, -1, np.int64) split[train], split[test] = 0, 1 np.save(CACHE / "nyu_img.npy", out_img) np.save(CACHE / "nyu_depth.npy", out_dep) np.save(CACHE / "nyu_split.npy", split) _folds("nyu", n) write_json(CACHE / "nyu_meta.json", {"mat_bytes": os.path.getsize(mat), "n": n, "train": 795, "test": 654}) log(f"[nyu] images {out_img.shape}, depth {out_dep.min():.3f}-{out_dep.max():.3f} m") (CACHE / "nyu.done").touch() # ----------------------------------------------------------------------------- ImageNet val (iREPA arrow copy) def _arrow_rows(path): import pyarrow as pa with pa.memory_map(str(path)) as src: for batch in pa.ipc.open_stream(src): labels = batch.column("label").to_pylist() img_bytes = batch.column("image").field("bytes").to_pylist() for i in range(batch.num_rows): yield labels[i], img_bytes[i] def _decode256(b): a = np.array(Image.open(io.BytesIO(b)).convert("RGB")) return a if a.shape[:2] == (256, 256) else center_crop_arr(a, 256) def prepare_imagenet_val(): if (CACHE / "inet_eval.done").exists(): return from huggingface_hub import HfApi, hf_hub_download 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")) raw = DATA / "imagenet_val_irepa" paths = [hf_hub_download(IREPA_REPO, f, local_dir=str(raw)) for f in files] labels = np.asarray([lab for p in paths for lab, _ in _arrow_rows(p)]) assert len(labels) == 50000 and len(np.unique(labels)) == N_CLASSES, len(labels) rng = np.random.default_rng(0) eval_idx = [] for c in range(N_CLASSES): # same draws as sets 1-2 (which also took 5 more per class for inet_latfit) idx = np.flatnonzero(labels == c) eval_idx += list(idx[rng.permutation(len(idx))][:EVAL_PER_CLASS]) eval_idx = np.asarray(eval_idx) want = {int(i): None for i in eval_idx} gi = 0 for p in paths: for _, b in _arrow_rows(p): if gi in want: want[gi] = _decode256(b) gi += 1 np.save(CACHE / "inet_eval_img.npy", np.stack([want[int(i)] for i in eval_idx])) np.save(CACHE / "inet_eval_lbl.npy", labels[eval_idx].astype(np.int64)) np.save(CACHE / "inet_eval_srcidx.npy", eval_idx) _folds("inet_eval", len(eval_idx)) shutil.rmtree(raw, ignore_errors=True) log(f"[inet-val] {len(eval_idx)} images from {len(files)} arrow shards") (CACHE / "inet_eval.done").touch() # ----------------------------------------------------------------------------- ImageNet train (timm wds, gated) TOKEN_FILE = Path.home() / ".cache" / "huggingface" / "token" def wait_token(max_hours=6.0): """HF token written on the VM by the user from Colab Secrets (HF_TOKEN). Only its presence is ever logged.""" import time t0 = time.time() while not (TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip()): if time.time() - t0 > max_hours * 3600: raise RuntimeError("no HF token on the VM") if int(time.time() - t0) % 600 < 30: log("[inet-train] waiting for the HF token file on the VM") time.sleep(30) log("[inet-train] HF token present") return TOKEN_FILE.read_text().strip() def prepare_imagenet_train(max_shards=300): if (CACHE / "inet_train.done").exists(): return from huggingface_hub import hf_hub_download repo, tmp = "timm/imagenet-1k-wds", DATA / "imagenet_train_wds" tmp.mkdir(parents=True, exist_ok=True) counts = np.zeros(N_CLASSES, np.int64) imgs = np.zeros((N_CLASSES * TRAIN_PER_CLASS, 256, 256, 3), np.uint8) lbls = np.full(N_CLASSES * TRAIN_PER_CLASS, -1, np.int64) keys = [None] * len(lbls) nxt, nbytes = 0, 0 token = wait_token() def dl(i): return hf_hub_download(repo, f"imagenet1k-train-{i:04d}.tar", repo_type="dataset", local_dir=str(tmp), token=token) 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 short after {max_shards} shards (min/class {counts.min()})") path = futs.pop(i).result() if i + 8 < max_shards: futs[i + 8] = ex.submit(dl, i + 8) nbytes += os.path.getsize(path) members = {} with tarfile.open(path) as tf: for m in tf: if m.isfile(): key, ext = m.name.rsplit(".", 1) members.setdefault(key, {})[ext] = tf.extractfile(m).read() for key, d in members.items(): 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") imgs[nxt] = center_crop_arr(np.array(Image.open(io.BytesIO(img)).convert("RGB")), 256) lbls[nxt], keys[nxt] = c, key counts[c] += 1 nxt += 1 os.remove(path) if i % 10 == 0: log(f"[inet-train] shard {i}: {nxt}/{len(lbls)}, min/class {counts.min()}, {nbytes/1e9:.1f} GB read") i += 1 for f in futs.values(): f.cancel() 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]) (CACHE / "inet_train_keys.txt").write_text("\n".join(keys[j] for j in order)) _folds("inet_train", len(lbls)) write_json(CACHE / "inet_train_meta.json", {"source": repo, "shards_used": i, "bytes_read": nbytes}) shutil.rmtree(tmp, ignore_errors=True) log(f"[inet-train] done: {i} shards, {nbytes/1e9:.1f} GB read") (CACHE / "inet_train.done").touch() # ----------------------------------------------------------------------------- NYU normals (FAIR / Probe3D) class _NumpyOnlyUnpickler(__import__("pickle").Unpickler): """The FAIR file is a gzip pickle {"all_normals": float32 [1449, 480, 640, 3]}; allow numpy array rebuilding only.""" OK = {("numpy.core.multiarray", "_reconstruct"), ("numpy._core.multiarray", "_reconstruct"), ("numpy", "ndarray"), ("numpy", "dtype")} def find_class(self, module, name): if (module, name) not in self.OK: raise __import__("pickle").UnpicklingError(f"blocked global {module}.{name}") return np.core.multiarray._reconstruct if name == "_reconstruct" else getattr(np, name) def prepare_normals(): if (CACHE / "nyu_normals.done").exists(): return import gzip import zipfile from common5 import sha256 d = DATA / "nyu" d.mkdir(parents=True, exist_ok=True) z = _curl(NORMALS_URL, str(d / "nyuv2_surfacenormal_metadata.zip"), min_bytes=800_000_000) with zipfile.ZipFile(z) as zf: with zf.open("surfacenormal_metadata/all_normals.pklz") as raw, gzip.open(raw) as g: obj = _NumpyOnlyUnpickler(g).load() arr, msk, names = obj["all_normals"], obj["all_valid_depth_masks"], obj["all_filenames"] assert arr.shape == (1449, 480, 640, 3) and msk.shape == (1449, 480, 640), (arr.shape, msk.shape) assert list(names) == [f"{i:06d}" for i in range(1, 1450)], "frame order differs from the labeled .mat" c0, c1 = NYU_CROP_COLS nrm = arr[:, :, c0:c1].astype(np.float16) # [1449, 480, 480, 3], same crop as depth valid = msk[:, :, c0:c1] > 0.5 # FAIR / Probe3D evaluation mask (valid depth) del arr, msk, obj np.save(CACHE / "nyu_normals.npy", nrm) np.save(CACHE / "nyu_normals_valid.npy", valid) norm = np.linalg.norm(nrm[:50].astype(np.float32), axis=-1) info = {"url": NORMALS_URL, "zip_bytes": os.path.getsize(z), "zip_sha256": sha256(z), "valid_frac": float(valid.mean()), "norm_pct_1_50_99_first50": [float(np.percentile(norm[valid[:50]], q)) for q in (1, 50, 99)]} info["alignment_vs_depth"] = _normals_alignment_check(nrm, valid) write_json(CACHE / "nyu_normals_meta.json", info) log(f"[normals] {nrm.shape} valid {info['valid_frac']:.3f}, alignment {info['alignment_vs_depth']}") (CACHE / "nyu_normals.done").touch() def _normals_alignment_check(nrm, valid, n=60): """Correlation (3x3) between the given normals and normals computed from the depth maps (NYU intrinsics, finite differences) on n images: a dominant (+/-) diagonal means the two are pixel-aligned in the same frame.""" dep = np.load(CACHE / "nyu_depth.npy", mmap_mode="r") fx, fy, cx, cy = 518.8579, 519.4696, 325.5824 - NYU_CROP_COLS[0], 253.7362 v, u = np.mgrid[0:480, 0:480].astype(np.float32) acc = [] for i in range(0, 1449, 1449 // n): z = np.asarray(dep[i], np.float32) P = np.stack([(u - cx) * z / fx, (v - cy) * z / fy, z], -1) dx, dy = P[1:-1, 2:] - P[1:-1, :-2], P[2:, 1:-1] - P[:-2, 1:-1] n_d = np.cross(dx, dy) n_d /= np.linalg.norm(n_d, axis=-1, keepdims=True) + 1e-9 g = nrm[i, 1:-1, 1:-1].astype(np.float32) m = valid[i, 1:-1, 1:-1] & (z[1:-1, 1:-1] > 0) acc.append((g[m], n_d[m])) G = np.concatenate([a for a, _ in acc]) Dn = np.concatenate([b for _, b in acc]) C = np.corrcoef(G.T, Dn.T)[:3, 3:] return [[round(float(x), 3) for x in row] for row in C] # ----------------------------------------------------------------------------- ADE20K def _ade_resize_crop(img, lbl, size=256): w, h = img.size sc = size / min(w, h) nw, nh = max(size, round(w * sc)), max(size, round(h * sc)) img, lbl = img.resize((nw, nh), Image.BICUBIC), lbl.resize((nw, nh), Image.NEAREST) l, t = (nw - size) // 2, (nh - size) // 2 return (np.asarray(img.crop((l, t, l + size, t + size)).convert("RGB")), np.asarray(lbl.crop((l, t, l + size, t + size)))) def prepare_ade(): if (CACHE / "ade.done").exists(): return import zipfile from common5 import sha256 d = DATA / "ade" d.mkdir(parents=True, exist_ok=True) z = _curl(ADE_URL, str(d / "ADEChallengeData2016.zip"), min_bytes=900_000_000) with zipfile.ZipFile(z) as zf: names = set(zf.namelist()) for split, sub, n_expect in (("ade_train", "training", 20210), ("ade_val", "validation", 2000)): imgs = sorted(n for n in names if n.startswith(f"ADEChallengeData2016/images/{sub}/") and n.endswith(".jpg")) assert len(imgs) == n_expect, (sub, len(imgs)) if split == "ade_train": pick = np.sort(np.random.default_rng(4000).choice(len(imgs), ADE_TRAIN_SUBSET, replace=False)) imgs = [imgs[i] for i in pick] X = np.zeros((len(imgs), 256, 256, 3), np.uint8) Y = np.zeros((len(imgs), 256, 256), np.uint8) for j, n in enumerate(imgs): ln = n.replace("/images/", "/annotations/").replace(".jpg", ".png") im = Image.open(io.BytesIO(zf.read(n))) lb = Image.open(io.BytesIO(zf.read(ln))) X[j], Y[j] = _ade_resize_crop(im, lb) assert Y.max() <= ADE_CLASSES, Y.max() np.save(CACHE / f"{split}_img.npy", X) np.save(CACHE / f"{split}_lbl.npy", Y) (CACHE / f"{split}_names.txt").write_text("\n".join(Path(n).name for n in imgs)) _folds(split, len(imgs)) log(f"[ade] {split}: {X.shape}, labelled pixels {float((Y > 0).mean()):.3f}") write_json(CACHE / "ade_meta.json", {"url": ADE_URL, "zip_bytes": os.path.getsize(z), "zip_sha256": sha256(z), "train_subset": ADE_TRAIN_SUBSET, "subset_rng": 4000}) (CACHE / "ade.done").touch() def load(split): """dict(img uint8 mmap [N,256,256,3], fold [N], lbl [N] or None, split-specific extras).""" d = {"img": np.load(CACHE / f"{split}_img.npy", mmap_mode="r"), "fold": np.load(CACHE / f"{split}_fold.npy")} lp = CACHE / f"{split}_lbl.npy" d["lbl"] = np.load(lp) if lp.exists() else None if split == "nyu": d["depth"] = np.load(CACHE / "nyu_depth.npy", mmap_mode="r") d["split"] = np.load(CACHE / "nyu_split.npy") if (CACHE / "nyu_normals.npy").exists(): d["normals"] = np.load(CACHE / "nyu_normals.npy", mmap_mode="r") d["normals_valid"] = np.load(CACHE / "nyu_normals_valid.npy", mmap_mode="r") return d if __name__ == "__main__": what = sys.argv[1].split(",") if len(sys.argv) > 1 else ["nyu", "val", "train"] if "nyu" in what: prepare_nyu() if "val" in what: prepare_imagenet_val() if "train" in what: prepare_imagenet_train() if "normals" in what: prepare_normals() if "ade" in what: prepare_ade()