Spaces:
Running on Zero
Running on Zero
fwDiT demo: REPA-256 + SiT-512 checkpoints, authors' sampler, presets/knobs, examples
Browse filesFiles changed (11)
- README.md+30-6
- app.pyAdded+247
- fwdit/__init__.pyAdded+5
- fwdit/backbones/__init__.pyAdded+52
- fwdit/backbones/dit.pyAdded+373
- fwdit/backbones/repa.pyAdded+395
- fwdit/backbones/sit.pyAdded+375
- fwdit/model.pyAdded+161
- fwdit/sampling.pyAdded+165
- imagenet_names.jsonAdded+1
- requirements.txtAdded+8
12345678910111213---title: Fwdit Class Conditional Imagegenemoji: 📈colorFrom: pinkcolorTo: pinksdk: gradiosdk_version: 6.33.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334353637---title: fwDiTemoji: 🔄colorFrom: pinkcolorTo: graysdk: gradiosdk_version: 6.33.0app_file: app.pyshort_description: Cross-step feature forwarding for diffusion transformerspython_version: "3.12"startup_duration_timeout: 1h---# fwDiT: Boosting Diffusion Transformers with Cross-Step Feature ForwardingClass-conditional ImageNet generation with the authors' released fwDiT 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 withoutany output-space guidance (unguided FID-50k 1.36 with REPA-SiT-XL/2). The demo runs thereference implementation (vendored `fwdit/` package) with the paper's solvers(DDPM ancestral for DiT, Euler–Maruyama SDE for SiT/REPA) and exposes the method's knobs:adapter scale `s`, F-CFG feature-space guidance weight `w` with its interval `t_min`,output-space CFG, steps, and seed.Two checkpoints are preloaded:| Checkpoint | Presets (paper FID-50k) ||---|---|| `danielgilo/fwdit-repa-sit-xl-2-256` | fwdit (205 steps) · 1.36 · fwdit+F-CFG (146 steps) · 1.30 || `danielgilo/fwdit-sit-xl-2-512` | fwdit+AS (205 steps, s=0.95) · 2.98 · fwdit · 3.04 |The remaining released variants (SiT-XL/2 @256 and DiT-XL/2 @256) are not preloaded to staywithin the Space's memory budget; the DiT variant is additionally CC BY-NC 4.0.**Paper**: [arXiv:2612.02632](https://arxiv.org/abs/2612.02632) ·**Code**: [github.com/DanielGilo/fwdit](https://github.com/DanielGilo/fwdit) (MIT) ·**Models**: [huggingface.co/danielgilo](https://huggingface.co/danielgilo) (MIT)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""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 withtheir reference sampling implementation (vendored `fwdit/` package, MIT): a frozen DiT/SiTbackbone, a psi projector that forwards late-layer features to the next sampling step, phiLoRA adapters, and the paper's F-CFG feature-space guidance."""import spaces # noqa: F401 — must be imported before torch on ZeroGPU
import jsonimport threadingimport timefrom pathlib import Path
import torchimport gradio as grfrom PIL import Image
from fwdit import FwDiT, decode, load_vae, settingsfrom 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__).parentCLASS_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: cold start + per-step cost (calibrated on the live Space).""" try: per_step = 1.7 if "512" in str(model_key) else 0.55 # seconds / step, batch ~4 if float(fcfg or 1) > 1: per_step *= 2.2 # the unconditional passes inside the F-CFG interval if float(cfg or 1) > 1: per_step *= 2.0 n = 1 + 0.05 * max(0, int(batch or 4) - 1) return min(280, int(35 + per_step * float(steps or 205) * n)) except Exception: return 200
@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'sown late-layer features from one sampling step to the next, so each step costs a **single networkevaluation** — beating guided baselines without any output-space guidance (unguided FID 1.36 withREPA-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", 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 612345"""fwDiT: Boosting Diffusion Transformers with Cross-Step Feature Forwarding."""from .model import FwDiTfrom .sampling import FeatureForwarding, sample, settings, load_vae, decode
__all__ = ["FwDiT", "FeatureForwarding", "sample", "settings", "load_vae", "decode"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""The three pre-trained backbones and the few facts fwDiT needs about each.
dit.py, sit.py and repa.py are the upstream model definitions, verbatim. All three expose the same pieces:x_embedder + pos_embed (E), t_embedder + y_embedder (the conditioning c), blocks, final_layer + unpatchify (the head).What differs is collected in `Backbone`: out_channels channels of the head's output that the solver reads (DiT: noise and learned variance; SiT: velocity [the learned-sigma half is dropped]; REPA: velocity) solver the sampler the backbone was trained / evaluated with (fwdit.sampling) progress(t) the solver's time t mapped to the paper's convention (0 = noise, 1 = data), for the F-CFG interval"""import mathimport numpy as npimport torchimport torch.nn as nn
def ddpm_alphas_cumprod(T=1000): """DiT's linear beta schedule (betas 1e-4 .. 0.02 over T = 1000 steps), cumulative product of 1 - beta (float64).""" betas = np.linspace(1000 / T * 0.0001, 1000 / T * 0.02, T, dtype=np.float64) return np.cumprod(1.0 - betas)
class Backbone: def __init__(self, name, image_size, num_classes, learn_sigma): family, arch = name.split("-", 1) if name.startswith("REPA-") else (name.split("-")[0], name) self.family, size = family, image_size // 8 # SD-VAE latents: 8x downsampling, 4 channels if family == "DiT": from .dit import DiT_models self.net = DiT_models[arch](input_size=size, num_classes=num_classes) self.solver, self.out_channels = "ddpm", 2 * self.net.in_channels abar = torch.tensor(ddpm_alphas_cumprod()) self._t_of_step = abar.sqrt() / (abar.sqrt() + (1 - abar).sqrt()) # flow-matching t with the same SNR elif family == "SiT": from .sit import SiT_models self.net = SiT_models[arch](input_size=size, num_classes=num_classes, learn_sigma=learn_sigma) self.solver, self.out_channels = "sde-sit", self.net.in_channels elif family == "REPA": from .repa import SiT_models # REPA's alignment projectors (z_dims) are a training-time head; without them the network is unchanged self.net = SiT_models[arch](input_size=size, num_classes=num_classes, use_cfg=True, z_dims=[], fused_attn=False, qk_norm=False) self.solver, self.out_channels = "sde-repa", self.net.in_channels else: raise ValueError(f"unknown backbone {name!r}: DiT-*, SiT-* or REPA-SiT-*") self.null_label = num_classes
def progress(self, t): """The paper's time (0 = noise, 1 = data). DiT: the flow-matching t with the same SNR as DDPM step t (SNR = abar / (1 - abar) = (t / (1 - t))^2, so t >= 0.5 <=> abar >= 0.5); SiT: t; REPA: 1 - t.""" if self.family == "DiT": return self._t_of_step.to(t.device)[t.long()] return t.double() if self.family == "SiT" else 1 - t.double()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373# Verbatim copy of https://github.com/facebookresearch/DiT/blob/ed81ce2229091fd4ecc9a223645f95cf379d582b/models.py (model definitions only).# License: CC BY-NC 4.0 (Meta Platforms, Inc.), see third_party/LICENSES/DiT.txt. Not modified.
# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------
import torchimport torch.nn as nnimport numpy as npimport mathfrom timm.models.vision_transformer import PatchEmbed, Attention, Mlp
def modulate(x, shift, scale): return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
################################################################################## Embedding Layers for Timesteps and Class Labels ##################################################################################
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """ def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t): t_freq = self.timestep_embedding(t, self.frequency_embedding_size) t_emb = self.mlp(t_freq) return t_emb
class LabelEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """ def __init__(self, num_classes, hidden_size, dropout_prob): super().__init__() use_cfg_embedding = dropout_prob > 0 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) self.num_classes = num_classes self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob else: drop_ids = force_drop_ids == 1 labels = torch.where(drop_ids, self.num_classes, labels) return labels
def forward(self, labels, train, force_drop_ids=None): use_dropout = self.dropout_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): labels = self.token_drop(labels, force_drop_ids) embeddings = self.embedding_table(labels) return embeddings
################################################################################## Core DiT Model ##################################################################################
class DiTBlock(nn.Module): """ A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning. """ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True) )
def forward(self, x, c): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) return x
class FinalLayer(nn.Module): """ The final layer of DiT. """ def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True) )
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class DiT(nn.Module): """ Diffusion model with a Transformer backbone. """ def __init__( self, input_size=32, patch_size=2, in_channels=4, hidden_size=1152, depth=28, num_heads=16, mlp_ratio=4.0, class_dropout_prob=0.1, num_classes=1000, learn_sigma=True, ): super().__init__() self.learn_sigma = learn_sigma self.in_channels = in_channels self.out_channels = in_channels * 2 if learn_sigma else in_channels self.patch_size = patch_size self.num_heads = num_heads
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) self.t_embedder = TimestepEmbedder(hidden_size) self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) num_patches = self.x_embedder.num_patches # Will use fixed sin-cos embedding: self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
self.blocks = nn.ModuleList([ DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth) ]) self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize (and freeze) pos_embed by sin-cos embedding: pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w = self.x_embedder.proj.weight.data nn.init.xavier_uniform_(w.view([w.shape[0], -1])) nn.init.constant_(self.x_embedder.proj.bias, 0)
# Initialize label embedding table: nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in DiT blocks: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers: nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
def unpatchify(self, x): """ x: (N, T, patch_size**2 * C) imgs: (N, H, W, C) """ c = self.out_channels p = self.x_embedder.patch_size[0] h = w = int(x.shape[1] ** 0.5) assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) x = torch.einsum('nhwpqc->nchpwq', x) imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) return imgs
def forward(self, x, t, y): """ Forward pass of DiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N,) tensor of class labels """ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2 t = self.t_embedder(t) # (N, D) y = self.y_embedder(y, self.training) # (N, D) c = t + y # (N, D) for block in self.blocks: x = block(x, c) # (N, T, D) x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) x = self.unpatchify(x) # (N, out_channels, H, W) return x
def forward_with_cfg(self, x, t, y, cfg_scale): """ Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance. """ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb half = x[: len(x) // 2] combined = torch.cat([half, half], dim=0) model_out = self.forward(combined, t, y) # For exact reproducibility reasons, we apply classifier-free guidance on only # three channels by default. The standard approach to cfg applies it to all channels. # This can be done by uncommenting the following line and commenting-out the line following that. # eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] eps, rest = model_out[:, :3], model_out[:, 3:] cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) eps = torch.cat([half_eps, half_eps], dim=0) return torch.cat([eps, rest], dim=1)
################################################################################## Sine/Cosine Positional Embedding Functions ################################################################################### https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): """ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) """ grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0)
grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token and extra_tokens > 0: pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) """ assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=np.float64) omega /= embed_dim / 2. omega = 1. / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2) emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) return emb
################################################################################## DiT Configs ##################################################################################
def DiT_XL_2(**kwargs): return DiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
def DiT_XL_4(**kwargs): return DiT(depth=28, hidden_size=1152, patch_size=4, num_heads=16, **kwargs)
def DiT_XL_8(**kwargs): return DiT(depth=28, hidden_size=1152, patch_size=8, num_heads=16, **kwargs)
def DiT_L_2(**kwargs): return DiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
def DiT_L_4(**kwargs): return DiT(depth=24, hidden_size=1024, patch_size=4, num_heads=16, **kwargs)
def DiT_L_8(**kwargs): return DiT(depth=24, hidden_size=1024, patch_size=8, num_heads=16, **kwargs)
def DiT_B_2(**kwargs): return DiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
def DiT_B_4(**kwargs): return DiT(depth=12, hidden_size=768, patch_size=4, num_heads=12, **kwargs)
def DiT_B_8(**kwargs): return DiT(depth=12, hidden_size=768, patch_size=8, num_heads=12, **kwargs)
def DiT_S_2(**kwargs): return DiT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)
def DiT_S_4(**kwargs): return DiT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)
def DiT_S_8(**kwargs): return DiT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)
DiT_models = { 'DiT-XL/2': DiT_XL_2, 'DiT-XL/4': DiT_XL_4, 'DiT-XL/8': DiT_XL_8, 'DiT-L/2': DiT_L_2, 'DiT-L/4': DiT_L_4, 'DiT-L/8': DiT_L_8, 'DiT-B/2': DiT_B_2, 'DiT-B/4': DiT_B_4, 'DiT-B/8': DiT_B_8, 'DiT-S/2': DiT_S_2, 'DiT-S/4': DiT_S_4, 'DiT-S/8': DiT_S_8,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395# Verbatim copy of https://github.com/sihyun-yu/REPA/blob/2b8c181/models/sit.py (model definitions only).# License: MIT (Sihyun Yu), see third_party/LICENSES/REPA.txt. Not modified.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------
import torchimport torch.nn as nnimport numpy as npimport mathfrom timm.models.vision_transformer import PatchEmbed, Attention, Mlp
def build_mlp(hidden_size, projector_dim, z_dim): return nn.Sequential( nn.Linear(hidden_size, projector_dim), nn.SiLU(), nn.Linear(projector_dim, projector_dim), nn.SiLU(), nn.Linear(projector_dim, z_dim), )
def modulate(x, shift, scale): return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
################################################################################## Embedding Layers for Timesteps and Class Labels ################################################################################## class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """ def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size @staticmethod def positional_embedding(t, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t): self.timestep_embedding = self.positional_embedding t_freq = self.timestep_embedding(t, dim=self.frequency_embedding_size).to(t.dtype) t_emb = self.mlp(t_freq) return t_emb
class LabelEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """ def __init__(self, num_classes, hidden_size, dropout_prob): super().__init__() use_cfg_embedding = dropout_prob > 0 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) self.num_classes = num_classes self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob else: drop_ids = force_drop_ids == 1 labels = torch.where(drop_ids, self.num_classes, labels) return labels
def forward(self, labels, train, force_drop_ids=None): use_dropout = self.dropout_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): labels = self.token_drop(labels, force_drop_ids) embeddings = self.embedding_table(labels) return embeddings
################################################################################## Core SiT Model ##################################################################################
class SiTBlock(nn.Module): """ A SiT block with adaptive layer norm zero (adaLN-Zero) conditioning. """ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = Attention( hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=block_kwargs["qk_norm"] ) if "fused_attn" in block_kwargs.keys(): self.attn.fused_attn = block_kwargs["fused_attn"] self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp( in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0 ) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True) )
def forward(self, x, c): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( self.adaLN_modulation(c).chunk(6, dim=-1) ) x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
return x
class FinalLayer(nn.Module): """ The final layer of SiT. """ def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True) )
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x)
return x
class SiT(nn.Module): """ Diffusion model with a Transformer backbone. """ def __init__( self, path_type='edm', input_size=32, patch_size=2, in_channels=4, hidden_size=1152, decoder_hidden_size=768, encoder_depth=8, depth=28, num_heads=16, mlp_ratio=4.0, class_dropout_prob=0.1, num_classes=1000, use_cfg=False, z_dims=[768], projector_dim=2048, **block_kwargs # fused_attn ): super().__init__() self.path_type = path_type self.in_channels = in_channels self.out_channels = in_channels self.patch_size = patch_size self.num_heads = num_heads self.use_cfg = use_cfg self.num_classes = num_classes self.z_dims = z_dims self.encoder_depth = encoder_depth
self.x_embedder = PatchEmbed( input_size, patch_size, in_channels, hidden_size, bias=True ) self.t_embedder = TimestepEmbedder(hidden_size) # timestep embedding type self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) num_patches = self.x_embedder.num_patches # Will use fixed sin-cos embedding: self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
self.blocks = nn.ModuleList([ SiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, **block_kwargs) for _ in range(depth) ]) self.projectors = nn.ModuleList([ build_mlp(hidden_size, projector_dim, z_dim) for z_dim in z_dims ]) self.final_layer = FinalLayer(decoder_hidden_size, patch_size, self.out_channels) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize (and freeze) pos_embed by sin-cos embedding: pos_embed = get_2d_sincos_pos_embed( self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5) ) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w = self.x_embedder.proj.weight.data nn.init.xavier_uniform_(w.view([w.shape[0], -1])) nn.init.constant_(self.x_embedder.proj.bias, 0)
# Initialize label embedding table: nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in SiT blocks: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers: nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
def unpatchify(self, x, patch_size=None): """ x: (N, T, patch_size**2 * C) imgs: (N, H, W, C) """ c = self.out_channels p = self.x_embedder.patch_size[0] if patch_size is None else patch_size h = w = int(x.shape[1] ** 0.5) assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) x = torch.einsum('nhwpqc->nchpwq', x) imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) return imgs def forward(self, x, t, y, return_logvar=False): """ Forward pass of SiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N,) tensor of class labels """ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2 N, T, D = x.shape
# timestep and class embedding t_embed = self.t_embedder(t) # (N, D) y = self.y_embedder(y, self.training) # (N, D) c = t_embed + y # (N, D)
for i, block in enumerate(self.blocks): x = block(x, c) # (N, T, D) if (i + 1) == self.encoder_depth: zs = [projector(x.reshape(-1, D)).reshape(N, T, -1) for projector in self.projectors] x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) x = self.unpatchify(x) # (N, out_channels, H, W)
return x, zs
################################################################################## Sine/Cosine Positional Embedding Functions ################################################################################### https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): """ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) """ grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0)
grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token and extra_tokens > 0: pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) """ assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=np.float64) omega /= embed_dim / 2. omega = 1. / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2) emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) return emb
################################################################################## SiT Configs ##################################################################################
def SiT_XL_2(**kwargs): return SiT(depth=28, hidden_size=1152, decoder_hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
def SiT_XL_4(**kwargs): return SiT(depth=28, hidden_size=1152, decoder_hidden_size=1152, patch_size=4, num_heads=16, **kwargs)
def SiT_XL_8(**kwargs): return SiT(depth=28, hidden_size=1152, decoder_hidden_size=1152, patch_size=8, num_heads=16, **kwargs)
def SiT_L_2(**kwargs): return SiT(depth=24, hidden_size=1024, decoder_hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
def SiT_L_4(**kwargs): return SiT(depth=24, hidden_size=1024, decoder_hidden_size=1024, patch_size=4, num_heads=16, **kwargs)
def SiT_L_8(**kwargs): return SiT(depth=24, hidden_size=1024, decoder_hidden_size=1024, patch_size=8, num_heads=16, **kwargs)
def SiT_B_2(**kwargs): return SiT(depth=12, hidden_size=768, decoder_hidden_size=768, patch_size=2, num_heads=12, **kwargs)
def SiT_B_4(**kwargs): return SiT(depth=12, hidden_size=768, decoder_hidden_size=768, patch_size=4, num_heads=12, **kwargs)
def SiT_B_8(**kwargs): return SiT(depth=12, hidden_size=768, decoder_hidden_size=768, patch_size=8, num_heads=12, **kwargs)
def SiT_S_2(**kwargs): return SiT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)
def SiT_S_4(**kwargs): return SiT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)
def SiT_S_8(**kwargs): return SiT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)
SiT_models = { 'SiT-XL/2': SiT_XL_2, 'SiT-XL/4': SiT_XL_4, 'SiT-XL/8': SiT_XL_8, 'SiT-L/2': SiT_L_2, 'SiT-L/4': SiT_L_4, 'SiT-L/8': SiT_L_8, 'SiT-B/2': SiT_B_2, 'SiT-B/4': SiT_B_4, 'SiT-B/8': SiT_B_8, 'SiT-S/2': SiT_S_2, 'SiT-S/4': SiT_S_4, 'SiT-S/8': SiT_S_8,}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375# Verbatim copy of https://github.com/willisma/SiT/blob/a87098c/models.py (model definitions only).# License: MIT (Meta Platforms, Inc. and affiliates), see third_party/LICENSES/SiT.txt. Not modified.
# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# --------------------------------------------------------# References:# GLIDE: https://github.com/openai/glide-text2im# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py# --------------------------------------------------------
import torchimport torch.nn as nnimport numpy as npimport mathfrom timm.models.vision_transformer import PatchEmbed, Attention, Mlp
def modulate(x, shift, scale): return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
################################################################################## Embedding Layers for Timesteps and Class Labels ##################################################################################
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """ def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t): t_freq = self.timestep_embedding(t, self.frequency_embedding_size) t_emb = self.mlp(t_freq) return t_emb
class LabelEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """ def __init__(self, num_classes, hidden_size, dropout_prob): super().__init__() use_cfg_embedding = dropout_prob > 0 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) self.num_classes = num_classes self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob else: drop_ids = force_drop_ids == 1 labels = torch.where(drop_ids, self.num_classes, labels) return labels
def forward(self, labels, train, force_drop_ids=None): use_dropout = self.dropout_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): labels = self.token_drop(labels, force_drop_ids) embeddings = self.embedding_table(labels) return embeddings
################################################################################## Core SiT Model ##################################################################################
class SiTBlock(nn.Module): """ A SiT block with adaptive layer norm zero (adaLN-Zero) conSiTioning. """ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True) )
def forward(self, x, c): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) return x
class FinalLayer(nn.Module): """ The final layer of SiT. """ def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True) )
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class SiT(nn.Module): """ Diffusion model with a Transformer backbone. """ def __init__( self, input_size=32, patch_size=2, in_channels=4, hidden_size=1152, depth=28, num_heads=16, mlp_ratio=4.0, class_dropout_prob=0.1, num_classes=1000, learn_sigma=True, ): super().__init__() self.learn_sigma = learn_sigma self.in_channels = in_channels self.out_channels = in_channels * 2 if learn_sigma else in_channels self.patch_size = patch_size self.num_heads = num_heads
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) self.t_embedder = TimestepEmbedder(hidden_size) self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) num_patches = self.x_embedder.num_patches # Will use fixed sin-cos embedding: self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
self.blocks = nn.ModuleList([ SiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth) ]) self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize (and freeze) pos_embed by sin-cos embedding: pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w = self.x_embedder.proj.weight.data nn.init.xavier_uniform_(w.view([w.shape[0], -1])) nn.init.constant_(self.x_embedder.proj.bias, 0)
# Initialize label embedding table: nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in SiT blocks: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers: nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.final_layer.linear.weight, 0) nn.init.constant_(self.final_layer.linear.bias, 0)
def unpatchify(self, x): """ x: (N, T, patch_size**2 * C) imgs: (N, H, W, C) """ c = self.out_channels p = self.x_embedder.patch_size[0] h = w = int(x.shape[1] ** 0.5) assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) x = torch.einsum('nhwpqc->nchpwq', x) imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) return imgs
def forward(self, x, t, y): """ Forward pass of SiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N,) tensor of class labels """ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2 t = self.t_embedder(t) # (N, D) y = self.y_embedder(y, self.training) # (N, D) c = t + y # (N, D) for block in self.blocks: x = block(x, c) # (N, T, D) x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) x = self.unpatchify(x) # (N, out_channels, H, W) if self.learn_sigma: x, _ = x.chunk(2, dim=1) return x
def forward_with_cfg(self, x, t, y, cfg_scale): """ Forward pass of SiT, but also batches the unconSiTional forward pass for classifier-free guidance. """ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb half = x[: len(x) // 2] combined = torch.cat([half, half], dim=0) model_out = self.forward(combined, t, y) # For exact reproducibility reasons, we apply classifier-free guidance on only # three channels by default. The standard approach to cfg applies it to all channels. # This can be done by uncommenting the following line and commenting-out the line following that. # eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] eps, rest = model_out[:, :3], model_out[:, 3:] cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) eps = torch.cat([half_eps, half_eps], dim=0) return torch.cat([eps, rest], dim=1)
################################################################################## Sine/Cosine Positional Embedding Functions ################################################################################### https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): """ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) """ grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0)
grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token and extra_tokens > 0: pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) """ assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=np.float64) omega /= embed_dim / 2. omega = 1. / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2) emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) return emb
################################################################################## SiT Configs ##################################################################################
def SiT_XL_2(**kwargs): return SiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
def SiT_XL_4(**kwargs): return SiT(depth=28, hidden_size=1152, patch_size=4, num_heads=16, **kwargs)
def SiT_XL_8(**kwargs): return SiT(depth=28, hidden_size=1152, patch_size=8, num_heads=16, **kwargs)
def SiT_L_2(**kwargs): return SiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
def SiT_L_4(**kwargs): return SiT(depth=24, hidden_size=1024, patch_size=4, num_heads=16, **kwargs)
def SiT_L_8(**kwargs): return SiT(depth=24, hidden_size=1024, patch_size=8, num_heads=16, **kwargs)
def SiT_B_2(**kwargs): return SiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
def SiT_B_4(**kwargs): return SiT(depth=12, hidden_size=768, patch_size=4, num_heads=12, **kwargs)
def SiT_B_8(**kwargs): return SiT(depth=12, hidden_size=768, patch_size=8, num_heads=12, **kwargs)
def SiT_S_2(**kwargs): return SiT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)
def SiT_S_4(**kwargs): return SiT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)
def SiT_S_8(**kwargs): return SiT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)
SiT_models = { 'SiT-XL/2': SiT_XL_2, 'SiT-XL/4': SiT_XL_4, 'SiT-XL/8': SiT_XL_8, 'SiT-L/2': SiT_L_2, 'SiT-L/4': SiT_L_4, 'SiT-L/8': SiT_L_8, 'SiT-B/2': SiT_B_2, 'SiT-B/4': SiT_B_4, 'SiT-B/8': SiT_B_8, 'SiT-S/2': SiT_S_2, 'SiT-S/4': SiT_S_4, 'SiT-S/8': SiT_S_8,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""fwDiT: a pre-trained diffusion transformer that forwards its own late-layer features to the next sampling step.
Notation (paper): the base network has L blocks of width d; m = L - K. h^m the trunk tokens after block m psi the projector: a copy of the last K blocks, a parameter-free LayerNorm, and a final bias-free linear map W (zero-init): f = psi(h^m) = W LN(blocks(h^m)) phi LoRA adapters on qkv / proj / fc1 / fc2 of every block: W_l + s B_l A_l, with adapter scale s h^0 the input tokens of the next evaluation: h^0 = E(x_t) + f (E: patch embedding + positions)The base weights are frozen; psi and phi are the fine-tuned parameters. Since W is linear, the sampler carriesu = LN(blocks(h^m)) and injects f = W u, so that feature-space guidance can mix the u's (identical to mixing the f's).
Checkpoints (config.json + model.safetensors, fp32, adapters unmerged): base.* (the pre-trained network, unchangednames), psi.blocks.<j>.*, psi.proj.weight (W), phi.blocks.<l>.<qkv|proj|fc1|fc2>.<A|B>."""import mathfrom copy import deepcopyimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import PyTorchModelHubMixin
from .backbones import Backbone
def layer_norm(z): """Parameter-free LayerNorm over channels (psi's normalisation).""" return F.layer_norm(z, (z.shape[-1],), eps=1e-6)
def adapted_linears(block): return {"qkv": block.attn.qkv, "proj": block.attn.proj, "fc1": block.mlp.fc1, "fc2": block.mlp.fc2}
class LoRA(nn.Module): """One adapter of phi: A (r x in, Kaiming-uniform init), B (out x r, zero init); alpha = r, so the update is s B A."""
def __init__(self, linear, rank): super().__init__() self.A = nn.Parameter(torch.empty(rank, linear.in_features)) self.B = nn.Parameter(torch.zeros(linear.out_features, rank)) nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
class Projector(nn.Module): """psi = W LN(blocks(h^m)): the K blocks are initialised from the base's last K, W at zero."""
def __init__(self, blocks, d): super().__init__() self.blocks = nn.ModuleList(deepcopy(b) for b in blocks) self.proj = nn.Linear(d, d, bias=False) nn.init.zeros_(self.proj.weight)
def normed(self, h, c): """u = LN(blocks(h^m)), the features before W.""" for block in self.blocks: h = block(h, c) return layer_norm(h)
def forward(self, h, c): return self.proj(self.normed(h, c))
class FwDiT(nn.Module, PyTorchModelHubMixin, library_name="fwdit", repo_url="https://github.com/DanielGilo/fwdit", license="mit", tags=["fwdit", "diffusion-transformer", "image-generation", "class-conditional", "imagenet"]): """fwDiT around a pre-trained backbone ('DiT-XL/2', 'SiT-XL/2' or 'REPA-SiT-XL/2').
model = FwDiT.from_pretrained("danielgilo/fwdit-sit-xl-2-256") # or a local directory `sampling` holds the paper's sampling settings (see fwdit.sampling.sample)."""
def __init__(self, backbone="SiT-XL/2", image_size=256, num_classes=1000, K=6, rank=32, learn_sigma=True, sampling=None): super().__init__() self.backbone = Backbone(backbone, image_size, num_classes, learn_sigma) self.base = self.backbone.net.requires_grad_(False) L, d = len(self.base.blocks), self.base.pos_embed.shape[-1] assert 0 < K < L, f"K must be in (0, {L})" self.m, self.image_size, self.sampling = L - K, image_size, sampling or {} self.psi = Projector(self.base.blocks[self.m:], d) self.phi = nn.Module() self.phi.blocks = nn.ModuleList() for block in self.base.blocks: adapters = nn.ModuleDict({n: LoRA(lin, rank) for n, lin in adapted_linears(block).items()}) for n, lin in adapted_linears(block).items(): lin.register_forward_hook(self._lora_hook(adapters[n])) self.phi.blocks.append(adapters) self.s = 1.0 # adapter scale self._merged = None # the original base weights while s B A is merged in
# ---- adapters ----------------------------------------------------------------------------------------------------- def _lora_hook(self, lora): def hook(linear, inputs, output): if self._merged is not None: return output return output + F.linear(F.linear(inputs[0], lora.A), lora.B) * self.s return hook
def set_adapter_scale(self, s): """Adapter scale s (1: as fine-tuned; 0: the pre-trained weights, still reading the forwarded features).""" assert self._merged is None, "call unmerge_adapters() first" self.s = float(s) return self
@torch.no_grad() def merge_adapters(self, s=None): """Fold s B A into the base weights (faster sampling; equal to the unmerged model up to float rounding). The factors are kept: unmerge_adapters() restores the base weights exactly.""" self.unmerge_adapters() if s is not None: self.s = float(s) self._merged = [] for block, adapters in zip(self.base.blocks, self.phi.blocks): for n, lin in adapted_linears(block).items(): self._merged.append(lin.weight.clone()) lin.weight += self.s * (adapters[n].B @ adapters[n].A) return self
@torch.no_grad() def unmerge_adapters(self): if self._merged is not None: weights = iter(self._merged) for block in self.base.blocks: for lin in adapted_linears(block).values(): lin.weight.copy_(next(weights)) self._merged = None return self
def _save_pretrained(self, save_directory): assert self._merged is None, "checkpoints store the unmerged adapters: call unmerge_adapters() first" return super()._save_pretrained(save_directory)
@classmethod def _from_pretrained(cls, **kwargs): return super()._from_pretrained(**{**kwargs, "strict": True}).eval()
# ---- the network ---------------------------------------------------------------------------------------------------- def trunk(self, x, t, y, u=None): """Blocks 1..m on h^0 = E(x_t) + W u (u = None: nothing forwarded) -> (h^m, c).""" b = self.base h = b.x_embedder(x) + b.pos_embed if u is not None: h = h + self.psi.proj(u) c = b.t_embedder(t) + b.y_embedder(y, self.training) for block in b.blocks[:self.m]: h = block(h, c) return h, c
def tail(self, h, c): """Blocks m+1..L and the head -> the backbone's output (DiT: noise and variance; SiT, REPA: velocity).""" for block in self.base.blocks[self.m:]: h = block(h, c) out = self.base.unpatchify(self.base.final_layer(h, c)) return out[:, :self.backbone.out_channels]
def forward(self, x, t, y, u=None): """One network evaluation reading forwarded features W u (u = None: nothing forwarded, the base network with adapters).""" return self.tail(*self.trunk(x, t, y, u))
def features(self, h, c): """u = LN(psi's blocks(h^m)): the features forwarded to the next evaluation (f = W u).""" return self.psi.normed(h, c)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Sampling: fwDiT's single-pass sampler and the backbones' solvers.
FeatureForwarding turns the model into a stateful function out(x, t, y) that a solver calls once per step, in order: first step a feature pass: u from the trunk on (x_t, y) with nothing forwarded each step ONE network evaluation reading W u; its trunk tokens h^m also give the next step's u (cost per step: L + K blocks; L once more at the first step)Guidance (optional; the paper's weights w and gamma, 1 = off): F-CFG u_g = u_u + w (u_c - u_u), the features of a conditional and an unconditional (null label, nothing forwarded) evaluation; with an interval (t >= t_min, paper time), the unconditional pass runs only inside it. CFG out = out_u + gamma (out_c - out_u) on the denoiser channels (DiT: the noise; its variance stays conditional). Both together share one unconditional pass per step.
Solvers (one network evaluation per step), exactly as the paper's numbers were sampled: ddpm DiT: DDPM ancestral sampling with the learned variance, on `steps` of the 1000 training steps sde-sit SiT: Euler-Maruyama on the flow-matching SDE (diffusion = sigma_t), last step its mean sde-repa REPA: the same SDE as REPA's euler_maruyama_sampler (float64, its own time grid and last step)"""import numpy as npimport torch
from .backbones import ddpm_alphas_cumprod
class FeatureForwarding: """fwDiT's single-pass sampler as a model function for one sampling run (see the module docstring)."""
def __init__(self, model, fcfg=1.0, cfg=1.0, fcfg_t_min=None): self.model, self.w, self.gamma, self.t_min = model, float(fcfg), float(cfg), fcfg_t_min self.u_c = self.u_u = None # the features carried to the next step (conditional, unconditional)
def _uncond(self, x, t, y): return self.model.trunk(x, t, torch.full_like(y, self.model.backbone.null_label))
@torch.no_grad() def __call__(self, x, t, y): model = self.model fcfg = self.w != 1.0 and (self.t_min is None or bool((model.backbone.progress(t) >= self.t_min).all())) if self.u_c is None: # first step: the feature pass self.u_c = model.features(*model.trunk(x, t, y)) if fcfg and self.u_u is None: # first step inside the F-CFG interval: a fresh u_u self.u_u = model.features(*self._uncond(x, t, y)) u = self.u_u + self.w * (self.u_c - self.u_u) if fcfg else self.u_c h, c = model.trunk(x, t, y, u) out, self.u_c, self.u_u = model.tail(h, c), model.features(h, c), None if fcfg or self.gamma != 1.0: # the unconditional pass h, c = self._uncond(x, t, y) self.u_u = model.features(h, c) if fcfg else None if self.gamma != 1.0: n = model.base.in_channels out_u = model.tail(h, c) out = torch.cat([out_u[:, :n] + self.gamma * (out[:, :n] - out_u[:, :n]), out[:, n:]], dim=1) return out
# ---- solvers: fn(x, t, y) -> network output; z: initial noise ----------------------------------------------------------def ddpm(fn, z, y, steps): """DDPM ancestral sampling (DiT) on `steps` evenly spaced of the 1000 training steps, with the learned variance (log-variance interpolated between the posterior's and beta's; Nichol & Dhariwal). Coefficients in float64.""" acp_full = ddpm_alphas_cumprod() keep, idx = [], 0.0 # evenly spaced steps (rounded), as DiT's respacing for _ in range(steps): keep.append(round(idx)); idx += (len(acp_full) - 1) / (steps - 1) betas = 1 - acp_full[keep] / np.append(1.0, acp_full[keep][:-1]) # the respaced chain's betas acp = np.cumprod(1 - betas) acp_prev = np.append(1.0, acp[:-1]) post_var = betas * (1 - acp_prev) / (1 - acp) coef = {k: torch.from_numpy(v).to(z.device) for k, v in dict( recip=np.sqrt(1 / acp), recipm1=np.sqrt(1 / acp - 1), log_beta=np.log(betas), log_post=np.log(np.append(post_var[1], post_var[1:])), mean_x0=betas * np.sqrt(acp_prev) / (1 - acp), mean_xt=(1 - acp_prev) * np.sqrt(1 - betas) / (1 - acp)).items()} timesteps = torch.tensor(keep, device=z.device) x = z for i in reversed(range(steps)): k = {n: v[i].float() for n, v in coef.items()} eps, v = fn(x, timesteps[i].repeat(x.shape[0]), y).chunk(2, dim=1) log_var = (v + 1) / 2 * k["log_beta"] + (1 - (v + 1) / 2) * k["log_post"] x0 = k["recip"] * x - k["recipm1"] * eps x = k["mean_x0"] * x0 + k["mean_xt"] * x if i > 0: x = x + torch.exp(0.5 * log_var) * torch.randn_like(x) return x
def sde_sit(fn, z, y, steps, last_step=0.04): """SiT's Euler-Maruyama sampler (diffusion_form 'sigma', last_step 'Mean'): x_t = t x_data + (1 - t) noise, dx = [v + sigma_t score] dt + sqrt(2 sigma_t) dW, score = (t v - x) / (sigma_t^2 + t sigma_t), sigma_t = 1 - t, on t in linspace(0, 1 - last_step, steps), then one noise-free step of size last_step. float32; the noise is drawn on the CPU (global generator), as SiT does.""" ts = torch.linspace(0, 1 - last_step, steps) dt = ts[1] - ts[0]
def drift(x, t): tt, sigma = t.view(-1, 1, 1, 1), 1 - t.view(-1, 1, 1, 1) v = fn(x, t, y) return v + sigma * ((tt * v - x) / (sigma ** 2 + tt * sigma)), sigma
x = z for ti in ts[:-1]: dw = torch.randn(x.size()).to(x) * torch.sqrt(dt) d, sigma = drift(x, torch.ones(x.size(0)).to(x) * ti) x = x + d * dt + torch.sqrt(2 * sigma) * dw return x + drift(x, torch.ones(x.size(0), device=x.device) * (1 - last_step))[0] * last_step
def sde_repa(fn, z, y, steps): """REPA's Euler-Maruyama sampler: x_t = (1 - t) x_data + t noise, drift v - t score, diffusion 2t, on t in linspace(1, 0.04, steps), then one noise-free step to t = 0. float64 (the network runs in float32).""" ts = torch.cat([torch.linspace(1., 0.04, steps, dtype=torch.float64), torch.zeros(1, dtype=torch.float64)])
def drift(x, t_cur): v = fn(x.float(), torch.full((x.shape[0],), float(t_cur), device=x.device), y).double() t = torch.full((x.shape[0], 1, 1, 1), float(t_cur), device=x.device, dtype=torch.float64) r = -(1 - t) # alpha_t / alpha_t' return v - 0.5 * (2 * t_cur) * ((r * v - x) / (t ** 2 - r * t))
x = z.double() for t_cur, t_next in zip(ts[:-2], ts[1:-1]): dt = t_next - t_cur x = x + drift(x, t_cur) * dt + torch.sqrt(2 * t_cur) * torch.randn_like(x) * torch.sqrt(torch.abs(dt)) return x + (ts[-1] - ts[-2]) * drift(x, ts[-2])
SOLVERS = {"ddpm": ddpm, "sde-sit": sde_sit, "sde-repa": sde_repa}
def settings(model, preset=None, **overrides): """The paper's settings stored in config.json ("sampling": presets of steps / s / fcfg / fcfg_t_min / cfg; default: the model's default preset), with any of them overridden (None = keep).""" presets = model.sampling.get("presets", {}) name = preset or model.sampling.get("default") out = {"steps": 205, "s": 1.0, "fcfg": 1.0, "fcfg_t_min": None, "cfg": 1.0, **presets.get(name, {})} out.update({k: v for k, v in overrides.items() if v is not None}) return out
@torch.no_grad()def sample(model, y, z=None, preset=None, merge=True, **overrides): """Latents for class labels y with the paper's settings (see `settings`). merge=True folds s B A into the weights (faster; equal up to float rounding); merge=False runs the adapters unmerged, as the paper's numbers were sampled.""" cfg = settings(model, preset, **overrides) model.unmerge_adapters() if merge: model.merge_adapters(cfg["s"]) else: model.set_adapter_scale(cfg["s"]) if z is None: r = model.image_size // 8 z = torch.randn(len(y), model.base.in_channels, r, r, device=y.device) fn = FeatureForwarding(model, cfg["fcfg"], cfg["cfg"], cfg["fcfg_t_min"]) return SOLVERS[model.backbone.solver](fn, z, y, cfg["steps"]).float()
VAE = "stabilityai/sd-vae-ft-ema"
def load_vae(device): from diffusers.models import AutoencoderKL return AutoencoderKL.from_pretrained(VAE).to(device).eval()
@torch.no_grad()def decode(vae, latents, chunk=32): """Latents -> uint8 images (N, H, W, 3), as in the paper's evaluation.""" imgs = torch.cat([vae.decode(c / 0.18215).sample for c in latents.split(chunk)]) return torch.clamp(127.5 * imgs + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", torch.uint8).numpy()1["tench","goldfish","great_white_shark","tiger_shark","hammerhead","electric_ray","stingray","cock","hen","ostrich","brambling","goldfinch","house_finch","junco","indigo_bunting","robin","bulbul","jay","magpie","chickadee","water_ouzel","kite","bald_eagle","vulture","great_grey_owl","European_fire_salamander","common_newt","eft","spotted_salamander","axolotl","bullfrog","tree_frog","tailed_frog","loggerhead","leatherback_turtle","mud_turtle","terrapin","box_turtle","banded_gecko","common_iguana","American_chameleon","whiptail","agama","frilled_lizard","alligator_lizard","Gila_monster","green_lizard","African_chameleon","Komodo_dragon","African_crocodile","American_alligator","triceratops","thunder_snake","ringneck_snake","hognose_snake","green_snake","king_snake","garter_snake","water_snake","vine_snake","night_snake","boa_constrictor","rock_python","Indian_cobra","green_mamba","sea_snake","horned_viper","diamondback","sidewinder","trilobite","harvestman","scorpion","black_and_gold_garden_spider","barn_spider","garden_spider","black_widow","tarantula","wolf_spider","tick","centipede","black_grouse","ptarmigan","ruffed_grouse","prairie_chicken","peacock","quail","partridge","African_grey","macaw","sulphur-crested_cockatoo","lorikeet","coucal","bee_eater","hornbill","hummingbird","jacamar","toucan","drake","red-breasted_merganser","goose","black_swan","tusker","echidna","platypus","wallaby","koala","wombat","jellyfish","sea_anemone","brain_coral","flatworm","nematode","conch","snail","slug","sea_slug","chiton","chambered_nautilus","Dungeness_crab","rock_crab","fiddler_crab","king_crab","American_lobster","spiny_lobster","crayfish","hermit_crab","isopod","white_stork","black_stork","spoonbill","flamingo","little_blue_heron","American_egret","bittern","crane","limpkin","European_gallinule","American_coot","bustard","ruddy_turnstone","red-backed_sandpiper","redshank","dowitcher","oystercatcher","pelican","king_penguin","albatross","grey_whale","killer_whale","dugong","sea_lion","Chihuahua","Japanese_spaniel","Maltese_dog","Pekinese","Shih-Tzu","Blenheim_spaniel","papillon","toy_terrier","Rhodesian_ridgeback","Afghan_hound","basset","beagle","bloodhound","bluetick","black-and-tan_coonhound","Walker_hound","English_foxhound","redbone","borzoi","Irish_wolfhound","Italian_greyhound","whippet","Ibizan_hound","Norwegian_elkhound","otterhound","Saluki","Scottish_deerhound","Weimaraner","Staffordshire_bullterrier","American_Staffordshire_terrier","Bedlington_terrier","Border_terrier","Kerry_blue_terrier","Irish_terrier","Norfolk_terrier","Norwich_terrier","Yorkshire_terrier","wire-haired_fox_terrier","Lakeland_terrier","Sealyham_terrier","Airedale","cairn","Australian_terrier","Dandie_Dinmont","Boston_bull","miniature_schnauzer","giant_schnauzer","standard_schnauzer","Scotch_terrier","Tibetan_terrier","silky_terrier","soft-coated_wheaten_terrier","West_Highland_white_terrier","Lhasa","flat-coated_retriever","curly-coated_retriever","golden_retriever","Labrador_retriever","Chesapeake_Bay_retriever","German_short-haired_pointer","vizsla","English_setter","Irish_setter","Gordon_setter","Brittany_spaniel","clumber","English_springer","Welsh_springer_spaniel","cocker_spaniel","Sussex_spaniel","Irish_water_spaniel","kuvasz","schipperke","groenendael","malinois","briard","kelpie","komondor","Old_English_sheepdog","Shetland_sheepdog","collie","Border_collie","Bouvier_des_Flandres","Rottweiler","German_shepherd","Doberman","miniature_pinscher","Greater_Swiss_Mountain_dog","Bernese_mountain_dog","Appenzeller","EntleBucher","boxer","bull_mastiff","Tibetan_mastiff","French_bulldog","Great_Dane","Saint_Bernard","Eskimo_dog","malamute","Siberian_husky","dalmatian","affenpinscher","basenji","pug","Leonberg","Newfoundland","Great_Pyrenees","Samoyed","Pomeranian","chow","keeshond","Brabancon_griffon","Pembroke","Cardigan","toy_poodle","miniature_poodle","standard_poodle","Mexican_hairless","timber_wolf","white_wolf","red_wolf","coyote","dingo","dhole","African_hunting_dog","hyena","red_fox","kit_fox","Arctic_fox","grey_fox","tabby","tiger_cat","Persian_cat","Siamese_cat","Egyptian_cat","cougar","lynx","leopard","snow_leopard","jaguar","lion","tiger","cheetah","brown_bear","American_black_bear","ice_bear","sloth_bear","mongoose","meerkat","tiger_beetle","ladybug","ground_beetle","long-horned_beetle","leaf_beetle","dung_beetle","rhinoceros_beetle","weevil","fly","bee","ant","grasshopper","cricket","walking_stick","cockroach","mantis","cicada","leafhopper","lacewing","dragonfly","damselfly","admiral","ringlet","monarch","cabbage_butterfly","sulphur_butterfly","lycaenid","starfish","sea_urchin","sea_cucumber","wood_rabbit","hare","Angora","hamster","porcupine","fox_squirrel","marmot","beaver","guinea_pig","sorrel","zebra","hog","wild_boar","warthog","hippopotamus","ox","water_buffalo","bison","ram","bighorn","ibex","hartebeest","impala","gazelle","Arabian_camel","llama","weasel","mink","polecat","black-footed_ferret","otter","skunk","badger","armadillo","three-toed_sloth","orangutan","gorilla","chimpanzee","gibbon","siamang","guenon","patas","baboon","macaque","langur","colobus","proboscis_monkey","marmoset","capuchin","howler_monkey","titi","spider_monkey","squirrel_monkey","Madagascar_cat","indri","Indian_elephant","African_elephant","lesser_panda","giant_panda","barracouta","eel","coho","rock_beauty","anemone_fish","sturgeon","gar","lionfish","puffer","abacus","abaya","academic_gown","accordion","acoustic_guitar","aircraft_carrier","airliner","airship","altar","ambulance","amphibian","analog_clock","apiary","apron","ashcan","assault_rifle","backpack","bakery","balance_beam","balloon","ballpoint","Band_Aid","banjo","bannister","barbell","barber_chair","barbershop","barn","barometer","barrel","barrow","baseball","basketball","bassinet","bassoon","bathing_cap","bath_towel","bathtub","beach_wagon","beacon","beaker","bearskin","beer_bottle","beer_glass","bell_cote","bib","bicycle-built-for-two","bikini","binder","binoculars","birdhouse","boathouse","bobsled","bolo_tie","bonnet","bookcase","bookshop","bottlecap","bow","bow_tie","brass","brassiere","breakwater","breastplate","broom","bucket","buckle","bulletproof_vest","bullet_train","butcher_shop","cab","caldron","candle","cannon","canoe","can_opener","cardigan","car_mirror","carousel","carpenter's_kit","carton","car_wheel","cash_machine","cassette","cassette_player","castle","catamaran","CD_player","cello","cellular_telephone","chain","chainlink_fence","chain_mail","chain_saw","chest","chiffonier","chime","china_cabinet","Christmas_stocking","church","cinema","cleaver","cliff_dwelling","cloak","clog","cocktail_shaker","coffee_mug","coffeepot","coil","combination_lock","computer_keyboard","confectionery","container_ship","convertible","corkscrew","cornet","cowboy_boot","cowboy_hat","cradle","crane","crash_helmet","crate","crib","Crock_Pot","croquet_ball","crutch","cuirass","dam","desk","desktop_computer","dial_telephone","diaper","digital_clock","digital_watch","dining_table","dishrag","dishwasher","disk_brake","dock","dogsled","dome","doormat","drilling_platform","drum","drumstick","dumbbell","Dutch_oven","electric_fan","electric_guitar","electric_locomotive","entertainment_center","envelope","espresso_maker","face_powder","feather_boa","file","fireboat","fire_engine","fire_screen","flagpole","flute","folding_chair","football_helmet","forklift","fountain","fountain_pen","four-poster","freight_car","French_horn","frying_pan","fur_coat","garbage_truck","gasmask","gas_pump","goblet","go-kart","golf_ball","golfcart","gondola","gong","gown","grand_piano","greenhouse","grille","grocery_store","guillotine","hair_slide","hair_spray","half_track","hammer","hamper","hand_blower","hand-held_computer","handkerchief","hard_disc","harmonica","harp","harvester","hatchet","holster","home_theater","honeycomb","hook","hoopskirt","horizontal_bar","horse_cart","hourglass","iPod","iron","jack-o'-lantern","jean","jeep","jersey","jigsaw_puzzle","jinrikisha","joystick","kimono","knee_pad","knot","lab_coat","ladle","lampshade","laptop","lawn_mower","lens_cap","letter_opener","library","lifeboat","lighter","limousine","liner","lipstick","Loafer","lotion","loudspeaker","loupe","lumbermill","magnetic_compass","mailbag","mailbox","maillot","maillot","manhole_cover","maraca","marimba","mask","matchstick","maypole","maze","measuring_cup","medicine_chest","megalith","microphone","microwave","military_uniform","milk_can","minibus","miniskirt","minivan","missile","mitten","mixing_bowl","mobile_home","Model_T","modem","monastery","monitor","moped","mortar","mortarboard","mosque","mosquito_net","motor_scooter","mountain_bike","mountain_tent","mouse","mousetrap","moving_van","muzzle","nail","neck_brace","necklace","nipple","notebook","obelisk","oboe","ocarina","odometer","oil_filter","organ","oscilloscope","overskirt","oxcart","oxygen_mask","packet","paddle","paddlewheel","padlock","paintbrush","pajama","palace","panpipe","paper_towel","parachute","parallel_bars","park_bench","parking_meter","passenger_car","patio","pay-phone","pedestal","pencil_box","pencil_sharpener","perfume","Petri_dish","photocopier","pick","pickelhaube","picket_fence","pickup","pier","piggy_bank","pill_bottle","pillow","ping-pong_ball","pinwheel","pirate","pitcher","plane","planetarium","plastic_bag","plate_rack","plow","plunger","Polaroid_camera","pole","police_van","poncho","pool_table","pop_bottle","pot","potter's_wheel","power_drill","prayer_rug","printer","prison","projectile","projector","puck","punching_bag","purse","quill","quilt","racer","racket","radiator","radio","radio_telescope","rain_barrel","recreational_vehicle","reel","reflex_camera","refrigerator","remote_control","restaurant","revolver","rifle","rocking_chair","rotisserie","rubber_eraser","rugby_ball","rule","running_shoe","safe","safety_pin","saltshaker","sandal","sarong","sax","scabbard","scale","school_bus","schooner","scoreboard","screen","screw","screwdriver","seat_belt","sewing_machine","shield","shoe_shop","shoji","shopping_basket","shopping_cart","shovel","shower_cap","shower_curtain","ski","ski_mask","sleeping_bag","slide_rule","sliding_door","slot","snorkel","snowmobile","snowplow","soap_dispenser","soccer_ball","sock","solar_dish","sombrero","soup_bowl","space_bar","space_heater","space_shuttle","spatula","speedboat","spider_web","spindle","sports_car","spotlight","stage","steam_locomotive","steel_arch_bridge","steel_drum","stethoscope","stole","stone_wall","stopwatch","stove","strainer","streetcar","stretcher","studio_couch","stupa","submarine","suit","sundial","sunglass","sunglasses","sunscreen","suspension_bridge","swab","sweatshirt","swimming_trunks","swing","switch","syringe","table_lamp","tank","tape_player","teapot","teddy","television","tennis_ball","thatch","theater_curtain","thimble","thresher","throne","tile_roof","toaster","tobacco_shop","toilet_seat","torch","totem_pole","tow_truck","toyshop","tractor","trailer_truck","tray","trench_coat","tricycle","trimaran","tripod","triumphal_arch","trolleybus","trombone","tub","turnstile","typewriter_keyboard","umbrella","unicycle","upright","vacuum","vase","vault","velvet","vending_machine","vestment","viaduct","violin","volleyball","waffle_iron","wall_clock","wallet","wardrobe","warplane","washbasin","washer","water_bottle","water_jug","water_tower","whiskey_jug","whistle","wig","window_screen","window_shade","Windsor_tie","wine_bottle","wing","wok","wooden_spoon","wool","worm_fence","wreck","yawl","yurt","web_site","comic_book","crossword_puzzle","street_sign","traffic_light","book_jacket","menu","plate","guacamole","consomme","hot_pot","trifle","ice_cream","ice_lolly","French_loaf","bagel","pretzel","cheeseburger","hotdog","mashed_potato","head_cabbage","broccoli","cauliflower","zucchini","spaghetti_squash","acorn_squash","butternut_squash","cucumber","artichoke","bell_pepper","cardoon","mushroom","Granny_Smith","strawberry","orange","lemon","fig","pineapple","banana","jackfruit","custard_apple","pomegranate","hay","carbonara","chocolate_sauce","dough","meat_loaf","pizza","potpie","burrito","red_wine","espresso","cup","eggnog","alp","bubble","cliff","coral_reef","geyser","lakeside","promontory","sandbar","seashore","valley","volcano","ballplayer","groom","scuba_diver","rapeseed","daisy","yellow_lady's_slipper","corn","acorn","hip","buckeye","coral_fungus","agaric","gyromitra","stinkhorn","earthstar","hen-of-the-woods","bolete","ear","toilet_tissue"]12345678torch==2.11.0torchvision==0.26.0timmdiffusersacceleratesafetensorsnumpypillowREADME.md+30-6
app.pyAdded+247
fwdit/__init__.pyAdded+5
fwdit/backbones/__init__.pyAdded+52
fwdit/backbones/dit.pyAdded+373
fwdit/backbones/repa.pyAdded+395
fwdit/backbones/sit.pyAdded+375
fwdit/model.pyAdded+161
fwdit/sampling.pyAdded+165
imagenet_names.jsonAdded+1
requirements.txtAdded+8