"""smalt denoiser (MIT). The denoiser: one bidirectional transformer over [registers | text tokens | pixel tokens]. Pixels are palette tokens (0 = transparent, 1..K-1 colours, K = [MASK]). Text tokens come from our own small BPE (no frozen text tower) and are updated by every block next to the pixels. Hourglass: pixel-level blocks on the full grid, a 2x2 merge, core blocks on the patch grid, unmerge + zero-init skip, pixel-level blocks again. Each block: RMSNorm -> adaLN modulate -> joint attention (QK-RMSNorm, 2D axial RoPE) -> gate; RMSNorm -> modulate -> SwiGLU with a depthwise 3x3 conv on the gate branch (spatial tokens only) -> gate. adaLN-single: one MLP of (pooled text, Fourier(mask ratio)) gives shift/scale/gate for all blocks, plus a learned per-block table; every gate starts at zero so every block starts as the identity, and the head starts at zero (uniform logits). """ import math from dataclasses import dataclass, asdict import torch import torch.nn as nn import torch.nn.functional as F @dataclass class ModelCfg: grid: int = 16 n_colors: int = 512 # palette size incl. transparent; [MASK] = n_colors text_vocab: int = 4096 text_len: int = 24 width: int = 256 heads: int = 4 depth_in: int = 1 depth_core: int = 4 depth_out: int = 1 mlp_ratio: float = 3.0 n_reg: int = 4 rope_theta: float = 100.0 merge: bool = True # 2x2 hourglass; False = every block at pixel level def to_dict(self): return asdict(self) def fourier(x, n_freq): """x (..., c) -> (..., c + 2*c*n_freq).""" f = math.pi * (2.0 ** torch.arange(n_freq, device=x.device, dtype=torch.float32)) a = x[..., None].float() * f return torch.cat([x.float(), a.sin().flatten(-2), a.cos().flatten(-2)], -1) def rope_tables(pos, head_dim, theta): """pos (L,2) float row/col -> cos, sin (L, head_dim/2): half the pairs rotate with the row, half with the column.""" nf = head_dim // 4 freqs = theta ** (-torch.arange(nf, dtype=torch.float64) / nf) ang = torch.cat([pos[:, :1].double() * freqs, pos[:, 1:].double() * freqs], -1) return ang.cos().float(), ang.sin().float() def apply_rope(x, cos, sin): x1, x2 = x.chunk(2, -1) return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1).type_as(x) def modulate(x, shift, scale): return x * (1 + scale[:, None]) + shift[:, None] class Attention(nn.Module): def __init__(self, d, heads): super().__init__() self.h, self.hd = heads, d // heads self.qkv = nn.Linear(d, 3 * d, bias=False) self.proj = nn.Linear(d, d, bias=False) self.qn = nn.RMSNorm(self.hd) self.kn = nn.RMSNorm(self.hd) def forward(self, x, cos, sin): b, n, _ = x.shape q, k, v = self.qkv(x).view(b, n, 3, self.h, self.hd).permute(2, 0, 3, 1, 4) q = apply_rope(self.qn(q), cos, sin).to(v.dtype) k = apply_rope(self.kn(k), cos, sin).to(v.dtype) o = F.scaled_dot_product_attention(q, k, v) return self.proj(o.transpose(1, 2).reshape(b, n, -1)) class ConvSwiGLU(nn.Module): def __init__(self, d, hidden): super().__init__() self.w_in = nn.Linear(d, 2 * hidden, bias=False) self.dw = nn.Conv2d(hidden, hidden, 3, padding=1, groups=hidden) nn.init.zeros_(self.dw.weight) nn.init.zeros_(self.dw.bias) self.w_out = nn.Linear(hidden, d, bias=False) def forward(self, x, n_prefix, g): v, gate = self.w_in(x).chunk(2, -1) sp = gate[:, n_prefix:] b = x.shape[0] conv = self.dw(sp.transpose(1, 2).reshape(b, -1, g, g)).flatten(2).transpose(1, 2) gate = torch.cat([gate[:, :n_prefix], sp + conv], 1) return self.w_out(F.silu(gate) * v) class Block(nn.Module): def __init__(self, d, heads, hidden): super().__init__() self.n1 = nn.RMSNorm(d, elementwise_affine=False) self.attn = Attention(d, heads) self.n2 = nn.RMSNorm(d, elementwise_affine=False) self.mlp = ConvSwiGLU(d, hidden) self.table = nn.Parameter(torch.zeros(6, d)) def forward(self, x, mod, cos, sin, n_prefix, g): sh1, sc1, g1, sh2, sc2, g2 = (mod + self.table).unbind(1) x = x + g1[:, None] * self.attn(modulate(self.n1(x), sh1, sc1), cos, sin) x = x + g2[:, None] * self.mlp(modulate(self.n2(x), sh2, sc2), n_prefix, g) return x class Smalt(nn.Module): def __init__(self, cfg: ModelCfg, pal_lab): super().__init__() self.cfg = cfg d, g, k = cfg.width, cfg.grid, cfg.n_colors assert (d // cfg.heads) % 4 == 0, "head dim must be a multiple of 4 (2D RoPE)" assert not cfg.merge or g % 2 == 0 self.mask_id = k self.n_prefix = cfg.n_reg + cfg.text_len hidden = int(cfg.mlp_ratio * d) # colours: learned(c) + MLP(Fourier(L, a, b, opaque, mask)) so rare shades start next to similar common ones feats = torch.zeros(k + 1, 5) feats[1:k, :3] = torch.as_tensor(pal_lab, dtype=torch.float32)[1:k] feats[1:k, 3] = 1.0 feats[k, 4] = 1.0 self.register_buffer("color_feats", feats) self.color_emb = nn.Embedding(k + 1, d) nn.init.normal_(self.color_emb.weight, std=0.02) self.color_mlp = nn.Sequential(nn.Linear(5 + 5 * 2 * 6, d), nn.SiLU(), nn.Linear(d, d)) self.sc_proj = nn.Linear(k, d, bias=False) # self-conditioning: previous step's distribution nn.init.zeros_(self.sc_proj.weight) self.text_emb = nn.Embedding(cfg.text_vocab, d) nn.init.normal_(self.text_emb.weight, std=0.02) self.text_pos = nn.Parameter(torch.randn(cfg.text_len, d) * 0.02) self.registers = nn.Parameter(torch.randn(cfg.n_reg, d) * 0.02) self.null_pooled = nn.Parameter(torch.zeros(d)) self.cond = nn.Sequential(nn.Linear(d + 1 + 2 * 8, d), nn.SiLU(), nn.Linear(d, d)) self.mod = nn.Linear(d, 6 * d) self.final_mod = nn.Linear(d, 2 * d) for m in (self.mod, self.final_mod): nn.init.zeros_(m.weight) nn.init.zeros_(m.bias) self.blocks_in = nn.ModuleList([Block(d, cfg.heads, hidden) for _ in range(cfg.depth_in)]) self.blocks_core = nn.ModuleList([Block(d, cfg.heads, hidden) for _ in range(cfg.depth_core)]) self.blocks_out = nn.ModuleList([Block(d, cfg.heads, hidden) for _ in range(cfg.depth_out)]) if cfg.merge: self.merge = nn.Linear(4 * d, d, bias=False) self.unmerge = nn.Linear(d, 4 * d, bias=False) self.skip = nn.Linear(d, d, bias=False) nn.init.zeros_(self.skip.weight) self.norm_out = nn.RMSNorm(d, elementwise_affine=False) self.head = nn.Linear(d, k) nn.init.zeros_(self.head.weight) nn.init.zeros_(self.head.bias) # RoPE: prefix tokens sit at the grid centre (their order comes from text_pos); pixels at (row, col); # merged patches at the centre of their 2x2 block, so both levels share one frame hd = d // cfg.heads c = (g - 1) / 2 pre = torch.full((self.n_prefix, 2), c) rr, cc = torch.meshgrid(torch.arange(g), torch.arange(g), indexing="ij") pix = torch.stack([rr.flatten(), cc.flatten()], -1).float() cos, sin = rope_tables(torch.cat([pre, pix]), hd, cfg.rope_theta) self.register_buffer("cos_pix", cos, persistent=False) self.register_buffer("sin_pix", sin, persistent=False) if cfg.merge: h = g // 2 rr, cc = torch.meshgrid(torch.arange(h), torch.arange(h), indexing="ij") pat = torch.stack([rr.flatten() * 2 + 0.5, cc.flatten() * 2 + 0.5], -1).float() cos, sin = rope_tables(torch.cat([pre, pat]), hd, cfg.rope_theta) self.register_buffer("cos_core", cos, persistent=False) self.register_buffer("sin_core", sin, persistent=False) def color_table(self): return self.color_emb.weight + self.color_mlp(fourier(self.color_feats, 6)) def _merge(self, x): b, g, d = x.shape[0], self.cfg.grid, self.cfg.width x = x.view(b, g // 2, 2, g // 2, 2, d).permute(0, 1, 3, 2, 4, 5).reshape(b, (g // 2) ** 2, 4 * d) return self.merge(x) def _unmerge(self, x): b, g, d = x.shape[0], self.cfg.grid, self.cfg.width x = self.unmerge(x).view(b, g // 2, g // 2, 2, 2, d).permute(0, 1, 3, 2, 4, 5) return x.reshape(b, g * g, d) def forward(self, tokens, text, ratio, prev=None): """tokens (B, G*G) long with [MASK]; text (B, L) long (all PAD = unconditional); ratio (B,) masked fraction; prev (B, G*G, K) previous predicted distribution or None. Returns logits (B, G*G, K).""" cfg = self.cfg b = tokens.shape[0] x = F.embedding(tokens, self.color_table()) if prev is not None: x = x + self.sc_proj(prev.to(x.dtype)) * (tokens == self.mask_id)[..., None].to(x.dtype) t = self.text_emb(text) + self.text_pos nonpad = (text != 0)[..., None].to(t.dtype) cnt = nonpad.sum(1) pooled = torch.where(cnt > 0, (t * nonpad).sum(1) / cnt.clamp_min(1), self.null_pooled.to(t.dtype)) c = self.cond(torch.cat([pooled.float(), fourier(ratio[:, None], 8)], -1)) mod = self.mod(F.silu(c)).view(b, 6, cfg.width) p = self.n_prefix x = torch.cat([self.registers.expand(b, -1, -1).to(x.dtype), t.to(x.dtype), x], 1) for blk in self.blocks_in: x = blk(x, mod, self.cos_pix, self.sin_pix, p, cfg.grid) if cfg.merge: pre = x[:, p:] x = torch.cat([x[:, :p], self._merge(pre)], 1) for blk in self.blocks_core: x = blk(x, mod, self.cos_core, self.sin_core, p, cfg.grid // 2) x = torch.cat([x[:, :p], self._unmerge(x[:, p:]) + self.skip(pre)], 1) else: for blk in self.blocks_core: x = blk(x, mod, self.cos_pix, self.sin_pix, p, cfg.grid) for blk in self.blocks_out: x = blk(x, mod, self.cos_pix, self.sin_pix, p, cfg.grid) sh, sc = self.final_mod(F.silu(c)).chunk(2, -1) return self.head(modulate(self.norm_out(x[:, p:]), sh, sc)) def count_params(model): return sum(p.numel() for p in model.parameters())