Spaces:
Running on Zero

nyxia commited on
Commit
6a76c87
·
0 Parent(s):

smalt studio

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pixilab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: smalt studio
3
+ emoji: 🧪
4
+ colorFrom: indigo
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 6.32.0
8
+ python_version: '3.12'
9
+ app_file: app.py
10
+ pinned: false
11
+ license: mit
12
+ short_description: Tiny text-to-pixel-art model, 16x16 sprites from a prompt
13
+ models:
14
+ - PixilabAI/smalt-small
15
+ tags:
16
+ - pixel-art
17
+ - text-to-image
18
+ - sprites
19
+ - game-assets
20
+ - masked-diffusion
21
+ ---
22
+
23
+ # smalt studio
24
+
25
+ Type a prompt, watch 16×16 sprites fill in step by step, remix or recolour the one you like, download PNGs and a
26
+ sprite sheet. Model: [PixilabAI/smalt-small](https://huggingface.co/PixilabAI/smalt-small) (24.5M parameters, MIT).
app.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """smalt studio: a Hugging Face Space for smalt, the tiny text-to-pixel-art model (MIT).
2
+
3
+ Explore pre-made sprites (hover to replay how they were painted), type a prompt and watch 16x16 sprites fill in,
4
+ remix or recolour the one you like, download PNGs and a sprite sheet. ZeroGPU when available, otherwise CPU.
5
+ `/generate` is a plain API endpoint for scripts.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import html
11
+ import inspect
12
+ import io
13
+ import json
14
+ import math
15
+ import os
16
+ import random
17
+ import tempfile
18
+ import time
19
+ import zipfile
20
+ from pathlib import Path
21
+
22
+ try: # must come before torch on ZeroGPU
23
+ import spaces
24
+ except ImportError:
25
+ spaces = None
26
+
27
+ import gradio as gr
28
+ import numpy as np
29
+ import torch
30
+ from PIL import Image
31
+
32
+ from cards import card, sprite_rgba
33
+ from smalt import SmaltPipeline
34
+
35
+ HERE = Path(__file__).parent
36
+ MODEL_DIR = HERE / "model"
37
+ ON_ZERO_GPU = bool(os.environ.get("SPACES_ZERO_GPU"))
38
+ HAS_GPU = ON_ZERO_GPU or torch.cuda.is_available()
39
+ torch.set_num_threads(max(1, min(8, os.cpu_count() or 1)))
40
+
41
+ PIPE_CPU = SmaltPipeline(MODEL_DIR, device="cpu")
42
+ PIPE_GPU = SmaltPipeline(MODEL_DIR, device="cuda") if HAS_GPU else None
43
+ G = PIPE_CPU.cfg.grid
44
+ N = G * G
45
+ PAL = PIPE_CPU.palette # (K, 3) uint8, index 0 = transparent
46
+ K = len(PAL)
47
+ LAB = np.asarray(json.loads((MODEL_DIR / "palette.json").read_text())["lab"], dtype=np.float64)
48
+ PARAMS = sum(p.numel() for p in PIPE_CPU.model.parameters())
49
+ MAX = {"gpu": (16, 32), "cpu": (8, 24)} # (sprites shown, steps)
50
+ CARD = 240
51
+ print(f"[smalt] {PARAMS / 1e6:.1f}M params, gpu={HAS_GPU} zero_gpu={ON_ZERO_GPU}", flush=True)
52
+
53
+ KINDS = {"Object": "", "Creature": "", "Tile": "tile with ", "Effect": "effect ", "UI": "ui ", "Letter": "text "}
54
+ PREFIXES = ("tile with ", "fragment of ", "effect ", "ui ", "text ")
55
+ IDEAS = {
56
+ "Object": ["red health potion", "blue mana potion", "green poison potion", "treasure chest", "silver sword",
57
+ "red key", "iron shield", "magic spellbook", "red apple", "wooden bow", "iron axe", "red heart"],
58
+ "Creature": ["green dragon", "red dragon", "purple bat", "yellow bat", "purple slime monster", "orange fox",
59
+ "knight in silver armor", "skeleton warrior with sword", "green goblin"],
60
+ "Tile": ["tile with stone bricks", "tile with blue water", "tile with green grass", "tile with wooden planks",
61
+ "tile with orange lava", "tile with yellow sand"],
62
+ "Effect": ["effect orange fireball", "effect blue magic sparkle", "effect green poison cloud",
63
+ "effect yellow lightning bolt"],
64
+ "UI": ["ui wooden button", "ui gold frame", "ui inventory slot"],
65
+ "Letter": ["text gold letter "],
66
+ }
67
+ CHIPS = ["red health potion", "treasure chest", "purple slime monster", "silver sword", "green dragon",
68
+ "magic spellbook", "tile with stone bricks", "text gold letter a"]
69
+
70
+
71
+ # ------------------------------------------------------------------------------------------------- pixels
72
+ def rgba(tok: np.ndarray) -> np.ndarray:
73
+ return sprite_rgba(tok, None, PAL, K, G)
74
+
75
+
76
+ def zip_of(tokens: np.ndarray, prompt: str) -> str:
77
+ slug = "".join(c if c.isalnum() else "-" for c in prompt.lower()).strip("-")[:40] or "sprite"
78
+ path = Path(tempfile.mkdtemp()) / f"smalt-{slug}.zip"
79
+ cols = min(len(tokens), 8)
80
+ rows = math.ceil(len(tokens) / cols)
81
+ sheet = Image.new("RGBA", (cols * G, rows * G), (0, 0, 0, 0))
82
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
83
+ for i, t in enumerate(tokens):
84
+ im = Image.fromarray(rgba(t), "RGBA")
85
+ sheet.paste(im, ((i % cols) * G, (i // cols) * G))
86
+ for s in (1, 8):
87
+ buf = io.BytesIO()
88
+ (im if s == 1 else im.resize((G * s, G * s), Image.NEAREST)).save(buf, "PNG")
89
+ z.writestr(f"{slug}_{i + 1}{'' if s == 1 else '_8x'}.png", buf.getvalue())
90
+ buf = io.BytesIO()
91
+ sheet.save(buf, "PNG")
92
+ z.writestr(f"{slug}_sheet.png", buf.getvalue())
93
+ z.writestr("prompt.txt", prompt + "\n")
94
+ return str(path)
95
+
96
+
97
+ def hue_shift(tok: np.ndarray, deg: float) -> np.ndarray:
98
+ """Rotate every saturated colour's OKLab hue by `deg`, snapped to the nearest palette colour; greys stay."""
99
+ out = tok.copy()
100
+ used = np.unique(tok[(tok > 0) & (tok < K)])
101
+ cand = LAB[1:]
102
+ rad = math.radians(deg)
103
+ for t in used:
104
+ L, a, b = LAB[t]
105
+ c = math.hypot(a, b)
106
+ if c < 0.03:
107
+ continue
108
+ h = math.atan2(b, a) + rad
109
+ target = np.array([L, c * math.cos(h), c * math.sin(h)])
110
+ out[tok == t] = 1 + int(((cand - target) ** 2).sum(1).argmin())
111
+ return out
112
+
113
+
114
+ def score(tok: np.ndarray, conf: np.ndarray) -> float:
115
+ """How sure the model was of the colours it put down (mean log-prob over opaque pixels)."""
116
+ op = tok > 0
117
+ return float(np.log(conf[op].clip(1e-6)).mean()) if op.any() else -1e9
118
+
119
+
120
+ # ------------------------------------------------------------------------------------------------- sampling
121
+ def _steps(pipe: SmaltPipeline, job: dict):
122
+ for st in pipe.stream(job["prompt"], n=job["draw"], seed=job["seed"], canvas=job.get("canvas"),
123
+ keep=job.get("keep"), steps=job["steps"], guidance=job["guidance"],
124
+ temperature=job["temperature"]):
125
+ yield (st.index, st.total, st.tokens.cpu().numpy(), st.preview.cpu().numpy(),
126
+ st.confidence.float().cpu().numpy())
127
+
128
+
129
+ def _gpu_duration(job: dict) -> int:
130
+ return int(min(30, 6 + 0.01 * job["draw"] * job["steps"]))
131
+
132
+
133
+ def _steps_gpu(job: dict):
134
+ yield from _steps(PIPE_GPU, job)
135
+
136
+
137
+ if spaces is not None and ON_ZERO_GPU:
138
+ _steps_gpu = spaces.GPU(duration=_gpu_duration)(_steps_gpu)
139
+
140
+
141
+ def _job(prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of):
142
+ prompt = " ".join(str(prompt or "").split())[:160]
143
+ if not prompt:
144
+ raise gr.Error("Type a prompt first.")
145
+ dev = "gpu" if (HAS_GPU and device != "CPU") else "cpu"
146
+ max_n, max_steps = MAX[dev]
147
+ n = int(min(max(int(n), 1), max_n))
148
+ seed = random.randint(0, 2**31 - 1) if random_seed or seed is None else int(seed) % 2**31
149
+ return {"prompt": prompt, "n": n, "draw": min(2 * n, 32) if best_of else n,
150
+ "steps": int(min(max(steps, 4), max_steps)), "guidance": float(guidance),
151
+ "temperature": float(temperature), "seed": seed, "dev": dev}
152
+
153
+
154
+ def _run(job: dict):
155
+ """Yields (card images, status markdown, final tokens or None)."""
156
+ t0 = time.perf_counter()
157
+ gen = _steps_gpu(job) if job["dev"] == "gpu" else _steps(PIPE_CPU, job)
158
+ label = ("ZeroGPU" if ON_ZERO_GPU else "GPU") if job["dev"] == "gpu" else "CPU"
159
+ pick = f" · keeping the best {job['n']} of {job['draw']}" if job["draw"] > job["n"] else ""
160
+ last = conf = None
161
+ for k, total, tok, pre, cf in gen:
162
+ last, conf = tok, cf
163
+ bar = "▰" * (k + 1) + "▱" * (total - k - 1)
164
+ yield ([card(t, PAL, LAB, pre=p, size=CARD) for t, p in zip(tok, pre)],
165
+ f"`{bar}` painting · step {k + 1}/{total} · {label}{pick}", None)
166
+ order = sorted(range(len(last)), key=lambda i: -score(last[i], conf[i]))[:job["n"]]
167
+ best = last[order]
168
+ ms = round((time.perf_counter() - t0) * 1000)
169
+ yield ([card(t, PAL, LAB, size=CARD) for t in best],
170
+ f"**{job['n']} sprite{'s' if job['n'] > 1 else ''}** · {ms} ms · {label} · seed `{job['seed']}`{pick}", best)
171
+
172
+
173
+ def _dl(path):
174
+ return gr.DownloadButton(value=path, interactive=True)
175
+
176
+
177
+ def _emit(job, title=""):
178
+ for imgs, msg, tok in _run(job):
179
+ if tok is None:
180
+ yield imgs, msg, gr.skip(), gr.skip(), gr.skip()
181
+ else:
182
+ yield imgs, title + msg, {"prompt": job["prompt"], "tokens": tok.tolist()}, \
183
+ _dl(zip_of(tok, job["prompt"])), job["seed"]
184
+
185
+
186
+ def forge(prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of):
187
+ yield from _emit(_job(prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of))
188
+
189
+
190
+ def remix(state, sel, prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of, keep_share):
191
+ if not state:
192
+ raise gr.Error("Paint some sprites first, then click one to remix it.")
193
+ base = np.asarray(state["tokens"][sel if sel is not None and sel < len(state["tokens"]) else 0], dtype=np.int64)
194
+ job = _job(prompt or state["prompt"], n, steps, guidance, temperature, seed, random_seed, device, best_of)
195
+ rng = np.random.default_rng(job["seed"])
196
+ keep = rng.random(N) < float(keep_share)
197
+ if keep.all():
198
+ keep[rng.integers(0, N)] = False
199
+ job["canvas"], job["keep"] = base, keep
200
+ yield from _emit(job, "Remix · ")
201
+
202
+
203
+ def palette_swap(state, sel):
204
+ if not state:
205
+ raise gr.Error("Paint some sprites first, then click one to recolour it.")
206
+ base = np.asarray(state["tokens"][sel if sel is not None and sel < len(state["tokens"]) else 0], dtype=np.int64)
207
+ toks = np.stack([base] + [hue_shift(base, d) for d in (45, 90, 135, 180, 225, 270, 315)])
208
+ name = state["prompt"] + " recolours"
209
+ return ([card(t, PAL, LAB, size=CARD) for t in toks], "**8 recolours** of the selected sprite (palette-exact)",
210
+ {"prompt": name, "tokens": toks.tolist()}, _dl(zip_of(toks, name)))
211
+
212
+
213
+ def pick(evt: gr.SelectData):
214
+ return evt.index
215
+
216
+
217
+ def set_kind(kind, prompt):
218
+ p = (prompt or "").strip()
219
+ for pre in PREFIXES:
220
+ if p.lower().startswith(pre):
221
+ p = p[len(pre):]
222
+ break
223
+ if not p or kind == "Letter":
224
+ return dice(kind)
225
+ return KINDS[kind] + p
226
+
227
+
228
+ def dice(kind):
229
+ s = random.choice(IDEAS.get(kind, IDEAS["Object"]))
230
+ return s + random.choice("abcdefghijklmnopqrstuvwxyz") if kind == "Letter" else s
231
+
232
+
233
+ def generate(prompt: str, n: int = 4, seed: int = -1, steps: int = 16, guidance: float = 3.0,
234
+ temperature: float = 0.4, best_of: bool = True) -> dict:
235
+ """Generate 16x16 sprites. Returns {"seed", "sprites": [[palette id x 256], ...], "png": [base64 16x16 PNG]}."""
236
+ job = _job(prompt, n, steps, guidance, temperature, None if seed is None or seed < 0 else seed,
237
+ seed is None or seed < 0, "GPU", best_of)
238
+ tok = None
239
+ for _, _, tok in _run(job): # same path as the UI (ZeroGPU when available); the last yield has the tokens
240
+ pass
241
+ pngs = []
242
+ for t in tok:
243
+ buf = io.BytesIO()
244
+ Image.fromarray(rgba(t), "RGBA").save(buf, "PNG")
245
+ pngs.append(base64.b64encode(buf.getvalue()).decode("ascii"))
246
+ return {"seed": job["seed"], "sprites": tok.tolist(), "png": pngs}
247
+
248
+
249
+ # ------------------------------------------------------------------------------------------------- static pages
250
+ LOGO = base64.b64encode((HERE / "assets" / "logo.png").read_bytes()).decode("ascii")
251
+ EXPLORE = json.loads((HERE / "assets" / "explore.json").read_text())
252
+
253
+ SIDE_HEAD = f"""
254
+ <div class="sm-side-head">
255
+ <img class="sm-logo" alt="smalt" src="data:image/png;base64,{LOGO}">
256
+ <p class="sm-blurb">A <b>{PARAMS / 1e6:.1f}M-parameter</b> model that paints <b>16×16 pixel-art sprites</b> from a
257
+ short prompt. Every pixel comes from a fixed 512-colour palette, so sprites are crisp, transparent and game-ready.</p>
258
+ <p class="sm-by">by <b>Pixilab</b> · MIT · <a href="https://huggingface.co/PixilabAI/smalt-small" target="_blank">model card ↗</a></p>
259
+ </div>
260
+ """
261
+
262
+
263
+ def explore_html() -> str:
264
+ cards = []
265
+ for i, it in enumerate(EXPLORE["items"]):
266
+ cards.append(
267
+ f'<figure class="ex-card" style="--frames:{it["frames"]};animation-delay:{i * 35}ms">'
268
+ f'<div class="ex-anim" style="background-image:url({it["strip"]})"></div>'
269
+ f'<img class="ex-img" alt="{html.escape(it["prompt"])}" src="{it["card"]}">'
270
+ f'<figcaption>{html.escape(it["prompt"])}</figcaption></figure>')
271
+ return ('<div class="ex-head"><h2>Explore</h2><p>Sprites painted by smalt, best of 8 by the model\'s own '
272
+ 'confidence. <b>Hover</b> to replay how each one was painted, step by step. Type any of these prompts in '
273
+ 'the sidebar and press <b>Paint</b> to make your own.</p></div>'
274
+ f'<div class="ex-grid">{"".join(cards)}</div>')
275
+
276
+
277
+ def palette_html() -> str:
278
+ sw = "".join(f'<i style="background:{s["hex"]}" title="{s["hex"]} · #{s["i"]}"></i>' for s in EXPLORE["palette"])
279
+ return ('<div class="ex-head"><h2>Palette</h2><p>All 511 colours smalt paints with (plus transparent). Every pixel '
280
+ 'of every sprite is exactly one of these, so there is never blur or a stray in-between shade.</p></div>'
281
+ f'<div class="pal-grid">{sw}</div>')
282
+
283
+
284
+ HOW = """
285
+ ## How it works
286
+
287
+ smalt starts from a **blank 16×16 canvas** where every pixel is *masked*. At each step it looks at the prompt and at
288
+ the pixels already placed, predicts a colour for every empty pixel, and **keeps the ones it is most sure about**.
289
+ After about **16 steps** the whole sprite is filled in. You can watch it happen in the Studio, or hover a sprite in
290
+ Explore to replay it.
291
+
292
+ - **Palette tokens, not RGB.** Each pixel is one of 512 palette entries (0 = transparent), so outputs are pixel-perfect.
293
+ - **Its own little text encoder.** No CLIP, no VAE; the whole thing is 24.5M parameters and runs on a laptop CPU.
294
+ - **Best of N.** With *best of 2×* on, the Studio paints twice as many sprites and keeps the ones the model was most
295
+ confident about.
296
+ - **Remix** keeps a random part of the selected sprite and repaints the rest around it (inpainting).
297
+ - **Recolour** rotates the hue of every saturated colour and snaps it back onto the palette.
298
+
299
+ **Prompting:** short, colour first, then the thing: `red health potion`, `purple slime monster`, `silver sword`.
300
+ Tiles start with `tile with`, effects with `effect`, interface pieces with `ui`, letters with `text`
301
+ (`text gold letter a`).
302
+
303
+ **Limitations:** 16×16 only; trees, crowns, coins, effects and UI bars are weaker than objects and creatures.
304
+
305
+ """
306
+
307
+ CSS = (HERE / "style.css").read_text()
308
+ THEME_COLORS = dict(
309
+ body_background_fill="#0b1029", body_text_color="#ece6d6", body_text_color_subdued="#9aa3d4",
310
+ block_background_fill="#121a45", block_border_color="#232c66", block_label_text_color="#9aa3d4",
311
+ block_title_text_color="#ece6d6", block_label_background_fill="#121a45", block_info_text_color="#9aa3d4",
312
+ background_fill_primary="#121a45", background_fill_secondary="#0e1538", border_color_primary="#232c66",
313
+ border_color_accent="#f2c45a", input_background_fill="#0b1029", input_border_color="#2a3474",
314
+ input_placeholder_color="#6871a8", button_primary_background_fill="#f2c45a",
315
+ button_primary_background_fill_hover="#ffd472", button_primary_text_color="#0b1029",
316
+ button_secondary_background_fill="#1a2357", button_secondary_background_fill_hover="#243079",
317
+ button_secondary_text_color="#ece6d6", button_secondary_border_color="#2a3474", slider_color="#f2c45a",
318
+ color_accent="#f2c45a", color_accent_soft="#1a2357", checkbox_background_color="#0b1029",
319
+ checkbox_background_color_selected="#f2c45a", checkbox_border_color="#2a3474", link_text_color="#f2c45a",
320
+ code_background_fill="#1a2357", table_even_background_fill="#121a45", table_odd_background_fill="#0e1538",
321
+ panel_background_fill="#0e1538",
322
+ )
323
+ _SETTABLE = set(inspect.signature(gr.themes.Base.set).parameters)
324
+ THEME = gr.themes.Base( # dark in both modes
325
+ primary_hue=gr.themes.Color(*["#fff4d6", "#ffe8ad", "#ffdb85", "#f8cd6a", "#f2c45a", "#e0b04a", "#b5852a",
326
+ "#8f6720", "#6e4d12", "#4d3509", "#2e1f05"]),
327
+ neutral_hue=gr.themes.Color(*["#ece6d6", "#c9cdea", "#9aa3d4", "#6871a8", "#3a4796", "#2a3474", "#1a2357",
328
+ "#121a45", "#0e1538", "#0b1029", "#050818"]),
329
+ font=[gr.themes.GoogleFont("Instrument Sans"), "ui-sans-serif", "sans-serif"],
330
+ font_mono=[gr.themes.GoogleFont("Martian Mono"), "ui-monospace", "monospace"],
331
+ radius_size=gr.themes.sizes.radius_lg,
332
+ ).set(**THEME_COLORS, **{k + "_dark": v for k, v in THEME_COLORS.items() if k + "_dark" in _SETTABLE})
333
+
334
+ with gr.Blocks(title="smalt · pixel painter") as demo:
335
+ state = gr.State(None)
336
+ sel = gr.State(0)
337
+ with gr.Row(equal_height=False, elem_id="sm-shell"):
338
+ with gr.Column(scale=1, min_width=320, elem_id="sm-side"):
339
+ gr.HTML(SIDE_HEAD)
340
+ prompt = gr.Textbox(lines=2, max_lines=3, show_label=False, placeholder="Type a prompt here",
341
+ max_length=160, elem_id="sm-prompt", autofocus=True)
342
+ with gr.Row(elem_id="sm-chips"):
343
+ chips = [gr.Button(c, size="sm", elem_classes="sm-chip") for c in CHIPS]
344
+ kind = gr.Radio(list(KINDS), value="Object", label="kind", elem_id="sm-kinds")
345
+ n = gr.Radio([1, 4, 8, 16] if HAS_GPU else [1, 4, 8], value=4, label="images", elem_id="sm-n")
346
+ with gr.Row():
347
+ dice_btn = gr.Button("🎲 random", elem_id="sm-dice", scale=1)
348
+ go = gr.Button("Paint", variant="primary", elem_id="sm-go", scale=2)
349
+ with gr.Accordion("settings", open=False, elem_id="sm-settings"):
350
+ best_of = gr.Checkbox(value=True, label="best of 2× (paint twice as many, keep the cleanest)")
351
+ steps = gr.Slider(4, 32, value=16, step=1, label="steps")
352
+ guidance = gr.Slider(1.0, 8.0, value=3.0, step=0.5, label="guidance")
353
+ temperature = gr.Slider(0.1, 1.5, value=0.4, step=0.05, label="temperature")
354
+ keep_share = gr.Slider(0.1, 0.9, value=0.5, step=0.05, label="remix: share of pixels kept")
355
+ with gr.Row():
356
+ seed = gr.Number(value=0, precision=0, label="seed", minimum=0)
357
+ random_seed = gr.Checkbox(value=True, label="random seed")
358
+ device = gr.Radio(["GPU", "CPU"], value="GPU", label="run on", visible=HAS_GPU)
359
+ with gr.Column(scale=3, elem_id="sm-mainc"):
360
+ with gr.Tabs(selected="explore", elem_id="sm-tabs") as tabs:
361
+ with gr.Tab("Explore", id="explore"):
362
+ gr.HTML(explore_html())
363
+ with gr.Tab("Studio", id="studio"):
364
+ status = gr.Markdown("Type a prompt, or click one of the chips, and press **Paint**.",
365
+ elem_id="sm-status")
366
+ gallery = gr.Gallery(show_label=False, columns=4, height="auto", object_fit="contain",
367
+ format="png", allow_preview=False, elem_id="sm-gallery", interactive=False)
368
+ with gr.Row(elem_id="sm-actions"):
369
+ remix_btn = gr.Button("↻ Remix selected", elem_classes="sm-act")
370
+ swap_btn = gr.Button("◐ Recolour selected", elem_classes="sm-act")
371
+ files = gr.DownloadButton("⬇ PNGs + sprite sheet", value=None, interactive=False,
372
+ elem_classes="sm-act sm-dl")
373
+ with gr.Tab("Palette", id="palette"):
374
+ gr.HTML(palette_html())
375
+ with gr.Tab("How it works", id="how"):
376
+ gr.Markdown(HOW, elem_id="sm-how")
377
+
378
+ run_in = [prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of]
379
+ run_out = [gallery, status, state, files, seed]
380
+ lim = 4 if HAS_GPU else 1
381
+
382
+ def to_studio():
383
+ return gr.Tabs(selected="studio")
384
+
385
+ for trig in (go.click, prompt.submit):
386
+ trig(to_studio, None, tabs, api_name=False).then(forge, run_in, run_out, concurrency_limit=lim,
387
+ show_progress="hidden", api_name=False)
388
+ for b, text in zip(chips, CHIPS):
389
+ b.click(lambda t=text: t, None, prompt, api_name=False).then(to_studio, None, tabs, api_name=False).then(
390
+ forge, run_in, run_out, concurrency_limit=lim, show_progress="hidden", api_name=False)
391
+ remix_btn.click(remix, [state, sel] + run_in + [keep_share], run_out, concurrency_limit=lim,
392
+ show_progress="hidden", api_name=False)
393
+ swap_btn.click(palette_swap, [state, sel], [gallery, status, state, files], api_name=False)
394
+ gallery.select(pick, None, sel, api_name=False)
395
+ kind.change(set_kind, [kind, prompt], prompt, api_name=False)
396
+ dice_btn.click(dice, kind, prompt, api_name=False)
397
+ gr.api(generate, api_name="generate")
398
+
399
+ demo.queue(max_size=64)
400
+
401
+ if __name__ == "__main__":
402
+ demo.launch(theme=THEME, css=CSS, footer_links=[], ssr_mode=False,
403
+ head='<link href="https://fonts.googleapis.com/css2?family=Jersey+10&display=swap" rel="stylesheet">')
assets/explore.json ADDED
The diff for this file is too large to render. See raw diff
 
assets/logo.png ADDED
build_assets.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the Explore grid and the palette sheet for smalt studio (run once, offline; MIT).
2
+
3
+ python build_assets.py --model model --out assets/explore.json
4
+ For every prompt: 4 candidates, keep the one the model is most sure about, record every decoding step of it as a
5
+ horizontal strip of cards (frame 0 = empty canvas) so the page can replay the unmasking on hover with pure CSS.
6
+ """
7
+ import argparse
8
+ import base64
9
+ import io
10
+ import json
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ from PIL import Image
16
+
17
+ HERE = Path(__file__).resolve().parent
18
+ sys.path.insert(0, str(HERE))
19
+ from cards import card # noqa: E402
20
+ from smalt import SmaltPipeline # noqa: E402
21
+
22
+ PROMPTS = ["red health potion", "blue mana potion", "treasure chest", "silver sword", "red key", "magic spellbook",
23
+ "red apple", "iron shield", "green dragon", "yellow bat", "purple slime monster", "knight in silver armor",
24
+ "tile with stone bricks", "tile with blue water", "text gold letter a", "red heart"]
25
+
26
+ # confidence is not legibility: for letters the most "sure" pick can be a different glyph
27
+ FEWER = {"text gold letter a": 4}
28
+
29
+
30
+ def b64(img: Image.Image) -> str:
31
+ buf = io.BytesIO()
32
+ img.save(buf, "PNG", optimize=True)
33
+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
34
+
35
+
36
+ def score(tok: np.ndarray, conf: np.ndarray) -> float:
37
+ op = tok > 0
38
+ return float(np.log(conf[op].clip(1e-6)).mean()) if op.any() else -1e9
39
+
40
+
41
+ def main():
42
+ ap = argparse.ArgumentParser()
43
+ ap.add_argument("--model", default=str(HERE / "model"))
44
+ ap.add_argument("--out", default=str(HERE / "assets" / "explore.json"))
45
+ ap.add_argument("--size", type=int, default=176)
46
+ ap.add_argument("--cands", type=int, default=8)
47
+ ap.add_argument("--seed", type=int, default=2024)
48
+ ap.add_argument("--device", default=None)
49
+ a = ap.parse_args()
50
+ pipe = SmaltPipeline(a.model, device=a.device)
51
+ pal = pipe.palette
52
+ lab = np.asarray(json.loads((Path(a.model) / "palette.json").read_text())["lab"])
53
+ k = len(pal)
54
+ items = []
55
+ for i, p in enumerate(PROMPTS):
56
+ nc = FEWER.get(p, a.cands)
57
+ steps = list(pipe.stream(p, n=nc, seed=a.seed + i))
58
+ last = steps[-1]
59
+ toks, conf = last.tokens.cpu().numpy(), last.confidence.float().cpu().numpy()
60
+ best = int(np.argmax([score(toks[j], conf[j]) for j in range(nc)]))
61
+ final = toks[best]
62
+ from cards import dominant
63
+ tint = dominant(final, pal, lab, k)
64
+ frames = [card(np.full(len(final), k), pal, lab, pre=np.zeros(len(final), int), size=a.size, tint=tint)]
65
+ for st in steps:
66
+ frames.append(card(st.tokens[best].cpu().numpy(), pal, lab, pre=st.preview[best].cpu().numpy(),
67
+ size=a.size, tint=tint))
68
+ strip = Image.new("RGBA", (a.size * len(frames), a.size), (0, 0, 0, 0))
69
+ for j, f in enumerate(frames):
70
+ strip.paste(f, (j * a.size, 0))
71
+ items.append({"prompt": p, "card": b64(card(final, pal, lab, size=a.size)), "strip": b64(strip),
72
+ "frames": len(frames), "sprite": final.astype(int).tolist()})
73
+ print(f"{p}: best {best}", flush=True)
74
+ sw = [{"hex": "#%02x%02x%02x" % tuple(int(v) for v in pal[t]), "i": t} for t in range(1, k)]
75
+ Path(a.out).write_text(json.dumps({"items": items, "palette": sw}))
76
+ print(a.out, sum(len(x["strip"]) + len(x["card"]) for x in items) // 1024, "KB of images")
77
+
78
+
79
+ if __name__ == "__main__":
80
+ main()
cards.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sprite cards for smalt studio (MIT): the sprite, big and crisp, on a soft card tinted with its own main colour."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ from PIL import Image, ImageDraw
6
+
7
+ BASE = np.array([34, 39, 78], np.float64) # dark smalt card
8
+
9
+
10
+ def dominant(tok: np.ndarray, pal: np.ndarray, lab: np.ndarray, k: int) -> np.ndarray:
11
+ """Most frequent opaque colour that is neither near-black (outlines) nor near-grey; falls back to any opaque."""
12
+ t = tok[(tok > 0) & (tok < k)]
13
+ if not len(t):
14
+ return np.array([200, 204, 220], np.float64)
15
+ ids, cnt = np.unique(t, return_counts=True)
16
+ order = np.argsort(-cnt)
17
+ for i in order:
18
+ L, a, b = lab[ids[i]]
19
+ if L > 0.3 and np.hypot(a, b) > 0.04:
20
+ return pal[ids[i]].astype(np.float64)
21
+ return pal[ids[order[0]]].astype(np.float64)
22
+
23
+
24
+ def sprite_rgba(tok: np.ndarray, pre, pal: np.ndarray, k: int, g: int = 16, ghost: int = 70) -> np.ndarray:
25
+ tok = tok.astype(np.int64)
26
+ show = tok.copy()
27
+ alpha = np.full(tok.shape, 255, np.uint8)
28
+ und = tok >= k
29
+ if pre is not None:
30
+ show[und] = np.asarray(pre).astype(np.int64)[und]
31
+ alpha[und] = ghost
32
+ else:
33
+ alpha[und] = 0
34
+ show = np.clip(show, 0, k - 1)
35
+ alpha[show == 0] = 0
36
+ return np.concatenate([pal[show], alpha[:, None]], 1).reshape(g, g, 4).astype(np.uint8)
37
+
38
+
39
+ def card(tok: np.ndarray, pal: np.ndarray, lab: np.ndarray, pre=None, size: int = 240, tint=None) -> Image.Image:
40
+ k = len(pal)
41
+ g = int(np.sqrt(len(tok)))
42
+ base = dominant(tok if pre is None else np.where(tok >= k, pre, tok), pal, lab, k) if tint is None else tint
43
+ bg = tuple(int(v) for v in (BASE * 0.8 + base * 0.2))
44
+ img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
45
+ ImageDraw.Draw(img).rounded_rectangle([0, 0, size - 1, size - 1], radius=max(6, size // 14), fill=bg + (255,))
46
+ s = max(1, int(size * 0.72) // g)
47
+ off = (size - g * s) // 2
48
+ spr = Image.fromarray(sprite_rgba(tok, pre, pal, k, g), "RGBA").resize((g * s, g * s), Image.NEAREST)
49
+ a = np.asarray(spr)[..., 3]
50
+ shadow = np.zeros((g * s, g * s, 4), np.uint8)
51
+ shadow[..., :3] = (6, 8, 22)
52
+ shadow[..., 3] = (a > 200) * 110
53
+ img.alpha_composite(Image.fromarray(shadow, "RGBA"), (off + max(1, s // 3), off + s))
54
+ img.alpha_composite(spr, (off, off))
55
+ return img
model/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architecture": "smalt",
3
+ "model": {
4
+ "grid": 16,
5
+ "n_colors": 512,
6
+ "text_vocab": 4096,
7
+ "text_len": 32,
8
+ "width": 384,
9
+ "heads": 6,
10
+ "depth_in": 2,
11
+ "depth_core": 6,
12
+ "depth_out": 2,
13
+ "mlp_ratio": 3.0,
14
+ "n_reg": 4,
15
+ "rope_theta": 100.0,
16
+ "merge": true
17
+ },
18
+ "n_used": 512,
19
+ "defaults": {
20
+ "steps": 16,
21
+ "guidance": 3.0,
22
+ "temperature": 0.4
23
+ }
24
+ }
model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55796cd3962878d1bdca81f57ecf87c2ebe6ae947715a334722a09a21521f0a4
3
+ size 97908284
model/palette.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"rgb": [[0, 0, 0], [252, 253, 252], [57, 57, 58], [73, 74, 74], [117, 118, 116], [50, 50, 51], [231, 239, 242], [38, 35, 34], [254, 31, 19], [244, 246, 246], [22, 25, 29], [42, 42, 41], [77, 82, 84], [101, 100, 100], [31, 29, 28], [65, 66, 66], [126, 126, 128], [109, 109, 106], [88, 86, 83], [88, 93, 95], [12, 12, 12], [147, 13, 12], [17, 19, 18], [183, 192, 197], [252, 199, 35], [129, 17, 16], [140, 146, 148], [159, 130, 94], [253, 212, 46], [226, 227, 228], [136, 106, 70], [52, 44, 35], [168, 114, 58], [36, 32, 51], [146, 118, 83], [112, 183, 176], [32, 21, 14], [152, 153, 151], [135, 135, 136], [157, 102, 36], [90, 48, 18], [153, 191, 223], [251, 186, 40], [200, 197, 190], [121, 97, 66], [209, 22, 22], [175, 177, 173], [178, 88, 37], [72, 60, 46], [162, 14, 14], [6, 7, 8], [192, 205, 213], [132, 129, 115], [63, 31, 7], [252, 160, 42], [252, 142, 38], [115, 9, 9], [48, 34, 19], [167, 169, 168], [182, 134, 84], [100, 91, 81], [42, 47, 62], [198, 142, 88], [188, 185, 179], [162, 161, 155], [255, 225, 45], [147, 137, 122], [108, 102, 86], [255, 252, 38], [102, 80, 52], [88, 85, 108], [110, 189, 201], [25, 21, 45], [250, 240, 49], [112, 89, 61], [85, 69, 47], [205, 167, 127], [77, 39, 14], [166, 142, 109], [65, 74, 94], [249, 224, 170], [252, 232, 147], [194, 24, 13], [180, 167, 140], [252, 222, 101], [208, 207, 205], [252, 174, 44], [250, 207, 165], [230, 109, 34], [59, 37, 49], [115, 70, 25], [117, 111, 88], [116, 205, 248], [61, 52, 39], [100, 9, 9], [4, 2, 2], [219, 217, 214], [25, 15, 26], [122, 79, 52], [179, 16, 11], [242, 187, 140], [220, 202, 167], [145, 155, 174], [124, 173, 61], [81, 10, 8], [249, 103, 30], [45, 24, 8], [205, 190, 158], [204, 148, 44], [234, 23, 23], [225, 160, 53], [92, 115, 120], [249, 195, 98], [195, 152, 109], [161, 101, 72], [189, 103, 34], [174, 181, 189], [182, 124, 45], [228, 164, 103], [96, 55, 42], [146, 177, 210], [24, 13, 8], [168, 157, 114], [152, 150, 126], [48, 88, 92], [251, 125, 40], [102, 174, 179], [157, 168, 186], [181, 141, 54], [225, 179, 44], [250, 250, 154], [197, 76, 31], [107, 120, 147], [233, 125, 63], [241, 178, 96], [74, 49, 40], [141, 90, 59], [85, 80, 64], [251, 237, 104], [127, 221, 250], [253, 73, 23], [83, 65, 61], [36, 159, 222], [68, 175, 61], [29, 68, 8], [130, 64, 23], [232, 140, 47], [155, 123, 44], [121, 197, 191], [35, 111, 27], [204, 112, 43], [140, 76, 31], [157, 86, 31], [99, 176, 213], [103, 67, 43], [204, 218, 226], [251, 212, 123], [164, 135, 36], [56, 64, 81], [180, 110, 85], [122, 125, 93], [130, 103, 92], [19, 37, 47], [94, 72, 67], [254, 247, 187], [164, 73, 28], [36, 101, 52], [213, 127, 34], [250, 119, 115], [102, 36, 24], [84, 103, 103], [36, 90, 22], [69, 47, 62], [31, 124, 22], [189, 122, 83], [228, 195, 47], [228, 216, 153], [64, 132, 30], [61, 44, 18], [138, 114, 105], [217, 47, 47], [74, 60, 85], [223, 96, 38], [247, 237, 229], [227, 215, 183], [124, 87, 84], [192, 163, 84], [54, 254, 251], [113, 53, 20], [139, 166, 167], [224, 202, 130], [66, 34, 32], [227, 210, 99], [165, 137, 137], [115, 204, 223], [232, 63, 61], [41, 119, 61], [252, 92, 86], [131, 87, 28], [250, 65, 65], [205, 182, 125], [107, 191, 225], [204, 92, 36], [203, 168, 28], [36, 154, 35], [88, 29, 18], [183, 82, 81], [204, 177, 89], [251, 251, 109], [147, 81, 71], [121, 134, 159], [108, 79, 72], [115, 61, 56], [198, 231, 245], [49, 167, 38], [65, 6, 6], [11, 56, 9], [188, 250, 251], [50, 25, 25], [90, 98, 122], [221, 251, 252], [99, 60, 16], [19, 3, 3], [196, 99, 97], [43, 56, 30], [23, 140, 28], [252, 252, 222], [17, 4, 26], [169, 47, 37], [106, 190, 50], [178, 202, 243], [84, 194, 250], [100, 129, 127], [141, 114, 45], [134, 139, 102], [231, 113, 111], [24, 38, 24], [33, 74, 82], [115, 103, 125], [196, 54, 58], [75, 51, 16], [171, 221, 244], [28, 48, 18], [140, 238, 251], [31, 67, 44], [219, 106, 100], [151, 59, 17], [104, 169, 249], [252, 238, 208], [161, 120, 116], [25, 52, 52], [185, 153, 140], [210, 194, 101], [32, 58, 99], [220, 149, 97], [11, 25, 6], [43, 77, 30], [83, 61, 26], [139, 140, 172], [137, 68, 57], [6, 15, 32], [156, 207, 228], [152, 254, 237], [21, 82, 6], [199, 171, 159], [94, 108, 144], [0, 0, 0], [130, 43, 20], [42, 103, 89], [229, 230, 206], [53, 166, 246], [132, 204, 65], [42, 35, 65], [114, 159, 207], [226, 87, 90], [140, 190, 48], [108, 85, 25], [131, 101, 36], [28, 101, 21], [252, 221, 190], [247, 145, 99], [134, 215, 200], [87, 138, 174], [27, 95, 189], [41, 182, 246], [57, 156, 115], [107, 97, 22], [30, 212, 201], [124, 187, 250], [132, 132, 42], [77, 107, 47], [65, 166, 77], [159, 95, 95], [56, 111, 197], [56, 45, 82], [98, 114, 77], [149, 44, 44], [109, 157, 38], [207, 75, 75], [222, 75, 30], [59, 61, 125], [168, 208, 79], [231, 223, 49], [59, 171, 155], [171, 171, 55], [35, 62, 65], [47, 148, 249], [11, 40, 5], [47, 144, 68], [66, 192, 104], [59, 103, 161], [93, 52, 66], [53, 5, 3], [70, 215, 250], [94, 69, 90], [207, 131, 95], [60, 74, 53], [51, 132, 89], [250, 220, 220], [61, 98, 123], [249, 200, 200], [172, 152, 41], [114, 142, 139], [249, 166, 121], [6, 10, 2], [87, 126, 48], [185, 60, 14], [40, 127, 180], [13, 131, 247], [59, 141, 208], [148, 224, 60], [180, 131, 191], [252, 144, 144], [131, 118, 156], [143, 153, 67], [91, 74, 28], [184, 36, 48], [193, 188, 41], [40, 186, 26], [133, 198, 106], [51, 121, 111], [1, 1, 3], [44, 202, 35], [90, 139, 38], [247, 182, 182], [214, 208, 44], [22, 45, 77], [168, 110, 171], [80, 142, 80], [58, 66, 22], [241, 207, 231], [32, 86, 62], [51, 236, 250], [97, 150, 73], [169, 225, 225], [43, 153, 168], [38, 2, 1], [166, 66, 66], [101, 127, 255], [75, 94, 24], [49, 80, 115], [107, 149, 252], [46, 13, 36], [90, 172, 111], [128, 58, 70], [67, 250, 8], [120, 71, 124], [103, 149, 187], [92, 124, 188], [115, 113, 31], [66, 143, 132], [5, 23, 135], [46, 191, 191], [198, 56, 151], [241, 166, 164], [2, 3, 24], [169, 171, 237], [219, 114, 186], [28, 111, 247], [89, 94, 65], [114, 156, 162], [153, 179, 180], [39, 115, 147], [111, 184, 130], [113, 34, 49], [220, 143, 143], [163, 222, 162], [35, 51, 134], [165, 152, 195], [202, 218, 251], [71, 215, 99], [194, 126, 126], [95, 231, 51], [63, 218, 166], [84, 38, 45], [102, 112, 217], [33, 60, 165], [99, 151, 122], [135, 32, 61], [251, 19, 251], [49, 94, 213], [193, 160, 196], [58, 171, 196], [63, 26, 98], [95, 87, 164], [53, 85, 149], [42, 133, 149], [33, 83, 170], [18, 78, 137], [25, 40, 102], [119, 255, 88], [78, 17, 37], [248, 231, 253], [230, 229, 130], [90, 72, 134], [219, 186, 211], [14, 27, 73], [1, 9, 98], [189, 234, 190], [123, 226, 123], [244, 172, 255], [8, 86, 250], [32, 6, 57], [0, 20, 251], [6, 13, 173], [68, 84, 49], [179, 89, 129], [94, 108, 255], [186, 231, 107], [174, 189, 114], [224, 246, 208], [141, 93, 139], [245, 128, 251], [133, 163, 127], [155, 179, 143], [74, 81, 19], [133, 201, 163], [47, 195, 163], [96, 226, 226], [32, 97, 138], [0, 4, 55], [182, 54, 99], [96, 6, 109], [102, 33, 146], [177, 13, 177], [249, 192, 255], [230, 138, 202], [171, 82, 182], [211, 90, 177], [245, 100, 255], [156, 104, 247], [142, 68, 96], [123, 133, 211], [57, 217, 0], [246, 152, 255], [255, 30, 77], [106, 36, 92], [116, 32, 126], [89, 57, 106], [85, 13, 78], [211, 52, 100], [183, 111, 147], [55, 9, 66], [197, 249, 84], [89, 37, 74], [178, 255, 182], [65, 26, 65], [187, 88, 204], [164, 31, 112], [252, 80, 110], [19, 254, 156], [108, 104, 162], [213, 16, 213], [64, 64, 191], [208, 100, 213], [60, 252, 204], [145, 24, 144], [164, 33, 76], [39, 52, 252], [205, 98, 251], [231, 57, 167], [28, 59, 217], [24, 25, 197], [147, 70, 161], [80, 4, 139], [137, 49, 137], [140, 142, 245], [216, 49, 255], [250, 163, 199], [250, 211, 255], [222, 163, 213], [202, 137, 255], [255, 113, 156], [141, 41, 244], [133, 96, 169], [180, 13, 255], [129, 80, 202], [237, 49, 120], [153, 23, 195], [51, 19, 142], [160, 75, 240], [79, 41, 115], [220, 106, 140], [104, 28, 251], [229, 43, 80], [123, 39, 182], [245, 85, 154], [255, 58, 219], [34, 16, 90], [79, 79, 252], [248, 106, 199], [91, 0, 216]], "lab": [[0.0, 0.0, 0.0], [0.993013, -0.001386, 0.00095], [0.34495, 0.000482, -0.001648], [0.408179, -0.001264, -0.000389], [0.56433, -0.002027, 0.002546], [0.31751, 0.000492, -0.001683], [0.946954, -0.007029, -0.006342], [0.25906, 0.003787, 0.00311], [0.634398, 0.216614, 0.122307], [0.971627, -0.002037, -0.000627], [0.211997, -0.002274, -0.008868], [0.284641, -0.000511, 0.001722], [0.434776, -0.005252, -0.004996], [0.504132, 0.001204, 0.000373], [0.232594, 0.002406, 0.002726], [0.378135, -0.001288, -0.000396], [0.593743, 0.000842, -0.002878], [0.533802, -0.001311, 0.004411], [0.454034, 0.001111, 0.005354], [0.474599, -0.005145, -0.004892], [0.15434, 0.0, 0.0], [0.422331, 0.145185, 0.078478], [0.184081, -0.003623, 0.000998], [0.802274, -0.007586, -0.009604], [0.85321, 0.005201, 0.167709], [0.388529, 0.129021, 0.067847], [0.65564, -0.005873, -0.004858], [0.624956, 0.018708, 0.058764], [0.880016, -0.010978, 0.16998], [0.915345, -0.000655, -0.001609], [0.545359, 0.020861, 0.06032], [0.298977, 0.006595, 0.018385], [0.597009, 0.0423, 0.089873], [0.257167, 0.014128, -0.03265], [0.584041, 0.018325, 0.057793], [0.730623, -0.0718, -0.009727], [0.207727, 0.013291, 0.018024], [0.681515, -0.001933, 0.002429], [0.623723, 0.000417, -0.00142], [0.557791, 0.041887, 0.097715], [0.357294, 0.044575, 0.059381], [0.788088, -0.026799, -0.055119], [0.827546, 0.023987, 0.160014], [0.823853, 0.000449, 0.010207], [0.508645, 0.015837, 0.052458], [0.54747, 0.189103, 0.101704], [0.7576, -0.003767, 0.004728], [0.561761, 0.09069, 0.097208], [0.364652, 0.009211, 0.026842], [0.452846, 0.156612, 0.084337], [0.127561, -0.001427, -0.003177], [0.840786, -0.010488, -0.014729], [0.60174, -0.002567, 0.020793], [0.278739, 0.035803, 0.048853], [0.78151, 0.06489, 0.148134], [0.750935, 0.091617, 0.142519], [0.35454, 0.121285, 0.064596], [0.264654, 0.012723, 0.030702], [0.732881, -0.002586, 0.000691], [0.656025, 0.035634, 0.081388], [0.476696, 0.006598, 0.018392], [0.30697, 0.000167, -0.028011], [0.690058, 0.043069, 0.088114], [0.786465, 0.000854, 0.008997], [0.708052, -0.001344, 0.008548], [0.907682, -0.027334, 0.176786], [0.634579, 0.005129, 0.024389], [0.511074, 4.5e-05, 0.025512], [0.962412, -0.065034, 0.191459], [0.446896, 0.015276, 0.048797], [0.461192, 0.013222, -0.034728], [0.752033, -0.070174, -0.037512], [0.214168, 0.015504, -0.043664], [0.933926, -0.053063, 0.181537], [0.480079, 0.0162, 0.048707], [0.401122, 0.010487, 0.039237], [0.752951, 0.026374, 0.06488], [0.318593, 0.04244, 0.052637], [0.66008, 0.013717, 0.052693], [0.409264, -0.002552, -0.035583], [0.914395, 0.005242, 0.074454], [0.928746, -0.012172, 0.1066], [0.519441, 0.175372, 0.099668], [0.732232, 0.003297, 0.040245], [0.902887, -0.013578, 0.142313], [0.854729, 0.00028, 0.002945], [0.806587, 0.043902, 0.153314], [0.881473, 0.029892, 0.067027], [0.669339, 0.115985, 0.125125], [0.296355, 0.037272, -0.009415], [0.43822, 0.040072, 0.075045], [0.540653, -0.003134, 0.03485], [0.808812, -0.066124, -0.081534], [0.330657, 0.005768, 0.02456], [0.322904, 0.108719, 0.057021], [0.091281, 0.007908, 0.002694], [0.886023, 0.00094, 0.004538], [0.18712, 0.021506, -0.015926], [0.469403, 0.043128, 0.055925], [0.486935, 0.167968, 0.093345], [0.831002, 0.042025, 0.077923], [0.844972, 0.005379, 0.050582], [0.687762, -0.00349, -0.03002], [0.689767, -0.096708, 0.116166], [0.282978, 0.090456, 0.047991], [0.688837, 0.143801, 0.131119], [0.233988, 0.023905, 0.035611], [0.8057, 0.003367, 0.04636], [0.703708, 0.027042, 0.129223], [0.59474, 0.206718, 0.111903], [0.750826, 0.035464, 0.135379], [0.538904, -0.023756, -0.015063], [0.847016, 0.022276, 0.127831], [0.709755, 0.031535, 0.070927], [0.565665, 0.061215, 0.063929], [0.601939, 0.078789, 0.109533], [0.770017, -0.004372, -0.013135], [0.631866, 0.038925, 0.110435], [0.767062, 0.048208, 0.097327], [0.383979, 0.04929, 0.038997], [0.748809, -0.019863, -0.055234], [0.172854, 0.015113, 0.015567], [0.694656, -0.005761, 0.060066], [0.668148, -0.007916, 0.033336], [0.432693, -0.041677, -0.018486], [0.723119, 0.11633, 0.134739], [0.705624, -0.067608, -0.026486], [0.728732, -0.00487, -0.028503], [0.665244, 0.012702, 0.113047], [0.787016, 0.004519, 0.149312], [0.964399, -0.037354, 0.112126], [0.572975, 0.127952, 0.103541], [0.57197, -0.004036, -0.044431], [0.700341, 0.102183, 0.113929], [0.806312, 0.038635, 0.117041], [0.340155, 0.030289, 0.025973], [0.5169, 0.050471, 0.063277], [0.431269, -0.001245, 0.026051], [0.932453, -0.035221, 0.14876], [0.849757, -0.075016, -0.06295], [0.661117, 0.183293, 0.127192], [0.393225, 0.021936, 0.014079], [0.667539, -0.073411, -0.116035], [0.668043, -0.143619, 0.111044], [0.344858, -0.071299, 0.065714], [0.448757, 0.069154, 0.078864], [0.722602, 0.073556, 0.13141], [0.598825, 0.006688, 0.103079], [0.772362, -0.075184, -0.012293], [0.477349, -0.109137, 0.086012], [0.638253, 0.084154, 0.112722], [0.485564, 0.063389, 0.082295], [0.527655, 0.067431, 0.093173], [0.721907, -0.05897, -0.072304], [0.418277, 0.036489, 0.050058], [0.880165, -0.011394, -0.01487], [0.884918, 0.007417, 0.116345], [0.63327, -0.003361, 0.117172], [0.371264, -0.002634, -0.031112], [0.608642, 0.073819, 0.062711], [0.578392, -0.017684, 0.043303], [0.53733, 0.028234, 0.026593], [0.253801, -0.017847, -0.024641], [0.42344, 0.02634, 0.017134], [0.967331, -0.016144, 0.075087], [0.516359, 0.095986, 0.091959], [0.452046, -0.087662, 0.053213], [0.675162, 0.069005, 0.127143], [0.722143, 0.147698, 0.06482], [0.357319, 0.082794, 0.052482], [0.498173, -0.02195, -0.006477], [0.415672, -0.087475, 0.073639], [0.336639, 0.037321, -0.014472], [0.513503, -0.125048, 0.098095], [0.641236, 0.063515, 0.076845], [0.822174, -0.015122, 0.156367], [0.877183, -0.012386, 0.081205], [0.54802, -0.1108, 0.101588], [0.306613, 0.011333, 0.045552], [0.572371, 0.024916, 0.022124], [0.578657, 0.184086, 0.091959], [0.381188, 0.028985, -0.034841], [0.640714, 0.12827, 0.115856], [0.951749, 0.007308, 0.013372], [0.880573, 7.7e-05, 0.044519], [0.495338, 0.045354, 0.020403], [0.725001, 0.000885, 0.104323], [0.905657, -0.142917, -0.033703], [0.402841, 0.066045, 0.069405], [0.704969, -0.028301, -0.009886], [0.841354, -0.005025, 0.094517], [0.294456, 0.045152, 0.020392], [0.856077, -0.024676, 0.130583], [0.655876, 0.032454, 0.010581], [0.796499, -0.074993, -0.048843], [0.619573, 0.185048, 0.090751], [0.50661, -0.100787, 0.061054], [0.685362, 0.176749, 0.085549], [0.494147, 0.032018, 0.08736], [0.652245, 0.199035, 0.096393], [0.782667, 0.002107, 0.079095], [0.764344, -0.065483, -0.068844], [0.606339, 0.113366, 0.108845], [0.741794, -0.007786, 0.14567], [0.600292, -0.147075, 0.111827], [0.320744, 0.075725, 0.048445], [0.566337, 0.121451, 0.050939], [0.766051, -0.004991, 0.112238], [0.961566, -0.05313, 0.153424], [0.510618, 0.078558, 0.044691], [0.618387, -0.004642, -0.040616], [0.456427, 0.034047, 0.022939], [0.426088, 0.068658, 0.033951], [0.908518, -0.02782, -0.02814], [0.639164, -0.152535, 0.11958], [0.243827, 0.079051, 0.040099], [0.299418, -0.070093, 0.053901], [0.943872, -0.059155, -0.018533], [0.248265, 0.03764, 0.013947], [0.498444, 0.000346, -0.039659], [0.966863, -0.029423, -0.01019], [0.394663, 0.034055, 0.070904], [0.13221, 0.031665, 0.013449], [0.61402, 0.114937, 0.047818], [0.321232, -0.030263, 0.035678], [0.558138, -0.140865, 0.105598], [0.983304, -0.011479, 0.037321], [0.147152, 0.032702, -0.038836], [0.492118, 0.140118, 0.077417], [0.721271, -0.135747, 0.132421], [0.834931, -0.009803, -0.062632], [0.773158, -0.074873, -0.103403], [0.580193, -0.032684, -0.006379], [0.564442, 0.004124, 0.093068], [0.6227, -0.021825, 0.048524], [0.686495, 0.135734, 0.056691], [0.250977, -0.026368, 0.018784], [0.383199, -0.040379, -0.025261], [0.532796, 0.023433, -0.028317], [0.549184, 0.163343, 0.072416], [0.341694, 0.017286, 0.057476], [0.870311, -0.040731, -0.044949], [0.283498, -0.041276, 0.039552], [0.893415, -0.084107, -0.042076], [0.348635, -0.052412, 0.025498], [0.657326, 0.129683, 0.06003], [0.474041, 0.100285, 0.088457], [0.725385, -0.036155, -0.13007], [0.952489, 0.002966, 0.041973], [0.612014, 0.04721, 0.022058], [0.30374, -0.031826, -0.008858], [0.708407, 0.031099, 0.029297], [0.808215, -0.019558, 0.114125], [0.349876, -0.01481, -0.077357], [0.729535, 0.060787, 0.091001], [0.19449, -0.0306, 0.02797], [0.38195, -0.062148, 0.05624], [0.376417, 0.013398, 0.057406], [0.650514, 0.011152, -0.046146], [0.47099, 0.083233, 0.048959], [0.170061, -0.006004, -0.038027], [0.825985, -0.042677, -0.04298], [0.929889, -0.098984, -0.003841], [0.384854, -0.09282, 0.076281], [0.762402, 0.026317, 0.025914], [0.534021, -0.002144, -0.059269], [0.0, 0.0, 0.0], [0.416382, 0.101635, 0.072324], [0.469387, -0.067161, 0.004921], [0.917777, -0.010354, 0.030146], [0.699577, -0.065883, -0.138346], [0.770448, -0.125465, 0.135156], [0.27938, 0.021568, -0.050155], [0.688827, -0.028506, -0.08152], [0.640004, 0.160719, 0.065456], [0.740094, -0.105555, 0.137714], [0.461389, 0.004128, 0.081644], [0.524279, 0.010284, 0.089477], [0.445392, -0.10458, 0.082089], [0.915419, 0.020826, 0.04924], [0.755339, 0.098421, 0.096518], [0.822781, -0.082651, -0.00157], [0.611941, -0.038226, -0.06746], [0.499142, -0.033588, -0.158823], [0.733716, -0.083972, -0.118226], [0.623678, -0.106596, 0.03354], [0.487866, -0.018238, 0.090542], [0.785788, -0.131427, -0.018614], [0.77414, -0.039181, -0.104491], [0.595723, -0.036654, 0.104452], [0.489673, -0.061745, 0.070707], [0.645177, -0.130274, 0.089245], [0.557137, 0.078762, 0.028777], [0.5489, -0.027672, -0.143587], [0.327373, 0.028838, -0.058298], [0.528655, -0.035461, 0.04657], [0.454368, 0.127675, 0.058667], [0.63876, -0.097788, 0.118709], [0.593026, 0.153367, 0.067439], [0.612218, 0.153847, 0.113199], [0.393089, 0.016551, -0.104686], [0.80333, -0.091863, 0.133219], [0.882635, -0.051028, 0.169892], [0.674134, -0.102676, -0.003307], [0.719766, -0.044818, 0.127522], [0.343601, -0.030235, -0.013949], [0.660056, -0.052941, -0.167051], [0.245579, -0.052837, 0.044094], [0.578975, -0.121153, 0.077453], [0.7177, -0.144886, 0.084222], [0.509901, -0.025475, -0.101761], [0.380677, 0.061778, -0.001576], [0.214927, 0.066934, 0.037401], [0.817316, -0.101938, -0.078613], [0.425079, 0.041513, -0.022089], [0.681418, 0.074309, 0.076456], [0.390336, -0.027657, 0.027303], [0.551611, -0.095912, 0.04065], [0.919217, 0.031725, 0.01017], [0.478928, -0.029986, -0.050322], [0.875586, 0.05308, 0.017529], [0.678072, -0.018794, 0.125379], [0.624223, -0.031679, -0.00465], [0.796965, 0.075621, 0.086952], [0.135717, -0.014788, 0.019525], [0.546319, -0.077081, 0.086827], [0.532467, 0.133959, 0.102707], [0.570506, -0.056477, -0.099597], [0.616756, -0.051762, -0.189674], [0.623943, -0.051071, -0.118021], [0.827009, -0.135368, 0.152632], [0.678797, 0.078164, -0.065365], [0.768342, 0.122511, 0.045895], [0.591546, 0.029703, -0.050893], [0.656508, -0.047093, 0.100779], [0.416626, 0.001427, 0.067194], [0.511045, 0.168067, 0.071278], [0.775207, -0.046778, 0.148619], [0.688138, -0.174556, 0.136541], [0.761294, -0.103202, 0.095797], [0.528461, -0.072036, -0.003471], [0.071162, 0.002932, -0.01339], [0.732025, -0.184809, 0.143074], [0.581047, -0.094036, 0.104392], [0.836209, 0.0718, 0.024433], [0.836333, -0.050288, 0.161373], [0.29634, -0.014696, -0.063728], [0.620763, 0.090945, -0.063438], [0.588769, -0.090966, 0.066133], [0.361037, -0.031468, 0.057955], [0.890135, 0.045207, -0.019541], [0.409564, -0.066941, 0.022319], [0.8627, -0.127782, -0.054166], [0.617473, -0.089018, 0.083713], [0.871465, -0.054871, -0.015892], [0.629547, -0.085356, -0.046287], [0.17368, 0.055923, 0.031866], [0.514513, 0.122178, 0.051704], [0.642069, 0.004687, -0.191087], [0.451083, -0.053412, 0.080658], [0.423605, -0.020917, -0.066105], [0.686764, -0.01196, -0.158465], [0.223481, 0.060194, -0.020636], [0.676385, -0.105208, 0.059797], [0.444165, 0.095409, 0.018858], [0.860277, -0.217519, 0.177172], [0.475659, 0.081883, -0.058871], [0.651542, -0.032951, -0.068313], [0.59006, -0.01229, -0.104594], [0.534423, -0.031319, 0.096421], [0.598177, -0.078075, -0.004142], [0.305057, -0.014944, -0.178849], [0.733009, -0.111953, -0.029835], [0.581367, 0.193629, -0.054891], [0.796976, 0.083406, 0.03193], [0.116935, 0.001349, -0.050752], [0.763871, 0.020521, -0.091941], [0.694324, 0.147136, -0.052115], [0.57737, -0.036278, -0.214824], [0.4693, -0.019688, 0.040171], [0.664282, -0.04135, -0.021149], [0.74743, -0.02697, -0.009503], [0.523778, -0.056625, -0.067589], [0.720142, -0.094464, 0.051811], [0.379397, 0.108251, 0.024955], [0.728057, 0.088575, 0.031527], [0.844846, -0.082809, 0.05971], [0.363526, -0.000792, -0.139692], [0.705768, 0.030386, -0.055708], [0.886869, -0.004374, -0.048586], [0.777383, -0.166942, 0.1096], [0.663501, 0.080053, 0.028457], [0.820593, -0.183568, 0.156402], [0.795753, -0.143799, 0.036241], [0.334474, 0.067154, 0.014218], [0.588958, 0.017369, -0.157476], [0.408664, -0.009092, -0.171441], [0.631222, -0.066347, 0.025352], [0.420314, 0.136654, 0.021766], [0.696289, 0.267744, -0.165197], [0.522297, -0.01721, -0.189249], [0.746787, 0.050423, -0.0373], [0.688751, -0.085362, -0.061184], [0.313697, 0.067257, -0.101199], [0.501403, 0.032935, -0.115009], [0.458186, -0.014007, -0.110317], [0.571084, -0.073243, -0.045316], [0.460164, -0.024356, -0.147931], [0.420297, -0.034497, -0.10903], [0.306037, -0.002605, -0.110544], [0.890979, -0.182332, 0.15196], [0.290168, 0.091531, 0.008294], [0.947917, 0.025707, -0.022738], [0.901753, -0.03788, 0.115862], [0.449194, 0.04301, -0.090298], [0.824863, 0.045361, -0.021579], [0.243587, -0.003882, -0.087444], [0.236032, -0.013671, -0.146759], [0.893765, -0.062352, 0.042888], [0.826316, -0.137256, 0.100286], [0.839883, 0.107122, -0.083626], [0.53085, -0.031742, -0.250076], [0.205794, 0.048711, -0.077926], [0.454152, -0.030998, -0.302774], [0.346863, -0.019612, -0.227131], [0.422453, -0.036359, 0.04546], [0.584205, 0.124406, -0.013749], [0.603288, 0.014511, -0.215476], [0.870618, -0.094336, 0.129273], [0.769334, -0.047097, 0.088367], [0.9471, -0.037001, 0.041011], [0.546426, 0.076474, -0.047502], [0.773325, 0.168978, -0.116162], [0.682768, -0.047494, 0.039291], [0.738642, -0.040549, 0.040218], [0.415484, -0.036147, 0.07503], [0.779883, -0.082297, 0.031554], [0.734299, -0.128302, 0.013206], [0.841111, -0.109754, -0.029836], [0.471726, -0.045065, -0.080676], [0.162885, -0.010045, -0.097794], [0.534549, 0.166863, 0.009791], [0.355934, 0.128359, -0.101099], [0.413542, 0.108413, -0.13792], [0.536646, 0.205082, -0.1266], [0.87854, 0.083646, -0.062483], [0.749719, 0.127784, -0.048411], [0.58679, 0.13746, -0.103135], [0.647997, 0.170368, -0.062558], [0.741572, 0.203933, -0.142337], [0.640116, 0.093169, -0.183021], [0.488845, 0.10499, -0.00405], [0.641685, 0.014292, -0.116203], [0.773061, -0.195786, 0.160022], [0.810413, 0.13789, -0.100792], [0.641207, 0.232875, 0.079533], [0.386766, 0.111863, -0.048883], [0.418206, 0.130588, -0.097486], [0.403268, 0.059969, -0.064188], [0.319525, 0.113289, -0.058693], [0.581696, 0.193894, 0.027883], [0.630649, 0.099817, -0.019308], [0.254936, 0.079678, -0.069498], [0.915909, -0.113102, 0.160137], [0.352199, 0.085876, -0.031533], [0.931637, -0.102407, 0.069736], [0.292659, 0.070523, -0.045013], [0.626733, 0.150332, -0.119268], [0.489056, 0.179062, -0.034553], [0.676867, 0.200499, 0.052327], [0.877931, -0.191344, 0.082925], [0.545418, 0.024926, -0.085881], [0.615605, 0.236086, -0.145697], [0.456522, 0.018791, -0.192024], [0.673245, 0.15971, -0.10872], [0.888008, -0.159972, 0.024986], [0.469425, 0.16938, -0.103531], [0.478004, 0.165898, 0.021418], [0.490305, -0.011047, -0.281509], [0.687659, 0.160859, -0.1649], [0.640741, 0.225079, -0.052117], [0.457508, -0.015701, -0.238225], [0.392432, -0.011371, -0.24376], [0.528131, 0.122805, -0.098508], [0.357128, 0.096135, -0.159136], [0.47427, 0.136401, -0.086058], [0.690029, 0.028234, -0.146751], [0.660182, 0.218175, -0.191203], [0.811511, 0.110723, -0.012715], [0.913155, 0.057163, -0.043903], [0.786553, 0.08413, -0.045069], [0.74115, 0.108144, -0.137933], [0.730722, 0.176576, 0.010891], [0.551253, 0.130008, -0.235129], [0.557352, 0.068884, -0.093629], [0.596888, 0.190472, -0.229043], [0.547031, 0.087494, -0.159614], [0.628886, 0.22368, 0.017313], [0.516281, 0.171029, -0.170132], [0.336409, 0.039847, -0.175517], [0.601182, 0.130375, -0.196538], [0.369525, 0.070546, -0.101904], [0.668494, 0.145952, 0.007659], [0.511155, 0.077377, -0.270965], [0.60197, 0.208017, 0.062969], [0.475648, 0.124408, -0.168778], [0.682847, 0.203757, -0.009312], [0.701457, 0.252215, -0.107383], [0.257409, 0.031815, -0.117819], [0.544845, 0.019056, -0.247476], [0.726832, 0.191834, -0.058144], [0.450273, 0.07826, -0.24652]]}
model/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.9.1
2
+ tokenizers
3
+ safetensors
4
+ numpy
5
+ pillow
smalt/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """smalt: tiny text-to-pixel-art model, 16x16 sprites from a prompt (MIT)."""
2
+ from .model import ModelCfg, Smalt
3
+ from .pipeline import SmaltPipeline
4
+ from .sampler import Step, generate, sample_steps
5
+
6
+ __all__ = ["ModelCfg", "Smalt", "SmaltPipeline", "Step", "generate", "sample_steps"]
7
+ __version__ = "1.0.0"
smalt/model.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """smalt denoiser (MIT). The denoiser: one bidirectional transformer over [registers | text tokens | pixel tokens].
2
+
3
+ Pixels are palette tokens (0 = transparent, 1..K-1 colours, K = [MASK]). Text tokens come from our own small BPE
4
+ (no frozen text tower) and are updated by every block next to the pixels. Hourglass: pixel-level blocks on the full
5
+ grid, a 2x2 merge, core blocks on the patch grid, unmerge + zero-init skip, pixel-level blocks again.
6
+ Each block: RMSNorm -> adaLN modulate -> joint attention (QK-RMSNorm, 2D axial RoPE) -> gate; RMSNorm -> modulate ->
7
+ SwiGLU with a depthwise 3x3 conv on the gate branch (spatial tokens only) -> gate. adaLN-single: one MLP of
8
+ (pooled text, Fourier(mask ratio)) gives shift/scale/gate for all blocks, plus a learned per-block table; every gate
9
+ starts at zero so every block starts as the identity, and the head starts at zero (uniform logits).
10
+ """
11
+ import math
12
+ from dataclasses import dataclass, asdict
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+
18
+
19
+ @dataclass
20
+ class ModelCfg:
21
+ grid: int = 16
22
+ n_colors: int = 512 # palette size incl. transparent; [MASK] = n_colors
23
+ text_vocab: int = 4096
24
+ text_len: int = 24
25
+ width: int = 256
26
+ heads: int = 4
27
+ depth_in: int = 1
28
+ depth_core: int = 4
29
+ depth_out: int = 1
30
+ mlp_ratio: float = 3.0
31
+ n_reg: int = 4
32
+ rope_theta: float = 100.0
33
+ merge: bool = True # 2x2 hourglass; False = every block at pixel level
34
+
35
+ def to_dict(self):
36
+ return asdict(self)
37
+
38
+
39
+ def fourier(x, n_freq):
40
+ """x (..., c) -> (..., c + 2*c*n_freq)."""
41
+ f = math.pi * (2.0 ** torch.arange(n_freq, device=x.device, dtype=torch.float32))
42
+ a = x[..., None].float() * f
43
+ return torch.cat([x.float(), a.sin().flatten(-2), a.cos().flatten(-2)], -1)
44
+
45
+
46
+ def rope_tables(pos, head_dim, theta):
47
+ """pos (L,2) float row/col -> cos, sin (L, head_dim/2): half the pairs rotate with the row, half with the column."""
48
+ nf = head_dim // 4
49
+ freqs = theta ** (-torch.arange(nf, dtype=torch.float64) / nf)
50
+ ang = torch.cat([pos[:, :1].double() * freqs, pos[:, 1:].double() * freqs], -1)
51
+ return ang.cos().float(), ang.sin().float()
52
+
53
+
54
+ def apply_rope(x, cos, sin):
55
+ x1, x2 = x.chunk(2, -1)
56
+ return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1).type_as(x)
57
+
58
+
59
+ def modulate(x, shift, scale):
60
+ return x * (1 + scale[:, None]) + shift[:, None]
61
+
62
+
63
+ class Attention(nn.Module):
64
+ def __init__(self, d, heads):
65
+ super().__init__()
66
+ self.h, self.hd = heads, d // heads
67
+ self.qkv = nn.Linear(d, 3 * d, bias=False)
68
+ self.proj = nn.Linear(d, d, bias=False)
69
+ self.qn = nn.RMSNorm(self.hd)
70
+ self.kn = nn.RMSNorm(self.hd)
71
+
72
+ def forward(self, x, cos, sin):
73
+ b, n, _ = x.shape
74
+ q, k, v = self.qkv(x).view(b, n, 3, self.h, self.hd).permute(2, 0, 3, 1, 4)
75
+ q = apply_rope(self.qn(q), cos, sin).to(v.dtype)
76
+ k = apply_rope(self.kn(k), cos, sin).to(v.dtype)
77
+ o = F.scaled_dot_product_attention(q, k, v)
78
+ return self.proj(o.transpose(1, 2).reshape(b, n, -1))
79
+
80
+
81
+ class ConvSwiGLU(nn.Module):
82
+ def __init__(self, d, hidden):
83
+ super().__init__()
84
+ self.w_in = nn.Linear(d, 2 * hidden, bias=False)
85
+ self.dw = nn.Conv2d(hidden, hidden, 3, padding=1, groups=hidden)
86
+ nn.init.zeros_(self.dw.weight)
87
+ nn.init.zeros_(self.dw.bias)
88
+ self.w_out = nn.Linear(hidden, d, bias=False)
89
+
90
+ def forward(self, x, n_prefix, g):
91
+ v, gate = self.w_in(x).chunk(2, -1)
92
+ sp = gate[:, n_prefix:]
93
+ b = x.shape[0]
94
+ conv = self.dw(sp.transpose(1, 2).reshape(b, -1, g, g)).flatten(2).transpose(1, 2)
95
+ gate = torch.cat([gate[:, :n_prefix], sp + conv], 1)
96
+ return self.w_out(F.silu(gate) * v)
97
+
98
+
99
+ class Block(nn.Module):
100
+ def __init__(self, d, heads, hidden):
101
+ super().__init__()
102
+ self.n1 = nn.RMSNorm(d, elementwise_affine=False)
103
+ self.attn = Attention(d, heads)
104
+ self.n2 = nn.RMSNorm(d, elementwise_affine=False)
105
+ self.mlp = ConvSwiGLU(d, hidden)
106
+ self.table = nn.Parameter(torch.zeros(6, d))
107
+
108
+ def forward(self, x, mod, cos, sin, n_prefix, g):
109
+ sh1, sc1, g1, sh2, sc2, g2 = (mod + self.table).unbind(1)
110
+ x = x + g1[:, None] * self.attn(modulate(self.n1(x), sh1, sc1), cos, sin)
111
+ x = x + g2[:, None] * self.mlp(modulate(self.n2(x), sh2, sc2), n_prefix, g)
112
+ return x
113
+
114
+
115
+ class Smalt(nn.Module):
116
+ def __init__(self, cfg: ModelCfg, pal_lab):
117
+ super().__init__()
118
+ self.cfg = cfg
119
+ d, g, k = cfg.width, cfg.grid, cfg.n_colors
120
+ assert (d // cfg.heads) % 4 == 0, "head dim must be a multiple of 4 (2D RoPE)"
121
+ assert not cfg.merge or g % 2 == 0
122
+ self.mask_id = k
123
+ self.n_prefix = cfg.n_reg + cfg.text_len
124
+ hidden = int(cfg.mlp_ratio * d)
125
+
126
+ # colours: learned(c) + MLP(Fourier(L, a, b, opaque, mask)) so rare shades start next to similar common ones
127
+ feats = torch.zeros(k + 1, 5)
128
+ feats[1:k, :3] = torch.as_tensor(pal_lab, dtype=torch.float32)[1:k]
129
+ feats[1:k, 3] = 1.0
130
+ feats[k, 4] = 1.0
131
+ self.register_buffer("color_feats", feats)
132
+ self.color_emb = nn.Embedding(k + 1, d)
133
+ nn.init.normal_(self.color_emb.weight, std=0.02)
134
+ self.color_mlp = nn.Sequential(nn.Linear(5 + 5 * 2 * 6, d), nn.SiLU(), nn.Linear(d, d))
135
+ self.sc_proj = nn.Linear(k, d, bias=False) # self-conditioning: previous step's distribution
136
+ nn.init.zeros_(self.sc_proj.weight)
137
+
138
+ self.text_emb = nn.Embedding(cfg.text_vocab, d)
139
+ nn.init.normal_(self.text_emb.weight, std=0.02)
140
+ self.text_pos = nn.Parameter(torch.randn(cfg.text_len, d) * 0.02)
141
+ self.registers = nn.Parameter(torch.randn(cfg.n_reg, d) * 0.02)
142
+ self.null_pooled = nn.Parameter(torch.zeros(d))
143
+
144
+ self.cond = nn.Sequential(nn.Linear(d + 1 + 2 * 8, d), nn.SiLU(), nn.Linear(d, d))
145
+ self.mod = nn.Linear(d, 6 * d)
146
+ self.final_mod = nn.Linear(d, 2 * d)
147
+ for m in (self.mod, self.final_mod):
148
+ nn.init.zeros_(m.weight)
149
+ nn.init.zeros_(m.bias)
150
+
151
+ self.blocks_in = nn.ModuleList([Block(d, cfg.heads, hidden) for _ in range(cfg.depth_in)])
152
+ self.blocks_core = nn.ModuleList([Block(d, cfg.heads, hidden) for _ in range(cfg.depth_core)])
153
+ self.blocks_out = nn.ModuleList([Block(d, cfg.heads, hidden) for _ in range(cfg.depth_out)])
154
+ if cfg.merge:
155
+ self.merge = nn.Linear(4 * d, d, bias=False)
156
+ self.unmerge = nn.Linear(d, 4 * d, bias=False)
157
+ self.skip = nn.Linear(d, d, bias=False)
158
+ nn.init.zeros_(self.skip.weight)
159
+
160
+ self.norm_out = nn.RMSNorm(d, elementwise_affine=False)
161
+ self.head = nn.Linear(d, k)
162
+ nn.init.zeros_(self.head.weight)
163
+ nn.init.zeros_(self.head.bias)
164
+
165
+ # RoPE: prefix tokens sit at the grid centre (their order comes from text_pos); pixels at (row, col);
166
+ # merged patches at the centre of their 2x2 block, so both levels share one frame
167
+ hd = d // cfg.heads
168
+ c = (g - 1) / 2
169
+ pre = torch.full((self.n_prefix, 2), c)
170
+ rr, cc = torch.meshgrid(torch.arange(g), torch.arange(g), indexing="ij")
171
+ pix = torch.stack([rr.flatten(), cc.flatten()], -1).float()
172
+ cos, sin = rope_tables(torch.cat([pre, pix]), hd, cfg.rope_theta)
173
+ self.register_buffer("cos_pix", cos, persistent=False)
174
+ self.register_buffer("sin_pix", sin, persistent=False)
175
+ if cfg.merge:
176
+ h = g // 2
177
+ rr, cc = torch.meshgrid(torch.arange(h), torch.arange(h), indexing="ij")
178
+ pat = torch.stack([rr.flatten() * 2 + 0.5, cc.flatten() * 2 + 0.5], -1).float()
179
+ cos, sin = rope_tables(torch.cat([pre, pat]), hd, cfg.rope_theta)
180
+ self.register_buffer("cos_core", cos, persistent=False)
181
+ self.register_buffer("sin_core", sin, persistent=False)
182
+
183
+ def color_table(self):
184
+ return self.color_emb.weight + self.color_mlp(fourier(self.color_feats, 6))
185
+
186
+ def _merge(self, x):
187
+ b, g, d = x.shape[0], self.cfg.grid, self.cfg.width
188
+ x = x.view(b, g // 2, 2, g // 2, 2, d).permute(0, 1, 3, 2, 4, 5).reshape(b, (g // 2) ** 2, 4 * d)
189
+ return self.merge(x)
190
+
191
+ def _unmerge(self, x):
192
+ b, g, d = x.shape[0], self.cfg.grid, self.cfg.width
193
+ x = self.unmerge(x).view(b, g // 2, g // 2, 2, 2, d).permute(0, 1, 3, 2, 4, 5)
194
+ return x.reshape(b, g * g, d)
195
+
196
+ def forward(self, tokens, text, ratio, prev=None):
197
+ """tokens (B, G*G) long with [MASK]; text (B, L) long (all PAD = unconditional); ratio (B,) masked fraction;
198
+ prev (B, G*G, K) previous predicted distribution or None. Returns logits (B, G*G, K)."""
199
+ cfg = self.cfg
200
+ b = tokens.shape[0]
201
+ x = F.embedding(tokens, self.color_table())
202
+ if prev is not None:
203
+ x = x + self.sc_proj(prev.to(x.dtype)) * (tokens == self.mask_id)[..., None].to(x.dtype)
204
+ t = self.text_emb(text) + self.text_pos
205
+ nonpad = (text != 0)[..., None].to(t.dtype)
206
+ cnt = nonpad.sum(1)
207
+ pooled = torch.where(cnt > 0, (t * nonpad).sum(1) / cnt.clamp_min(1), self.null_pooled.to(t.dtype))
208
+ c = self.cond(torch.cat([pooled.float(), fourier(ratio[:, None], 8)], -1))
209
+ mod = self.mod(F.silu(c)).view(b, 6, cfg.width)
210
+ p = self.n_prefix
211
+ x = torch.cat([self.registers.expand(b, -1, -1).to(x.dtype), t.to(x.dtype), x], 1)
212
+
213
+ for blk in self.blocks_in:
214
+ x = blk(x, mod, self.cos_pix, self.sin_pix, p, cfg.grid)
215
+ if cfg.merge:
216
+ pre = x[:, p:]
217
+ x = torch.cat([x[:, :p], self._merge(pre)], 1)
218
+ for blk in self.blocks_core:
219
+ x = blk(x, mod, self.cos_core, self.sin_core, p, cfg.grid // 2)
220
+ x = torch.cat([x[:, :p], self._unmerge(x[:, p:]) + self.skip(pre)], 1)
221
+ else:
222
+ for blk in self.blocks_core:
223
+ x = blk(x, mod, self.cos_pix, self.sin_pix, p, cfg.grid)
224
+ for blk in self.blocks_out:
225
+ x = blk(x, mod, self.cos_pix, self.sin_pix, p, cfg.grid)
226
+
227
+ sh, sc = self.final_mod(F.silu(c)).chunk(2, -1)
228
+ return self.head(modulate(self.norm_out(x[:, p:]), sh, sc))
229
+
230
+
231
+ def count_params(model):
232
+ return sum(p.numel() for p in model.parameters())
smalt/pipeline.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load smalt from a folder or the Hub and turn prompts into 16x16 RGBA sprites (MIT).
2
+
3
+ from smalt import SmaltPipeline
4
+ pipe = SmaltPipeline.from_pretrained("PixilabAI/smalt-small") # or a local folder
5
+ sprites = pipe("red health potion", n=4, seed=0) # list of 16x16 RGBA PIL images
6
+ sprites[0].resize((128, 128), 0).save("potion.png") # 0 = nearest neighbour
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ from .model import ModelCfg, Smalt
17
+ from .sampler import generate, sample_steps
18
+
19
+ DEFAULTS = {"steps": 16, "guidance": 3.0, "temperature": 0.4}
20
+
21
+
22
+ class SmaltPipeline:
23
+ def __init__(self, folder, device=None):
24
+ from safetensors.torch import load_file
25
+ from tokenizers import Tokenizer
26
+
27
+ folder = Path(folder)
28
+ conf = json.loads((folder / "config.json").read_text())
29
+ pal = json.loads((folder / "palette.json").read_text())
30
+ self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
31
+ self.cfg = ModelCfg(**conf["model"])
32
+ self.n_used = int(conf["n_used"])
33
+ self.palette = np.asarray(pal["rgb"], dtype=np.uint8) # (K, 3); index 0 = transparent
34
+ self.model = Smalt(self.cfg, np.asarray(pal["lab"], dtype=np.float32))
35
+ self.model.load_state_dict(load_file(str(folder / "model.safetensors")))
36
+ self.model.to(self.device).eval()
37
+ self.tokenizer = Tokenizer.from_file(str(folder / "tokenizer.json"))
38
+ self.defaults = {**DEFAULTS, **conf.get("defaults", {})}
39
+
40
+ @classmethod
41
+ def from_pretrained(cls, repo_or_folder, device=None, token=None, revision=None):
42
+ p = Path(repo_or_folder)
43
+ if not p.is_dir():
44
+ from huggingface_hub import snapshot_download
45
+ p = Path(snapshot_download(str(repo_or_folder), token=token, revision=revision,
46
+ allow_patterns=["config.json", "palette.json", "tokenizer.json",
47
+ "model.safetensors"]))
48
+ return cls(p, device)
49
+
50
+ # -- text ---------------------------------------------------------------------------------------------------
51
+ def encode(self, prompts):
52
+ """list[str] -> (B, text_len) long, truncated and right-padded with 0."""
53
+ L = self.cfg.text_len
54
+ out = np.zeros((len(prompts), L), dtype=np.int64)
55
+ for i, e in enumerate(self.tokenizer.encode_batch([p.strip() for p in prompts])):
56
+ ids = e.ids[:L]
57
+ out[i, :len(ids)] = ids
58
+ return torch.from_numpy(out).to(self.device)
59
+
60
+ # -- pixels -------------------------------------------------------------------------------------------------
61
+ def to_rgba(self, tokens):
62
+ """(B, N) palette ids -> (B, G, G, 4) uint8; ids >= K ([MASK]) come out transparent."""
63
+ t = np.asarray(tokens.cpu() if torch.is_tensor(tokens) else tokens).astype(np.int64)
64
+ g = self.cfg.grid
65
+ k = len(self.palette)
66
+ rgb = self.palette[np.clip(t, 0, k - 1)]
67
+ a = np.where((t == 0) | (t >= k), 0, 255).astype(np.uint8)[..., None]
68
+ return np.concatenate([rgb, a], -1).reshape(len(t), g, g, 4)
69
+
70
+ def to_images(self, tokens):
71
+ from PIL import Image
72
+ return [Image.fromarray(a, "RGBA") for a in self.to_rgba(tokens)]
73
+
74
+ # -- sampling -----------------------------------------------------------------------------------------------
75
+ def _kw(self, prompt, n, seed, canvas, keep, **kw):
76
+ prompts = [prompt] * n if isinstance(prompt, str) else list(prompt)
77
+ text = self.encode(prompts)
78
+ gen = torch.Generator(device=self.device)
79
+ gen.manual_seed(int(seed) if seed is not None else int(torch.randint(0, 2**31 - 1, ()).item()))
80
+ if canvas is not None:
81
+ canvas = torch.as_tensor(np.asarray(canvas), device=self.device).long().view(-1, self.cfg.grid ** 2)
82
+ keep = torch.as_tensor(np.asarray(keep), device=self.device).bool().view(-1, self.cfg.grid ** 2)
83
+ if canvas.shape[0] == 1:
84
+ canvas, keep = canvas.expand(len(prompts), -1), keep.expand(len(prompts), -1)
85
+ opts = {**self.defaults, **{k: v for k, v in kw.items() if v is not None}}
86
+ return text, dict(steps=int(opts["steps"]), guidance=float(opts["guidance"]),
87
+ temperature=float(opts["temperature"]), n_used=self.n_used, canvas=canvas, keep=keep,
88
+ generator=gen)
89
+
90
+ def _autocast(self):
91
+ return torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda")
92
+
93
+ def stream(self, prompt, n=4, seed=None, canvas=None, keep=None, **kw):
94
+ """Yields smalt.sampler.Step after every decoding step."""
95
+ text, opts = self._kw(prompt, n, seed, canvas, keep, **kw)
96
+ with self._autocast():
97
+ yield from sample_steps(self.model, text, **opts)
98
+
99
+ def tokens(self, prompt, n=4, seed=None, canvas=None, keep=None, **kw):
100
+ text, opts = self._kw(prompt, n, seed, canvas, keep, **kw)
101
+ with self._autocast():
102
+ return generate(self.model, text, **opts)
103
+
104
+ def __call__(self, prompt, n=4, seed=None, canvas=None, keep=None, **kw):
105
+ """prompt (str, repeated n times, or a list of prompts) -> list of 16x16 RGBA PIL images."""
106
+ return self.to_images(self.tokens(prompt, n, seed, canvas, keep, **kw))
smalt/sampler.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parallel decoding for smalt (MIT): a blank 16x16 canvas becomes a sprite in a few steps.
2
+
3
+ Every step runs one batched forward (conditional + unconditional) for classifier-free guidance, samples a colour for
4
+ every masked pixel, ranks the masked pixels by log-confidence plus annealed Gumbel noise and commits enough of them to
5
+ follow a cosine schedule. An uncertain pixel is committed only if it is the best-scored masked pixel in its 3x3
6
+ neighbourhood, which keeps speckles away. The guided distribution feeds the next step. Inpainting: pass a canvas and a
7
+ keep mask; kept pixels never change.
8
+
9
+ `sample_steps` yields the state after every step (used for the live unmasking view); `generate` returns the result.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from dataclasses import dataclass
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+
19
+
20
+ @dataclass
21
+ class Step:
22
+ index: int # 0-based decoding step
23
+ total: int
24
+ tokens: torch.Tensor # (B, N) long, [MASK] where still undecided
25
+ preview: torch.Tensor # (B, N) long, the model's current best guess everywhere
26
+ confidence: torch.Tensor # (B, N) float in [0, 1], probability of the committed colour (0 where undecided)
27
+
28
+
29
+ @torch.no_grad()
30
+ def sample_steps(model, text, steps=16, guidance=3.0, temperature=0.7, top_p=1.0, gumbel=1.0, conf_free=0.9,
31
+ n_used=None, canvas=None, keep=None, generator=None):
32
+ """text (B, L) long token ids. canvas (B, N) long + keep (B, N) bool for inpainting. Yields Step."""
33
+ dev = text.device
34
+ b = text.shape[0]
35
+ g = model.cfg.grid
36
+ n = g * g
37
+ k = model.cfg.n_colors
38
+ mask_id = model.mask_id
39
+ x = torch.full((b, n), mask_id, dtype=torch.long, device=dev)
40
+ if canvas is not None:
41
+ x = torch.where(keep, canvas.long(), x)
42
+ prev = torch.zeros(b, n, k, device=dev)
43
+ uncond = torch.zeros_like(text)
44
+ conf = torch.where(x != mask_id, 1.0, 0.0)
45
+ bad = None
46
+ if n_used is not None and n_used < k:
47
+ bad = torch.zeros(k, dtype=torch.bool, device=dev)
48
+ bad[n_used:] = True
49
+
50
+ def guided(xc, prevc):
51
+ ratio = (xc == mask_id).float().mean(1)
52
+ lo = model(torch.cat([xc, xc]), torch.cat([text, uncond]), torch.cat([ratio, ratio]),
53
+ torch.cat([prevc, prevc])).float()
54
+ lc, lu = lo.chunk(2)
55
+ lg = lu + guidance * (lc - lu)
56
+ if bad is not None:
57
+ lg = lg.masked_fill(bad, float("-inf"))
58
+ return lg
59
+
60
+ def draw(lg):
61
+ lt = lg / max(temperature, 1e-6)
62
+ if top_p < 1.0:
63
+ sp, si = lt.softmax(-1).sort(-1, descending=True)
64
+ drop = sp.cumsum(-1) - sp > top_p
65
+ lt = lt.masked_fill(torch.zeros_like(drop).scatter(-1, si, drop), float("-inf"))
66
+ s = torch.multinomial(lt.softmax(-1).view(-1, k), 1, generator=generator).view(b, n)
67
+ logp = lg.log_softmax(-1).gather(-1, s[..., None]).squeeze(-1)
68
+ return s, logp
69
+
70
+ for step in range(steps):
71
+ masked = x == mask_id
72
+ n_masked = masked.sum(1)
73
+ if int(n_masked.max()) == 0:
74
+ break
75
+ lg = guided(x, prev)
76
+ sampled, logp = draw(lg)
77
+ last = step == steps - 1
78
+ target = math.floor(n * math.cos(math.pi / 2 * (step + 1) / steps)) if not last else 0
79
+ n_commit = (n_masked - target).clamp(min=1)
80
+ gs = gumbel * (1 - (step + 1) / steps)
81
+ noise = -torch.log(-torch.log(torch.rand(b, n, device=dev, generator=generator).clamp(1e-9, 1 - 1e-9)))
82
+ score = (logp + gs * noise).masked_fill(~masked, float("-inf"))
83
+ if last:
84
+ eligible = masked
85
+ else:
86
+ local = F.max_pool2d(score.view(b, 1, g, g), 3, 1, 1).view(b, n)
87
+ eligible = masked & ((logp.exp() >= conf_free) | (score >= local))
88
+ se = score.masked_fill(~eligible, float("-inf"))
89
+ order = se.argsort(1, descending=True)
90
+ rank = torch.empty_like(order).scatter_(1, order, torch.arange(n, device=dev).expand(b, n))
91
+ commit = eligible & (rank < n_commit[:, None])
92
+ x = torch.where(commit, sampled, x)
93
+ conf = torch.where(commit, logp.exp(), conf)
94
+ prev = lg.softmax(-1)
95
+ preview = torch.where(x == mask_id, lg.argmax(-1), x)
96
+ yield Step(step, steps, x.clone(), preview, conf.clone())
97
+
98
+
99
+ @torch.no_grad()
100
+ def generate(model, text, **kw):
101
+ """Run every step and return the final tokens (B, N)."""
102
+ last = None
103
+ for last in sample_steps(model, text, **kw):
104
+ pass
105
+ return last.tokens if last is not None else kw["canvas"]
style.css ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* smalt studio (MIT): night smalt glaze, gold ink, sprites on dark tinted cards. Dark in every browser mode. */
2
+ :root, .dark { color-scheme: dark; }
3
+ body, gradio-app { background: #0b1029 !important; }
4
+ .gradio-container { max-width: 1440px !important; margin: 0 auto !important; padding: 0 !important; color: #ece6d6 !important;
5
+ background:
6
+ radial-gradient(1000px 500px at 85% -10%, rgba(75, 99, 216, .22), transparent 60%),
7
+ radial-gradient(700px 500px at -10% 110%, rgba(164, 76, 240, .12), transparent 60%), #0b1029 !important; }
8
+ footer { display: none !important; }
9
+ #sm-shell { gap: 0 !important; align-items: stretch !important; }
10
+
11
+ /* ---------- sidebar ---------- */
12
+ #sm-side { background: rgba(14, 21, 56, .92) !important; border-right: 1px solid #1d2560; padding: 26px 24px 28px !important;
13
+ gap: 14px !important; position: sticky; top: 0; align-self: flex-start; min-height: 100vh; }
14
+ .sm-side-head { text-align: center; }
15
+ .sm-logo { width: 292px; max-width: 100%; image-rendering: pixelated; image-rendering: crisp-edges;
16
+ filter: drop-shadow(0 4px 0 rgba(0, 0, 0, .45)); margin: 4px auto 14px; display: block; }
17
+ .sm-blurb { text-align: left; font-size: 15px; line-height: 1.55; color: #c9cdea; margin: 0 0 8px; }
18
+ .sm-blurb b { color: #ece6d6; }
19
+ .sm-by { font-size: 13px; color: #9aa3d4; margin: 0; }
20
+ .sm-by a { color: #f2c45a; text-decoration: none; }
21
+ .sm-by a:hover { text-decoration: underline; }
22
+ #sm-side .block, #sm-side .form { box-shadow: none !important; }
23
+ #sm-prompt textarea { font-size: 16px !important; line-height: 1.45 !important; padding: 14px 16px !important; border-radius: 14px !important;
24
+ border: 1px solid #2a3474 !important; background: #0b1029 !important; color: #ece6d6 !important; }
25
+ #sm-prompt textarea:focus { border-color: #f2c45a !important; box-shadow: 0 0 0 3px rgba(242, 196, 90, .18) !important; }
26
+ #sm-chips { flex-wrap: wrap !important; gap: 7px !important; }
27
+ #sm-chips .sm-chip { flex: 0 0 auto !important; min-width: 0 !important; width: auto !important; border-radius: 999px !important;
28
+ padding: 6px 13px !important; font-size: 13px !important; font-weight: 500 !important; background: #121a45 !important;
29
+ border: 1px solid #2a3474 !important; color: #c9cdea !important; box-shadow: none !important; }
30
+ #sm-chips .sm-chip:hover { border-color: #f2c45a !important; color: #f2c45a !important; background: #1a2357 !important; }
31
+ #sm-kinds .wrap, #sm-n .wrap { gap: 4px !important; }
32
+ #sm-kinds label, #sm-n label { border-radius: 10px !important; padding: 5px 11px !important; font-size: 13px !important;
33
+ background: #0e1538 !important; border: 1px solid #1d2560 !important; color: #c9cdea !important; }
34
+ #sm-kinds label.selected, #sm-n label.selected, #sm-kinds label:has(input:checked), #sm-n label:has(input:checked) {
35
+ background: #f2c45a !important; border-color: #f2c45a !important; color: #0b1029 !important; font-weight: 700; }
36
+ #sm-kinds input[type=radio], #sm-n input[type=radio] { display: none !important; }
37
+ #sm-go { font-family: "Jersey 10", "Instrument Sans", sans-serif !important; font-size: 27px !important; letter-spacing: .5px;
38
+ border-radius: 14px !important; min-height: 52px; color: #0b1029 !important;
39
+ background: linear-gradient(180deg, #ffe08f, #f2c45a 50%, #c9952f) !important; box-shadow: 0 4px 0 #6e4d12 !important;
40
+ transition: transform .06s; }
41
+ #sm-go:active { transform: translateY(3px); box-shadow: 0 1px 0 #6e4d12 !important; }
42
+ #sm-dice { border-radius: 14px !important; min-height: 52px; font-size: 14px !important; }
43
+ #sm-settings { border-radius: 14px !important; }
44
+
45
+ /* ---------- tabs ---------- */
46
+ #sm-mainc { padding: 18px 30px 40px !important; }
47
+ #sm-tabs button[role="tab"], #sm-tabs .tab-container button, #sm-tabs .tab-wrapper button {
48
+ color: #9aa3d4 !important; background: transparent !important; font-size: 16px !important; font-weight: 600 !important; }
49
+ #sm-tabs button[role="tab"]:hover, #sm-tabs .tab-container button:hover { color: #ece6d6 !important; }
50
+ #sm-tabs button[role="tab"][aria-selected="true"], #sm-tabs .tab-container button.selected { color: #f2c45a !important; }
51
+ #sm-tabs button[role="tab"][aria-selected="true"]::after, #sm-tabs .tab-container button.selected::after { background: #f2c45a !important; }
52
+ #sm-tabs .tab-container, #sm-tabs .tab-wrapper { border-color: #1d2560 !important; background: transparent !important; }
53
+ #sm-tabs .tabitem, #sm-tabs [role="tabpanel"] { background: transparent !important; border: 0 !important; }
54
+
55
+ /* ---------- explore + palette ---------- */
56
+ .ex-head h2 { font-size: 30px; margin: 10px 0 4px; letter-spacing: -.3px; color: #ece6d6; font-weight: 700; }
57
+ .ex-head p { margin: 0 0 22px; color: #9aa3d4; font-size: 15px; max-width: 760px; }
58
+ .ex-head b { color: #f2c45a; }
59
+ .ex-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(176px, 1fr)); gap: 18px; }
60
+ .ex-card { position: relative; margin: 0; aspect-ratio: 1; border-radius: 18px; overflow: hidden; cursor: default;
61
+ box-shadow: 0 10px 26px -14px rgba(0, 0, 0, .7); transition: transform .18s ease, box-shadow .18s ease;
62
+ animation: ex-in .5s ease both; }
63
+ @keyframes ex-in { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
64
+ .ex-card:hover { transform: translateY(-4px); box-shadow: 0 0 0 2px rgba(242, 196, 90, .55), 0 18px 34px -16px rgba(0,0,0,.8); }
65
+ .ex-card img, .ex-anim { position: absolute; inset: 0; width: 100%; height: 100%; image-rendering: pixelated; image-rendering: crisp-edges; }
66
+ .ex-anim { background-repeat: no-repeat; background-size: calc(var(--frames) * 100%) 100%; background-position: 0 0; opacity: 0; }
67
+ .ex-card:hover .ex-anim { opacity: 1; animation: ex-play 1.3s steps(16) forwards; }
68
+ .ex-card:hover img { opacity: 0; }
69
+ @keyframes ex-play { from { background-position: 0 0; } to { background-position: 100% 0; } }
70
+ .ex-card figcaption { position: absolute; left: 10px; right: 10px; bottom: 9px; font-size: 12px; font-weight: 600; color: #ece6d6;
71
+ background: rgba(11, 16, 41, .82); backdrop-filter: blur(4px); border-radius: 8px; padding: 4px 8px;
72
+ opacity: 0; transform: translateY(4px); transition: opacity .15s, transform .15s; }
73
+ .ex-card:hover figcaption { opacity: 1; transform: none; }
74
+ .pal-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(26px, 1fr)); gap: 3px; }
75
+ .pal-grid i { aspect-ratio: 1; border-radius: 5px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.08); }
76
+ .pal-grid i:hover { transform: scale(1.6); box-shadow: 0 4px 10px rgba(0,0,0,.6); position: relative; z-index: 2; }
77
+
78
+ /* ---------- studio ---------- */
79
+ #sm-status { min-height: 28px; color: #9aa3d4; font-size: 14px; }
80
+ #sm-status strong { color: #ece6d6; }
81
+ #sm-status code { color: #f2c45a !important; background: transparent !important; letter-spacing: -1px; }
82
+ #sm-gallery, #sm-gallery > div { background: transparent !important; border: 0 !important; box-shadow: none !important; }
83
+ #sm-gallery .grid-wrap { padding: 0 !important; }
84
+ #sm-gallery .grid-container { gap: 16px !important; }
85
+ #sm-gallery .grid-wrap, #sm-gallery .grid-container { max-height: none !important; overflow: visible !important; }
86
+ #sm-gallery { height: auto !important; }
87
+ #sm-gallery .thumbnail-item { border: 0 !important; background: transparent !important; border-radius: 18px !important;
88
+ box-shadow: 0 10px 26px -14px rgba(0,0,0,.7) !important; transition: transform .15s; }
89
+ #sm-gallery .thumbnail-item:hover { transform: translateY(-3px); }
90
+ #sm-gallery .thumbnail-item.selected { box-shadow: 0 0 0 3px #f2c45a, 0 10px 26px -14px rgba(0,0,0,.8) !important; }
91
+ #sm-gallery img { image-rendering: pixelated !important; image-rendering: crisp-edges !important; border-radius: 18px; }
92
+ #sm-actions { align-items: center !important; gap: 10px !important; margin-top: 10px; }
93
+ #sm-actions .sm-act { min-height: 46px; border-radius: 12px !important; font-size: 15px !important; font-weight: 600 !important;
94
+ background: #121a45 !important; border: 1px solid #2a3474 !important; color: #ece6d6 !important; }
95
+ #sm-actions .sm-act:hover:not(:disabled) { border-color: #f2c45a !important; color: #f2c45a !important; background: #1a2357 !important; }
96
+ #sm-actions .sm-dl:not(:disabled) { background: #f2c45a !important; color: #0b1029 !important; border-color: #f2c45a !important; }
97
+ #sm-actions .sm-act:disabled { opacity: .45 !important; }
98
+
99
+ /* ---------- how it works ---------- */
100
+ #sm-how { max-width: 820px; font-size: 15px; color: #c9cdea; }
101
+ #sm-how h2, #sm-how strong { color: #ece6d6; }
102
+ #sm-how code { color: #f2c45a !important; background: #1a2357 !important; border: 0 !important; padding: 1px 6px !important;
103
+ border-radius: 6px !important; font-size: 13px !important; }
104
+
105
+ @media (max-width: 900px) {
106
+ #sm-side { position: static; min-height: 0; border-right: 0; border-bottom: 1px solid #1d2560; }
107
+ #sm-mainc { padding: 14px 14px 30px !important; }
108
+ .ex-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px; }
109
+ }
110
+ @media (prefers-reduced-motion: reduce) { .ex-card, .ex-card:hover .ex-anim { animation: none !important; } }