Set 5, phase 1 (step 0): checkpoint verification, ADM FID-4K for SiT, JiT/encoder load checks, report
9d945e1 verified Download set5/code/s0b_jit.py from LamTNguyen/repa-representation-probing: direct link, hf CLI and curl.
- Browser
- Download file 9.1 kB
-
https://huggingface.co/datasets/LamTNguyen/repa-representation-probing/resolve/main/set5/code/s0b_jit.py
- Command line
-
hf download hf://datasets/LamTNguyen/repa-representation-probing/set5/code/s0b_jit.py
-
curl -L -o s0b_jit.py https://huggingface.co/datasets/LamTNguyen/repa-representation-probing/resolve/main/set5/code/s0b_jit.py
9.1 kB
| """Step 0b: JiT checkpoints (LTH14/JiT @ cbc743a, Dropbox folder linked at README L103). | |
| python s0b_jit.py inspect # CPU only: download B/16, L/16, sha256, read keys/epoch/args; H/16 via ranged reads | |
| python s0b_jit.py gpu # GPU: strict-load ema1 into JiT, 16-image grids (no CFG and README CFG) | |
| Keys/epoch/args are read with a stub unpickler that resolves no real globals (no code from the file runs); the | |
| tensors themselves are loaded with torch.load(weights_only=True) (argparse.Namespace allow-listed for 'args'). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import collections | |
| import io | |
| import pickle | |
| import subprocess | |
| import sys | |
| import zipfile | |
| from pathlib import Path | |
| import requests | |
| import torch | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common5 import CKPT, OUT_LOCAL, WORK, disk_free_gb, is_done, log, mark_done, sha256, sync_out, write_json # noqa: E402 | |
| JIT_REPO, JIT_COMMIT = "https://github.com/LTH14/JiT.git", "cbc743a2ada5e9762697da2c83f8c4f8379e8c17" | |
| FOLDER, RLKEY = "https://www.dropbox.com/scl/fo/3ken1avtsd81ip67b9qpi", "14gjrblmljewpl6ygxzlr3njm" | |
| FILES = {"B": ("AGlp4FoN0cIF8nMbS4DN7Ns/jit-b-16", 1_576_057_392), | |
| "L": ("AGEqmJoyiacjYKSG_DnOX-c/jit-l-16", 5_510_063_042), | |
| "H": ("AB5Oa_hLi4LK7TVft6JtpWE/jit-h-16", 11_434_631_825)} | |
| FULL = ("B", "L") # downloaded for probing; H only inspected remotely unless time allows | |
| CFG = {"B": 3.0, "L": 2.4, "H": 2.2} # README eval commands, interval [0.1, 1] | |
| STEP0 = OUT_LOCAL / "step0" | |
| def url(size): | |
| return f"{FOLDER}/{FILES[size][0]}/checkpoint-last.pth?rlkey={RLKEY}&dl=1" | |
| def local(size): | |
| return CKPT / f"jit-{size.lower()}-16.pth" | |
| class RangeFile(io.RawIOBase): | |
| """Seekable read-only view of a remote file through HTTP Range requests (for zipfile).""" | |
| def __init__(self, u): | |
| r = requests.get(u, stream=True, allow_redirects=True, timeout=60) | |
| self.url, self.size, self.pos = r.url, int(r.headers["content-length"]), 0 | |
| r.close() | |
| def seekable(self): | |
| return True | |
| def readable(self): | |
| return True | |
| def tell(self): | |
| return self.pos | |
| def seek(self, off, whence=0): | |
| self.pos = {0: off, 1: self.pos + off, 2: self.size + off}[whence] | |
| return self.pos | |
| def readinto(self, b): | |
| if self.pos >= self.size: | |
| return 0 | |
| end = min(self.size, self.pos + len(b)) - 1 | |
| data = requests.get(self.url, headers={"Range": f"bytes={self.pos}-{end}"}, timeout=120).content | |
| b[:len(data)] = data | |
| self.pos += len(data) | |
| return len(data) | |
| class Stub: | |
| def __init__(self, *a, **k): | |
| self.args = a | |
| def __setstate__(self, state): | |
| self.state = state | |
| class StubUnpickler(pickle.Unpickler): | |
| """Structure-only unpickler: every global except OrderedDict becomes an inert Stub subclass.""" | |
| def find_class(self, mod, name): | |
| if (mod, name) == ("collections", "OrderedDict"): | |
| return collections.OrderedDict | |
| return type(f"{mod}.{name}", (Stub,), {}) | |
| def persistent_load(self, pid): | |
| return ("storage", pid[2] if len(pid) > 2 else None) | |
| def structure(fileobj): | |
| z = zipfile.ZipFile(fileobj) | |
| pkl = [n for n in z.namelist() if n.endswith("data.pkl")][0] | |
| obj = StubUnpickler(io.BytesIO(z.read(pkl))).load() | |
| rec = {"zip_entries": len(z.namelist()), "pickle": pkl, "top_keys": list(obj.keys())} | |
| for k in ("epoch",): | |
| if k in obj: | |
| rec[k] = obj[k] | |
| if "args" in obj: | |
| a = obj["args"] | |
| st = getattr(a, "state", None) | |
| rec["args"] = st if isinstance(st, dict) else repr(a) | |
| for k in ("model", "model_ema1", "model_ema2"): | |
| if k in obj and isinstance(obj[k], dict): | |
| rec[f"{k}_n_tensors"] = len(obj[k]) | |
| rec[f"{k}_first_keys"] = list(obj[k])[:3] | |
| return rec | |
| def inspect(): | |
| STEP0.mkdir(parents=True, exist_ok=True) | |
| for size in FILES: | |
| rel = f"step0/jit_{size}_inspect.done" | |
| if is_done(rel): | |
| continue | |
| rec = {"model": f"JiT-{size}/16", "url": url(size), "expected_bytes": FILES[size][1]} | |
| if True: # ranged zip reads failed on Dropbox's redirect for H; download every /16 file, delete H after | |
| p = local(size) | |
| if not p.exists() or p.stat().st_size != FILES[size][1]: | |
| log(f"[JiT-{size}] downloading ({FILES[size][1]/1e9:.1f} GB), free {disk_free_gb():.0f} GB") | |
| subprocess.run(["curl", "-sSfL", "--retry", "10", "-C", "-", "-o", str(p), url(size)], check=True) | |
| rec.update(size_bytes=p.stat().st_size, sha256=sha256(p)) | |
| rec["structure"] = structure(str(p)) | |
| torch.serialization.add_safe_globals([argparse.Namespace]) | |
| ck = torch.load(p, map_location="cpu", weights_only=True) | |
| m, e1, e2 = ck["model"], ck["model_ema1"], ck["model_ema2"] | |
| rec["weights_only_load"] = True | |
| rec["n_params_model"] = int(sum(v.numel() for v in m.values())) | |
| rec["max_abs_diff_model_vs_ema1"] = float(max((m[k].float() - e1[k].float()).abs().max() for k in m)) | |
| rec["max_abs_diff_ema1_vs_ema2"] = float(max((e1[k].float() - e2[k].float()).abs().max() for k in m)) | |
| rec["y_embedder_rows"] = [tuple(v.shape) for k, v in m.items() if "y_embedder" in k] | |
| del ck, m, e1, e2 | |
| if size not in FULL: | |
| p.unlink() | |
| rec["deleted_after_inspection"] = True | |
| else: | |
| log(f"[JiT-{size}] ranged read of the pickle only") | |
| rf = RangeFile(url(size)) | |
| rec["size_bytes"] = rf.size | |
| rec["structure"] = structure(io.BufferedReader(rf, buffer_size=1 << 20)) | |
| write_json(STEP0 / f"jit_{size}_inspect.json", rec) | |
| log(f"[JiT-{size}] keys {rec['structure']['top_keys']} epoch {rec['structure'].get('epoch')}") | |
| mark_done(rel) | |
| def jit_code(): | |
| d = WORK / "jit_official" | |
| if not (d / "model_jit.py").exists(): | |
| subprocess.run(["git", "clone", "-q", JIT_REPO, str(d)], check=True) | |
| subprocess.run(["git", "-C", str(d), "checkout", "-q", JIT_COMMIT], check=True) | |
| if str(d) not in sys.path: | |
| sys.path.insert(0, str(d)) | |
| from denoiser import Denoiser | |
| return Denoiser | |
| def gpu(): | |
| import numpy as np | |
| from PIL import Image | |
| Denoiser = jit_code() | |
| torch.serialization.add_safe_globals([argparse.Namespace]) | |
| classes = [88, 207, 279, 291, 360, 387, 417, 812, 933, 963, 970, 980, 1, 130, 323, 954] | |
| for size in FULL: | |
| rel = f"step0/jit_{size}_gpu.done" | |
| if is_done(rel): | |
| continue | |
| p = local(size) | |
| if not p.exists() or p.stat().st_size != FILES[size][1]: # new VM: re-download and check against step 0b | |
| subprocess.run(["curl", "-sSfL", "--retry", "10", "-C", "-", "-o", str(p), url(size)], check=True) | |
| import json | |
| rec0 = OUT_LOCAL / "step0" / f"jit_{size}_inspect.json" | |
| if not rec0.exists(): | |
| from common5 import OUT_DRIVE | |
| rec0 = OUT_DRIVE / "step0" / f"jit_{size}_inspect.json" | |
| if sha256(p) != json.loads(rec0.read_text())["sha256"]: | |
| raise RuntimeError(f"JiT-{size}: sha256 differs from the step-0b record") | |
| 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) | |
| res = den.load_state_dict(ck["model_ema1"], strict=True) | |
| rec = {"model": f"JiT-{size}/16", "strict_load_ema1": str(res), | |
| "n_params_net": int(sum(p.numel() for p in den.net.parameters())), | |
| "n_blocks": len(den.net.blocks), "in_context_start": getattr(den.net, "in_context_start", None), | |
| "in_context_len": getattr(den.net, "in_context_len", None)} | |
| del ck | |
| den = den.cuda().eval() | |
| y = torch.tensor(classes, device="cuda") | |
| for cfg in (1.0, CFG[size]): | |
| den.cfg_scale = cfg | |
| torch.manual_seed(0) | |
| x = den.generate(y) | |
| img = ((x.clamp(-1, 1) + 1) * 127.5).round().to(torch.uint8).permute(0, 2, 3, 1).cpu().numpy() | |
| rows = [np.concatenate(img[r * 4:(r + 1) * 4], 1) for r in range(4)] | |
| Image.fromarray(np.concatenate(rows, 0)).save(STEP0 / f"jit_{size}_grid_cfg{cfg}.png") | |
| rec["grid_classes"] = classes | |
| rec["sampler"] = "heun 50 steps, CFG interval [0.1, 1]; grids at cfg 1.0 and README cfg" | |
| write_json(STEP0 / f"jit_{size}_gpu.json", rec) | |
| del den | |
| torch.cuda.empty_cache() | |
| mark_done(rel) | |
| sync_out() | |
| if __name__ == "__main__": | |
| {"inspect": inspect, "gpu": gpu}[sys.argv[1]]() | |