File size: 7,722 Bytes
b14f573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""pixy: text -> 16x16 sprites in your palette, from the PyTorch weights (model.safetensors).

  pip install torch transformers safetensors pillow
  python sample.py --prompt "spooky mushroom" --palette endesga32 --n 8 --out mushrooms.png
  python sample.py --prompt "golden key" --palette "#0f380f,#306230,#8bac0f,#9bbc0f"

The palette is an input: every pixel is either transparent or one of your colours (1-32 of them).
Sampling is confidence-ordered parallel unmasking (MaskGIT-style) with classifier-free guidance.
This script covers text prompts; the image guide, recolour and the other tools live in the web app.
MIT licence. The CLIP text encoder (openai/clip-vit-base-patch32) is MIT, Copyright (c) 2021 OpenAI.
"""

from __future__ import annotations

import argparse
import json
import math
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from safetensors.torch import load_file

from model import MASK, N_PIX, ModelConfig, PaletteSpriteModel

HERE = Path(__file__).resolve().parent
PRESETS = {
    "pico8": "000000 1d2b53 7e2553 008751 ab5236 5f574f c2c3c7 fff1e8 ff004d ffa300 ffec27 00e436 29adff 83769c ff77a8 ffccaa",
    "sweetie16": "1a1c2c 5d275d b13e53 ef7d57 ffcd75 a7f070 38b764 257179 29366f 3b5dc9 41a6f6 73eff7 f4f4f4 94b0c2 566c86 333c57",
    "endesga32": "be4a2f d77643 ead4aa e4a672 b86f50 733e39 3e2731 a22633 e43b44 f77622 feae34 fee761 63c74d 3e8948 265c42 193c3e "
                 "124e89 0099db 2ce8f5 ffffff c0cbdc 8b9bb4 5a6988 3a4466 262b44 181425 ff0044 68386c b55088 f6757a e8b796 c28569",
    "gameboy": "0f380f 306230 8bac0f 9bbc0f",
}

# sRGB -> OKLab (Björn Ottosson), the colour space the model reads palettes in
_M1 = torch.tensor([[0.4122214708, 0.5363325363, 0.0514459929], [0.2119034982, 0.6806995451, 0.1073969566],
                    [0.0883024619, 0.2817188376, 0.6299787005]])
_M2 = torch.tensor([[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099],
                    [0.0259040371, 0.7827717662, -0.8086757660]])


def srgb_to_oklab(rgb: torch.Tensor) -> torch.Tensor:
    lin = torch.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
    lms = lin @ _M1.T
    lms = torch.sign(lms) * lms.abs().pow(1.0 / 3.0)
    return lms @ _M2.T


def parse_palette(s: str) -> np.ndarray:
    hexes = PRESETS[s].split() if s in PRESETS else [h.strip().lstrip("#") for h in s.replace(";", ",").split(",") if h.strip()]
    return np.array([[int(h[i:i + 2], 16) for i in (0, 2, 4)] for h in hexes], dtype=np.uint8)


def load(device: torch.device):
    cfg = json.loads((HERE / "config.json").read_text())
    model = PaletteSpriteModel(ModelConfig(**cfg["model_cfg"]))
    model.load_state_dict(load_file(str(HERE / "model.safetensors")))
    return model.to(device).eval(), cfg


class Clip:
    """Text features the model was trained on: CLIP's pooled output first, then its 32 token states -> [B, 33, 512]."""

    def __init__(self, name: str, max_len: int, device: torch.device):
        from transformers import AutoTokenizer, CLIPTextModel
        self.tok = AutoTokenizer.from_pretrained(name)
        self.model = CLIPTextModel.from_pretrained(name).to(device).eval()
        self.max_len, self.device = max_len, device

    @torch.no_grad()
    def __call__(self, prompts: list[str]):
        enc = self.tok(prompts, padding="max_length", max_length=self.max_len, truncation=True, return_tensors="pt")
        ids, mask = enc["input_ids"].to(self.device), enc["attention_mask"].to(self.device)
        out = self.model(input_ids=ids, attention_mask=mask)
        feats = torch.cat([out.pooler_output[:, None], out.last_hidden_state], 1).float()
        return feats, torch.cat([torch.ones_like(mask[:, :1]), mask], 1).bool()


def _gumbel(shape, dev, gen):
    u = torch.rand(shape, device="cpu", generator=gen).to(dev).clamp(1e-9, 1 - 1e-9)
    return -torch.log(-torch.log(u))


@torch.no_grad()
def sample(model, text, text_mask, pal_lab, pal_valid, steps=12, cfg=3.0, temperature=1.0, choice_noise=2.0, seed=0):
    """Start fully masked; each step predicts every pixel and keeps the most confident ones (cosine schedule)."""
    B, dev = pal_lab.shape[0], pal_lab.device
    gen = torch.Generator().manual_seed(seed)
    pix = torch.full((B, N_PIX), MASK, dtype=torch.long, device=dev)
    n0 = (pix == MASK).sum(1)
    T, M = torch.cat([text, text]), torch.cat([text_mask, text_mask])  # prompt branch + unconditional branch
    D = torch.cat([torch.zeros(B, dtype=torch.bool, device=dev), torch.ones(B, dtype=torch.bool, device=dev)])
    L, V = pal_lab.repeat(2, 1, 1), pal_valid.repeat(2, 1)
    for s in range(steps):
        masked = pix == MASK
        if not masked.any():
            break
        c, u = model(T, M, D, L, V, pix.repeat(2, 1), None, None).split(B)
        logits = (u + cfg * (c - u)) / max(temperature, 1e-4)
        logp = logits.log_softmax(-1)
        x = (logp + _gumbel(logp.shape, dev, gen)).argmax(-1)
        conf = logp.gather(-1, x[..., None])[..., 0]
        anneal = choice_noise * (1.0 - (s + 1) / steps)
        if anneal > 0:
            conf = conf + anneal * _gumbel(conf.shape, dev, gen)
        conf = torch.where(masked, conf, torch.full_like(conf, float("inf")))
        n_keep = (n0.float() * math.cos(0.5 * math.pi * (s + 1) / steps)).floor().long()
        if s == steps - 1:
            n_keep = torch.zeros_like(n_keep)
        rank = conf.argsort(1).argsort(1)
        new = torch.where(masked, x, pix)
        pix = torch.where(masked & (rank < n_keep[:, None]), torch.full_like(pix, MASK), new)
    return pix  # [B, 256]: 0 transparent, k = palette[k - 1]


def generate(prompt: str, palette: np.ndarray, n: int = 4, seed: int = 0, device: torch.device | None = None, **kw) -> np.ndarray:
    device = device or torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
    model, cfg = load(device)
    te = cfg["text_encoder"]
    text, mask = Clip(te["name"], te["max_length"], device)([prompt] * n)
    k, p_max = len(palette), cfg["model_cfg"]["p_max"]
    if not 1 <= k <= p_max:
        raise ValueError(f"the palette needs 1 to {p_max} colours, got {k}")
    lab = torch.zeros(n, p_max, 3)
    lab[:, :k] = srgb_to_oklab(torch.from_numpy(palette).float() / 255)
    valid = (torch.arange(p_max)[None] < k).expand(n, -1).contiguous()
    return sample(model, text, mask, lab.to(device), valid.to(device), seed=seed, **kw).view(n, 16, 16).cpu().numpy()


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--prompt", required=True)
    ap.add_argument("--palette", default="endesga32", help="preset (pico8, sweetie16, endesga32, gameboy) or hex list")
    ap.add_argument("--n", type=int, default=4)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--steps", type=int, default=12)
    ap.add_argument("--cfg", type=float, default=3.0)
    ap.add_argument("--temperature", type=float, default=1.0)
    ap.add_argument("--out", default="sprites.png")
    ap.add_argument("--scale", type=int, default=8)
    a = ap.parse_args()
    pal = parse_palette(a.palette)
    pix = generate(a.prompt, pal, a.n, a.seed, steps=a.steps, cfg=a.cfg, temperature=a.temperature)
    rgba = np.zeros((a.n, 16, 16, 4), np.uint8)
    rgba[..., :3] = np.concatenate([np.zeros((1, 3), np.uint8), pal])[pix]
    rgba[..., 3] = (pix > 0) * 255
    sheet = Image.fromarray(np.concatenate(list(rgba), 1))
    sheet.resize((16 * a.n * a.scale, 16 * a.scale), Image.NEAREST).save(a.out)
    print(f"saved {a.n} sprites to {a.out}")


if __name__ == "__main__":
    main()