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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trout denoiser: a dual-resolution (hourglass) masked-diffusion transformer for palette pixel art.
|
| 2 |
+
|
| 3 |
+
Written from scratch for Trout. Every 16x16 sprite is a 256-token sentence over a
|
| 4 |
+
512-colour palette; a bidirectional transformer unmasks all pixels in parallel,
|
| 5 |
+
conditioned on a frozen CLIP text encoder.
|
| 6 |
+
|
| 7 |
+
pixel level (16x16) --2x2 merge--> patch level (8x8) --unmerge + skip--> pixel level
|
| 8 |
+
depth_in blocks depth_core blocks depth_out blocks
|
| 9 |
+
|
| 10 |
+
Ingredients (same family as tessera-small, ~47.6M parameters):
|
| 11 |
+
* colour-grounded token embeddings: palette token = learned vector + MLP(Fourier(OKLab)).
|
| 12 |
+
* joint bidirectional attention over [registers | text | image] with QK-RMSNorm.
|
| 13 |
+
* 2D axial RoPE on image tokens; patch-level tokens sit at sub-pixel centres so both
|
| 14 |
+
resolutions share one positional frame. Text/register tokens are not rotated.
|
| 15 |
+
* Conv-SwiGLU: depthwise 3x3 conv on the gate branch of image tokens.
|
| 16 |
+
* adaLN-single modulation from (pooled text + mask ratio) with per-block offsets and
|
| 17 |
+
zero-initialised gates, so every block starts as an identity.
|
| 18 |
+
* self-conditioning: the previous step's predicted distribution is projected and added
|
| 19 |
+
at masked positions.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import math
|
| 25 |
+
from typing import Optional, Tuple
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
|
| 31 |
+
from .config import TroutConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ------------------------------------------------------------------ building blocks
|
| 35 |
+
|
| 36 |
+
class RMSNorm(nn.Module):
|
| 37 |
+
def __init__(self, dim: int, eps: float = 1e-6, affine: bool = True):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.eps = eps
|
| 40 |
+
self.weight = nn.Parameter(torch.ones(dim)) if affine else None
|
| 41 |
+
|
| 42 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 43 |
+
dtype = x.dtype
|
| 44 |
+
x32 = x.float()
|
| 45 |
+
y = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 46 |
+
if self.weight is not None:
|
| 47 |
+
y = y * self.weight.float()
|
| 48 |
+
return y.to(dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _rope_freqs(head_dim: int, theta: float) -> torch.Tensor:
|
| 52 |
+
n = head_dim // 4 # rotation pairs per spatial axis
|
| 53 |
+
return 1.0 / (theta ** (torch.arange(n, dtype=torch.float64) / n))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def build_rope(n_prefix: int, grid: int, head_dim: int, theta: float, stride: int = 1):
|
| 57 |
+
"""cos/sin tables (n_prefix + grid^2, head_dim/2) for 2D axial RoPE.
|
| 58 |
+
|
| 59 |
+
Image token (i, j) at a level with `stride` pixels per token sits at the pixel-space
|
| 60 |
+
centre (i*stride + (stride-1)/2, j*stride + (stride-1)/2). Prefix tokens get angle 0.
|
| 61 |
+
"""
|
| 62 |
+
f = _rope_freqs(head_dim, theta)
|
| 63 |
+
ii, jj = torch.meshgrid(torch.arange(grid, dtype=torch.float64),
|
| 64 |
+
torch.arange(grid, dtype=torch.float64), indexing="ij")
|
| 65 |
+
off = (stride - 1) / 2.0
|
| 66 |
+
rows = (ii.reshape(-1) * stride + off)[:, None] * f[None]
|
| 67 |
+
cols = (jj.reshape(-1) * stride + off)[:, None] * f[None]
|
| 68 |
+
ang = torch.cat([rows, cols], 1)
|
| 69 |
+
ang = torch.cat([torch.zeros(n_prefix, ang.shape[1], dtype=ang.dtype), ang], 0)
|
| 70 |
+
return ang.cos().float(), ang.sin().float()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 74 |
+
# x: (B, H, N, hd); cos/sin: (N, hd/2)
|
| 75 |
+
x1, x2 = x.float().chunk(2, dim=-1)
|
| 76 |
+
out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
|
| 77 |
+
return out.to(x.dtype)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def fourier_features(x: torch.Tensor, n_freqs: int) -> torch.Tensor:
|
| 81 |
+
"""x: (..., C) roughly in [-1, 1] -> (..., C * 2 * n_freqs) sin/cos features."""
|
| 82 |
+
freqs = (2.0 ** torch.arange(n_freqs, device=x.device, dtype=torch.float32)) * math.pi
|
| 83 |
+
ang = x.float().unsqueeze(-1) * freqs
|
| 84 |
+
return torch.cat([ang.sin(), ang.cos()], dim=-1).flatten(-2)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ------------------------------------------------------------------ transformer block
|
| 88 |
+
|
| 89 |
+
class Attention(nn.Module):
|
| 90 |
+
def __init__(self, dim: int, n_heads: int):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.n_heads = n_heads
|
| 93 |
+
self.head_dim = dim // n_heads
|
| 94 |
+
self.qkv = nn.Linear(dim, 3 * dim, bias=False)
|
| 95 |
+
self.proj = nn.Linear(dim, dim, bias=False)
|
| 96 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 97 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 98 |
+
|
| 99 |
+
def forward(self, x, cos, sin):
|
| 100 |
+
B, N, D = x.shape
|
| 101 |
+
qkv = self.qkv(x).view(B, N, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
|
| 102 |
+
q, k, v = qkv.unbind(0)
|
| 103 |
+
q = apply_rope(self.q_norm(q), cos, sin)
|
| 104 |
+
k = apply_rope(self.k_norm(k), cos, sin)
|
| 105 |
+
o = F.scaled_dot_product_attention(q, k, v)
|
| 106 |
+
return self.proj(o.transpose(1, 2).reshape(B, N, D))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class ConvSwiGLU(nn.Module):
|
| 110 |
+
"""SwiGLU whose gate branch gets a residual depthwise 3x3 conv over the image grid."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, dim: int, hidden: int, conv: bool = True):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.w12 = nn.Linear(dim, 2 * hidden, bias=False)
|
| 115 |
+
self.w3 = nn.Linear(hidden, dim, bias=False)
|
| 116 |
+
self.dw = nn.Conv2d(hidden, hidden, 3, padding=1, groups=hidden, bias=True) if conv else None
|
| 117 |
+
|
| 118 |
+
def forward(self, x, n_prefix: int, hw: Tuple[int, int]):
|
| 119 |
+
a, g = self.w12(x).chunk(2, dim=-1)
|
| 120 |
+
if self.dw is not None:
|
| 121 |
+
B, _, C = g.shape
|
| 122 |
+
H, W = hw
|
| 123 |
+
g_pre, g_img = g[:, :n_prefix], g[:, n_prefix:]
|
| 124 |
+
conv = self.dw(g_img.transpose(1, 2).reshape(B, C, H, W)).flatten(2).transpose(1, 2)
|
| 125 |
+
g = torch.cat([g_pre, g_img + conv.to(g_img.dtype)], dim=1)
|
| 126 |
+
return self.w3(a * F.silu(g))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class Block(nn.Module):
|
| 130 |
+
def __init__(self, cfg: TroutConfig):
|
| 131 |
+
super().__init__()
|
| 132 |
+
self.norm1 = RMSNorm(cfg.dim, affine=False)
|
| 133 |
+
self.attn = Attention(cfg.dim, cfg.n_heads)
|
| 134 |
+
self.norm2 = RMSNorm(cfg.dim, affine=False)
|
| 135 |
+
self.mlp = ConvSwiGLU(cfg.dim, cfg.mlp_hidden, conv=cfg.conv_ffn)
|
| 136 |
+
# per-block offsets added to the shared adaLN-single modulation (shift/scale/gate x2)
|
| 137 |
+
self.mod_bias = nn.Parameter(torch.zeros(6, cfg.dim))
|
| 138 |
+
|
| 139 |
+
def forward(self, x, mod, cos, sin, n_prefix: int, hw: Tuple[int, int]):
|
| 140 |
+
m = (mod + self.mod_bias).unsqueeze(2) # (B, 6, 1, D)
|
| 141 |
+
sh1, sc1, g1, sh2, sc2, g2 = m.unbind(1)
|
| 142 |
+
h = self.norm1(x) * (1 + sc1) + sh1
|
| 143 |
+
x = x + g1 * self.attn(h, cos, sin)
|
| 144 |
+
h = self.norm2(x) * (1 + sc2) + sh2
|
| 145 |
+
x = x + g2 * self.mlp(h, n_prefix, hw)
|
| 146 |
+
return x
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------------ the model
|
| 150 |
+
|
| 151 |
+
class Trout(nn.Module):
|
| 152 |
+
def __init__(self, cfg: TroutConfig, palette_lab: Optional[torch.Tensor] = None,
|
| 153 |
+
palette_rgb: Optional[torch.Tensor] = None):
|
| 154 |
+
super().__init__()
|
| 155 |
+
cfg.validate()
|
| 156 |
+
self.cfg = cfg
|
| 157 |
+
K, D, G = cfg.vocab_size, cfg.dim, cfg.grid_size
|
| 158 |
+
self.mask_id = cfg.mask_id
|
| 159 |
+
|
| 160 |
+
if palette_lab is None:
|
| 161 |
+
palette_lab = torch.zeros(K, 3)
|
| 162 |
+
if palette_rgb is None:
|
| 163 |
+
palette_rgb = torch.zeros(K, 3, dtype=torch.uint8)
|
| 164 |
+
assert palette_lab.shape == (K, 3), f"palette has {palette_lab.shape[0]} colours, config says {K}"
|
| 165 |
+
self.register_buffer("palette_lab", palette_lab.float().clone())
|
| 166 |
+
self.register_buffer("palette_rgb", palette_rgb.to(torch.uint8).clone())
|
| 167 |
+
|
| 168 |
+
# ---- colour-grounded token embeddings ----
|
| 169 |
+
self.tok_emb = nn.Embedding(K + 1, D) # +1 for MASK
|
| 170 |
+
n_feat = 3 + 3 * 2 * cfg.color_freqs + 1
|
| 171 |
+
self.color_mlp = nn.Sequential(nn.Linear(n_feat, D), nn.SiLU(), nn.Linear(D, D))
|
| 172 |
+
self.pos_emb = nn.Parameter(torch.zeros(1, G * G, D))
|
| 173 |
+
self.sc_proj = nn.Linear(K, D, bias=False) if cfg.self_cond else None
|
| 174 |
+
|
| 175 |
+
# ---- text conditioning ----
|
| 176 |
+
self.text_norm = RMSNorm(cfg.text_dim)
|
| 177 |
+
self.text_proj = nn.Linear(cfg.text_dim, D)
|
| 178 |
+
self.null_text = nn.Parameter(torch.zeros(1, cfg.text_len, D))
|
| 179 |
+
self.pool_mlp = nn.Sequential(RMSNorm(cfg.text_dim), nn.Linear(cfg.text_dim, D), nn.SiLU(), nn.Linear(D, D))
|
| 180 |
+
self.null_cond = nn.Parameter(torch.zeros(1, D))
|
| 181 |
+
self.ratio_mlp = nn.Sequential(nn.Linear(2 * 8, D), nn.SiLU(), nn.Linear(D, D))
|
| 182 |
+
self.registers = nn.Parameter(torch.zeros(1, cfg.n_registers, D))
|
| 183 |
+
self.t_block = nn.Sequential(nn.SiLU(), nn.Linear(D, 6 * D))
|
| 184 |
+
|
| 185 |
+
# ---- hourglass backbone ----
|
| 186 |
+
if cfg.hourglass:
|
| 187 |
+
p = cfg.patch
|
| 188 |
+
self.blocks_in = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_in)])
|
| 189 |
+
self.down = nn.Sequential(RMSNorm(p * p * D), nn.Linear(p * p * D, D))
|
| 190 |
+
self.blocks_core = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_core)])
|
| 191 |
+
self.up = nn.Linear(D, p * p * D)
|
| 192 |
+
self.blocks_out = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_out)])
|
| 193 |
+
else:
|
| 194 |
+
self.blocks_in = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_in + cfg.depth_core + cfg.depth_out)])
|
| 195 |
+
self.down = self.up = None
|
| 196 |
+
self.blocks_core = nn.ModuleList()
|
| 197 |
+
self.blocks_out = nn.ModuleList()
|
| 198 |
+
|
| 199 |
+
self.norm_out = RMSNorm(D, affine=False)
|
| 200 |
+
self.final_mod = nn.Sequential(nn.SiLU(), nn.Linear(D, 2 * D))
|
| 201 |
+
self.head = nn.Linear(D, K)
|
| 202 |
+
|
| 203 |
+
# ---- fixed tables ----
|
| 204 |
+
self.n_prefix = cfg.n_registers + cfg.text_len
|
| 205 |
+
cf, sf = build_rope(self.n_prefix, G, cfg.head_dim, cfg.rope_theta, stride=1)
|
| 206 |
+
self.register_buffer("rope_cos", cf, persistent=False)
|
| 207 |
+
self.register_buffer("rope_sin", sf, persistent=False)
|
| 208 |
+
if cfg.hourglass:
|
| 209 |
+
cc, sc = build_rope(self.n_prefix, G // cfg.patch, cfg.head_dim, cfg.rope_theta, stride=cfg.patch)
|
| 210 |
+
else:
|
| 211 |
+
cc, sc = cf[:1], sf[:1]
|
| 212 |
+
self.register_buffer("rope_cos_core", cc, persistent=False)
|
| 213 |
+
self.register_buffer("rope_sin_core", sc, persistent=False)
|
| 214 |
+
self.register_buffer("color_feats", self._color_features(self.palette_lab), persistent=False)
|
| 215 |
+
self.grad_checkpointing = False
|
| 216 |
+
|
| 217 |
+
self._init_weights()
|
| 218 |
+
|
| 219 |
+
# ---------------------------------------------------------------- helpers
|
| 220 |
+
def _color_features(self, lab: torch.Tensor) -> torch.Tensor:
|
| 221 |
+
x = torch.stack([lab[:, 0] * 2 - 1, lab[:, 1] / 0.4, lab[:, 2] / 0.4], -1)
|
| 222 |
+
alpha = torch.ones(lab.shape[0], 1)
|
| 223 |
+
alpha[0] = 0.0 # token 0 = transparent
|
| 224 |
+
x = x * alpha
|
| 225 |
+
return torch.cat([x, fourier_features(x, self.cfg.color_freqs), alpha], -1)
|
| 226 |
+
|
| 227 |
+
def set_palette(self, palette_lab: torch.Tensor, palette_rgb: torch.Tensor) -> None:
|
| 228 |
+
self.palette_lab.copy_(palette_lab.float())
|
| 229 |
+
self.palette_rgb.copy_(palette_rgb.to(torch.uint8))
|
| 230 |
+
self.color_feats = self._color_features(self.palette_lab.detach().cpu()).to(self.palette_lab.device)
|
| 231 |
+
|
| 232 |
+
def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
|
| 233 |
+
super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
|
| 234 |
+
self.color_feats = self._color_features(self.palette_lab.detach().cpu()).to(self.palette_lab.device)
|
| 235 |
+
|
| 236 |
+
def _init_weights(self) -> None:
|
| 237 |
+
def init(m):
|
| 238 |
+
if isinstance(m, nn.Linear):
|
| 239 |
+
nn.init.trunc_normal_(m.weight, std=0.02)
|
| 240 |
+
if m.bias is not None:
|
| 241 |
+
nn.init.zeros_(m.bias)
|
| 242 |
+
elif isinstance(m, nn.Embedding):
|
| 243 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 244 |
+
self.apply(init)
|
| 245 |
+
nn.init.trunc_normal_(self.pos_emb, std=0.02)
|
| 246 |
+
nn.init.normal_(self.null_text, std=0.02)
|
| 247 |
+
nn.init.normal_(self.null_cond, std=0.02)
|
| 248 |
+
nn.init.normal_(self.registers, std=0.02)
|
| 249 |
+
# zero-init: conditioning outputs, gates, head, self-cond, hourglass up path
|
| 250 |
+
for m in [self.t_block[-1], self.final_mod[-1], self.head]:
|
| 251 |
+
nn.init.zeros_(m.weight)
|
| 252 |
+
nn.init.zeros_(m.bias)
|
| 253 |
+
if self.sc_proj is not None:
|
| 254 |
+
nn.init.zeros_(self.sc_proj.weight)
|
| 255 |
+
if self.up is not None:
|
| 256 |
+
nn.init.zeros_(self.up.weight)
|
| 257 |
+
nn.init.zeros_(self.up.bias)
|
| 258 |
+
for blk in list(self.blocks_in) + list(self.blocks_core) + list(self.blocks_out):
|
| 259 |
+
if blk.mlp.dw is not None:
|
| 260 |
+
nn.init.zeros_(blk.mlp.dw.weight)
|
| 261 |
+
nn.init.zeros_(blk.mlp.dw.bias)
|
| 262 |
+
|
| 263 |
+
def _merge(self, h: torch.Tensor) -> torch.Tensor:
|
| 264 |
+
B, N, D = h.shape
|
| 265 |
+
G, p = self.cfg.grid_size, self.cfg.patch
|
| 266 |
+
g = G // p
|
| 267 |
+
h = h.view(B, g, p, g, p, D).permute(0, 1, 3, 2, 4, 5).reshape(B, g * g, p * p * D)
|
| 268 |
+
return self.down(h)
|
| 269 |
+
|
| 270 |
+
def _split(self, h: torch.Tensor) -> torch.Tensor:
|
| 271 |
+
B = h.shape[0]
|
| 272 |
+
G, p, D = self.cfg.grid_size, self.cfg.patch, self.cfg.dim
|
| 273 |
+
g = G // p
|
| 274 |
+
h = self.up(h).view(B, g, g, p, p, D).permute(0, 1, 3, 2, 4, 5).reshape(B, G * G, D)
|
| 275 |
+
return h
|
| 276 |
+
|
| 277 |
+
def _run(self, blk: Block, xs, mod, cos, sin, n_pre: int, hw: Tuple[int, int]):
|
| 278 |
+
if self.grad_checkpointing and self.training and torch.is_grad_enabled():
|
| 279 |
+
return torch.utils.checkpoint.checkpoint(blk, xs, mod, cos, sin, n_pre, hw, use_reentrant=False)
|
| 280 |
+
return blk(xs, mod, cos, sin, n_pre, hw)
|
| 281 |
+
|
| 282 |
+
def embed_table(self) -> torch.Tensor:
|
| 283 |
+
K = self.cfg.vocab_size
|
| 284 |
+
w = self.tok_emb.weight
|
| 285 |
+
colors = w[:K] + self.color_mlp(self.color_feats).to(w.dtype)
|
| 286 |
+
return torch.cat([colors, w[K:]], 0)
|
| 287 |
+
|
| 288 |
+
# ---------------------------------------------------------------- forward
|
| 289 |
+
def forward(self, x: torch.Tensor, text_states: torch.Tensor, text_pooled: torch.Tensor,
|
| 290 |
+
mask_ratio: Optional[torch.Tensor] = None, sc_probs: Optional[torch.Tensor] = None,
|
| 291 |
+
drop_text: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 292 |
+
"""
|
| 293 |
+
x: (B, N) long, palette ids or mask_id
|
| 294 |
+
text_states: (B, L, text_dim) frozen text-encoder token states
|
| 295 |
+
text_pooled: (B, text_dim) pooled text embedding
|
| 296 |
+
mask_ratio: (B,) fraction of masked tokens (computed from x if None)
|
| 297 |
+
sc_probs: (B, N, K) previous-step predicted distribution (self-conditioning) or None
|
| 298 |
+
drop_text: (B,) bool, replace text with the learned null condition (CFG)
|
| 299 |
+
returns logits (B, N, K) in float32
|
| 300 |
+
"""
|
| 301 |
+
cfg = self.cfg
|
| 302 |
+
B, N = x.shape
|
| 303 |
+
D, G = cfg.dim, cfg.grid_size
|
| 304 |
+
is_mask = x == self.mask_id
|
| 305 |
+
if mask_ratio is None:
|
| 306 |
+
mask_ratio = is_mask.float().mean(1)
|
| 307 |
+
|
| 308 |
+
# ---- image tokens ----
|
| 309 |
+
h = F.embedding(x, self.embed_table()).float() + self.pos_emb
|
| 310 |
+
if self.sc_proj is not None and sc_probs is not None:
|
| 311 |
+
h = h + self.sc_proj(sc_probs.to(self.sc_proj.weight.dtype)).float() * is_mask.unsqueeze(-1)
|
| 312 |
+
|
| 313 |
+
# ---- text tokens + global conditioning ----
|
| 314 |
+
t = self.text_proj(self.text_norm(text_states.float())).float()
|
| 315 |
+
c = self.pool_mlp(text_pooled.float()).float()
|
| 316 |
+
if drop_text is not None:
|
| 317 |
+
t = torch.where(drop_text.view(B, 1, 1), self.null_text, t)
|
| 318 |
+
c = torch.where(drop_text.view(B, 1), self.null_cond, c)
|
| 319 |
+
r = mask_ratio.float().view(B, 1) * 2 - 1
|
| 320 |
+
g = c + self.ratio_mlp(fourier_features(r, 8).view(B, -1)).float()
|
| 321 |
+
mod = self.t_block(g).float().view(B, 6, D)
|
| 322 |
+
|
| 323 |
+
prefix = torch.cat([self.registers.expand(B, -1, -1), t], 1)
|
| 324 |
+
n_pre = prefix.shape[1]
|
| 325 |
+
xs = torch.cat([prefix, h], 1)
|
| 326 |
+
|
| 327 |
+
# ---- pixel level (in) ----
|
| 328 |
+
for blk in self.blocks_in:
|
| 329 |
+
xs = self._run(blk, xs, mod, self.rope_cos, self.rope_sin, n_pre, (G, G))
|
| 330 |
+
|
| 331 |
+
# ---- patch level (core) ----
|
| 332 |
+
if cfg.hourglass:
|
| 333 |
+
pre, img = xs[:, :n_pre], xs[:, n_pre:]
|
| 334 |
+
skip = img
|
| 335 |
+
xs = torch.cat([pre, self._merge(img).float()], 1)
|
| 336 |
+
gc = G // cfg.patch
|
| 337 |
+
for blk in self.blocks_core:
|
| 338 |
+
xs = self._run(blk, xs, mod, self.rope_cos_core, self.rope_sin_core, n_pre, (gc, gc))
|
| 339 |
+
pre, core = xs[:, :n_pre], xs[:, n_pre:]
|
| 340 |
+
xs = torch.cat([pre, skip + self._split(core).float()], 1)
|
| 341 |
+
|
| 342 |
+
# ---- pixel level (out) ----
|
| 343 |
+
for blk in self.blocks_out:
|
| 344 |
+
xs = self._run(blk, xs, mod, self.rope_cos, self.rope_sin, n_pre, (G, G))
|
| 345 |
+
|
| 346 |
+
img = xs[:, n_pre:]
|
| 347 |
+
shift, scale = self.final_mod(g).float().unsqueeze(1).chunk(2, dim=-1)
|
| 348 |
+
img = self.norm_out(img) * (1 + scale) + shift
|
| 349 |
+
return self.head(img).float()
|
| 350 |
+
|
| 351 |
+
# ---------------------------------------------------------------- reporting
|
| 352 |
+
def num_params(self, trainable_only: bool = True) -> int:
|
| 353 |
+
return sum(p.numel() for p in self.parameters() if p.requires_grad or not trainable_only)
|
| 354 |
+
|
| 355 |
+
def flops_per_sample(self) -> float:
|
| 356 |
+
"""Rough forward FLOPs per image (matmuls + attention)."""
|
| 357 |
+
cfg = self.cfg
|
| 358 |
+
D, Hd = cfg.dim, cfg.mlp_hidden
|
| 359 |
+
n_pre = self.n_prefix
|
| 360 |
+
per_tok = 2 * (4 * D * D + 3 * D * Hd)
|
| 361 |
+
|
| 362 |
+
def stage(n_img, depth):
|
| 363 |
+
n = n_pre + n_img
|
| 364 |
+
return depth * (n * per_tok + 4 * n * n * D)
|
| 365 |
+
|
| 366 |
+
G = cfg.grid_size
|
| 367 |
+
if cfg.hourglass:
|
| 368 |
+
f = stage(G * G, cfg.depth_in + cfg.depth_out) + stage((G // cfg.patch) ** 2, cfg.depth_core)
|
| 369 |
+
else:
|
| 370 |
+
f = stage(G * G, cfg.depth_in + cfg.depth_core + cfg.depth_out)
|
| 371 |
+
f += 2 * G * G * D * cfg.vocab_size * (2 if cfg.self_cond else 1)
|
| 372 |
+
return float(f)
|