File size: 15,113 Bytes
40c5ebe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6, affine=True):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim)) if affine else None
def forward(self, x):
y = (x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype)
return y * self.weight if self.weight is not None else y
class Rotary2D(nn.Module):
def __init__(self, h, w, head_dim, base=10_000.0):
super().__init__()
pair = head_dim // 4
inv = 1.0 / (base ** (np.arange(pair, dtype=np.float64) / pair))
fr = np.repeat(np.outer(np.arange(h), inv), w, axis=0)
fc = np.tile(np.outer(np.arange(w), inv), (h, 1))
for name, val in (("cos_row", np.cos(fr)), ("sin_row", np.sin(fr)), ("cos_col", np.cos(fc)), ("sin_col", np.sin(fc))):
self.register_buffer(name, torch.from_numpy(val).float(), persistent=False)
@staticmethod
def _rot(v, cos, sin):
a, b = v.chunk(2, -1)
return torch.cat([a * cos - b * sin, a * sin + b * cos], -1)
def forward(self, q, k):
cr, sr, cc, sc = (getattr(self, n).to(q.dtype) for n in ("cos_row", "sin_row", "cos_col", "sin_col"))
def rot(x):
r, c = x.chunk(2, -1)
return torch.cat([self._rot(r, cr, sr), self._rot(c, cc, sc)], -1)
return rot(q), rot(k)
class SelfAttention(nn.Module):
def __init__(self, dim, heads):
super().__init__()
self.heads, self.hd = heads, dim // heads
self.qkv = nn.Linear(dim, 3 * dim, bias=False)
self.proj = nn.Linear(dim, dim, bias=False)
self.q_norm, self.k_norm = RMSNorm(self.hd), RMSNorm(self.hd)
def forward(self, x, rope):
b, n, d = x.shape
q, k, v = self.qkv(x).view(b, n, 3, self.heads, self.hd).permute(2, 0, 3, 1, 4).unbind(0)
q, k = rope(self.q_norm(q), self.k_norm(k))
return self.proj(F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(b, n, d))
class CrossAttention(nn.Module):
def __init__(self, dim, heads):
super().__init__()
self.heads, self.hd = heads, dim // heads
self.q, self.k, self.v, self.proj = (nn.Linear(dim, dim, bias=False) for _ in range(4))
self.q_norm, self.k_norm = RMSNorm(self.hd), RMSNorm(self.hd)
def forward(self, x, ctx, mask):
b, n, d = x.shape
m = ctx.shape[1]
q = self.q_norm(self.q(x).view(b, n, self.heads, self.hd).transpose(1, 2))
k = self.k_norm(self.k(ctx).view(b, m, self.heads, self.hd).transpose(1, 2))
v = self.v(ctx).view(b, m, self.heads, self.hd).transpose(1, 2)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask[:, None, None, :])
return self.proj(out.transpose(1, 2).reshape(b, n, d))
class SwiGLU(nn.Module):
def __init__(self, dim, hidden):
super().__init__()
self.w12 = nn.Linear(dim, 2 * hidden)
self.w3 = nn.Linear(hidden, dim)
def forward(self, x):
a, b = self.w12(x).chunk(2, -1)
return self.w3(F.silu(a) * b)
class DiTBlock(nn.Module):
"""ada_rank 0: Nyx's per-block AdaLN Linear(cond, 6d).
ada_rank r > 0: adaLN-single with a per-block low-rank residual (nyx-efficiency.md section 1):
ada_i(cond) = g_i * shared_d(cond) + B_i(A_i(cond)) + E_i
shared_d is one Linear per width (owned by the model); g_i is a per-block gain (6d) so a new
block can start as exact identity (g = B = E = 0)."""
def __init__(self, dim, heads, hidden, cond_dim, ada_rank=0):
super().__init__()
self.ada_rank = ada_rank
if ada_rank:
self.ada_A = nn.Linear(cond_dim, ada_rank, bias=False)
self.ada_B = nn.Linear(ada_rank, 6 * dim, bias=False)
self.ada_E = nn.Parameter(torch.zeros(6 * dim))
self.ada_g = nn.Parameter(torch.ones(6 * dim))
else:
self.ada = nn.Linear(cond_dim, 6 * dim)
self.norm_in = RMSNorm(dim, affine=False)
self.norm_mlp = RMSNorm(dim, affine=False)
self.cross_norm = RMSNorm(dim)
self.self_attn = SelfAttention(dim, heads)
self.cross_attn = CrossAttention(dim, heads)
self.mlp = SwiGLU(dim, hidden)
self.cross_gate = nn.Parameter(torch.zeros(1))
def modulation(self, cond, shared=None):
if self.ada_rank:
return self.ada_g * shared + self.ada_B(self.ada_A(cond)) + self.ada_E
return self.ada(cond)
def forward(self, x, cond, rope, ctx, mask, shared=None):
s1, c1, g1, s2, c2, g2 = (t.unsqueeze(1) for t in self.modulation(cond, shared).chunk(6, -1))
x = x + g1 * self.self_attn(self.norm_in(x) * (1 + c1) + s1, rope)
x = x + self.cross_gate * self.cross_attn(self.cross_norm(x), ctx, mask)
return x + g2 * self.mlp(self.norm_mlp(x) * (1 + c2) + s2)
class ConvResBlock(nn.Module):
def __init__(self, ch, cond_dim, groups=8):
super().__init__()
self.norm = nn.GroupNorm(groups, ch)
self.ada = nn.Linear(cond_dim, 2 * ch)
self.conv = nn.Conv2d(ch, ch, 3, padding=1)
def forward(self, x, cond):
scale, shift = self.ada(cond)[:, :, None, None].chunk(2, 1)
return x + self.conv(F.silu(self.norm(x) * (1 + scale) + shift))
# rows of a 3x3 kernel that land on each of the two low-res rows read by output phase a
_FOLD = torch.tensor([[[1., 0., 0.], [0., 1., 1.]], # a = 0: input rows (i-1, i)
[[1., 1., 0.], [0., 0., 1.]]]) # a = 1: input rows (i, i+1)
class PhaseConv(nn.Conv2d):
"""A 3x3 conv applied after nearest-2x upsampling, computed exactly at the low resolution
(docs/research/nyx-efficiency.md section 2): output pixel (2i+a, 2j+b) reads a 2x2 low-res
window, so the 9 taps fold into one 2x2 kernel per phase: 16 MACs per low-res position and
channel pair instead of 36. Same parameter (a 3x3 weight), so Nyx weights load unchanged.
`forward(x_lowres)` == `conv2d(interpolate(x_lowres, 2, "nearest"), weight, padding=1)`."""
def __init__(self, cin, cout, phase=True):
super().__init__(cin, cout, 3, padding=1)
self.phase = phase
def forward(self, x):
if not self.phase:
return super().forward(F.interpolate(x, scale_factor=2, mode="nearest"))
b, _, h, w = x.shape
R = _FOLD.to(self.weight)
outs = []
for a in (0, 1):
for c in (0, 1):
k = torch.einsum("rk,oikl,cl->oirc", R[a], self.weight, R[c])
outs.append(F.conv2d(F.pad(x, (1 - c, c, 1 - a, a)), k, self.bias))
y = torch.stack(outs, 2).view(b, -1, 2, 2, h, w) # [B, O, a, c, H, W]
return y.permute(0, 1, 4, 2, 5, 3).reshape(b, -1, 2 * h, 2 * w)
def sinusoidal(t, dim=256, max_period=10_000.0):
half = dim // 2
inv = 1.0 / (max_period ** (torch.arange(half, device=t.device, dtype=torch.float32) / half))
f = t.float()[:, None] * inv[None]
return torch.cat([f.cos(), f.sin()], -1)
class SolsticeGenerator(nn.Module):
def __init__(self, text_dim=768, pool_dim=768, text_tokens=32, text_norm=True, cond_dim=384,
outer_blocks=2, core_blocks=8, outer_dim=256, core_dim=384, outer_heads=4, core_heads=6,
outer_hidden=768, core_hidden=1024, stem=64, channels=4, phase_up=False, ada_rank=0,
guidance=False, pred="v", self_cond=False, pix_blocks=0, pix_heads=4, pix_hidden=384):
super().__init__()
# pred "x0" (2026-12-02, change 5): the head predicts the clean sprite and forward() returns the velocity
# (x_t - x0_hat) / t, so losses, samplers and exports keep working with v. self_cond (change 3): 4 more
# input channels carry the previous x0 estimate (zeros when absent, so the model also runs without it).
self.pred, self.self_cond = pred, self_cond
self.text_tokens, self.pool_dim, self.channels = text_tokens, pool_dim, channels
self.checkpoint = False
self.outer_dim, self.core_dim = outer_dim, core_dim
self.time_mlp = nn.Sequential(nn.Linear(256, cond_dim), nn.SiLU(), nn.Linear(cond_dim, cond_dim))
if pool_dim:
self.pool_mlp = nn.Sequential(nn.Linear(pool_dim, cond_dim), nn.SiLU(), nn.Linear(cond_dim, cond_dim))
self.pool_norm = RMSNorm(pool_dim) if text_norm else nn.Identity()
self.text_norm = RMSNorm(text_dim) if text_norm else nn.Identity()
self.text_proj_outer = nn.Linear(text_dim, outer_dim)
self.text_proj_inner = nn.Linear(text_dim, core_dim)
self.stem_conv = nn.Conv2d(channels * (2 if self_cond else 1), stem, 3, padding=1)
self.stem_blocks = nn.ModuleList([ConvResBlock(stem, cond_dim) for _ in range(2)])
self.down_32 = nn.Conv2d(stem, outer_dim, 2, stride=2)
self.rope_16 = Rotary2D(16, 16, outer_dim // outer_heads)
self.ada_rank = ada_rank
if ada_rank:
self.ada_shared_outer = nn.Linear(cond_dim, 6 * outer_dim)
self.ada_shared_core = nn.Linear(cond_dim, 6 * core_dim)
self.outer_encoder = nn.ModuleList([DiTBlock(outer_dim, outer_heads, outer_hidden, cond_dim, ada_rank) for _ in range(outer_blocks)])
self.down_16 = nn.Conv2d(outer_dim, core_dim, 2, stride=2)
self.rope_8 = Rotary2D(8, 8, core_dim // core_heads)
self.bottleneck = nn.ModuleList([DiTBlock(core_dim, core_heads, core_hidden, cond_dim, ada_rank) for _ in range(core_blocks)])
self.up_16 = PhaseConv(core_dim, outer_dim, phase_up)
self.fuse_16 = nn.Conv2d(2 * outer_dim, outer_dim, 1)
self.outer_decoder = nn.ModuleList([DiTBlock(outer_dim, outer_heads, outer_hidden, cond_dim, ada_rank) for _ in range(outer_blocks)])
self.up_32 = PhaseConv(outer_dim, stem, phase_up)
self.fuse_32 = nn.Conv2d(2 * stem, stem, 1)
self.out_blocks = nn.ModuleList([ConvResBlock(stem, cond_dim) for _ in range(2)])
# full-resolution attention (2026-12-02, change 2 / A/B "e"): DiT blocks over all 32x32 pixels at the stem
# width, after the head's skip fuse, so each pixel is decided while attending to the whole sprite and the text
self.pix_blocks = nn.ModuleList([DiTBlock(stem, pix_heads, pix_hidden, cond_dim) for _ in range(pix_blocks)])
if pix_blocks:
self.rope_32 = Rotary2D(32, 32, stem // pix_heads)
self.text_proj_pix = nn.Linear(text_dim, stem)
self.out_norm = nn.GroupNorm(8, stem)
self.out_conv = nn.Conv2d(stem, channels, 3, padding=1)
self.apply(self._init)
for blk in self.dit_blocks():
if ada_rank: # from scratch: zero B_i and the shared maps keep AdaLN-Zero's identity start
nn.init.zeros_(blk.ada_B.weight)
else:
nn.init.zeros_(blk.ada.weight)
nn.init.zeros_(blk.ada.bias)
nn.init.zeros_(blk.cross_gate)
if ada_rank:
for lin in (self.ada_shared_outer, self.ada_shared_core):
nn.init.zeros_(lin.weight)
nn.init.zeros_(lin.bias)
nn.init.zeros_(self.out_conv.weight)
nn.init.zeros_(self.out_conv.bias)
# guidance-scale embedding for CFG distillation (distill.py). Built after the init above, so a
# model without it draws the same random init as before; its last layer is zero, so a student
# loaded from a teacher computes exactly the teacher's output until it is trained.
self.w_mlp = None
if guidance:
self.w_mlp = nn.Sequential(nn.Linear(256, cond_dim), nn.SiLU(), nn.Linear(cond_dim, cond_dim))
nn.init.xavier_uniform_(self.w_mlp[0].weight)
nn.init.zeros_(self.w_mlp[0].bias)
nn.init.zeros_(self.w_mlp[2].weight)
nn.init.zeros_(self.w_mlp[2].bias)
@staticmethod
def _init(m):
if isinstance(m, (nn.Linear, nn.Conv2d)):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
def dit_blocks(self):
yield from self.outer_encoder
yield from self.bottleneck
yield from self.outer_decoder
yield from self.pix_blocks
def gates(self):
return [float(b.cross_gate) for b in self.dit_blocks()]
def forward(self, x, t, pool, tokens, mask, w=None, sc=None):
b = x.shape[0]
x_t = x
if self.self_cond:
x = torch.cat([x, torch.zeros_like(x) if sc is None else sc.to(x.dtype)], 1)
mask = mask.clone()
mask[:, 0] = True
cond = self.time_mlp(sinusoidal(t).to(x.dtype))
if self.w_mlp is not None and w is not None:
cond = cond + self.w_mlp(sinusoidal(w).to(x.dtype))
if self.pool_dim:
cond = cond + self.pool_mlp(self.pool_norm(pool))
tok = self.text_norm(tokens)
ctx_o, ctx_i = self.text_proj_outer(tok), self.text_proj_inner(tok)
sh_o = self.ada_shared_outer(cond) if self.ada_rank else None
sh_i = self.ada_shared_core(cond) if self.ada_rank else None
h = self.stem_conv(x)
for blk in self.stem_blocks:
h = blk(h, cond)
skip_32 = h
z = self.down_32(h).flatten(2).transpose(1, 2)
for blk in self.outer_encoder:
z = blk(z, cond, self.rope_16, ctx_o, mask, sh_o)
skip_16 = z.transpose(1, 2).reshape(b, self.outer_dim, 16, 16)
z = self.down_16(skip_16).flatten(2).transpose(1, 2)
for blk in self.bottleneck:
if self.checkpoint and self.training:
z = torch.utils.checkpoint.checkpoint(blk, z, cond, self.rope_8, ctx_i, mask, sh_i, use_reentrant=False)
else:
z = blk(z, cond, self.rope_8, ctx_i, mask, sh_i)
h = self.up_16(z.transpose(1, 2).reshape(b, self.core_dim, 8, 8))
z = self.fuse_16(torch.cat([h, skip_16], 1)).flatten(2).transpose(1, 2)
for blk in self.outer_decoder:
z = blk(z, cond, self.rope_16, ctx_o, mask, sh_o)
h = self.up_32(z.transpose(1, 2).reshape(b, self.outer_dim, 16, 16))
h = self.fuse_32(torch.cat([h, skip_32], 1))
if len(self.pix_blocks):
z = h.flatten(2).transpose(1, 2)
ctx_p = self.text_proj_pix(tok)
for blk in self.pix_blocks:
z = blk(z, cond, self.rope_32, ctx_p, mask)
h = z.transpose(1, 2).reshape(b, -1, 32, 32)
for blk in self.out_blocks:
h = blk(h, cond)
out = self.out_conv(F.silu(self.out_norm(h)))
if self.pred == "x0": # x_t = x0 + t v -> v = (x_t - x0_hat) / t, t floored so the conversion stays bounded
return (x_t - out) / t.float().clamp(min=0.05).to(out.dtype)[:, None, None, None]
return out
@staticmethod
def x0_of(x_t, t, v):
"""The clean-sprite estimate implied by a velocity: x0 = x_t - t v."""
return x_t - t[:, None, None, None] * v
|