Dev.to AI 🤖 Ai 👁 0 📖 12 min read

Drawing pixel-art sprites with a tiny transformer on the M5Stack CoreS3

Sprite Maker is a small model on an ESP32-S3 that draws new 16 x 16 pixel-art game characters on the M5Stack CoreS3. You pick a knight, a slime or a ghost, and a sprite probably nobody has drawn before appears on the scr

Drawing pixel-art sprites with a tiny transformer on the M5Stack CoreS3

Sprite Maker is a small model on an ESP32-S3 that draws new 16 x 16 pixel-art game characters on the M5Stack CoreS3. You pick a knight, a slime or a ghost, and a sprite probably nobody has drawn before appears on the screen one pixel at a time, in about 18 seconds.

It was one of the five apps in my first post, which used Recipe Maker as the worked example and gave Sprite Maker a paragraph. This post covers what's different about drawing pictures with a language model: turning images into tokens, a two-stage training run, cleaning up wrong labels with a classifier, and checking that it isn't copying its training data.

The code is MIT and the model is CC BY-NC 4.0 (more on why below):

Sprites drawn by the model

Rows: knight, wizard, witch, robot, slime, ghost, dragon, skeleton, zombie, goblin, pirate, ninja, alien, cat, frog.

Pick a character Drawn on the device
Picker A sprite on the device

A sprite is a sentence

The model is the same kind as Recipe Maker's: a transformer that writes one token at a time, each chosen from what it predicts should come next. It uses the per-layer embedding layout and inference code from slvDev/esp32-ai, which the first post explains.

The difference is what a token is. Here a sprite is a sequence of 258 tokens:

<character> p0 p1 ... p255 <end>

The first token says which character to draw (knight, ghost, and so on). Then come the 256 pixels, row by row, left to right. Each pixel is one of 33 tokens: 0 for transparent, or 1 to 32 for a colour from a fixed palette. Then an end token.

So the whole vocabulary is 33 pixel tokens, 16 character tokens and one end token, 50 in all, padded to 64. Compare that with Recipe Maker's 8,192 word pieces. With so few tokens the lookup tables are tiny, and almost all of the 716,832 parameters (698,400) are in the transformer core: 5 layers, 128 wide, 4 attention heads. At 4 bits a weight the model file is 0.38 MB.

On the device, each pixel is drawn the moment it's written, so you watch the sprite fill in row by row.

The palette

The sprites come from the Pixel Art Atlas, 1.4 million 16 x 16 sprites released as CC0. The atlas uses 4,096 colours. One token per colour would be fine on a computer, but a fixed small palette keeps the vocabulary small and makes every pixel an easy choice.

training/palette.py fits a palette with weighted k-means: it groups the atlas's 4,096 colours into K clusters, weighting each colour by how many pixels use it, and uses each cluster's average as a palette colour. Then every atlas colour maps to its nearest palette colour:

def remap(atlas_palette, small):
    """Atlas colour index -> small palette index (1..K); 0 stays transparent."""
    d = ((atlas_palette[:, None, :].astype(int) - small[None].astype(int)) ** 2).sum(-1)
    m = d.argmin(1) + 1
    m[0] = 0
    return m

The script renders the same sprites with 64, 32 and 16 colours side by side, and I picked 32. The fitted palette is saved in the repo (training/palette32.npy), so retraining gives the same colours.

Which sprites are characters

The atlas labels each sprite with a subject, written by an AI captioning model: "fire dragon", "dragon shield", "green goblin". A sprite counts as a character if the last word of its subject is one of 16 names:

CHARACTERS = """knight wizard witch robot slime ghost dragon skeleton zombie goblin pirate ninja
alien cat frog monster""".split()

def head_class(subject):
    """'fire dragon' -> 'dragon'; 'dragon shield' -> None."""
    last = subject.split()[-1]
    last = re.sub(r"s$", "", last)
    return last if last in CHARACTERS else None

That gives 36,436 character sprites. Each is also added mirrored left to right, which doubles them for free: a knight facing the other way is still a knight.

Training in two stages

36,000 sprites isn't much. 1.4 million is, but most of them aren't characters: they're swords, potions, trees and tiles. So it's trained in two stages.

Stage 1: everything. All 1.4 million sprites, with an "other" start token for the ones that aren't characters, and the character sprites repeated 8 times so they aren't drowned out. This is where it learns what makes pixel art look right: outlines, shading and solid shapes. 12,000 steps of 32 sprites each, about 35 minutes on an M3 MacBook.

Stage 2: characters only. A short fine-tune, 1,500 more steps starting from stage 1, on the character sprites alone, so that each character token means its character.

Stage 2 is short, but it matters. Without it a "skeleton" came out as a skeleton about 3 times in 8. This is what stage 1 alone draws:

Sprites before the fine-tune

The training settings, from training/train.sh:

SHAPE="--arm ple --vocab 64 --d-model 128 --ple-dim 32 --n-layers 5 --target-core 700000 \
       --batch-size 32 --seq-len 257"
# 49 is the end-of-sprite token: training windows start at each sprite.
ESP32AI_DATA=data/sprites-all ESP32AI_ALIGN_EOT=49 PYTHONPATH=src \
    .venv/bin/python research/tinystories/train.py $SHAPE --steps 12000 --eval-every 1000 --tag sprites-all

Both stages use AdamW (gradient descent that adapts the step size for each weight, with weight decay of 0.1 pulling weights towards zero). The learning rate warms up over the first steps (200 in stage 1, 50 in stage 2) and then falls along a cosine curve. Stage 2 starts from a lower rate, 3e-4 against 1e-3, so it adjusts what stage 1 learnt rather than overwriting it.

Changes to the trainer

slvDev's trainer was written for text. Text is one long stream, so it cuts training examples at random points. For sprites that's wrong: an example that starts halfway down a knight has lost the token that says it's a knight. ESP32AI_ALIGN_EOT=49 makes every training window start right after an end token, at the start of a sprite.

That and two other changes (reading data from another folder, and starting from saved weights for stage 2) are in my fork of esp32-ai, at commit 75bc998. The same changes are in the repo as training/esp32-ai.patch, if you'd rather apply them to slvDev's commit 52ebcbb yourself.

Fixing wrong labels

The atlas's labels come from AI-written captions, and some are wrong, such as a "goblin" that's a knight in green. The fine-tune learns those mistakes along with everything else.

There are too many sprites to check by hand, so training/filter_sprites.py uses a small classifier to find them. The classifier is a convolutional network (one that looks at small patches of the image, the usual kind for pictures) that takes a sprite and says which of the 16 characters it is:

class Classifier(nn.Module):
    def __init__(self, n_colours, n_classes):
        super().__init__()
        self.emb = nn.Embedding(n_colours, 8)
        self.net = nn.Sequential(
            nn.Conv2d(8, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
            nn.Flatten(), nn.Linear(64 * 16, 128), nn.ReLU(), nn.Linear(128, n_classes))

Each pixel's palette index becomes 8 learnt numbers (nn.Embedding), then two rounds of 3 x 3 convolutions and halving the size, then two plain layers down to 16 scores.

Scoring every sprite fairly

A classifier asked about a sprite it trained on will just remember the label it was given, wrong or not. So each sprite is scored out of fold: the sprites are split into five groups, and each group is scored by a classifier trained on the other four. No sprite is ever scored by a classifier that has seen it.

A sprite and its mirror image are kept in the same group. Otherwise the classifier would have seen the mirror, which is nearly the same sprite:

mirror = px.reshape(-1, 16, 16)[:, :, ::-1].reshape(-1, 256)
key = [min(a.tobytes(), b.tobytes()) for a, b in zip(px, mirror)]
_, group = np.unique(np.array(key, dtype=object), return_inverse=True)
fold = np.random.default_rng(0).integers(0, FOLDS, group.max() + 1)[group]

Then a sprite stays in the fine-tune only if the classifier gives its own label a probability of at least 0.5. About a fifth of the character sprites are left out.

Balancing

The characters aren't equally common. There are far more knights and slimes than ghosts and skeletons, so a short fine-tune barely sees the rare ones. After filtering, each character gets a share in proportion to the square root of how many it has, with rare ones repeated:

cnt = np.array([(label[rows] == ci).sum() for ci in range(len(names))])
target = np.round(len(rows) * np.sqrt(cnt) / np.sqrt(cnt).sum()).astype(int)

The square root is a compromise. Equal shares would repeat a few hundred ghosts over and over. Shares in proportion to the count leave them rare. The square root sits between the two.

Filtering and balancing together lifted the average "looks like its character" score (next section) from 54% to 67%.

Leaving out "monster"

The model also knows "monster", but it's too vague. It was what the other characters were most often mistaken for, and it scored only 40% itself. So the picker on the device leaves it out (HIDDEN in training/make_sprites_h.py) and shows 15 characters.

Checking it

training/eval_sprites.py checks two things, on 125 sprites of each character drawn by host/draw.c. That's a C program that loads the same model file and runs the same inference code as the device, with the same 8-bit arithmetic, so what it measures is what the device draws.

Is it copying?

A model that draws a sprite it was trained on isn't drawing a new one. So every generated sprite is compared with every training sprite of the same character, counting the pixels that differ. A near copy is 13 pixels or fewer different (5% of 256).

There are none. Not one of the 1,875 is an exact or near copy, and the closest training sprite typically differs by about 115 of 256 pixels.

Does each character look like itself?

A second classifier, the same kind as the filter but trained on all the real character sprites, unfiltered, says which character each generated sprite looks like. On held-out real sprites it's right 87% of the time, so that's about the most these scores can be.

The number before the arrow is the model fine-tuned on the unfiltered sprites, and after it the filtered and balanced ones:

Character Looks like itself Most often mistaken for
skeleton 65% → 92% knight
slime 96% → 92% cat
cat 82% → 88% slime
ghost 57% → 81% slime
witch 50% → 73% wizard
ninja 51% → 66% pirate
pirate 50% → 66% knight
wizard 35% → 64% monster
knight 68% → 62% monster
dragon 62% → 61% knight
frog 54% → 60% slime
robot 58% → 56% knight
alien 36% → 54% slime
zombie 28% → 44% alien
goblin 19% → 38% knight
average 54% ‚Üí 67%

One caveat: the classifier that scored these is the same kind as the one that filtered the training data. Sprites that kind of classifier finds easy to recognise were the ones kept, so it will tend to score the fine-tuned model well. Some of the gain may come from that rather than from better drawing.

Some mix-ups are between characters that really do look alike: wizard and witch, pirate and ninja. Goblins and zombies are still the weakest. Most mistaken goblins are called knights, which fits with what the filter found in the labels.

On the device

Picking each pixel

At each step the model gives a score for every token, and the device picks one at random, weighted by those scores. Only the 33 pixel tokens are allowed, so it can't end early or write a character token in the middle of a sprite:

static int sample(const float *logits) {
  float pr[N_PIX_TOKENS], mx = logits[0], sum = 0.f;
  for (int v = 1; v < N_PIX_TOKENS; v++) if (logits[v] > mx) mx = logits[v];
  for (int v = 0; v < N_PIX_TOKENS; v++) { pr[v] = expf((logits[v] - mx) / TEMPERATURE); sum += pr[v]; }
  float r = (esp_random() / 4294967296.0f) * sum;
  for (int v = 0; v < N_PIX_TOKENS; v++) { r -= pr[v]; if (r <= 0.f) return v; }
  return N_PIX_TOKENS - 1;
}

Temperature divides the scores before they're turned into probabilities. Below 1 it makes likely pixels more likely still. It's set to 0.8, and the comment beside it says why:

static const float TEMPERATURE = 0.8f;      // 1.0 gives speckled, broken shapes

At 1.0, every so often it picks an unlikely colour, and in a 16 x 16 sprite one wrong pixel in an outline shows.

The random numbers come from esp_random(), the ESP32's hardware random number generator, so no two sprites are the same.

Speed and memory

It writes 13.9 pixels a second at 240 MHz, so a sprite takes about 18 seconds.

The model's working memory lives in PSRAM. The attention cache alone (the stored keys and values for every token written so far, which each new pixel looks back over) is 1.3 MB, more than the chip's internal RAM. The model itself goes into flash at 0x790000, 6 MB into a partition called model, so it can share that partition with the other apps' models.

A version for your computer

host/draw.c is the same model and arithmetic in a single C file. It draws 8 sprites of every character to a PNG:

cc -O2 -o draw host/draw.c -lm
./draw

The 120 sprites took under 2 seconds on my Mac. ./draw knight -n 12 -t 0.8 -s 7 -o knights.png draws 12 knights at temperature 0.8 with seed 7.

Licences

The code is MIT. firmware/src/llm.h is slvDev's inference code, also MIT.

The model is CC BY-NC 4.0, for non-commercial use. The Pixel Art Atlas is released as CC0, but its sprites were made with Krea 2, an image generator. Krea claims no ownership of outputs, but its commercial-use terms still apply to them, so a model trained on them shouldn't be offered for commercial use.

The full-precision weights are published as safetensors rather than a PyTorch checkpoint, because a checkpoint is a Python pickle and loading one can run code. training/weights.py turns them back into a checkpoint that training can start from, for anyone who wants to fine-tune it on new characters.

Run it

On your computer

cc -O2 -o draw host/draw.c -lm
./draw

On an M5Stack CoreS3

From firmware/, with PlatformIO. The model and the app are uploaded separately:

pio run -e m5stack-cores3 -t upload_model
pio run -e m5stack-cores3 -t upload

Over serial at 115200, type a character name (knight) to draw one and print its pixels. tools/screenshot.py saves the screen.

On any ESP32-S3 with PSRAM

The headless build is for boards with 8 MB of flash and PSRAM, such as an ESP32-S3-DevKitC-1 N8R8:

pio run -e esp32s3-headless -t upload_model
pio run -e esp32s3-headless -t upload

tools/serial_sprites.py asks it for some sprites and saves them as a PNG:

python3 tools/serial_sprites.py /dev/ttyUSB0 out.png knight ghost frog

That build takes about 19 seconds a sprite on a CoreS3.

Train it yourself

  1. Clone the fork of esp32-ai at the commit this model was trained with, and set up its environment:
   git clone https://github.com/justinmclean/esp32-ai.git ~/esp32-ai
   git -C ~/esp32-ai checkout 75bc998
  1. Point ESP32AI at it (the default is ~/esp32-ai), then download the Pixel Art Atlas (259 MB) and build both training files:
   training/prepare_data.sh
  1. Train both stages, filter and balance in between, and export the model into firmware/model. About 40 minutes on an M3 MacBook:
   training/train.sh

What I'd tell someone starting out

  • Anything you can write as a sequence, a language model can learn. A sprite is 256 tokens and a character name.
  • Keep the vocabulary small. A 32-colour palette made every pixel an easy choice and left nearly all the parameters for the part that does the work.
  • Learn the general skill on all the data, then fine-tune on what you want. Stage 1 taught it pixel art from 1.4 million sprites; stage 2 taught it which character is which.
  • Start each training example where your data starts. A sprite cut in half has lost its label.
  • Check your labels. AI-written captions had a fifth of the character sprites wrong enough to hurt. An out-of-fold classifier found them without me looking at 36,000 sprites.
  • Check it isn't copying. Comparing every generated sprite with the training set is cheap.
  • Read the licence of the data, and of whatever made the data.

Links

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.