File size: 9,098 Bytes
9d945e1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | """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
@torch.no_grad()
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]]()
|