"""Photon Head: a small bidirectional local DiT that generates one patch (2 latent frames) per backbone step with flow matching, conditioned on the backbone state h_t (AdaLN-Zero), the previous `n_ctx_patches` patches (DiTAR-style local context), and optional per-frame Score Clock features (pitch / onsets at 25 Hz). Time conditioning takes (t, r) so the same head can later be distilled with MeanFlow / shortcut objectives (r = t during standard flow-matching training; dt = t - r). CFG lives here only: a learned null replaces h_t with prob p_uncond. """ from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as F from ..config import HeadConfig from ..train.flow_loss import interpolate, sample_t def timestep_embedding(t: torch.Tensor, dim: int, max_period: float = 10_000.0) -> torch.Tensor: half = dim // 2 freqs = torch.exp(-math.log(max_period) * torch.arange(half, device=t.device, dtype=torch.float32) / half) args = t.float()[:, None] * 1000.0 * freqs[None] return torch.cat([torch.cos(args), torch.sin(args)], dim=-1) class DiTBlock(nn.Module): def __init__(self, dim: int, heads: int): super().__init__() self.heads = heads self.n1 = nn.LayerNorm(dim, elementwise_affine=False) self.qkv = nn.Linear(dim, 3 * dim) self.proj = nn.Linear(dim, dim) self.n2 = nn.LayerNorm(dim, elementwise_affine=False) self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(approximate="tanh"), nn.Linear(4 * dim, dim)) self.ada = nn.Linear(dim, 6 * dim) nn.init.zeros_(self.ada.weight) nn.init.zeros_(self.ada.bias) def forward(self, x, c): # x: (N, L, D), c: (N, D) s1, b1, g1, s2, b2, g2 = self.ada(F.silu(c))[:, None].chunk(6, dim=-1) h = self.n1(x) * (1 + s1) + b1 N, L, D = h.shape q, k, v = self.qkv(h).view(N, L, 3, self.heads, D // self.heads).permute(2, 0, 3, 1, 4) a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(N, L, D) x = x + g1 * self.proj(a) h = self.n2(x) * (1 + s2) + b2 return x + g2 * self.mlp(h) class PhotonHead(nn.Module): def __init__(self, cfg: HeadConfig, latent_dim: int, patch: int, cond_dim: int, frame_cond_dim: int = 0): super().__init__() self.cfg, self.patch, self.latent_dim = cfg, patch, latent_dim d = cfg.dim self.n_ctx = cfg.n_ctx_patches * patch # context frames self.inp = nn.Linear(latent_dim, d) self.pos = nn.Parameter(torch.randn(self.n_ctx + patch, d) * 0.02) self.cond = nn.Sequential(nn.Linear(cond_dim, d), nn.SiLU(), nn.Linear(d, d)) self.null_cond = nn.Parameter(torch.zeros(cond_dim)) self.t_mlp = nn.Sequential(nn.Linear(2 * 256, d), nn.SiLU(), nn.Linear(d, d)) self.frame_cond = nn.Linear(frame_cond_dim, d) if frame_cond_dim else None self.blocks = nn.ModuleList(DiTBlock(d, cfg.heads) for _ in range(cfg.layers)) self.norm_out = nn.LayerNorm(d, elementwise_affine=False) self.ada_out = nn.Linear(d, 2 * d) self.out = nn.Linear(d, latent_dim) for m in (self.ada_out, self.out): nn.init.zeros_(m.weight) nn.init.zeros_(m.bias) def forward(self, x_t, t, h, ctx, r=None, frame_cond=None): """x_t: (N, patch, D) noisy target frames; t, r: (N,); h: (N, cond_dim); ctx: (N, n_ctx, D) previous clean frames; frame_cond: (N, n_ctx + patch, frame_cond_dim). Returns predicted velocity (N, patch, D).""" r = t if r is None else r dt = self.inp.weight.dtype # timesteps / noise scales are fp32; run the net in param dtype x_t, ctx, h = x_t.to(dt), ctx.to(dt), h.to(dt) x = self.inp(torch.cat([ctx, x_t], dim=1)) + self.pos if self.frame_cond is not None and frame_cond is not None: x = x + self.frame_cond(frame_cond.to(dt)) temb = torch.cat([timestep_embedding(t, 256), timestep_embedding(t - r, 256)], dim=-1).to(dt) c = self.cond(h) + self.t_mlp(temb) for blk in self.blocks: x = blk(x, c) s, b = self.ada_out(F.silu(c))[:, None].chunk(2, dim=-1) x = self.norm_out(x) * (1 + s) + b return self.out(x[:, -self.patch :]) def drop_cond(self, h: torch.Tensor, p: float) -> torch.Tensor: if p <= 0 or not self.training: return h drop = torch.rand(h.shape[0], device=h.device) < p return torch.where(drop[:, None], self.null_cond.to(h.dtype).expand_as(h), h) def loss_terms(self, x1, h, ctx, frame_cond=None): """Flow-matching training on a flat batch of patches. Returns per-item MSE (N * K,) with K = cfg.noise_samples draws per backbone state (cheap: head is small).""" K = self.cfg.noise_samples rep = lambda z: None if z is None else z.repeat_interleave(K, dim=0) x1, h, ctx, frame_cond = rep(x1), rep(h), rep(ctx), rep(frame_cond) if self.cfg.ctx_noise > 0 and self.training: ctx = ctx + torch.randn_like(ctx) * self.cfg.ctx_noise * torch.rand(ctx.shape[0], 1, 1, device=ctx.device) h = self.drop_cond(h, self.cfg.p_uncond) t = sample_t(x1.shape[0], x1.device) x_t, v = interpolate(x1, torch.randn_like(x1), t) pred = self(x_t, t, h, ctx, frame_cond=frame_cond) return (pred.float() - v.float()).pow(2).flatten(1).mean(1) @torch.no_grad() def sample(self, h, ctx, n_steps: int = 8, cfg_scale: float = 1.5, temperature: float = 1.0, frame_cond=None, sway: float = -1.0): """Euler sampling with head-only CFG. sway < 0 front-loads steps near t=0 (F5 sway sampling).""" N = h.shape[0] x = torch.randn(N, self.patch, self.latent_dim, device=h.device, dtype=h.dtype) * temperature ts = torch.linspace(0, 1, n_steps + 1, device=h.device) if sway: ts = ts + sway * (torch.cos(math.pi / 2 * ts) - 1 + ts) null = self.null_cond.to(h.dtype).expand_as(h) for i in range(n_steps): t = ts[i].expand(N) if cfg_scale != 1.0: both = self(torch.cat([x, x]), torch.cat([t, t]), torch.cat([h, null]), torch.cat([ctx, ctx]), frame_cond=None if frame_cond is None else torch.cat([frame_cond, frame_cond])) vc, vu = both.chunk(2) v = vu + cfg_scale * (vc - vu) else: v = self(x, t, h, ctx, frame_cond=frame_cond) x = x + (ts[i + 1] - ts[i]) * v return x