viknesh100 commited on
Commit
692b006
·
verified ·
1 Parent(s): 3c31f6b

Add Sprite Flow 32x32 text-to-sprite model

Browse files
Files changed (7) hide show
  1. README.md +111 -0
  2. assets/samples.png +0 -0
  3. config.json +17 -0
  4. inference.py +28 -0
  5. model.safetensors +3 -0
  6. pipeline.py +188 -0
  7. requirements.txt +5 -0
README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ library_name: pytorch
4
+ pipeline_tag: text-to-image
5
+ language:
6
+ - en
7
+ tags:
8
+ - text-to-image
9
+ - pixel-art
10
+ - sprites
11
+ - flow-matching
12
+ - classifier-free-guidance
13
+ - safetensors
14
+ datasets:
15
+ - tkarr/sprite_caption_dataset
16
+ ---
17
+
18
+ # SpriteX32
19
+
20
+ A small text-to-image model that generates **32×32 pixel-art sprites** from English prompts.
21
+ It is a conditional U-Net trained with flow matching, conditioned on CLIP text embeddings,
22
+ and sampled with classifier-free guidance. It has 11.4M parameters and runs
23
+ comfortably on a CPU or a small GPU.
24
+
25
+ ![Samples](assets/samples.png)
26
+
27
+ *Seed 0, 50 steps, guidance 3.0, upscaled 4× with nearest-neighbour. Prompts, one per row, top to bottom:*
28
+
29
+ 1. a red sword
30
+ 2. a green slime monster
31
+ 3. a blue wizard
32
+ 4. Once it takes aim at its foe, it makes a headlong charge. It is famous for its violent nature.
33
+
34
+ ## Quick start
35
+
36
+ ```bash
37
+ pip install torch transformers safetensors huggingface_hub pillow
38
+ ```
39
+
40
+ ```python
41
+ import sys
42
+ from huggingface_hub import snapshot_download
43
+
44
+ path = snapshot_download("viknesh100/SpriteX32")
45
+ sys.path.insert(0, path)
46
+ from pipeline import SpriteFlowPipeline, make_grid
47
+
48
+ pipe = SpriteFlowPipeline.from_pretrained(path) # uses GPU if available
49
+ images = pipe("a green slime monster", num_images=8, seed=0, output_size=128)
50
+ make_grid(images, cols=4).save("sprites.png")
51
+ ```
52
+
53
+ Command line (from a clone of this repo):
54
+
55
+ ```bash
56
+ python inference.py --prompt "a blue wizard" --num_images 8 --seed 0 --out wizard.png
57
+ ```
58
+
59
+ ### Parameters
60
+
61
+ | Argument | Default | Notes |
62
+ |---|---|---|
63
+ | `num_images` | 4 | Images per prompt. Multiple prompts can be passed as a list. |
64
+ | `num_steps` | 50 | Euler steps. 20–100 is a reasonable range. |
65
+ | `guidance_scale` | 3.0 | Higher follows the prompt more strongly but reduces variety. Try 1.5–6. |
66
+ | `seed` | None | Set for reproducible output. |
67
+ | `output_size` | None | Native size is 32. Set e.g. 128 for a nearest-neighbour upscale. |
68
+
69
+ **Prompting tip:** the model only saw captions in the style of its training data, so prompts
70
+ that resemble short, descriptive sprite captions work best.
71
+
72
+ ## Model details
73
+
74
+ | | |
75
+ |---|---|
76
+ | Output | 32×32 RGB image (transparency is not generated) |
77
+ | Architecture | U-Net with residual blocks, self-attention at the lowest resolution, time and text conditioning |
78
+ | Text encoder | `openai/clip-vit-base-patch32` (frozen, pooled embedding, loaded separately at inference) |
79
+ | Objective | Flow matching: linear path from noise to image, velocity prediction |
80
+ | Sampler | Euler, with classifier-free guidance |
81
+ | Weights | `model.safetensors` (EMA weights) |
82
+
83
+ ## Training
84
+
85
+ - **Data:** [`tkarr/sprite_caption_dataset`](https://huggingface.co/datasets/tkarr/sprite_caption_dataset), 12,830 image–caption pairs.
86
+ - **Preprocessing:** images converted to RGBA, composited on a white background, resized to 32×32, scaled to [-1, 1].
87
+ - **Optimisation:** AdamW, learning rate 2e-4 with cosine decay, batch size 128, 15,000 steps, gradient clipping at 1.0.
88
+ - **Guidance:** the text condition was dropped for 15% of samples during training.
89
+ - **EMA:** decay 0.999, and the EMA weights are the ones released.
90
+ - **Hardware:** a single Google Colab GPU.
91
+
92
+ ## Limitations
93
+
94
+ - **Resolution:** fixed at 32×32. The model cannot produce larger images natively.
95
+ - **Prompt understanding:** the text is reduced to a single pooled CLIP vector, so colors and broad object types work much better than detailed or compositional prompts.
96
+ - **Training data:** a small dataset, so the model covers a limited range of subjects and styles. Caption quality was not audited.
97
+ - **Background:** outputs are RGB on a light background, with no alpha channel.
98
+ - **Evaluation:** only qualitative. No quantitative metrics (such as FID) were computed.
99
+
100
+ ## Intended use
101
+
102
+ Hobby, research, and educational use: prototyping sprite ideas, studying small text-to-image
103
+ models, or as a base for further fine-tuning. Review the training-data and license notes
104
+ below before any commercial use.
105
+
106
+ ## License and attribution
107
+
108
+ The weights in this repository are released under: **other**.
109
+ Training data came from `tkarr/sprite_caption_dataset`; check that dataset's page for the
110
+ terms that apply to its contents. The CLIP text encoder is a separate model from OpenAI,
111
+ released under the MIT license and downloaded at inference time.
assets/samples.png ADDED
config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "sprite-flow-unet",
3
+ "image_size": 32,
4
+ "base_channels": 64,
5
+ "channel_mults": [
6
+ 1,
7
+ 2,
8
+ 4
9
+ ],
10
+ "text_dim": 512,
11
+ "embed_dim": 256,
12
+ "text_scale": 20.0,
13
+ "text_encoder": "openai/clip-vit-base-patch32",
14
+ "max_text_tokens": 77,
15
+ "default_steps": 50,
16
+ "default_guidance_scale": 3.0
17
+ }
inference.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ from pipeline import SpriteFlowPipeline, make_grid
5
+
6
+
7
+ def main():
8
+ p = argparse.ArgumentParser(description="Generate pixel-art sprites from text.")
9
+ p.add_argument("--prompt", required=True, help="Text prompt")
10
+ p.add_argument("--model", default=str(Path(__file__).parent),
11
+ help="Local folder or Hugging Face repo id")
12
+ p.add_argument("--num_images", type=int, default=8)
13
+ p.add_argument("--steps", type=int, default=50)
14
+ p.add_argument("--guidance", type=float, default=3.0)
15
+ p.add_argument("--seed", type=int, default=None)
16
+ p.add_argument("--size", type=int, default=128, help="Output size in pixels (nearest-neighbour upscale)")
17
+ p.add_argument("--out", default="sprites.png")
18
+ args = p.parse_args()
19
+
20
+ pipe = SpriteFlowPipeline.from_pretrained(args.model)
21
+ images = pipe(args.prompt, num_images=args.num_images, num_steps=args.steps,
22
+ guidance_scale=args.guidance, seed=args.seed, output_size=args.size)
23
+ make_grid(images, cols=min(4, len(images))).save(args.out)
24
+ print("saved", args.out)
25
+
26
+
27
+ if __name__ == "__main__":
28
+ main()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0608ed920e83e5c5a7f9896f3e4c99717b1dc5004443099749d1ef8765b26d3e
3
+ size 45639420
pipeline.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sprite Flow: text-to-sprite flow-matching model (32x32)."""
2
+ import json
3
+ import math
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from huggingface_hub import snapshot_download
10
+ from PIL import Image
11
+ from safetensors.torch import load_file
12
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
13
+
14
+
15
+ def sinusoidal(t, dim):
16
+ half = dim // 2
17
+ freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half)
18
+ args = t[:, None] * 1000 * freqs[None]
19
+ return torch.cat([args.sin(), args.cos()], dim=1)
20
+
21
+
22
+ class ResBlock(nn.Module):
23
+ def __init__(self, cin, cout, emb):
24
+ super().__init__()
25
+ self.n1 = nn.GroupNorm(8, cin)
26
+ self.c1 = nn.Conv2d(cin, cout, 3, padding=1)
27
+ self.e = nn.Linear(emb, cout)
28
+ self.n2 = nn.GroupNorm(8, cout)
29
+ self.c2 = nn.Conv2d(cout, cout, 3, padding=1)
30
+ self.skip = nn.Conv2d(cin, cout, 1) if cin != cout else nn.Identity()
31
+
32
+ def forward(self, x, cond):
33
+ h = self.c1(F.silu(self.n1(x)))
34
+ h = h + self.e(cond)[:, :, None, None]
35
+ h = self.c2(F.silu(self.n2(h)))
36
+ return h + self.skip(x)
37
+
38
+
39
+ class Attn(nn.Module):
40
+ def __init__(self, c):
41
+ super().__init__()
42
+ self.norm = nn.GroupNorm(8, c)
43
+ self.qkv = nn.Conv2d(c, 3 * c, 1)
44
+ self.proj = nn.Conv2d(c, c, 1)
45
+
46
+ def forward(self, x):
47
+ B, C, H, W = x.shape
48
+ q, k, v = self.qkv(self.norm(x)).reshape(B, 3, C, H * W).unbind(1)
49
+ q, k, v = [t.transpose(1, 2).unsqueeze(1) for t in (q, k, v)]
50
+ out = F.scaled_dot_product_attention(q, k, v).squeeze(1)
51
+ out = out.transpose(1, 2).reshape(B, C, H, W)
52
+ return x + self.proj(out)
53
+
54
+
55
+ class UNet(nn.Module):
56
+ def __init__(self, ch=64, mults=(1, 2, 4), text_dim=512, emb=256, text_scale=20.0):
57
+ super().__init__()
58
+ chs = [ch * m for m in mults]
59
+ L = len(chs)
60
+ self.ch, self.L, self.text_scale = ch, L, text_scale
61
+ self.t_mlp = nn.Sequential(nn.Linear(ch, emb), nn.SiLU(), nn.Linear(emb, emb))
62
+ self.txt = nn.Sequential(nn.Linear(text_dim, emb), nn.SiLU(), nn.Linear(emb, emb))
63
+ self.inc = nn.Conv2d(3, ch, 3, padding=1)
64
+
65
+ self.down, self.attn_d, self.samp_d = nn.ModuleList(), nn.ModuleList(), nn.ModuleList()
66
+ cin = ch
67
+ for i, c in enumerate(chs):
68
+ self.down.append(nn.ModuleList([ResBlock(cin, c, emb), ResBlock(c, c, emb)]))
69
+ self.attn_d.append(Attn(c) if i == L - 1 else nn.Identity())
70
+ if i < L - 1:
71
+ self.samp_d.append(nn.Conv2d(c, c, 3, stride=2, padding=1))
72
+ cin = c
73
+
74
+ self.mid1 = ResBlock(chs[-1], chs[-1], emb)
75
+ self.mid_attn = Attn(chs[-1])
76
+ self.mid2 = ResBlock(chs[-1], chs[-1], emb)
77
+
78
+ self.up, self.attn_u, self.samp_u = nn.ModuleList(), nn.ModuleList(), nn.ModuleList()
79
+ for i, c in enumerate(chs):
80
+ self.up.append(nn.ModuleList([ResBlock(2 * c, c, emb), ResBlock(c, c, emb)]))
81
+ self.attn_u.append(Attn(c) if i == L - 1 else nn.Identity())
82
+ if i > 0:
83
+ self.samp_u.append(nn.Sequential(nn.Upsample(scale_factor=2, mode="nearest"),
84
+ nn.Conv2d(c, chs[i - 1], 3, padding=1)))
85
+ self.out = nn.Sequential(nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, 3, 3, padding=1))
86
+
87
+ def forward(self, x, t, text):
88
+ cond = self.t_mlp(sinusoidal(t, self.ch)) + self.txt(text * self.text_scale)
89
+ h = self.inc(x)
90
+ skips = []
91
+ for i in range(self.L):
92
+ h = self.down[i][0](h, cond)
93
+ h = self.down[i][1](h, cond)
94
+ h = self.attn_d[i](h)
95
+ skips.append(h)
96
+ if i < self.L - 1:
97
+ h = self.samp_d[i](h)
98
+ h = self.mid2(self.mid_attn(self.mid1(h, cond)), cond)
99
+ for i in reversed(range(self.L)):
100
+ h = torch.cat([h, skips[i]], dim=1)
101
+ h = self.up[i][0](h, cond)
102
+ h = self.up[i][1](h, cond)
103
+ h = self.attn_u[i](h)
104
+ if i > 0:
105
+ h = self.samp_u[i - 1](h)
106
+ return self.out(h)
107
+
108
+
109
+ def make_grid(images, cols, pad=4, bg=(255, 255, 255)):
110
+ """Arrange a flat list of PIL images into a grid with `cols` columns."""
111
+ w, h = images[0].size
112
+ rows = math.ceil(len(images) / cols)
113
+ grid = Image.new("RGB", (cols * w + (cols + 1) * pad, rows * h + (rows + 1) * pad), bg)
114
+ for i, im in enumerate(images):
115
+ r, c = divmod(i, cols)
116
+ grid.paste(im, (pad + c * (w + pad), pad + r * (h + pad)))
117
+ return grid
118
+
119
+
120
+ class SpriteFlowPipeline:
121
+ def __init__(self, unet, tokenizer, text_encoder, config, device):
122
+ self.device = device
123
+ self.config = config
124
+ self.unet = unet.to(device).eval()
125
+ self.tokenizer = tokenizer
126
+ self.text_encoder = text_encoder.to(device).eval()
127
+
128
+ @classmethod
129
+ def from_pretrained(cls, path_or_repo, device=None, revision=None, token=None):
130
+ device = device or ("cuda" if torch.cuda.is_available() else "cpu")
131
+ path = Path(str(path_or_repo))
132
+ if not path.is_dir():
133
+ path = Path(snapshot_download(str(path_or_repo), revision=revision, token=token))
134
+ config = json.loads((path / "config.json").read_text())
135
+ unet = UNet(
136
+ ch=config["base_channels"],
137
+ mults=tuple(config["channel_mults"]),
138
+ text_dim=config["text_dim"],
139
+ emb=config["embed_dim"],
140
+ text_scale=config["text_scale"],
141
+ )
142
+ unet.load_state_dict(load_file(str(path / "model.safetensors")))
143
+ tokenizer = CLIPTokenizer.from_pretrained(config["text_encoder"])
144
+ text_encoder = CLIPTextModelWithProjection.from_pretrained(config["text_encoder"])
145
+ return cls(unet, tokenizer, text_encoder, config, device)
146
+
147
+ @torch.no_grad()
148
+ def encode_prompts(self, prompts):
149
+ inputs = self.tokenizer(
150
+ prompts, padding=True, truncation=True,
151
+ max_length=self.config["max_text_tokens"], return_tensors="pt",
152
+ ).to(self.device)
153
+ emb = self.text_encoder(**inputs).text_embeds
154
+ return F.normalize(emb, dim=-1)
155
+
156
+ @torch.no_grad()
157
+ def __call__(self, prompt, num_images=4, num_steps=None, guidance_scale=None,
158
+ seed=None, output_size=None):
159
+ """Generate sprites. Returns a flat list of PIL images, grouped by prompt
160
+ (num_images consecutive images per prompt)."""
161
+ prompts = [prompt] if isinstance(prompt, str) else list(prompt)
162
+ num_steps = num_steps or self.config["default_steps"]
163
+ if guidance_scale is None:
164
+ guidance_scale = self.config["default_guidance_scale"]
165
+ size = self.config["image_size"]
166
+
167
+ cond = self.encode_prompts(prompts).repeat_interleave(num_images, dim=0)
168
+ uncond = torch.zeros_like(cond)
169
+ gen = None
170
+ if seed is not None:
171
+ gen = torch.Generator(device=self.device).manual_seed(seed)
172
+
173
+ b = cond.size(0)
174
+ x = torch.randn(b, 3, size, size, device=self.device, generator=gen)
175
+ for k in range(num_steps):
176
+ t = torch.full((b,), k / num_steps, device=self.device)
177
+ v = self.unet(torch.cat([x, x]), torch.cat([t, t]), torch.cat([cond, uncond]))
178
+ v_c, v_u = v.chunk(2)
179
+ x = x + (v_u + guidance_scale * (v_c - v_u)) / num_steps
180
+ return self._to_pil(x, output_size)
181
+
182
+ @staticmethod
183
+ def _to_pil(x, output_size=None):
184
+ arr = ((x.clamp(-1, 1) + 1) * 127.5).round().byte().permute(0, 2, 3, 1).cpu().numpy()
185
+ images = [Image.fromarray(a) for a in arr]
186
+ if output_size:
187
+ images = [im.resize((output_size, output_size), Image.NEAREST) for im in images]
188
+ return images
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch>=2.0
2
+ transformers>=4.30
3
+ safetensors
4
+ huggingface_hub
5
+ pillow