Download probe/external.py from LamTNguyen/repa-representation-probing: direct link, hf CLI and curl.
- Browser
- Download file 8.87 kB
-
https://huggingface.co/datasets/LamTNguyen/repa-representation-probing/resolve/main/probe/external.py
- Command line
-
hf download hf://datasets/LamTNguyen/repa-representation-probing/probe/external.py
-
curl -L -o external.py https://huggingface.co/datasets/LamTNguyen/repa-representation-probing/resolve/main/probe/external.py
8.87 kB
| """Set-2 checkpoints from other codebases. | |
| All of them use the SD-VAE encoder with latent = 0.18215 * posterior (iREPA's latent stats are exactly | |
| scale 0.18215, bias 0, and the sd-vae-ft-ema / ft-mse encoders are identical), so the set-1 latent cache, | |
| noise bank and folds are reused unchanged. What differs is the time convention: | |
| REPA-style codebases (REPA, HASTE, ELIT): x_t = (1 - t) x0 + t eps, t=0 clean -> t = s | |
| original SiT (willisma/SiT, DispLoss): x_t = t x0 + (1 - t) eps, t=1 clean -> t = 1 - s | |
| and the network output: REPA-style predicts v = eps - x0 = dx/ds; willisma predicts v = x0 - eps = -dx/ds. | |
| """ | |
| from __future__ import annotations | |
| import importlib.util | |
| import os | |
| import subprocess | |
| import torch | |
| from .common import ASSETS, CKPT, log, write_json | |
| from .fetch_ckpt import RAW, fetch_url | |
| from .models import NULL_CLASS, CheckpointError | |
| WILLISMA_REPO = "https://github.com/willisma/SiT.git" | |
| WILLISMA_COMMIT = "cbde832a40b153ccc79603412409da9c9b0c568c" | |
| def gdrive(file_id): | |
| return f"https://drive.usercontent.google.com/download?id={file_id}&export=download&confirm=t" | |
| SPECS = { | |
| # vanilla SiT-XL/2, 400K steps, batch 256 (REPA recipe re-implementation, snap-research/elit) | |
| "sit-baseline-400k": dict(url="https://huggingface.co/mali6/elit/resolve/main/sit_imagenet_256px_1k_0400000.pt", | |
| keys=("ema",), arch="repa", t_of_s="s", expect_steps=400000, | |
| source="snap-research/elit (HF mali6/elit)"), | |
| # original SiT-XL/2 release (~7M steps; zip prefix DiT-XL-7005600) | |
| "sit-7m": dict(url="https://www.dl.dropboxusercontent.com/scl/fi/as9oeomcbub47de5g4be0/SiT-XL-2-256.pt?rlkey=uxzxmpicu46coq3msb17b9ofa&dl=0", | |
| keys=(RAW,), arch="willisma", t_of_s="1-s", expect_steps=7005600, | |
| source="willisma/SiT download.py"), | |
| # REPA SiT-XL/2, 4M iterations, DINOv2-B at block 8 (raw state_dict, EMA by all evidence). | |
| # The official Dropbox link (REPA utils.download_model('last.pt')) gave a CRC error on data.pkl; this HF mirror | |
| # was pointed to by the REPA author (issue #10), same size (2,733,044,564 B), byte-identical on sampled ranges, | |
| # LFS sha256 bd62ad8b9ec5b12393b07745187bdd2f638af87d03236ee98faa5bc66ef0d0bc. Used with the user's approval. | |
| "repa-4m": dict(url="https://huggingface.co/kyungmnlee/DMF/resolve/main/sit_xl_2_repa_256.pt", | |
| keys=(RAW,), arch="repa", t_of_s="s", expect_steps=4000000, teacher="dinov2-vit-b", | |
| source="HF mirror kyungmnlee/DMF sit_xl_2_repa_256.pt (of sihyun-yu/REPA last.pt)"), | |
| # HASTE SiT-XL/2 2.5M (DINOv2-B alignment + attention distillation, stopped at 250K) | |
| "haste": dict(url=gdrive("1XS3jAU7LDoCzYrjIHB99MO_v7M33fYNT"), keys=("ema",), arch="repa", t_of_s="s", | |
| expect_steps=2500000, teacher="dinov2-vit-b", source="NUS-HPC-AI-Lab/HASTE Drive SiT-XL/2/2500000.pt"), | |
| # SiT-XL/2 + Dispersive loss, 80 epochs = step 400K (zip prefix 0400000) | |
| "dispersive-80ep": dict(url=gdrive("1NR_R6wYXS6dwCwYCM8h8EmeLpJjtiwVr"), keys=("ema",), arch="willisma", | |
| t_of_s="1-s", expect_steps=400000, source="raywang4/DispLoss Drive XL_2-disp.pt"), | |
| } | |
| def fetch_external(key): | |
| spec = SPECS[key] | |
| out = CKPT / f"{key}.pt" | |
| if out.exists(): | |
| return torch.load(out, map_location="cpu", weights_only=False) | |
| sds, meta = fetch_url(spec["url"], keys=spec["keys"], label=key) | |
| sd = sds[spec["keys"][0]] | |
| steps = meta.get("steps") | |
| if steps is None and meta.get("zip_prefix", "").split("-")[-1].isdigit(): | |
| steps = int(meta["zip_prefix"].split("-")[-1]) # e.g. "DiT-XL-7005600" or "0400000" | |
| meta["steps_resolved"] = steps | |
| obj = {"ema": sd, "meta": meta, "spec": {k: v for k, v in spec.items() if k != "keys"}} | |
| tmp = out.with_suffix(".tmp") | |
| torch.save(obj, tmp) | |
| os.replace(tmp, out) | |
| write_json(CKPT / f"{key}.meta.json", {"spec": obj["spec"], **meta}) | |
| return obj | |
| def _willisma_models(): | |
| d = ASSETS / "willisma_sit" | |
| if not (d / "models.py").exists(): | |
| subprocess.run(["git", "clone", "-q", WILLISMA_REPO, str(d)], check=True) | |
| subprocess.run(["git", "-C", str(d), "checkout", "-q", WILLISMA_COMMIT], check=True) | |
| spec = importlib.util.spec_from_file_location("willisma_sit_models", d / "models.py") | |
| mod = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(mod) | |
| return mod | |
| def build_external(key, ckpt, device="cuda"): | |
| spec = SPECS[key] | |
| sd = ckpt["ema"] | |
| if spec["arch"] == "willisma": | |
| mod = _willisma_models() | |
| out_ch = sd["final_layer.linear.weight"].shape[0] // 4 | |
| model = mod.SiT_XL_2(input_size=32, num_classes=1000, class_dropout_prob=0.1, learn_sigma=(out_ch == 8)) | |
| info = dict(arch="willisma/SiT SiT-XL/2", learn_sigma=out_ch == 8) | |
| else: | |
| from models.sit import SiT_models # iREPA's copy of REPA's SiT (identical parameter names) | |
| has_proj = any(k.startswith("projectors.0.") for k in sd) | |
| zdims = [sd["projectors.0.4.weight"].shape[0]] if has_proj else [] | |
| model = SiT_models["SiT-XL/2"](input_size=32, in_channels=4, num_classes=1000, use_cfg=True, z_dims=zdims, | |
| encoder_depth=8, projection_layer_type="mlp", old_projector_version=True, | |
| fused_attn=True, qk_norm=False) | |
| info = dict(arch="REPA-style SiT-XL/2", projector_z_dims=zdims) | |
| res = model.load_state_dict(sd, strict=False) | |
| if res.missing_keys or res.unexpected_keys: | |
| raise CheckpointError(f"{key}: strict load failed: missing={res.missing_keys[:10]} unexpected={res.unexpected_keys[:10]}") | |
| model.load_state_dict(sd, strict=True) | |
| model = model.to(device).eval().requires_grad_(False) | |
| meta = ckpt["meta"] | |
| info.update(n_params=sum(p.numel() for p in model.parameters()), steps=meta.get("steps_resolved"), | |
| t_of_s=spec["t_of_s"], source=spec["source"], zip_prefix=meta.get("zip_prefix")) | |
| args = meta.get("args") or {} | |
| for k in ("path_type", "prediction", "enc_type", "early_stop_point", "disp", "epochs", "global_batch_size", "vae"): | |
| if k in args: | |
| info[f"args.{k}"] = args[k] | |
| if info.get("args.path_type") not in (None, "linear", "Linear"): | |
| raise CheckpointError(f"{key}: path_type {info['args.path_type']} is not linear") | |
| return model, info | |
| class HookFeatures: | |
| """Block outputs via forward hooks; works for any SiT variant whose blocks live in model.blocks.""" | |
| def __init__(self, model, blocks, t_of_s): | |
| self.model, self.blocks = model, sorted(blocks) | |
| self.t_of_s = t_of_s | |
| self._feats = {} | |
| self._handles = [model.blocks[b - 1].register_forward_hook(self._hook(b)) for b in self.blocks] | |
| def close(self): | |
| """Remove the hooks. They close over self, so model -> hook -> self -> model is a reference cycle that | |
| refcounting alone never frees; without this every probed checkpoint stayed on the GPU (set-2 OOM).""" | |
| for h in self._handles: | |
| h.remove() | |
| self._handles = [] | |
| self._feats.clear() | |
| self.model = None | |
| def _hook(self, b): | |
| def fn(mod, inp, out): | |
| self._feats[b] = out[0] if isinstance(out, tuple) else out | |
| return fn | |
| def t(self, s): | |
| return 1.0 - s if self.t_of_s == "1-s" else s | |
| def __call__(self, x0, eps, s): | |
| x = (1.0 - s) * x0 + s * eps | |
| t = torch.full((x.shape[0],), float(self.t(s)), device=x.device) | |
| y = torch.full((x.shape[0],), NULL_CLASS, device=x.device, dtype=torch.long) | |
| self._feats.clear() | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| self.model(x, t, y) | |
| return [self._feats[b].float() for b in self.blocks] | |
| def sample_generic(model, t_of_s, ys, steps=50, cfg=4.0, seed=0, device="cuda"): | |
| """Euler in noise-ratio space s: 1 -> 0, with CFG on all 4 channels. Returns latents (0.18215-scaled).""" | |
| g = torch.Generator(device="cpu").manual_seed(seed) | |
| x = torch.randn(len(ys), 4, 32, 32, generator=g).to(device) | |
| null = torch.full_like(ys, NULL_CLASS) | |
| sgrid = torch.linspace(1.0, 0.0, steps + 1).tolist() | |
| sign = -1.0 if t_of_s == "1-s" else 1.0 # willisma predicts x0 - eps = -dx/ds | |
| for s_cur, s_next in zip(sgrid[:-1], sgrid[1:]): | |
| t = (1.0 - s_cur) if t_of_s == "1-s" else s_cur | |
| tt = torch.full((2 * len(ys),), float(t), device=device) | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| out = model(torch.cat([x, x]), tt, torch.cat([ys, null])) | |
| out = (out[0] if isinstance(out, tuple) else out)[:, :4].float() | |
| vc, vu = out.chunk(2) | |
| v = vu + cfg * (vc - vu) | |
| x = x + (s_next - s_cur) * sign * v | |
| return x | |