"""Inference for Pyramid Flow.""" import math import torch from torch import nn from torch.nn import functional as F from transformers import PreTrainedModel from .configuration_pyramid_flow import PyramidFlowConfig class RMSNorm(nn.Module): """nn.RMSNorm keeps fp32 weights; under bf16 autocast that mismatch falls back to an unfused kernel (PyTorch warns). Casting the weight to the activation dtype fixes it.""" def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), self.eps) class TimestepEmbed(nn.Module): def __init__(self, dim: int, freq_dim: int = 256): super().__init__() self.freq_dim = freq_dim self.mlp = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) def forward(self, t: torch.Tensor) -> torch.Tensor: # t: (B,) in [0,1] half = self.freq_dim // 2 f = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half) a = t.float().reshape(-1, 1) * 1000.0 * f[None] return self.mlp(torch.cat([a.cos(), a.sin()], dim=-1).to(self.mlp[0].weight.dtype)) class CrossAttention(nn.Module): def __init__(self, dim, heads, ctx_dim, n_null=2): super().__init__() self.h, self.dh, self.n_null = heads, dim // heads, n_null self.q = nn.Linear(dim, dim, bias=False) self.kv = nn.Linear(ctx_dim, 2 * dim, bias=False) self.proj = nn.Linear(dim, dim, bias=False) self.qn = RMSNorm(self.dh) self.kn = RMSNorm(self.dh) # learned null key/value slots, in projected space, always attendable self.null_kv = nn.Parameter(torch.randn(2, n_null, dim) * 0.02) if n_null else None nn.init.zeros_(self.proj.weight) # block starts as a no-op on the residual def forward(self, x, ctx, ctx_mask): B, N, _ = x.shape k, v = self.kv(ctx).chunk(2, dim=-1) if self.null_kv is not None: nk, nv = self.null_kv.to(k.dtype).unsqueeze(1).expand(-1, B, -1, -1) k, v = torch.cat([k, nk], 1), torch.cat([v, nv], 1) if ctx_mask is not None: ctx_mask = torch.cat([ctx_mask, ctx_mask.new_ones(B, self.n_null)], 1) L = k.shape[1] q = self.q(x).view(B, N, self.h, self.dh).transpose(1, 2) k, v = (t.view(B, L, self.h, self.dh).transpose(1, 2) for t in (k, v)) q, k = self.qn(q), self.kn(k) m = ctx_mask[:, None, None, :] if ctx_mask is not None else None o = F.scaled_dot_product_attention(q, k, v, attn_mask=m) return self.proj(o.transpose(1, 2).reshape(B, N, -1)) def rotate(t: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """t: (B, heads, N, head_dim); cos/sin: (N, head_dim//2)""" a, b = t.chunk(2, dim=-1) cos = cos.to(t.dtype)[None, None] sin = sin.to(t.dtype)[None, None] return torch.cat([a * cos - b * sin, a * sin + b * cos], dim=-1) class PyramidBlock(nn.Module): def __init__(self, width, heads, hidden, modulation_width, *, xsa=False): super().__init__() self.heads = heads self.head_width = width // heads self.pre_attn = RMSNorm(width) self.post_attn = RMSNorm(width) self.pre_ffn = RMSNorm(width) self.post_ffn = RMSNorm(width) self.q_norm = RMSNorm(self.head_width) self.k_norm = RMSNorm(self.head_width) self.qkv = nn.Linear(width, 3 * width) self.xsa = xsa self.head_gate = nn.Linear(width, heads) if modulation_width is not None and not xsa else None self.attn_out = nn.Linear(width, width) self.ffn_in = nn.Linear(width, 2 * hidden, bias=False) self.ffn_out = nn.Linear(hidden, width, bias=False) self.modulation = None if modulation_width is not None: self.modulation = nn.Linear(modulation_width, 4 * width) nn.init.zeros_(self.modulation.weight) nn.init.zeros_(self.modulation.bias) def forward(self, tokens, condition=None, mask=None, rotary=None): x = self.pre_attn(tokens) if self.modulation is not None: scale_a, gate_a, scale_f, gate_f = self.modulation(condition)[:, None].chunk(4, dim=-1) x = x * (1 + scale_a) b, n, width = x.shape q, k, v = self.qkv(x).reshape(b, n, 3, self.heads, self.head_width).permute(2, 0, 3, 1, 4) q, k = self.q_norm(q), self.k_norm(k) if rotary is not None: q, k = rotate(q, *rotary), rotate(k, *rotary) attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) if self.xsa: own_value = F.normalize(v.float(), dim=-1) attn_float = attn.float() attn = (attn_float - (attn_float * own_value).sum(-1, keepdim=True) * own_value).to(attn.dtype) attn = attn.transpose(1, 2) if self.head_gate is not None: attn = attn * self.head_gate(x).sigmoid().unsqueeze(-1) attn_update = self.post_attn(self.attn_out(attn.reshape(b, n, width))) tokens = tokens + (gate_a.tanh() * attn_update if self.modulation is not None else attn_update) x = self.pre_ffn(tokens) if self.modulation is not None: x = x * (1 + scale_f) value, gate = self.ffn_in(x).chunk(2, dim=-1) ffn_update = self.post_ffn(self.ffn_out(F.silu(gate) * value)) return tokens + (gate_f.tanh() * ffn_update if self.modulation is not None else ffn_update) class PixelReadout(nn.Module): def __init__(self, width, patch, channels=3): super().__init__() self.patch = patch self.channels = channels self.norm = nn.LayerNorm(width) self.modulation = nn.Parameter(torch.zeros(2, width)) self.out = nn.Linear(width, channels * patch * patch) def forward(self, tokens, time_embedding, grid, grid_width=None): modulation = self.modulation if time_embedding is None else time_embedding[:, None] + self.modulation shift, scale = modulation.unbind(-2) pixels = self.out(self.norm(tokens) * (1 + scale.unsqueeze(-2)) + shift.unsqueeze(-2)) p = self.patch grid_width = grid if grid_width is None else grid_width return pixels.reshape(-1, grid, grid_width, p, p, self.channels).permute(0, 5, 1, 3, 2, 4).reshape( -1, self.channels, grid * p, grid_width * p) class PyramidFlowModel(PreTrainedModel): """256-pixel text-to-image denoiser. Forward returns velocity in normalized latent space.""" config_class = PyramidFlowConfig main_input_name = "latents" def __init__(self, config): super().__init__(config) width = 608 self.image_stem = nn.Linear(16, width) self.text_stem = nn.Sequential(nn.LayerNorm(768), nn.Linear(768, width), nn.SiLU(), nn.Linear(width, width)) self.time = TimestepEmbed(width) self.modulation = nn.Linear(width, 128) self.stages = ((0, 4, 4), (4, 8, 8), (8, 16, 16)) shared = {i for first, end, _ in self.stages for i in range(first + 1, end - 1)} self.blocks = nn.ModuleList(PyramidBlock(width, 8, 1568, 128, xsa=i in shared) for i in range(16)) self.cross_norms = nn.ModuleList(RMSNorm(width) for _ in self.blocks) self.cross = nn.ModuleList(CrossAttention(width, 8, width, n_null=2) for _ in self.blocks) self.full = PixelReadout(width, 2, channels=4) self.child_offsets = nn.Parameter(torch.zeros(2, 2, 2, width)) for _, _, side in self.stages: for name in ("cos", "sin"): self.register_buffer(f"{name}_{side}", torch.empty(side * side, 38)) self.register_buffer("latent_mean", torch.empty(1, 256, 16)) self.register_buffer("latent_scale", torch.empty(1, 256, 16)) self.post_init() @staticmethod def _pack(spatial): batch, channels, side, _ = spatial.shape grid = side // 2 return spatial.reshape(batch, channels, grid, 2, grid, 2).permute(0, 2, 4, 1, 3, 5).reshape(batch, grid * grid, 16) @staticmethod def _unpack(latents): return latents.reshape(-1, 16, 16, 4, 2, 2).permute(0, 3, 1, 4, 2, 5).reshape(-1, 4, 32, 32) def forward(self, latents, noise_fraction, encoder_hidden_states, attention_mask): dtype = self.image_stem.weight.dtype spatial = self._unpack(latents.to(dtype)) text = self.text_stem(encoder_hidden_states.to(dtype)) embedding = self.time(1 - noise_fraction) condition = self.modulation(F.silu(embedding)) for stage, (first, end, side) in enumerate(self.stages): stage_input = self.image_stem(self._pack(F.avg_pool2d(spatial, 16 // side))) if side < 16 else self.image_stem(latents.to(dtype)) if stage == 0: image = stage_input else: parents = image.reshape(len(latents), side // 2, side // 2, -1) children = parents[:, :, None, :, None, :] + self.child_offsets[stage - 1].to(image.dtype)[None, None, :, None, :, :] image = children.reshape_as(stage_input) + stage_input rotary = getattr(self, f"cos_{side}"), getattr(self, f"sin_{side}") order = [first] + list(range(first + 1, end - 1)) * 4 + [end - 1] for i in order: image = self.blocks[i](image, condition, rotary=rotary) image = image + self.cross[i](self.cross_norms[i](image), text, attention_mask) clean = self._pack(self.full(image, embedding, 16).float()) return (clean - latents.float()) / noise_fraction[:, None, None].clamp_min(1e-6) @torch.inference_mode() def generate_image(self, prompt, *, seed=0, num_inference_steps=20, guidance_scale=4.0, tokenizer=None, text_encoder=None, vae=None): """Return a list of PIL RGB images for a string or list of strings.""" from diffusers import AutoencoderKL from PIL import Image from transformers import AutoTokenizer, T5EncoderModel prompts = [prompt] if isinstance(prompt, str) else list(prompt) if not prompts or not all(isinstance(p, str) for p in prompts): raise ValueError("Supply a prompt or a nonempty list of prompts") if not isinstance(num_inference_steps, int) or num_inference_steps < 1: raise ValueError("num_inference_steps must be a positive integer") device = self.image_stem.weight.device t5 = "google-t5/t5-base" revision = "a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1" if tokenizer is None: tokenizer = AutoTokenizer.from_pretrained(t5, revision=revision) if text_encoder is None: text_encoder = T5EncoderModel.from_pretrained(t5, revision=revision) if vae is None: vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", revision="31f26fdeee1355a5c34592e401dd41e45d25a493") text_encoder = text_encoder.eval().to(device) vae = vae.eval().to(device) tokens = tokenizer(prompts, max_length=120, padding="max_length", truncation=True, return_tensors="pt").to(device) mask = tokens.attention_mask.bool() text = text_encoder(**tokens).last_hidden_state.masked_fill(~mask.unsqueeze(-1), 0) null_mask = torch.zeros_like(mask) null_mask[:, 0] = True null_text = torch.zeros_like(text) rng = torch.Generator(device=device).manual_seed(seed) x = torch.randn(len(prompts), 256, 16, device=device, generator=rng) tau = 1 - torch.linspace(0, 1, num_inference_steps + 1, device=device) times = 1 - 2.8 * tau / (1 + 1.8 * tau) with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda" and torch.cuda.is_bf16_supported()): for start, end in zip(times[:-1], times[1:]): t = (1 - start).expand(len(x)) velocity = self(x, t, text, mask) if guidance_scale != 1: null = self(x, t, null_text, null_mask) velocity = null + guidance_scale * (velocity - null) x = x + (end - start) * velocity z = self._unpack(x.float() * self.latent_scale.float() + self.latent_mean.float()) rgb = vae.decode(z.to(vae.dtype) / vae.config.scaling_factor).sample.float() pixels = (rgb.clamp(-1, 1).add(1).mul(127.5)).round().to(torch.uint8).permute(0, 2, 3, 1).cpu() return [Image.fromarray(frame.numpy()) for frame in pixels]