Spaces:
Running on Zero
Running on Zero
File size: 12,315 Bytes
dd43bb2 93083c3 dd43bb2 93083c3 dd43bb2 93083c3 dd43bb2 4ad8b42 dd43bb2 | 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 250 251 252 253 254 255 256 257 | """fwDiT — class-conditional ImageNet generation with cross-step feature forwarding.
Demo for "fwDiT: Boosting Diffusion Transformers with Cross-Step Feature Forwarding"
(Gilo, Rotstein & Litany, arXiv:2612.02632). It runs the authors' released checkpoints with
their reference sampling implementation (vendored `fwdit/` package, MIT): a frozen DiT/SiT
backbone, a psi projector that forwards late-layer features to the next sampling step, phi
LoRA adapters, and the paper's F-CFG feature-space guidance.
"""
import spaces # noqa: F401 — must be imported before torch on ZeroGPU
import json
import threading
import time
from pathlib import Path
import torch
import gradio as gr
from PIL import Image
from fwdit import FwDiT, decode, load_vae, settings
from fwdit.sampling import FeatureForwarding, SOLVERS
torch.backends.cuda.matmul.allow_tf32 = True # the paper's protocol
# ---- the checkpoints (fp32, ~3.3 GB each; preloaded at module scope) ------------------------------------------
MODEL_CHOICES = [
("REPA-SiT-XL/2 @ 256 (best: FID 1.36)", "danielgilo/fwdit-repa-sit-xl-2-256"),
("SiT-XL/2 @ 512", "danielgilo/fwdit-sit-xl-2-512"),
]
DEFAULT_KEY = "danielgilo/fwdit-repa-sit-xl-2-256"
MODELS = {key: FwDiT.from_pretrained(key).to("cuda") for _, key in MODEL_CHOICES}
VAE = load_vae("cuda")
_LABELS = {key: label for label, key in MODEL_CHOICES}
HERE = Path(__file__).parent
CLASS_NAMES = json.loads((HERE / "imagenet_names.json").read_text())
CLASS_CHOICES = [(f"{i:3d} · {n.replace('_', ' ')}", i) for i, n in enumerate(CLASS_NAMES)]
_LOCK = threading.Lock() # sampling mutates the adapter state; serialize runs
def _presets_of(key):
"""Preset names from the checkpoint's config.json, in the file's order."""
return list(MODELS[key].sampling.get("presets", {}).keys())
def _default_preset(key):
return MODELS[key].sampling.get("default") or _presets_of(key)[0]
def _tmin(conf):
return float(conf["fcfg_t_min"]) if conf["fcfg_t_min"] is not None else 0.0
INIT = settings(MODELS[DEFAULT_KEY], _default_preset(DEFAULT_KEY))
class _ProgressingFF(FeatureForwarding):
"""FeatureForwarding that ticks the Gradio progress bar once per sampling step."""
def __init__(self, model, fcfg, cfg, t_min, tick):
super().__init__(model, fcfg, cfg, t_min)
self._tick = tick
def __call__(self, x, t, y):
out = super().__call__(x, t, y)
self._tick()
return out
def _estimate(model_key, class_id, preset, batch=4, s=1.0, fcfg=1.0, fcfg_t_min=0.0,
cfg=1.0, steps=205, seed=0, *args, **kwargs):
"""ZeroGPU duration estimate, calibrated on this Space's A100: ~0.0072 s per
sample-eval for the 256 model, ~0.030 s for the 512 model (linear in batch),
plus a fixed cushion for first-call weight streaming and the VAE decode.
The worst UI case (512 model, 250 steps, batch 8, CFG on) lands ~180 s,
under the free-tier cap.
"""
try:
n = max(1, int(batch or 4))
k = max(10.0, float(steps or 205))
per_eval = 0.030 if "512" in str(model_key) else 0.0072
extra = 0.0
if float(fcfg or 1) > 1: # one unconditional pass over the t >= t_min interval
extra += max(0.25, 1.0 - min(1.0, max(0.0, float(fcfg_t_min or 0))))
if float(cfg or 1) > 1: # output-space CFG doubles every step
extra += 1.0
t = k * (1.0 + extra) * per_eval * n
return int(min(280, t * 1.4 + 10.0))
except Exception:
return 120
@spaces.GPU(duration=_estimate)
def generate(model_key: str, class_id: int, preset: str, batch: int = 4, s: float = 1.0,
fcfg: float = 1.0, fcfg_t_min: float = 0.0, cfg: float = 1.0, steps: int = 205,
seed: int = 0, progress=gr.Progress()):
"""Generate `batch` ImageNet images of one class with an fwDiT checkpoint.
Args:
model_key: HF repo id of the fwDiT checkpoint (REPA-SiT-XL/2 @256 or SiT-XL/2 @512).
class_id: ImageNet class index, 0..999.
preset: sampling preset from the checkpoint's config.json ("fwdit", "fwdit+F-CFG", ...);
the knobs below override the preset's values.
batch: number of images (same class, independent noise).
s: adapter scale (1 = as fine-tuned; 0 = the pre-trained weights).
fcfg: F-CFG feature-space guidance weight w (1 = off).
fcfg_t_min: apply F-CFG only for t >= this, in the paper's time (0 = whole trajectory).
cfg: output-space CFG weight (1 = off).
steps: number of sampling steps.
seed: RNG seed (same seed = same images).
Returns:
A gallery of generated images and an info string with the settings used.
"""
t0 = time.perf_counter()
model_key = str(model_key)
class_id, batch, steps, seed = int(class_id), int(batch), int(steps), int(seed)
model = MODELS[model_key]
knobs = dict(steps=steps, s=float(s), fcfg=float(fcfg), fcfg_t_min=float(fcfg_t_min),
cfg=float(cfg))
conf = settings(model, preset, **knobs) # preset values + UI overrides
total = int(conf["steps"])
seen = 0
def tick():
nonlocal seen
seen += 1
progress((min(seen, total), total), desc="fwDiT sampling")
with _LOCK:
torch.manual_seed(seed)
model.unmerge_adapters()
model.merge_adapters(conf["s"]) # fold s·B·A into the weights (equal up to rounding)
y = torch.full((batch,), class_id, device="cuda", dtype=torch.long)
r = model.image_size // 8
z = torch.randn(batch, model.base.in_channels, r, r, device="cuda")
fn = _ProgressingFF(model, conf["fcfg"], conf["cfg"], conf["fcfg_t_min"], tick)
latents = SOLVERS[model.backbone.solver](fn, z, y, total).float()
images = decode(VAE, latents)
elapsed = time.perf_counter() - t0
fid = conf.get("fid50k")
fid_txt = f" · paper FID-50k {fid:g}" if fid else ""
interval = f", t≥{conf['fcfg_t_min']:g}" if conf["fcfg_t_min"] else ""
info = (f"**{_LABELS[model_key]}** · preset **{preset}**{fid_txt} · {total} steps · "
f"adapter s={conf['s']:g} · F-CFG w={conf['fcfg']:g}{interval} · CFG={conf['cfg']:g}"
f" · class {class_id} ({CLASS_NAMES[class_id].replace('_', ' ')}) · seed {seed}"
f" · {elapsed:.1f} s")
return [Image.fromarray(images[i]) for i in range(batch)], info
def on_model_change(model_key: str):
"""Update the preset list and knobs to the selected checkpoint's default preset."""
key = str(model_key)
presets = _presets_of(key)
default = _default_preset(key)
conf = settings(MODELS[key], default)
return (gr.update(choices=presets, value=default),
gr.update(value=int(conf["steps"])), gr.update(value=float(conf["s"])),
gr.update(value=float(conf["fcfg"])), gr.update(value=_tmin(conf)),
gr.update(value=float(conf["cfg"])),
gr.update(columns=2 if "512" in key else 4))
def on_preset_change(model_key: str, preset: str):
"""Update the knobs to the selected preset's paper values."""
conf = settings(MODELS[str(model_key)], str(preset))
return (gr.update(value=int(conf["steps"])), gr.update(value=float(conf["s"])),
gr.update(value=float(conf["fcfg"])), gr.update(value=_tmin(conf)),
gr.update(value=float(conf["cfg"])))
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
TITLE_MD = """
# fwDiT: Boosting Diffusion Transformers with Cross-Step Feature Forwarding
Class-conditional ImageNet generation with the authors' checkpoints. fwDiT forwards the model's
own late-layer features from one sampling step to the next, so each step costs a **single network
evaluation** — beating guided baselines without any output-space guidance (unguided FID 1.36 with
REPA-SiT-XL/2). F-CFG adds optional feature-space guidance.
[Paper](https://arxiv.org/abs/2612.02632) · [Code](https://github.com/DanielGilo/fwdit) ·
[Models](https://huggingface.co/danielgilo)
"""
with gr.Blocks(title="fwDiT") as demo:
gr.Markdown(TITLE_MD)
with gr.Column(elem_id="col-container"):
with gr.Row():
model_dd = gr.Dropdown(choices=MODEL_CHOICES, value=DEFAULT_KEY,
label="fwDiT checkpoint", filterable=False)
preset_dd = gr.Dropdown(choices=_presets_of(DEFAULT_KEY),
value=_default_preset(DEFAULT_KEY), label="Sampling preset",
allow_custom_value=True, # example rows carry other models' presets
info="paper settings from the checkpoint's config.json")
class_dd = gr.Dropdown(choices=CLASS_CHOICES, value=207, label="ImageNet class",
info="search by name or id · 1000 classes")
with gr.Row():
batch_sl = gr.Slider(1, 8, value=4, step=1, label="Images per run")
run_btn = gr.Button("Generate", variant="primary", size="lg")
gallery = gr.Gallery(label="Generated images", columns=4, height=560, allow_preview=True,
preview=True, object_fit="contain")
info_md = gr.Markdown()
with gr.Accordion("Advanced settings", open=False):
steps_sl = gr.Slider(10, 250, value=int(INIT["steps"]), step=1, label="Sampling steps")
s_sl = gr.Slider(0.0, 1.5, value=float(INIT["s"]), step=0.05,
label="Adapter scale s", info="1 = as fine-tuned; 0 = pre-trained weights")
fcfg_sl = gr.Slider(1.0, 4.0, value=float(INIT["fcfg"]), step=0.05,
label="F-CFG weight w", info="feature-space guidance (1 = off)")
tmin_sl = gr.Slider(0.0, 1.0, value=_tmin(INIT), step=0.05,
label="F-CFG interval t_min", info="apply F-CFG only for t ≥ t_min (0 = whole trajectory)")
cfg_sl = gr.Slider(1.0, 10.0, value=float(INIT["cfg"]), step=0.1,
label="CFG weight γ", info="output-space guidance (1 = off)")
seed_nb = gr.Number(value=0, label="Seed", precision=0)
model_dd.change(on_model_change, inputs=model_dd,
outputs=[preset_dd, steps_sl, s_sl, fcfg_sl, tmin_sl, cfg_sl, gallery])
preset_dd.change(on_preset_change, inputs=[model_dd, preset_dd],
outputs=[steps_sl, s_sl, fcfg_sl, tmin_sl, cfg_sl])
run_btn.click(generate,
inputs=[model_dd, class_dd, preset_dd, batch_sl, s_sl, fcfg_sl, tmin_sl,
cfg_sl, steps_sl, seed_nb],
outputs=[gallery, info_md], api_name="generate", concurrency_limit=1)
REPA = DEFAULT_KEY
S512 = "danielgilo/fwdit-sit-xl-2-512"
gr.Examples(
examples=[
# model, class, preset, batch, s, fcfg, fcfg_t_min, cfg, steps, seed
[REPA, 207, "fwdit+F-CFG", 4, 1.0, 1.6, 0.5, 1.0, 146, 0],
[REPA, 387, "fwdit+F-CFG", 4, 1.0, 1.6, 0.5, 1.0, 146, 0],
[REPA, 88, "fwdit+F-CFG", 4, 1.0, 1.6, 0.5, 1.0, 146, 0],
[REPA, 279, "fwdit+F-CFG", 4, 1.0, 1.6, 0.5, 1.0, 146, 0],
[REPA, 360, "fwdit", 4, 1.0, 1.0, 0.0, 1.0, 205, 0],
[REPA, 979, "fwdit", 4, 1.0, 1.0, 0.0, 1.0, 205, 0],
[S512, 974, "fwdit+AS", 4, 0.95, 1.0, 0.0, 1.0, 205, 0],
[S512, 417, "fwdit+AS", 4, 0.95, 1.0, 0.0, 1.0, 205, 0],
],
inputs=[model_dd, class_dd, preset_dd, batch_sl, s_sl, fcfg_sl, tmin_sl, cfg_sl,
steps_sl, seed_nb],
outputs=[gallery, info_md], fn=generate,
cache_examples=True, cache_mode="lazy",
example_labels=["golden retriever · F-CFG", "lesser panda · F-CFG",
"macaw · F-CFG", "Arctic fox · F-CFG",
"otter · unguided", "valley · unguided",
"geyser · 512px", "balloon · 512px"],
)
if __name__ == "__main__":
demo.launch(mcp_server=True, theme=gr.themes.Citrus(), css=CSS) # theme/css live on launch() in Gradio 6
|