multimodalart's picture
multimodalart HF Staff
fwDiT demo: REPA-256 + SiT-512 checkpoints, authors' sampler, presets/knobs, examples
dd43bb2 verified
Raw History Blame Contribute Delete
7.36 kB
"""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 carries
u = 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, unchanged
names), psi.blocks.<j>.*, psi.proj.weight (W), phi.blocks.<l>.<qkv|proj|fc1|fc2>.<A|B>.
"""
import math
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
from 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)