Download pixelart/model.py from azygod/pixelart-50m: direct link, hf CLI and curl.
- Browser
- Download file 7.41 kB
-
https://huggingface.co/azygod/pixelart-50m/resolve/main/pixelart/model.py
- Command line
-
hf download hf://azygod/pixelart-50m/pixelart/model.py
-
curl -L -o model.py https://huggingface.co/azygod/pixelart-50m/resolve/main/pixelart/model.py
7.41 kB
| """Small text-conditioned UNet for 32x32 RGBA pixel art, trained with flow matching. | |
| Flow matching (rectified flow): x_t = (1 - t) * x0 + t * noise, the network predicts the | |
| velocity v = noise - x0. Sampling integrates from t=1 (noise) to t=0 (data). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| def timestep_embedding(t: torch.Tensor, dim: int) -> torch.Tensor: | |
| half = dim // 2 | |
| freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device, dtype=torch.float32) / half) | |
| args = t.float()[:, None] * 1000 * freqs[None] | |
| return torch.cat([torch.cos(args), torch.sin(args)], dim=-1) | |
| class ResBlock(nn.Module): | |
| def __init__(self, cin: int, cout: int, emb_dim: int, dropout: float = 0.0): | |
| super().__init__() | |
| self.norm1 = nn.GroupNorm(32, cin) | |
| self.conv1 = nn.Conv2d(cin, cout, 3, padding=1) | |
| self.emb = nn.Linear(emb_dim, cout * 2) | |
| self.norm2 = nn.GroupNorm(32, cout) | |
| self.drop = nn.Dropout(dropout) | |
| self.conv2 = nn.Conv2d(cout, cout, 3, padding=1) | |
| nn.init.zeros_(self.conv2.weight) | |
| nn.init.zeros_(self.conv2.bias) | |
| self.skip = nn.Conv2d(cin, cout, 1) if cin != cout else nn.Identity() | |
| def forward(self, x, emb): | |
| h = self.conv1(F.silu(self.norm1(x))) | |
| scale, shift = self.emb(F.silu(emb))[:, :, None, None].chunk(2, dim=1) | |
| h = self.norm2(h) * (1 + scale) + shift | |
| h = self.conv2(self.drop(F.silu(h))) | |
| return h + self.skip(x) | |
| class AttnBlock(nn.Module): | |
| """Self-attention over spatial positions followed by cross-attention to text tokens.""" | |
| def __init__(self, ch: int, ctx_dim: int, heads: int = 4): | |
| super().__init__() | |
| self.norm1 = nn.GroupNorm(32, ch) | |
| self.self_attn = nn.MultiheadAttention(ch, heads, batch_first=True) | |
| self.norm2 = nn.LayerNorm(ch) | |
| self.cross_attn = nn.MultiheadAttention(ch, heads, kdim=ctx_dim, vdim=ctx_dim, batch_first=True) | |
| self.norm3 = nn.LayerNorm(ch) | |
| self.ff = nn.Sequential(nn.Linear(ch, ch * 4), nn.GELU(), nn.Linear(ch * 4, ch)) | |
| def forward(self, x, ctx, ctx_mask): | |
| b, c, h, w = x.shape | |
| s = self.norm1(x).flatten(2).transpose(1, 2) | |
| s = self.self_attn(s, s, s, need_weights=False)[0] | |
| tokens = x.flatten(2).transpose(1, 2) + s | |
| q = self.norm2(tokens) | |
| tokens = tokens + self.cross_attn(q, ctx, ctx, key_padding_mask=ctx_mask, need_weights=False)[0] | |
| tokens = tokens + self.ff(self.norm3(tokens)) | |
| return tokens.transpose(1, 2).reshape(b, c, h, w) | |
| class UNet(nn.Module): | |
| def __init__(self, in_ch: int = 4, base: int = 128, mults=(1, 2, 2), n_res: int = 2, | |
| attn_res=(16, 8), ctx_dim: int = 512, dropout: float = 0.1, size: int = 32): | |
| super().__init__() | |
| emb_dim = base * 4 | |
| self.base = base | |
| self.time_mlp = nn.Sequential(nn.Linear(base, emb_dim), nn.SiLU(), nn.Linear(emb_dim, emb_dim)) | |
| self.pool_proj = nn.Linear(ctx_dim, emb_dim) # pooled text embedding joins the time embedding | |
| self.ctx_proj = nn.Linear(ctx_dim, ctx_dim) | |
| self.inp = nn.Conv2d(in_ch, base, 3, padding=1) | |
| self.down = nn.ModuleList() | |
| chans, ch, res = [base], base, size | |
| for i, m in enumerate(mults): | |
| for _ in range(n_res): | |
| blocks = nn.ModuleList([ResBlock(ch, base * m, emb_dim, dropout)]) | |
| ch = base * m | |
| if res in attn_res: | |
| blocks.append(AttnBlock(ch, ctx_dim)) | |
| self.down.append(blocks) | |
| chans.append(ch) | |
| if i != len(mults) - 1: | |
| self.down.append(nn.ModuleList([nn.Conv2d(ch, ch, 3, stride=2, padding=1)])) | |
| chans.append(ch) | |
| res //= 2 | |
| self.mid = nn.ModuleList([ResBlock(ch, ch, emb_dim, dropout), AttnBlock(ch, ctx_dim), | |
| ResBlock(ch, ch, emb_dim, dropout)]) | |
| self.up = nn.ModuleList() | |
| for i, m in reversed(list(enumerate(mults))): | |
| for _ in range(n_res + 1): | |
| blocks = nn.ModuleList([ResBlock(ch + chans.pop(), base * m, emb_dim, dropout)]) | |
| ch = base * m | |
| if res in attn_res: | |
| blocks.append(AttnBlock(ch, ctx_dim)) | |
| self.up.append(blocks) | |
| if i != 0: | |
| self.up.append(nn.ModuleList([nn.Upsample(scale_factor=2, mode="nearest"), | |
| nn.Conv2d(ch, ch, 3, padding=1)])) | |
| res *= 2 | |
| self.out = nn.Sequential(nn.GroupNorm(32, ch), nn.SiLU(), nn.Conv2d(ch, in_ch, 3, padding=1)) | |
| nn.init.zeros_(self.out[-1].weight) | |
| nn.init.zeros_(self.out[-1].bias) | |
| def _run(self, blocks, h, emb, ctx, mask): | |
| for blk in blocks: | |
| if isinstance(blk, ResBlock): | |
| h = blk(h, emb) | |
| elif isinstance(blk, AttnBlock): | |
| h = blk(h, ctx, mask) | |
| else: | |
| h = blk(h) | |
| return h | |
| def forward(self, x, t, ctx, ctx_mask, pooled): | |
| """x: [B,4,32,32], t: [B] in [0,1], ctx: [B,L,D] text tokens, ctx_mask: [B,L] True=pad.""" | |
| emb = self.time_mlp(timestep_embedding(t, self.base)) + self.pool_proj(pooled) | |
| ctx = self.ctx_proj(ctx) | |
| h = self.inp(x) | |
| skips = [h] | |
| for blocks in self.down: | |
| h = self._run(blocks, h, emb, ctx, ctx_mask) | |
| skips.append(h) | |
| h = self._run(self.mid, h, emb, ctx, ctx_mask) | |
| for blocks in self.up: | |
| if isinstance(blocks[0], ResBlock): | |
| h = torch.cat([h, skips.pop()], dim=1) | |
| h = self._run(blocks, h, emb, ctx, ctx_mask) | |
| return self.out(h) | |
| def sample(model, ctx, mask, pooled, null_ctx, null_mask, null_pooled, steps: int = 40, | |
| cfg: float = 4.0, generator=None, cfg_interval: tuple[float, float] = (0.0, 1.0), shift: float = 1.0): | |
| """Heun integration of the learned flow from noise (t=1) to data (t=0) with CFG. | |
| Guidance is applied only while cfg_interval[0] <= t <= cfg_interval[1]; outside it the plain | |
| conditional velocity is used. Skipping guidance at the noisiest steps keeps more seed diversity. | |
| shift > 1 warps the time grid (t -> shift*t / (1 + (shift-1)*t)) to spend more steps at high noise. | |
| """ | |
| b = ctx.shape[0] | |
| x = torch.randn(b, 4, 32, 32, device=ctx.device, generator=generator) | |
| ts = torch.linspace(1.0, 0.0, steps + 1, device=ctx.device) | |
| if shift != 1.0: | |
| ts = shift * ts / (1 + (shift - 1) * ts) | |
| def velocity(x, t): | |
| tt = torch.full((b,), float(t), device=x.device) | |
| if not (cfg_interval[0] <= float(t) <= cfg_interval[1]): | |
| return model(x, tt, ctx, mask, pooled) | |
| both = model(torch.cat([x, x]), torch.cat([tt, tt]), | |
| torch.cat([ctx, null_ctx]), torch.cat([mask, null_mask]), torch.cat([pooled, null_pooled])) | |
| cond, unc = both.chunk(2) | |
| return unc + cfg * (cond - unc) | |
| for i in range(steps): | |
| t0, t1 = ts[i], ts[i + 1] | |
| v0 = velocity(x, t0) | |
| x_euler = x + (t1 - t0) * v0 | |
| if t1 > 0: | |
| v1 = velocity(x_euler, t1) | |
| x = x + (t1 - t0) * 0.5 * (v0 + v1) | |
| else: | |
| x = x_euler | |
| return x.clamp(-1, 1) | |