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
15.4 kB
"""Feature sources for set 5 (VM). Every source returns, for the requested blocks (1-indexed block outputs), a list of
patch-token tensors [B, 256, D] in float32. Checkpoints are re-checked against the step-0 size and sha256 records and
loaded with torch.load(weights_only=True) (encoders: same allow-list helper as step 0c).
SiTSource latent SD-VAE input x_s = (1-s)*x0 + s*eps, x0 = 0.18215 * posterior mean; willisma/SiT path
x_t = t*data + (1-t)*noise, so t = 1 - s; null label 1000; velocity output (data - noise).
JiTSource pixel input in [-1, 1]; JiT z = t*x + (1-t)*noise_scale*eps (noise_scale 1.0), so with s the noise
coefficient z = (1-s)*x + s*eps and t = 1 - s; null label 1000; x-prediction; the 32 in-context class
tokens (prepended from block 4 of B / 8 of L) are dropped.
EncoderSource clean image, ImageNet mean/std, 256 px with pos_embed bicubic-resampled to 16x16 (224 px for patch 14);
prefix tokens (CLS) dropped from the patch tokens and returned separately.
Forward passes run in fp32 (TF32 off) so features do not depend on reduced-precision matmuls.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
CODE = Path(__file__).resolve().parent
sys.path.insert(0, str(CODE))
from common5 import CKPT, OUT_DRIVE, OUT_LOCAL, WORK, log, sha256 # noqa: E402
NULL_LABEL = 1000
IMNET_MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
IMNET_STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
def step0_record(name):
for d in (OUT_LOCAL / "step0", OUT_DRIVE / "step0", CODE / "step0"):
if (d / name).exists():
return json.loads((d / name).read_text())
raise FileNotFoundError(f"step-0 record {name}")
def verify(path, rec, what):
path = Path(path)
size, digest = path.stat().st_size, sha256(path)
want_size = rec.get("size_bytes")
if digest != rec["sha256"] or (want_size and size != want_size):
raise RuntimeError(f"{what}: {path.name} size/sha256 ({size}, {digest[:16]}) differ from step 0 "
f"({want_size}, {rec['sha256'][:16]})")
return {"file": path.name, "size_bytes": size, "sha256": digest}
class _Stop(Exception):
pass
def tap_blocks(block_modules, wanted, run, post=None):
"""Outputs of blocks `wanted` (1-indexed) during run(); the forward is stopped after the deepest one."""
wanted = sorted(set(wanted))
out, hs = {}, []
for b in wanted:
def hook(_m, _i, o, b=b):
out[b] = post(b, o) if post else o
if b == wanted[-1]:
raise _Stop
hs.append(block_modules[b - 1].register_forward_hook(hook))
try:
run()
except _Stop:
pass
finally:
for h in hs:
h.remove()
return [out[b].float() for b in wanted]
# ----------------------------------------------------------------------------- SD-VAE (SiT input)
class VAE:
"""stabilityai/sd-vae-ft-ema (SiT's training default; ft-ema and ft-mse share the encoder). latent = 0.18215 *
posterior mean (the protocol's choice; SiT training samples from the posterior)."""
def __init__(self, device="cuda"):
from diffusers.models import AutoencoderKL
self.vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-ema").to(device).eval()
self.device = device
@torch.no_grad()
def encode(self, img_u8): # [B, 256, 256, 3] uint8 (numpy or tensor) -> [B, 4, 32, 32]
x = torch.as_tensor(np.asarray(img_u8)).to(self.device).permute(0, 3, 1, 2).float() / 127.5 - 1.0
return torch.cat([self.vae.encode(c).latent_dist.mean for c in x.split(32)]) * 0.18215 # chunks: memory
@torch.no_grad()
def decode(self, z):
return torch.cat([self.vae.decode(c / 0.18215).sample for c in z.split(50)])
def latents(split, img, vae_holder, cache_dir, bs=64):
"""Cached SiT input latents of a whole split ([N, 4, 32, 32] float32)."""
p = Path(cache_dir) / f"{split}_lat.npy"
if p.exists():
return np.load(p)
vae = vae_holder()
out = np.zeros((len(img), 4, 32, 32), np.float32)
for i in range(0, len(img), bs):
out[i:i + bs] = vae.encode(img[i:i + bs]).cpu().numpy()
np.save(p, out)
log(f"[latents] {split}: {out.shape}, mean {out.mean():.3f}, std {out.std():.3f}")
return out
# ----------------------------------------------------------------------------- SiT
SIT_REPO, SIT_COMMIT = "https://github.com/willisma/SiT.git", "cbde832a40b153ccc79603412409da9c9b0c568c"
def sit_code():
d = WORK / "willisma_sit"
if not (d / "models.py").exists():
subprocess.run(["git", "clone", "-q", SIT_REPO, str(d)], check=True)
subprocess.run(["git", "-C", str(d), "checkout", "-q", SIT_COMMIT], check=True)
if str(d) not in sys.path:
sys.path.insert(0, str(d))
import models as sit_models
return sit_models
class SiTSource:
kind = "latent"
group = "denoise_latent"
def __init__(self, size, device="cuda"):
from huggingface_hub import hf_hub_download
sit_models = sit_code()
p = Path(hf_hub_download("nyu-visionx/SiT-collections", f"SiT-{size}-2-256.pt", local_dir=str(CKPT)))
self.ckpt = verify(p, step0_record(f"sit_{size}_n4000.json"), f"SiT-{size}")
sd = torch.load(p, map_location="cpu", weights_only=True)
m = sit_models.SiT_models[f"SiT-{size}/2"](input_size=32, num_classes=1000, learn_sigma=True)
m.load_state_dict(sd, strict=True)
self.m = m.to(device).eval()
self.path, self.device = p, device
self.name, self.size = f"sit_{size.lower()}", size
self.n_blocks, self.dim = len(m.blocks), m.pos_embed.shape[-1]
@staticmethod
def t_of_s(s):
return 1.0 - s
def _t(self, B, t):
return torch.full((B,), float(t), device=self.device)
@torch.no_grad()
def tokens(self, x0, eps, s, blocks, y=None):
B = x0.shape[0]
xs = (1 - s) * x0 + s * eps
y = torch.full((B,), NULL_LABEL, device=self.device, dtype=torch.long) if y is None else y
return tap_blocks(self.m.blocks, blocks, lambda: self.m(xs, self._t(B, self.t_of_s(s)), y))
@torch.no_grad()
def predict(self, x, t, y=None):
y = torch.full((x.shape[0],), NULL_LABEL, device=self.device, dtype=torch.long) if y is None else y
return self.m(x, self._t(x.shape[0], t) if not torch.is_tensor(t) else t, y)
@torch.no_grad()
def sample_grid(self, vae, classes, seed=0):
"""SDE Euler-Maruyama 250 steps, no CFG (the step-0 FID setting), fp32 network."""
from transport import Sampler, create_transport
fn = Sampler(create_transport("Linear", "velocity", None, None, None)).sample_sde(
sampling_method="Euler", diffusion_form="sigma", diffusion_norm=1.0, last_step="Mean",
last_step_size=0.04, num_steps=250)
torch.manual_seed(seed)
z = torch.randn(len(classes), 4, 32, 32, device=self.device)
x = fn(z, self.m.forward, y=torch.tensor(classes, device=self.device))[-1]
return ((vae.decode(x) + 1) * 127.5).clamp(0, 255).round().to(torch.uint8)
def close(self):
del self.m
torch.cuda.empty_cache()
# ----------------------------------------------------------------------------- JiT
class JiTSource:
kind = "pixel"
group = "denoise_pixel"
CFG = {"B": 3.0, "L": 2.4, "H": 2.2}
def __init__(self, size, device="cuda"):
import s0b_jit
Denoiser = s0b_jit.jit_code()
p = s0b_jit.local(size)
if not p.exists() or p.stat().st_size != s0b_jit.FILES[size][1]:
subprocess.run(["curl", "-sSfL", "--retry", "10", "-C", "-", "-o", str(p), s0b_jit.url(size)], check=True)
self.ckpt = verify(p, step0_record(f"jit_{size}_inspect.json"), f"JiT-{size}")
torch.serialization.add_safe_globals([argparse.Namespace])
ck = torch.load(p, map_location="cpu", weights_only=True)
a = argparse.Namespace(model=f"JiT-{size}/16", img_size=256, class_num=1000, attn_dropout=0.0,
proj_dropout=0.0, label_drop_prob=0.1, P_mean=-0.8, P_std=0.8, t_eps=5e-2,
noise_scale=1.0, ema_decay1=0.9999, ema_decay2=0.9996, sampling_method="heun",
num_sampling_steps=50, cfg=1.0, interval_min=0.1, interval_max=1.0)
den = Denoiser(a)
den.load_state_dict(ck["model_ema1"], strict=True)
del ck
self.den = den.to(device).eval()
self.net = self.den.net
self.path, self.device = p, device
self.name, self.size = f"jit_{size.lower()}", size
self.n_blocks, self.dim = len(self.net.blocks), self.net.pos_embed.shape[-1]
self.noise_scale = a.noise_scale
self.ic_len, self.ic_start = self.net.in_context_len, self.net.in_context_start # start is 0-based
@staticmethod
def t_of_s(s):
return 1.0 - s
def _post(self, b, o):
o = o[:, self.ic_len:] if (b - 1) >= self.ic_start else o
assert o.shape[1] == 256, o.shape
return o
@torch.no_grad()
def tokens(self, x, eps, s, blocks, y=None):
B = x.shape[0]
z = (1 - s) * x + s * self.noise_scale * eps
t = torch.full((B,), self.t_of_s(s), device=self.device)
y = torch.full((B,), NULL_LABEL, device=self.device, dtype=torch.long) if y is None else y
return tap_blocks(self.net.blocks, blocks, lambda: self.net(z, t, y), self._post)
@torch.no_grad()
def predict(self, z, t, y=None):
y = torch.full((z.shape[0],), NULL_LABEL, device=self.device, dtype=torch.long) if y is None else y
return self.net(z, torch.full((z.shape[0],), float(t), device=self.device), y)
@torch.no_grad()
def sample_grid(self, classes, cfg, seed=0):
self.den.cfg_scale = cfg
torch.manual_seed(seed)
x = self.den.generate(torch.tensor(classes, device=self.device))
return ((x.clamp(-1, 1) + 1) * 127.5).round().to(torch.uint8)
def close(self):
del self.den, self.net
torch.cuda.empty_cache()
# ----------------------------------------------------------------------------- ViT encoders
GROUP = {"mae": "masked", "mocov3": "joint_embedding", "dino": "joint_embedding", "ibot": "joint_embedding",
"deit3": "supervised", "dinov2": "external_data"}
class EncoderSource:
kind = "image"
def __init__(self, name, device="cuda", native=False):
"""native=True: run at the encoder's training resolution 224 px with its own pos_embed (14x14 tokens for
patch 16; DINOv2/14 is always at 224 -> 16x16) -- the protocol's side check of the 256 px interpolation."""
import timm
from timm.layers import resample_abs_pos_embed
import s0c_encoders as E
sp = E.SPECS[name]
rec = step0_record(f"enc_{name}.json")
if "timm" in sp:
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
p = Path(hf_hub_download(f"timm/{sp['timm']}", "model.safetensors", local_dir=str(CKPT / name)))
self.ckpt = verify(p, rec, name)
sd = load_file(str(p))
else:
p = CKPT / f"{name}.pth"
if not p.exists():
subprocess.run(["curl", "-sSfL", "--retry", "10", "-o", str(p), sp["url"]], check=True)
self.ckpt = verify(p, rec, name)
ck, _ = E.torch_load_weights_only(p)
sd = ck[sp["key"]] if sp["key"] else ck
if "teacher" in sp: # teacher / momentum encoder (step 0c, user decision 2026-11-20 for MoCo v3)
sd = (E.mm_rename if sp.get("mm") else E.strip)(sd, sp["teacher"])
del ck
sd = {k: v for k, v in sd.items() if not k.startswith(("head", "masked_embed", "mask_token", "decoder"))}
self.px = 224 if ("patch14" in sp["arch"] or native) else 256
m = timm.create_model(sp["arch"], pretrained=False, num_classes=0, img_size=self.px)
no_embed_class = bool(getattr(m, "no_embed_class", False))
if not (native and "patch14" not in sp["arch"]):
sd["pos_embed"] = resample_abs_pos_embed(sd["pos_embed"], new_size=(16, 16),
num_prefix_tokens=0 if no_embed_class else m.num_prefix_tokens)
m.load_state_dict(sd, strict=True)
self.grid = self.px // (14 if "patch14" in sp["arch"] else 16)
self.m = m.to(device).eval()
self.path, self.device, self.name = p, device, name
self.group = GROUP[name.split("_")[0]]
self.prefix = m.num_prefix_tokens
self.n_blocks, self.dim = len(m.blocks), m.embed_dim
def _in(self, img_u8):
x = torch.as_tensor(np.asarray(img_u8)).to(self.device).permute(0, 3, 1, 2).float() / 255.0
if self.px != 256:
x = F.interpolate(x, size=(self.px, self.px), mode="bicubic", align_corners=False, antialias=True)
return (x - IMNET_MEAN.to(self.device)) / IMNET_STD.to(self.device)
@torch.no_grad()
def tokens(self, img_u8, blocks, with_cls=False):
x = self._in(img_u8)
outs = tap_blocks(self.m.blocks, blocks, lambda: self.m.forward_features(x))
patches = [o[:, self.prefix:] for o in outs]
assert patches[0].shape[1] == self.grid ** 2, patches[0].shape
if with_cls:
return patches, [o[:, 0] for o in outs]
return patches
def close(self):
del self.m
torch.cuda.empty_cache()
# ----------------------------------------------------------------------------- lower baselines
def patchify(x, p):
B, C, H, W = x.shape
return x.reshape(B, C, H // p, p, W // p, p).permute(0, 2, 4, 1, 3, 5).reshape(B, (H // p) * (W // p), C * p * p)
class PatchBaseline:
"""Protocol lower baselines (one 'layer'): 'latent' = noisy SD-VAE latent patches (2x2x4 = 16 dims, SiT input),
'pixel' = noisy pixel patches in [-1, 1] (16x16x3 = 768, JiT input), 'pixel_clean' = clean ImageNet-normalised
pixel patches (encoder input). Same noise bank and s as the models they bound."""
def __init__(self, which, device="cuda"):
self.which, self.device = which, device
self.kind = {"latent": "latent", "pixel": "pixel", "pixel_clean": "image"}[which]
self.name, self.group, self.n_blocks = f"base_{which}", "baseline", 1
self.dim = 16 if which == "latent" else 768
self.ckpt = None
@torch.no_grad()
def tokens(self, a, b=None, s=None, blocks=None, with_cls=False):
if self.kind == "image": # tokens(img_u8, blocks, with_cls)
with_cls = s if isinstance(s, bool) else with_cls
x = torch.as_tensor(np.asarray(a)).to(self.device).permute(0, 3, 1, 2).float() / 255.0
out = [patchify((x - IMNET_MEAN.to(self.device)) / IMNET_STD.to(self.device), 16)]
return (out, None) if with_cls else out
x = (1 - s) * a + s * b
return [patchify(x, 2 if self.kind == "latent" else 16)]
def close(self):
pass
def no_tf32():
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.set_float32_matmul_precision("highest")