"""Model construction: SiT checkpoints (EMA, strict load), teacher encoders, VAE-latent baseline.""" from __future__ import annotations import os import torch import torch.nn.functional as F from .common import CKPT, IREPA_REPO, log, write_json from .fetch_ckpt import fetch_subdicts NULL_CLASS = 1000 # CFG null label index (num_classes); never feed true labels class CheckpointError(RuntimeError): pass # ----------------------------------------------------------------------------- SiT (iREPA codebase) def fetch_irepa_ema(key: str, hf_path: str) -> dict: """Cache {'ema': state_dict, 'meta': {...}} for one iREPA checkpoint.""" out = CKPT / f"{key}.pt" if out.exists(): return torch.load(out, map_location="cpu", weights_only=False) sds, meta = fetch_subdicts(IREPA_REPO, hf_path, keys=("ema",)) obj = {"ema": sds["ema"], "meta": meta, "hf_path": hf_path} tmp = out.with_suffix(".tmp") torch.save(obj, tmp) os.replace(tmp, out) write_json(CKPT / f"{key}.meta.json", {"hf_path": hf_path, **meta}) return obj def build_irepa_sit(ckpt: dict, device="cuda"): from models.sit import SiT_models sd = ckpt["ema"] args = ckpt["meta"].get("args", {}) keys = list(sd.keys()) # Projector variant is identified from the stored keys, not guessed. if any(k.startswith("projectors.0.projection_layer.") for k in keys): old = False w = sd["projectors.0.projection_layer.weight"] if "projectors.0.projection_layer.weight" in sd else None if w is not None and w.ndim == 4: ptype, ksz, zdim = "conv", w.shape[-1], w.shape[0] elif w is not None and w.ndim == 2: ptype, ksz, zdim = "linear", 1, w.shape[0] else: ptype, ksz = "mlp", 1 last = max(int(k.split(".")[3]) for k in keys if k.startswith("projectors.0.projection_layer.") and k.endswith(".weight")) zdim = sd[f"projectors.0.projection_layer.{last}.weight"].shape[0] elif any(k.startswith("projectors.0.0.") for k in keys): old, ptype, ksz = True, "mlp", 1 zdim = sd["projectors.0.4.weight"].shape[0] else: raise CheckpointError(f"unrecognised projector keys: {[k for k in keys if 'projector' in k][:6]}") enc_depth = int(args.get("encoder_depth", 8)) model_name = args.get("model", "SiT-XL/2") n_cls_rows = sd["y_embedder.embedding_table.weight"].shape[0] model = SiT_models[model_name]( input_size=32, in_channels=4, num_classes=1000, use_cfg=True, z_dims=[zdim], encoder_depth=enc_depth, projection_layer_type=ptype, proj_kwargs_kernel_size=ksz, old_projector_version=old, fused_attn=True, qk_norm=bool(args.get("qk_norm", False)), class_dropout_prob=0.1 if n_cls_rows == 1001 else 0.0, ) res = model.load_state_dict(sd, strict=False) if res.missing_keys or res.unexpected_keys: raise CheckpointError(f"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) info = dict(model=model_name, encoder_depth=enc_depth, projector=ptype, kernel=ksz, old_projector_version=old, z_dim=zdim, n_params=sum(p.numel() for p in model.parameters()), steps=ckpt["meta"].get("steps"), enc_type=args.get("enc_type"), spnorm_method=args.get("spnorm_method"), proj_coeff=args.get("proj_coeff"), path_type=args.get("path_type")) if info["path_type"] not in (None, "linear"): raise CheckpointError(f"path_type {info['path_type']} != linear: noise-level mapping would differ") return model, info class SiTFeatures: """Callable: (clean latent x0, noise eps, s) -> list of block outputs [B, 256, 1152] (fp32).""" def __init__(self, model, blocks): self.model, self.blocks = model, sorted(blocks) @torch.no_grad() def __call__(self, x0, eps, s): # iREPA/REPA linear path: x_t = (1 - t) x0 + t eps, model input time = t in [0, 1] => t = s x = (1.0 - s) * x0 + s * eps t = torch.full((x.shape[0],), float(s), device=x.device) y = torch.full((x.shape[0],), NULL_CLASS, device=x.device, dtype=torch.long) with torch.autocast("cuda", dtype=torch.bfloat16): feats = self.model.forward_features(x, t, y, encoder_depths=self.blocks, proj=False) return [f.float() for f in feats] class VAEFeatures: """Lower baseline: the noisy VAE latent itself, patchified 2x2 -> 16x16 tokens of 16 dims.""" blocks = [0] @torch.no_grad() def __call__(self, x0, eps, s): x = (1.0 - s) * x0 + s * eps return [patchify(x)] def patchify(x): # [B, 4, 32, 32] -> [B, 256, 16] (same p,q,c order as SiT unpatchify) B = x.shape[0] x = x.reshape(B, 4, 16, 2, 16, 2).permute(0, 2, 4, 3, 5, 1) # B h w p q c return x.reshape(B, 256, 16) # ----------------------------------------------------------------------------- teachers (iREPA encoders) class TeacherFeatures: """Clean-image teacher: last-layer patch tokens on a 16x16 grid.""" blocks = [0] def __init__(self, enc_name, device="cuda"): from vision_encoder import create_encoder if enc_name.startswith("clip-"): _patch_clip_loader() self.enc = create_encoder(enc_name, torch.device(device), 256) self.enc.eval() self.dim = self.enc.embed_dim @torch.no_grad() def tokens(self, imgs_u8): # [B, 256, 256, 3] uint8 tensor on device x = imgs_u8.permute(0, 3, 1, 2).float() x = self.enc.preprocess(x) with torch.autocast("cuda", dtype=torch.bfloat16): out = self.enc.forward_features(x)["x_norm_patchtokens"] out = out.float() B, T, D = out.shape g = int(round(T ** 0.5)) if g * g != T: raise RuntimeError(f"teacher token count {T} is not a square grid") if g != 16: out = out.transpose(1, 2).reshape(B, D, g, g) out = F.interpolate(out, size=(16, 16), mode="bilinear", align_corners=False) out = out.reshape(B, D, 256).transpose(1, 2) return out # ----------------------------------------------------------------------------- CLIP weights source CLIP_HF_REPO = "timm/vit_large_patch14_clip_224.openai" # OpenAI CLIP ViT-L/14, OpenAI key names def _patch_clip_loader(): """openai/CLIP's download URL (openaipublic.azureedge.net) returns 404. Load the same OpenAI ViT-L/14 weights from the HF copy instead. Verified: tokens are bit-identical to openai/clip-vit-large-patch14.""" import clip if getattr(clip, "_repa_probe_patched", False): return def load(name, device="cpu", jit=False, download_root=None): if name != "ViT-L/14": raise ValueError(f"only ViT-L/14 is mirrored here, got {name}") from clip.model import build_model from huggingface_hub import hf_hub_download from safetensors.torch import load_file sd = load_file(hf_hub_download(CLIP_HF_REPO, "open_clip_model.safetensors")) model = build_model(sd).to(device) if str(device) == "cpu": model.float() return model.eval(), None clip.load = load clip._repa_probe_patched = True