File size: 11,720 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""Step 0a: inspect nyu-visionx/SiT-collections checkpoints, sample class-conditionally, ADM-suite eval.

Sampler = SiT's own sample_ddp.py defaults for the paper's SDE numbers: Linear path, velocity prediction,
Euler-Maruyama, diffusion-form sigma, norm 1.0, last step Mean (size 0.04), 250 steps, no CFG (model.forward),
sd-vae-ft-ema decoder, latent / 0.18215.  Deviation from sample_ddp.py (fp32/TF32): the network forward runs
under bf16 autocast for speed; sampler state, noise and VAE decode stay fp32.
Labels: N/1000 per class (balanced; the paper draws them uniformly at random), fixed seeds per batch.
Evaluation: the ADM suite (openai/guided-diffusion evaluations/evaluator.py, TensorFlow, reference batch
VIRTUAL_imagenet256_labeled.npz), as in the SiT paper: IS, FID, sFID, Precision, Recall.  This is FID-N (step 0
uses N=4000 by the user's choice; S also has N=10000 and its 4-per-class subset), not comparable in level to FID-50K
(fewer samples bias FID upward).  Note: per the SiT maintainer (willisma/SiT issue #42, 2025-11-05) the HF S/B/L
files are trained 800K steps, not the paper's 400K.

Usage on the VM:  FID_N=4000 python s0a_sit.py [S,B,L,XL]   (N = samples, 1000 | N)
Resumable: a size with out/step0/sit_<size>_n<N>.done is skipped; finished sample batches are not regenerated.
"""
from __future__ import annotations

import importlib.util
import os
import subprocess
import sys
import time
from pathlib import Path

import numpy as np
import torch
from PIL import Image

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

HF_REPO = "nyu-visionx/SiT-collections"
SIT_REPO, SIT_COMMIT = "https://github.com/willisma/SiT.git", "cbde832a40b153ccc79603412409da9c9b0c568c"
DROPBOX_XL = ("https://www.dl.dropboxusercontent.com/scl/fi/as9oeomcbub47de5g4be0/SiT-XL-2-256.pt"
              "?rlkey=uxzxmpicu46coq3msb17b9ofa&dl=0")
EVAL_DIR = WORK / "fid"
REF = EVAL_DIR / "VIRTUAL_imagenet256_labeled.npz"
ADM_COMMIT = "ed2f41c4d7b37d231b3688fbf4056b46f207cf24"
ADM_URL = f"https://raw.githubusercontent.com/openai/guided-diffusion/{ADM_COMMIT}/evaluations/evaluator.py"
N = int(os.environ.get("FID_N", 10000))
STEPS = 250
BATCH = {"S": 500, "B": 500, "L": 250, "XL": 250}
SDE = dict(sampling_method="Euler", diffusion_form="sigma", diffusion_norm=1.0, last_step="Mean",
           last_step_size=0.04, num_steps=STEPS)
STEP0 = OUT_LOCAL / "step0"


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  # noqa: F401  (willisma/SiT models.py)
    from transport import Sampler, create_transport
    return models, Sampler, create_transport


def inspect(obj):
    """What is in the file: a bare state dict, or a train.py checkpoint with model/ema/opt/args/steps."""
    info = {"container": type(obj).__name__}
    if isinstance(obj, dict) and obj and all(torch.is_tensor(v) for v in obj.values()):
        info.update(kind="bare state_dict", n_tensors=len(obj), n_params=int(sum(v.numel() for v in obj.values())),
                    dtypes=sorted({str(v.dtype) for v in obj.values()}))
        return obj, info
    keys = list(obj.keys())
    info.update(kind="checkpoint dict", top_keys=keys)
    for k in ("steps", "train_steps", "step", "epoch", "args"):
        if k in obj:
            info[k] = obj[k] if not hasattr(obj[k], "__dict__") else vars(obj[k])
    sd = obj["ema"] if "ema" in obj else obj.get("model", obj)
    info["used_key"] = "ema" if "ema" in obj else ("model" if "model" in obj else None)
    info["n_params"] = int(sum(v.numel() for v in sd.values()))
    return sd, info


def fetch(size):
    from huggingface_hub import hf_hub_download
    fn = f"SiT-{size}-2-256.pt"
    p = Path(hf_hub_download(HF_REPO, fn, local_dir=str(CKPT)))
    return p


def compare_xl_dropbox(hf_path, hf_sd, rec):
    """Is HF SiT-XL-2-256.pt the same file as the original 7M-step Dropbox release?"""
    dp = CKPT / "SiT-XL-2-256.dropbox.pt"
    if not dp.exists():
        subprocess.run(["curl", "-sSL", "--retry", "5", "-o", str(dp), DROPBOX_XL], check=True)
    rec["dropbox_xl"] = {"size_bytes": dp.stat().st_size, "sha256": sha256(dp)}
    rec["dropbox_xl"]["identical_file"] = rec["dropbox_xl"]["sha256"] == rec["sha256"]
    if not rec["dropbox_xl"]["identical_file"]:
        dsd, dinfo = inspect(torch.load(dp, map_location="cpu", weights_only=True))
        same_keys = set(dsd) == set(hf_sd)
        maxdiff = max(float((dsd[k].float() - hf_sd[k].float()).abs().max()) for k in hf_sd) if same_keys else None
        rec["dropbox_xl"].update(info=dinfo, same_keys=same_keys, max_abs_diff=maxdiff)
    dp.unlink()


def bf16_forward(model):
    """Network forward under bf16 autocast; the sampler state, noise and VAE stay fp32.  fp32/TF32 ran at ~16
    TFLOP/s on the A100 (SiT-S: 1.6 min per 500 samples; XL would take ~10 h for 10K), so step 0 uses bf16."""
    last = {}

    def fwd(x, t, y):
        # SiT's Euler-Maruyama drift calls the model twice per step with the same (x, t) objects (drift and score);
        # return the cached output for the second call.  Results are unchanged; compute halves.
        if last.get("x") is x and last.get("t") is t:
            return last["out"]
        with torch.autocast("cuda", dtype=torch.bfloat16):
            out = model.forward(x, t, y).float()
        last.update(x=x, t=t, out=out)
        return out
    return fwd


@torch.no_grad()
def sample_all(size, model, Sampler, create_transport, vae, outdir):
    transport = create_transport("Linear", "velocity", None, None, None)
    sample_fn = Sampler(transport).sample_sde(**SDE)
    rng = np.random.default_rng(0)
    labels = rng.permutation(np.repeat(np.arange(1000), N // 1000))
    bs = BATCH[size]
    t0 = time.time()
    for bi in range(int(np.ceil(N / bs))):
        idx = np.arange(bi * bs, min(N, (bi + 1) * bs))
        if all((outdir / f"{i:05d}.png").exists() for i in idx):
            continue
        torch.manual_seed(1000 + bi)
        y = torch.as_tensor(labels[idx], device="cuda")
        z = torch.randn(len(idx), 4, 32, 32, device="cuda")
        fwd = bf16_forward(model)
        x = sample_fn(z, fwd, y=y)[-1]
        img = torch.cat([vae.decode(c / 0.18215).sample for c in x.split(50)])  # chunked: full-batch decode OOMs
        img = ((img + 1) * 127.5).clamp(0, 255).round().to(torch.uint8).permute(0, 2, 3, 1).cpu().numpy()
        for i, a in zip(idx, img):
            Image.fromarray(a).save(outdir / f"{i:05d}.png")
        done = (bi + 1) * bs
        el = time.time() - t0
        log(f"[{size}] {min(done, N)}/{N} samples, {el/60:.1f} min")
    return labels


def pack_npz(outdir, idx, path):
    """ADM sample batch: arr_0 = uint8 [N, 256, 256, 3]."""
    arr = np.stack([np.asarray(Image.open(outdir / f"{i:05d}.png").convert("RGB")) for i in idx])
    np.savez(path, arr_0=arr)


def adm_eval(npz):
    """Run guided-diffusion's TensorFlow evaluator in its own process; parse IS, FID, sFID, Precision, Recall."""
    ev = EVAL_DIR / "evaluator.py"
    if not ev.exists():
        subprocess.run(["curl", "-sSfL", "-o", str(ev), ADM_URL], check=True)
    while not (EVAL_DIR / "ref.sha256").exists():  # reference batch still downloading
        time.sleep(20)
    env = dict(os.environ, TF_FORCE_GPU_ALLOW_GROWTH="true", TF_CPP_MIN_LOG_LEVEL="2")
    r = subprocess.run([sys.executable, str(ev), str(REF), str(npz)], cwd=EVAL_DIR, capture_output=True, text=True,
                       env=env)
    out = {}
    for line in r.stdout.splitlines():
        for k in ("Inception Score", "FID", "sFID", "Precision", "Recall"):
            if line.startswith(k + ":"):
                out[k] = float(line.split(":", 1)[1])
    if "FID" not in out:
        raise RuntimeError(f"ADM evaluator failed: {r.stdout[-1500:]} {r.stderr[-1500:]}")
    return out


def grid(outdir, labels, path, n=64):
    first = {}
    for i, c in enumerate(labels):
        if c not in first:
            first[c] = i
        if len(first) == n:
            break
    ims = [np.asarray(Image.open(outdir / f"{i:05d}.png")) for i in first.values()]
    rows = [np.concatenate(ims[r * 8:(r + 1) * 8], 1) for r in range(8)]
    Image.fromarray(np.concatenate(rows, 0)).resize((1024, 1024), Image.BICUBIC).save(path)
    return [int(c) for c in first]


def run(size, models, Sampler, create_transport, vae):
    tag = f"sit_{size}_n{N}"
    rel = f"step0/{tag}.done"
    if is_done(rel):
        log(f"[{size}] done, skip")
        return
    log(f"[{size}] disk free {disk_free_gb():.0f} GB")
    p = fetch(size)
    rec = {"model": f"SiT-{size}/2", "hf_repo": HF_REPO, "file": p.name, "size_bytes": p.stat().st_size,
           "sha256": sha256(p)}
    sd, rec["contents"] = inspect(torch.load(p, map_location="cpu", weights_only=True))
    out_ch = sd["final_layer.linear.weight"].shape[0] // 4
    rec["learn_sigma"] = out_ch == 8
    model = models.SiT_models[f"SiT-{size}/2"](input_size=32, num_classes=1000, learn_sigma=rec["learn_sigma"])
    model.load_state_dict(sd, strict=True)
    rec["strict_load"] = True
    rec["y_embedder_rows"] = int(sd["y_embedder.embedding_table.weight"].shape[0])
    if size == "XL":
        compare_xl_dropbox(p, sd, rec)
    model = model.cuda().eval()
    outdir = WORK / "samples" / tag
    outdir.mkdir(parents=True, exist_ok=True)
    t0 = time.time()
    labels = sample_all(size, model, Sampler, create_transport, vae, outdir)
    rec["sample_seconds"] = round(time.time() - t0)
    rec["grid_classes"] = grid(outdir, labels, STEP0 / f"{tag}_grid.png")
    del model
    torch.cuda.empty_cache()  # free the GPU before the TensorFlow evaluator runs (one GPU job at a time)
    evals = {}
    subsets = {N: np.arange(N)}
    if N > 4000:  # also FID-4K from the same samples: the first 4 of each class
        k = np.concatenate([np.flatnonzero(labels == c)[:4] for c in range(1000)])
        subsets[4000] = np.sort(k)
    for n, idx in subsets.items():
        npz = WORK / "samples" / f"{tag}_eval{n}.npz"
        pack_npz(outdir, idx, npz)
        evals[f"n{n}"] = adm_eval(npz)
        npz.unlink()
        log(f"[{size}] ADM eval N={n}: {evals[f'n{n}']}")
    rec.update(adm_eval=evals, n_samples=N, labels=f"{N // 1000} per class, seed 0", sampler=SDE, cfg=1.0,
               vae="stabilityai/sd-vae-ft-ema", precision="network bf16 autocast; sampler/VAE fp32",
               evaluator=f"openai/guided-diffusion evaluations/evaluator.py @ {ADM_COMMIT[:7]}, reference "
                         "VIRTUAL_imagenet256_labeled.npz", torch=torch.__version__, gpu=torch.cuda.get_device_name())
    write_json(STEP0 / f"{tag}.json", rec)
    p.unlink()  # checkpoint no longer needed for step 0; re-downloaded for probing
    subprocess.run(["rm", "-rf", str(outdir)])
    mark_done(rel, {"fid": evals[f"n{N}"].get("FID"), "n": N})


def main():
    sizes = (sys.argv[1] if len(sys.argv) > 1 else "S,B,L,XL").split(",")
    torch.set_float32_matmul_precision("high")
    torch.backends.cudnn.allow_tf32 = True
    STEP0.mkdir(parents=True, exist_ok=True)
    models, Sampler, create_transport = sit_code()
    from diffusers.models import AutoencoderKL
    vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-ema").cuda().eval()
    for size in sizes:
        run(size, models, Sampler, create_transport, vae)
        sync_out()
    log("all done")


if __name__ == "__main__":
    main()