Text-to-Image
ONNX
Safetensors
Transformers.js
pixel-art
sprite
16x16
icon
game-assets
maskgit
browser
webgpu
gamedev
Run this model with HF Jobs
Run CheezOne/pixel-art-sprite-generator-16x16 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/CheezOne/pixel-art-sprite-generator-16x16. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/CheezOne/pixel-art-sprite-generator-16x16 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use CheezOne/pixel-art-sprite-generator-16x16 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers.js
How to use CheezOne/pixel-art-sprite-generator-16x16 with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('text-to-image', 'CheezOne/pixel-art-sprite-generator-16x16');
Download scripts/pix2_train.py from CheezOne/pixel-art-sprite-generator-16x16: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/CheezOne/pixel-art-sprite-generator-16x16/resolve/main/scripts/pix2_train.py
- Command line
-
hf download hf://CheezOne/pixel-art-sprite-generator-16x16/scripts/pix2_train.py
-
curl -L -o pix2_train.py https://huggingface.co/CheezOne/pixel-art-sprite-generator-16x16/resolve/main/scripts/pix2_train.py
14.6 kB
| """Pixel sprite generator v2: MaskGIT over 16x16 palette tokens, conditioned on the TOKEN-LEVEL output of a frozen | |
| multilingual sentence encoder (v1 squeezed the prompt into one pooled vector and lost detail). | |
| Training captions are mixed per example so short, native-language prompts are in-distribution: | |
| full English caption | English subject only ("camera") | zh/ja/ko caption translation | zh/ja/ko subject translation | none (CFG) | |
| python pix2_train.py train <atlas_dir> <out_dir> --encoder <dir> [--translations tr.json] [--budget-min 200] | |
| python pix2_train.py sample <out_dir> <grid.png> --encoder <dir> --prompts "camera" "相机" ... | |
| python pix2_train.py compare <out_dir> <atlas_dir> <png> --encoder <dir> (real sprites left, short-prompt samples right) | |
| """ | |
| import argparse, json, math, os, random, time | |
| import numpy as np | |
| import torch, torch.nn as nn, torch.nn.functional as F | |
| SIDE = 16; SEQ = SIDE * SIDE; TXT = 32 | |
| DEV = "cuda" if torch.cuda.is_available() else "cpu" | |
| class TextEnc: | |
| """Frozen encoder; returns token states [B,TXT,H] and mask [B,TXT] (1 = real token).""" | |
| def __init__(self, path): | |
| from transformers import AutoTokenizer, AutoModel | |
| self.tok = AutoTokenizer.from_pretrained(path); self.m = AutoModel.from_pretrained(path).to(DEV).eval() | |
| self.dim = self.m.config.hidden_size | |
| def __call__(self, texts): | |
| e = self.tok(texts, padding="max_length", truncation=True, max_length=TXT, return_tensors="pt").to(DEV) | |
| with torch.autocast(DEV, dtype=torch.bfloat16, enabled=DEV == "cuda"): | |
| h = self.m(input_ids=e["input_ids"], attention_mask=e["attention_mask"]).last_hidden_state | |
| return h.float(), e["attention_mask"].float() | |
| class Block(nn.Module): | |
| """Pre-norm transformer block on F.scaled_dot_product_attention: exports to ONNX with a dynamic sequence length | |
| (nn.TransformerEncoder's export bakes the length into its reshapes).""" | |
| def __init__(self, d, heads): | |
| super().__init__(); self.h = heads | |
| self.n1 = nn.LayerNorm(d); self.qkv = nn.Linear(d, 3 * d); self.o = nn.Linear(d, d) | |
| self.n2 = nn.LayerNorm(d); self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d)) | |
| def forward(self, x, allow): # allow [B,1,1,S] bool: True = key may be attended to | |
| B, S_, D = x.shape | |
| q, k, v = self.qkv(self.n1(x)).view(B, S_, 3, self.h, D // self.h).permute(2, 0, 3, 1, 4) | |
| a = F.scaled_dot_product_attention(q, k, v, attn_mask=allow) | |
| x = x + self.o(a.transpose(1, 2).reshape(B, S_, D)) | |
| return x + self.mlp(self.n2(x)) | |
| class PixGen2(nn.Module): | |
| def __init__(self, vocab=4097, d=512, layers=10, heads=8, text_dim=384): | |
| super().__init__() | |
| self.mask_id = vocab | |
| self.tok = nn.Embedding(vocab + 1, d); self.pos = nn.Parameter(torch.zeros(1, SEQ, d)) | |
| self.tpos = nn.Parameter(torch.zeros(1, TXT, d)) | |
| self.tproj = nn.Sequential(nn.LayerNorm(text_dim), nn.Linear(text_dim, d), nn.GELU(), nn.Linear(d, d)) | |
| self.null = nn.Parameter(torch.zeros(1, 1, text_dim)) # unconditional "text": one token | |
| self.blocks = nn.ModuleList([Block(d, heads) for _ in range(layers)]) | |
| self.norm = nn.LayerNorm(d); self.head = nn.Linear(d, vocab) | |
| nn.init.normal_(self.pos, std=0.02); nn.init.normal_(self.tpos, std=0.02) | |
| def forward(self, tokens, text, text_mask): | |
| """tokens [B,256] long; text [B,TXT,text_dim]; text_mask [B,TXT] float (1 = real). Returns logits [B,256,vocab].""" | |
| t = self.tproj(text) + self.tpos[:, : text.shape[1]] | |
| x = self.tok(tokens) + self.pos | |
| allow = torch.cat([text_mask > 0.5, torch.ones_like(tokens, dtype=torch.bool)], 1)[:, None, None, :] | |
| h = torch.cat([t, x], 1) | |
| for blk in self.blocks: h = blk(h, allow) | |
| h = h[:, text.shape[1]:] | |
| return self.head(self.norm(h)) | |
| def uncond(self, B, L=TXT): | |
| text = torch.zeros(B, L, self.null.shape[-1], device=self.null.device); text[:, :1] = self.null | |
| m = torch.zeros(B, L, device=self.null.device); m[:, 0] = 1 | |
| return text, m | |
| def pick_texts(ids, caps, objs, tr, rnd, p_uncond): | |
| """One training string per example; None = unconditional.""" | |
| out = [] | |
| for i in ids: | |
| c, s = caps[i], objs[i]; r = rnd.random() | |
| if r < p_uncond: out.append(None); continue | |
| r = rnd.random(); tc = tr.get("caption", {}).get(c); ts = tr.get("subject", {}).get(s) | |
| if r < 0.35: out.append(c) | |
| elif r < 0.55: out.append(s) | |
| elif r < 0.75 and tc: out.append(rnd.choice(list(tc.values()))) | |
| elif ts: out.append(rnd.choice(list(ts.values()))) | |
| else: out.append(s if r < 0.9 else c) | |
| return out | |
| def encode_batch(enc, model, texts, noise=0.0): | |
| B = len(texts); real = [t if t is not None else "" for t in texts] | |
| h, m = enc(real) | |
| if noise: h = h + noise * torch.randn_like(h) * h.std() | |
| un = torch.tensor([t is None for t in texts], device=h.device) | |
| if un.any(): | |
| ut, um = model.uncond(int(un.sum())) | |
| h[un], m[un] = ut, um | |
| return h, m | |
| def train(a): | |
| tokens = np.load(os.path.join(a.atlas, "tokens.npy"), mmap_mode="r", allow_pickle=False) | |
| split = np.load(os.path.join(a.atlas, "split.npy"), allow_pickle=False) | |
| caps = json.load(open(os.path.join(a.atlas, "captions.json"))); objs = json.load(open(os.path.join(a.atlas, "objects.json"))) | |
| import gzip | |
| tr = json.load(gzip.open(a.translations, "rt") if str(a.translations).endswith(".gz") else open(a.translations)) if a.translations and os.path.exists(a.translations) else {} | |
| print("translations:", {k: len(v) for k, v in tr.items()}, flush=True) | |
| tr_ids = np.where(split == 0)[0]; va = np.where(split == 1)[0][:2048] | |
| if a.limit: va = tr_ids[a.limit: a.limit + 256]; tr_ids = tr_ids[: a.limit] # local smoke test | |
| hi = int(max(tr_ids.max(), va.max())) + 1 | |
| T = torch.from_numpy(np.asarray(tokens[:hi]).astype(np.int64)).to(DEV) | |
| enc = TextEnc(a.encoder) | |
| model = PixGen2(d=a.d, layers=a.layers, heads=a.heads, text_dim=enc.dim).to(DEV) | |
| print("params", round(sum(p.numel() for p in model.parameters()) / 1e6, 2), "M", flush=True) | |
| torch.backends.cuda.matmul.allow_tf32 = True; torch.backends.cudnn.allow_tf32 = True | |
| opt = torch.optim.AdamW(model.parameters(), lr=a.lr, betas=(0.9, 0.95), weight_decay=0.05) | |
| total = [a.steps] | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1, s / 1000) * 0.5 * (1 + math.cos(math.pi * min(1, s / total[0])))) | |
| os.makedirs(a.out, exist_ok=True) | |
| json.dump({"version": 2, "vocab": 4097, "d": a.d, "layers": a.layers, "heads": a.heads, "text_dim": enc.dim, "txt_len": TXT, "seq": SEQ, | |
| "encoder": a.encoder_name}, open(os.path.join(a.out, "config.json"), "w"), indent=1) | |
| import shutil; shutil.copy(os.path.join(a.atlas, "palette.npy"), os.path.join(a.out, "palette.npy")) | |
| save = lambda: (torch.save(model.state_dict(), os.path.join(a.out, "model.pt.tmp")), os.replace(os.path.join(a.out, "model.pt.tmp"), os.path.join(a.out, "model.pt"))) | |
| rnd = random.Random(0); g = torch.Generator().manual_seed(0); trd = torch.from_numpy(tr_ids) | |
| def masked(x): | |
| B = x.shape[0]; r = torch.cos(math.pi / 2 * torch.rand(B, 1, device=DEV)).clamp(min=1 / SEQ) | |
| m = torch.rand(B, SEQ, device=DEV) < r | |
| return torch.where(m, torch.full_like(x, model.mask_id), x), m | |
| def val_loss(kind): | |
| model.eval(); vl = []; vr = random.Random(1) | |
| with torch.no_grad(): | |
| for i in range(0, len(va), 256): | |
| ids = va[i:i + 256]; x = T[torch.from_numpy(ids).to(DEV)] | |
| texts = [caps[j] if kind == "caption" else objs[j] for j in ids] | |
| h, mk = encode_batch(enc, model, texts); inp, m = masked(x) | |
| with torch.autocast(DEV, dtype=torch.bfloat16, enabled=DEV == "cuda"): | |
| vl.append(F.cross_entropy(model(inp, h, mk)[m].float(), x[m]).item()) | |
| model.train(); return round(float(np.mean(vl)), 4) | |
| model.train(); t0 = time.time(); step = 0 | |
| while step < total[0]: | |
| step += 1 | |
| ids = trd[torch.randint(len(trd), (a.bs,), generator=g)].numpy() | |
| x = T[torch.from_numpy(ids).to(DEV)] | |
| h, mk = encode_batch(enc, model, pick_texts(ids, caps, objs, tr, rnd, a.p_uncond), noise=a.text_noise) | |
| inp, m = masked(x) | |
| with torch.autocast(DEV, dtype=torch.bfloat16, enabled=DEV == "cuda"): | |
| logits = model(inp, h, mk) | |
| loss = F.cross_entropy(logits[m].float(), x[m]) | |
| opt.zero_grad(set_to_none=True); loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step() | |
| if step == 300 and a.budget_min: # fit the schedule to the time budget, measured on this GPU | |
| sps = (time.time() - t0) / step; total[0] = max(300, min(a.steps, int(a.budget_min * 60 / sps))) | |
| print(json.dumps({"s_per_step": round(sps, 4), "planned_steps": total[0]}), flush=True) | |
| if step % a.log_every == 0 or step == total[0]: | |
| print(json.dumps({"step": step, "loss": round(loss.item(), 4), "val_caption": val_loss("caption"), "val_subject": val_loss("subject"), | |
| "lr": sched.get_last_lr()[0], "s": round(time.time() - t0)}), flush=True) | |
| save() | |
| save(); print("saved", a.out, flush=True) | |
| def load(out): | |
| cfg = json.load(open(os.path.join(out, "config.json"))) | |
| m = PixGen2(d=cfg["d"], layers=cfg["layers"], heads=cfg["heads"], text_dim=cfg["text_dim"]).to(DEV) | |
| pt = os.path.join(out, "model.pt") | |
| sd = torch.load(pt, map_location=DEV, weights_only=True) if os.path.exists(pt) else __import__("safetensors.torch").torch.load_file(os.path.join(out, "model.safetensors"), device=DEV) | |
| m.load_state_dict(sd); m.eval(); return m, cfg | |
| def generate(model, h, mk, steps=16, cfg=3.0, temp=1.0, seed=0): | |
| torch.manual_seed(seed); B = h.shape[0] | |
| x = torch.full((B, SEQ), model.mask_id, dtype=torch.long, device=h.device) | |
| uh, um = model.uncond(B, h.shape[1]) | |
| for s in range(steps): | |
| lc, lu = model(torch.cat([x, x]), torch.cat([h, uh]), torch.cat([mk, um])).float().chunk(2) | |
| probs = F.softmax((lu + cfg * (lc - lu)) / max(temp, 1e-4), -1) | |
| samp = torch.multinomial(probs.view(-1, probs.shape[-1]), 1).view(B, SEQ) | |
| conf = torch.gather(probs, -1, samp.unsqueeze(-1)).squeeze(-1) | |
| unknown = x == model.mask_id | |
| gum = -torch.log(-torch.log(torch.rand_like(conf) + 1e-9) + 1e-9) | |
| conf = torch.where(unknown, torch.log(conf + 1e-9) + temp * (1 - (s + 1) / steps) * gum, torch.full_like(conf, float("inf"))) | |
| k = int(math.floor(SEQ * math.cos(math.pi / 2 * (s + 1) / steps))) | |
| x = torch.where(unknown, samp, x) | |
| if k > 0: x.scatter_(1, conf.argsort(-1)[:, :k], model.mask_id) | |
| return x | |
| def to_rgba(tok, pal): | |
| px = np.asarray(tok).reshape(SIDE, SIDE); return np.dstack((pal[px], (px != 0).astype("uint8") * 255)) | |
| def draw_rows(rows, path, sc=4, left=220): | |
| from PIL import Image, ImageDraw, ImageFont | |
| n = max(len(r[1]) for r in rows); cell = 16 * sc + 4 | |
| img = Image.new("RGBA", (left + n * cell, len(rows) * cell), (238, 238, 238, 255)); d = ImageDraw.Draw(img) | |
| try: f = ImageFont.truetype("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 14) | |
| except Exception: f = ImageFont.load_default() | |
| for r, (lab, imgs) in enumerate(rows): | |
| d.text((4, r * cell + 24), lab[:28], fill=(0, 0, 0, 255), font=f) | |
| for k, im in enumerate(imgs): | |
| if im is None: continue | |
| img.alpha_composite(Image.fromarray(im).resize((16 * sc, 16 * sc), Image.NEAREST), (left + k * cell, r * cell)) | |
| img.save(path) | |
| def sample(a): | |
| model, cfg = load(a.out); enc = TextEnc(a.encoder); pal = np.load(os.path.join(a.out, "palette.npy"), allow_pickle=False) | |
| rows = [] | |
| for p in a.prompts: | |
| h, mk = enc([p] * a.n); toks = generate(model, h, mk, steps=a.steps, cfg=a.cfg, seed=1).cpu().numpy() | |
| rows.append((p, [to_rgba(t, pal) for t in toks])) | |
| draw_rows(rows, a.grid); print("grid", a.grid) | |
| def compare(a): | |
| """Left: 6 real training sprites of a subject; right: 6 samples from the SHORT prompt (what users type).""" | |
| model, cfg = load(a.out); enc = TextEnc(a.encoder); pal = np.load(os.path.join(a.out, "palette.npy"), allow_pickle=False) | |
| objs = json.load(open(os.path.join(a.atlas, "objects.json"))); T = np.load(os.path.join(a.atlas, "tokens.npy"), mmap_mode="r") | |
| rnd = random.Random(3); rows = [] | |
| for p, subj in [(x.split("=")[0], x.split("=")[-1]) for x in a.prompts]: | |
| idx = [j for j, o in enumerate(objs) if o == subj] | |
| real = [to_rgba(T[j], pal) for j in rnd.sample(idx, min(6, len(idx)))] | |
| h, mk = enc([p] * 6); gen = [to_rgba(t, pal) for t in generate(model, h, mk, steps=a.steps, cfg=a.cfg, seed=1).cpu().numpy()] | |
| rows.append((f"{p}", real + [None] + gen)) | |
| draw_rows(rows, a.png); print("compare", a.png) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(); sub = ap.add_subparsers(dest="cmd", required=True) | |
| p = sub.add_parser("train"); p.add_argument("atlas"); p.add_argument("out"); p.add_argument("--encoder", required=True) | |
| p.add_argument("--encoder-name", default="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"); p.add_argument("--translations") | |
| p.add_argument("--steps", type=int, default=200000); p.add_argument("--budget-min", type=float, default=0); p.add_argument("--bs", type=int, default=512) | |
| p.add_argument("--lr", type=float, default=5e-4); p.add_argument("--d", type=int, default=512); p.add_argument("--layers", type=int, default=10) | |
| p.add_argument("--heads", type=int, default=8); p.add_argument("--p-uncond", type=float, default=0.1); p.add_argument("--text-noise", type=float, default=0.05) | |
| p.add_argument("--log-every", type=int, default=2000); p.add_argument("--limit", type=int, default=0) | |
| for name in ("sample", "compare"): | |
| p = sub.add_parser(name); p.add_argument("out") | |
| if name == "compare": p.add_argument("atlas") | |
| p.add_argument("png" if name == "compare" else "grid"); p.add_argument("--encoder", required=True); p.add_argument("--prompts", nargs="+", required=True) | |
| p.add_argument("--n", type=int, default=8); p.add_argument("--steps", type=int, default=16); p.add_argument("--cfg", type=float, default=3.0) | |
| a = ap.parse_args(); {"train": train, "sample": sample, "compare": compare}[a.cmd](a) | |