Spaces:
Sleeping

AutoSprite / autosprite /model.py
neonforestmist's picture
AutoSprite: initial app (early checkpoint)
22938ed verified
Raw History Blame Contribute Delete
4.62 kB
"""The AutoSprite network: a small U-Net with a palette-pointer output head.
Instead of regressing RGB values (which blurs pixel art), every output pixel picks one
of the colors already present in the input frames, or transparency. Palette entries
are embedded from their RGB value plus the encoder features pooled over the pixels
where that color appears, so the network can tell "hair brown" from "shoe brown".
"""
from __future__ import annotations
import torch
from torch import nn
from torch.nn import functional as F
from . import NUM_POSES
from .features import IN_CHANNELS
def _norm(channels: int) -> nn.GroupNorm:
return nn.GroupNorm(8, channels)
class ResBlock(nn.Module):
def __init__(self, channels: int, dilation: int = 1):
super().__init__()
self.body = nn.Sequential(
_norm(channels),
nn.SiLU(),
nn.Conv2d(channels, channels, 3, padding=dilation, dilation=dilation),
_norm(channels),
nn.SiLU(),
nn.Conv2d(channels, channels, 3, padding=1),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x + self.body(x)
class GlobalContext(nn.Module):
"""Mixes a spatially pooled summary back into every position."""
def __init__(self, channels: int):
super().__init__()
self.proj = nn.Conv2d(channels * 2, channels, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
pooled = x.mean(dim=(2, 3), keepdim=True).expand_as(x)
return x + self.proj(torch.cat([x, pooled], dim=1))
class AutoSpriteNet(nn.Module):
def __init__(self, width: int = 48, embed: int = 32):
super().__init__()
c1, c2, c3 = width, width * 2, width * 4
self.embed = embed
self.stem = nn.Conv2d(IN_CHANNELS, c1, 3, padding=1)
self.enc1 = nn.Sequential(ResBlock(c1), ResBlock(c1, 2))
self.down1 = nn.Conv2d(c1, c2, 3, stride=2, padding=1)
self.enc2 = nn.Sequential(ResBlock(c2), ResBlock(c2, 2))
self.down2 = nn.Conv2d(c2, c3, 3, stride=2, padding=1)
self.mid = nn.Sequential(ResBlock(c3), GlobalContext(c3), ResBlock(c3), GlobalContext(c3), ResBlock(c3))
self.up2 = nn.Conv2d(c3 + c2, c2, 3, padding=1)
self.dec2 = nn.Sequential(ResBlock(c2), ResBlock(c2))
self.up1 = nn.Conv2d(c2 + c1, c1, 3, padding=1)
self.dec1 = nn.Sequential(ResBlock(c1), ResBlock(c1))
self.pixel_head = nn.Sequential(_norm(c1), nn.SiLU(), nn.Conv2d(c1, NUM_POSES * embed, 1))
self.palette_mlp = nn.Sequential(
nn.Linear(c1 + c1 + 3 + 3, 128),
nn.SiLU(),
nn.Linear(128, 128),
nn.SiLU(),
nn.Linear(128, embed + 1),
)
self.transparent = nn.Parameter(torch.zeros(embed + 1))
def forward(
self,
x: torch.Tensor,
palmask: torch.Tensor,
palrgb: torch.Tensor,
palvalid: torch.Tensor,
) -> torch.Tensor:
"""Return logits of shape (B, NUM_POSES, 1 + P, H, W); class 0 is transparent."""
b, _, h, w = x.shape
s1 = self.enc1(self.stem(x))
s2 = self.enc2(self.down1(s1))
m = self.mid(self.down2(s2))
u2 = F.interpolate(m, size=s2.shape[-2:], mode="nearest")
d2 = self.dec2(self.up2(torch.cat([u2, s2], dim=1)))
u1 = F.interpolate(d2, size=s1.shape[-2:], mode="nearest")
d1 = self.dec1(self.up1(torch.cat([u1, s1], dim=1)))
pix = self.pixel_head(d1).view(b, NUM_POSES, self.embed, h, w)
area = palmask.sum(dim=(2, 3))
denom = area.clamp(min=1e-3).unsqueeze(-1)
enc_feat = torch.einsum("bchw,bphw->bpc", s1, palmask) / denom
dec_feat = torch.einsum("bchw,bphw->bpc", d1, palmask) / denom
ys = x[:, -3]
xs = x[:, -2]
mean_y = torch.einsum("bhw,bphw->bp", ys, palmask) / denom.squeeze(-1)
mean_x = torch.einsum("bhw,bphw->bp", xs, palmask) / denom.squeeze(-1)
stats = torch.stack([mean_y, mean_x, area / (h * w)], dim=-1)
pal = self.palette_mlp(torch.cat([enc_feat, dec_feat, palrgb, stats], dim=-1))
trans = self.transparent.view(1, 1, -1).expand(b, 1, -1)
table = torch.cat([trans, pal], dim=1) # (B, 1 + P, embed + 1)
vec, bias = table[..., : self.embed], table[..., self.embed]
logits = torch.einsum("bkdhw,bpd->bkphw", pix, vec) / (self.embed**0.5)
logits = logits + bias.view(b, 1, -1, 1, 1)
valid = torch.cat([torch.ones_like(palvalid[:, :1]), palvalid], dim=1)
return logits.masked_fill(valid.view(b, 1, -1, 1, 1) < 0.5, -1e4)