"""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 np import 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()