"""Pixel DiT: a 58M-parameter text-to-pixel-art diffusion transformer trained from scratch. Usage: from model import PixelArtGenerator gen = PixelArtGenerator("trkmnu/pixel-dit") images = gen("a red dragon breathing fire on dark background, pixel art", seed=0) images[0].save("dragon.png") """ import json, math, os import torch import torch.nn as nn import torch.nn.functional as F def timestep_embedding(t, dim=256): half = dim // 2 freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half) args = t[:, None].float() * 1000 * freqs[None] return torch.cat([torch.cos(args), torch.sin(args)], dim=-1) def modulate(x, shift, scale): return x * (1 + scale[:, None]) + shift[:, None] class Attention(nn.Module): def __init__(self, dim, heads): super().__init__() self.heads = heads self.qkv = nn.Linear(dim, dim * 3) self.proj = nn.Linear(dim, dim) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.heads, C // self.heads).permute(2, 0, 3, 1, 4) x = F.scaled_dot_product_attention(qkv[0], qkv[1], qkv[2]) return self.proj(x.transpose(1, 2).reshape(B, N, C)) class DiTBlock(nn.Module): def __init__(self, dim, heads): super().__init__() self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) self.attn = Attention(dim, heads) self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) self.mlp = nn.Sequential(nn.Linear(dim, dim * 4), nn.GELU(approximate="tanh"), nn.Linear(dim * 4, dim)) self.ada = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6)) def forward(self, x, c): s1, sc1, g1, s2, sc2, g2 = self.ada(c).chunk(6, dim=-1) x = x + g1[:, None] * self.attn(modulate(self.norm1(x), s1, sc1)) x = x + g2[:, None] * self.mlp(modulate(self.norm2(x), s2, sc2)) return x class PixelDiT(nn.Module): def __init__(self, img=64, patch=4, dim=512, depth=12, heads=8, text_dim=512): super().__init__() self.patch, self.grid = patch, img // patch self.patch_embed = nn.Conv2d(3, dim, patch, stride=patch) self.pos = nn.Parameter(torch.zeros(1, self.grid ** 2, dim)) self.t_mlp = nn.Sequential(nn.Linear(256, dim), nn.SiLU(), nn.Linear(dim, dim)) self.txt_mlp = nn.Sequential(nn.Linear(text_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) self.null_text = nn.Parameter(torch.zeros(1, text_dim)) self.blocks = nn.ModuleList([DiTBlock(dim, heads) for _ in range(depth)]) self.norm_out = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) self.ada_out = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 2)) self.out = nn.Linear(dim, patch * patch * 3) def forward(self, x, t, text, drop_mask=None): text = F.normalize(text.float(), dim=-1) if drop_mask is not None: text = torch.where(drop_mask[:, None], self.null_text.expand_as(text), text) x = self.patch_embed(x).flatten(2).transpose(1, 2) + self.pos c = self.t_mlp(timestep_embedding(t)) + self.txt_mlp(text) for blk in self.blocks: x = blk(x, c) shift, scale = self.ada_out(c).chunk(2, dim=-1) x = self.out(modulate(self.norm_out(x), shift, scale)) B, g, p = x.shape[0], self.grid, self.patch return x.reshape(B, g, g, p, p, 3).permute(0, 5, 1, 3, 2, 4).reshape(B, 3, g * p, g * p) @torch.no_grad() def sample(model, text, steps=50, cfg=4.0, generator=None, return_trajectory=False): """Euler sampler for rectified flow, from pure noise (t=1) to image (t=0), with classifier-free guidance.""" B, dev = text.shape[0], text.device x = torch.randn(B, 3, 64, 64, generator=generator).to(dev) ts = torch.linspace(1, 0, steps + 1, device=dev) null = torch.ones(B, dtype=torch.bool, device=dev) traj = [x.clamp(-1, 1).cpu()] for i in range(steps): tt = ts[i].expand(B) v_c = model(x, tt, text) v_u = model(x, tt, text, null) x = x + (ts[i + 1] - ts[i]) * (v_u + cfg * (v_c - v_u)) if return_trajectory: traj.append(x.clamp(-1, 1).cpu()) x = x.clamp(-1, 1) return (x, traj) if return_trajectory else x def to_pil(x, upscale=4): from PIL import Image arr = ((x + 1) * 127.5).round().clamp(0, 255).byte().permute(0, 2, 3, 1).cpu().numpy() return [Image.fromarray(a).resize((64 * upscale, 64 * upscale), Image.NEAREST) for a in arr] class PixelArtGenerator: def __init__(self, repo_or_dir="trkmnu/pixel-dit", device=None): from safetensors.torch import load_file from transformers import CLIPTokenizer, CLIPTextModelWithProjection def get(name): if os.path.isdir(repo_or_dir): return os.path.join(repo_or_dir, name) from huggingface_hub import hf_hub_download return hf_hub_download(repo_or_dir, name) if device is None: device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu") self.device = device cfg = json.load(open(get("config.json"))) self.model = PixelDiT(**cfg["model"]).to(device).eval() self.model.load_state_dict(load_file(get("model.safetensors"))) self.tok = CLIPTokenizer.from_pretrained(cfg["text_encoder"]) self.text_model = CLIPTextModelWithProjection.from_pretrained(cfg["text_encoder"]).to(device).eval() @torch.no_grad() def encode(self, prompts): t = self.tok(prompts, padding=True, truncation=True, max_length=77, return_tensors="pt").to(self.device) return self.text_model(**t).text_embeds def __call__(self, prompts, steps=50, cfg=4.0, seed=0, upscale=4): if isinstance(prompts, str): prompts = [prompts] g = torch.Generator().manual_seed(seed) x = sample(self.model, self.encode(prompts), steps=steps, cfg=cfg, generator=g) return to_pil(x, upscale)