A diffusion model on the ESP32-S3 that draws butterflies in 3 seconds
This one draws butterflies from pure noise on an M5Stack CoreS3. It uses the same kind of method as Stable Diffusion, but in 0.17 M parameters and 8-bit integers, and takes about 3 seconds a butterfly, with nothing off the chip. Tap the screen for another.
The other models in this series (the recipe, sprite and card makers) are transformers that write one token at a time. This is a different kind of model with a different toolchain: a small convolutional network, quantised with Espressif's ESP-PPQ and run with their ESP-DL library.
Getting it to work came down to three problems: getting good shapes from a network this small, keeping the colours right in 8 bits, and getting it fast.
The code and model are here: esp32-diffusion on GitHub jmclean/esp32-diffusion on Hugging Face
Forming, step by step
The app on the CoreS3
How diffusion works
A diffusion model learns to remove noise. In training you take a real picture, bury it in a random amount of noise, and ask the network to work out what was there. Do that over a million times, at every noise level from barely touched to pure static, and the network gets good at it.
To draw something new, you start from pure noise, which has no picture in it at all, and ask the network for its best guess. That guess is blurry, but it has a shape. You mix most of the noise back in, ask again, and repeat. Each step there's less noise and the guess gets sharper, until there's no noise left and you have a picture nobody drew.
The animation above is that process. The app shows the network's guess after each step, so you can watch the shape appear and sharpen.
How much noise there is at each point is set by a noise schedule. This uses the cosine schedule, where a is how much of the picture is left at time t: nearly 1 at t = 0, a clean picture, and nearly 0 at t = 1, pure noise:
def alphas_bar(t):
# cosine schedule, t in [0, 1]; never exactly 0, so t = 1 can be undone
return (torch.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2).clamp(min=1e-4)
A noisy training picture is sqrt(a) * picture + sqrt(1 - a) * noise.
The network is a UNet, the same shape Stable Diffusion uses at its core. It shrinks the picture down through a few levels, so later layers see the whole butterfly at once, then grows it back up. Skip connections carry the detail from each level on the way down straight across to the same level on the way up, so fine detail isn't lost.
The training data
1,000 public domain (CC0) butterfly photos from the Smithsonian, from the huggan/smithsonian_butterflies_subset dataset. They're museum specimens photographed flat: every butterfly is face on, wings spread, in the middle of the frame.
Each one goes on a white background, is padded to a square and scaled to 64 x 64. Colours follow the photos: mostly browns, yellows and whites, with few blues.
The trick: half a butterfly
The first network drew whole 64 x 64 butterflies (0.21 M parameters) and got muddy shapes: Butterflies are symmetrical. So the network now draws only the left half, 64 high and 32 wide, and the right half is its mirror image.
That does two things. Half the pixels means the network can be twice as wide for the same work. And it never has to learn to make the two wings match.
Training learns from both halves of every photo, the right one mirrored so the body is on the right edge too:
if half:
# left halves, and right halves mirrored so the body is on the right edge too
data = torch.cat([data[..., :width], data.flip(3)[..., :width]])
That's 2,000 halves from 1,000 photos. On the device, the mirroring is one line in the display code:
rgb[r][c][k] = rgb[r][2 * W - 1 - c][k] = to_byte(img[(r * W + c) * 3 + k]);
The half-image network gives the butterflies at the top of this post, with a third less work per step than the whole-image one. Every butterfly is exactly symmetrical, by design.
Is it copying? With only 1,000 training photos, a model could just learn to reproduce them. I checked 128 generated butterflies against their nearest training half. The median distance is 0.31, the same as from a real butterfly to its nearest other real one. The closest matches are pale butterflies, close mostly because both are largely white background, and their wing patterns differ.
A network ESP-DL can run
ESP-DL is Espressif's library for running neural networks on their chips. It runs a limited set of layers, so the UNet (unet.py) uses only convolutions, Swish (the activation function, x * sigmoid(x)), add, concat and nearest-neighbour upsampling.
The network also needs to know how much noise is in the picture, the timestep. Larger diffusion models feed that in through extra layers, but here it goes in as a fourth input channel: a plane with every pixel set to t. That keeps the network at a single input:
def with_t(x, t):
# the timestep as a fourth channel, as the device feeds it
return torch.cat([x, t.view(-1, 1, 1, 1).expand(-1, 1, *x.shape[2:])], 1)
- Image 64 x 32 (left half), mirrored to 64 x 64
- Channels 24, 48, 96
- Parameters 169,731
- Work per step 116 M multiply-adds
- 8-bit model 210 KB
- Sampler DDIM, 10 steps, cosine schedule
Training is 20,000 steps of 64 halves, AdamW at a learning rate of 2e-3 with a one-cycle schedule, and an exponential moving average of the weights (a slowly updated copy, which gives smoother results than the weights at any one step). It takes 33 minutes on an M3 MacBook's GPU.
Keeping the colours in 8 bits
The network trains with 32-bit floats, but the board runs it with 8-bit integers, which are faster and four times smaller but less exact. ESP-DL stores each tensor as int8 values with one power-of-two scale, so a weight of 0.0371 might become 0.0391.
When the first network was converted to 8 bits, its butterflies turned blue. The small errors added up over the drawing steps. Two changes fixed it.
Guessing the picture, not just the noise
At each step the network makes a guess, and the sampler works out the finished picture from it. The first network guessed the noise, which is the usual approach. Getting the picture back from a noise guess means:
x0 = ((x - (1 - a).sqrt() * out) / a.sqrt()).clamp(-1, 1)
Early on, when the picture is almost all noise, a is tiny, so this divides by a tiny number. A small error in the guess became a big error in the picture, every step.
The fix is v-prediction: the network guesses a mix of the picture and the noise, v = sqrt(a) * noise - sqrt(1 - a) * picture. Getting the picture from that needs no division:
x0 = (a.sqrt() * x - (1 - a).sqrt() * out).clamp(-1, 1)
So small errors stay small. In training it's a one-line change to the target:
target = a.sqrt() * eps - (1 - a).sqrt() * x0 if args.pred == "v" else eps
Training with the rounding on
Even with v-prediction, rounding every weight and every layer's output adds up. So for the last quarter of training (5,000 of the 20,000 steps), the Mac does the same rounding the board will, and the network learns to draw good butterflies in spite of it. This is quantisation-aware training.
The rounding copies what ESP-DL does: int8, one power-of-two scale per tensor:
def fake_quant(w):
"""Round weights as ESP-DL stores them: int8, one power-of-two scale per tensor.
The gradient passes straight through, so training can learn weights that round well."""
scale = 2.0 ** torch.ceil(torch.log2(w.detach().abs().max().clamp(min=1e-8) / 127))
q = (w / scale).round().clamp(-128, 127) * scale
return w + (q - w).detach()
The last line is the trick. Rounding has no useful gradient (it's flat almost everywhere), so training couldn't learn through it. w + (q - w).detach() gives the rounded value going forward, but the gradient flows back as if there were no rounding. This is called a straight-through estimator.
The same rounding is applied to each layer's output (ActQ in unet.py), using a running average of the largest value seen to set the scale.
How much each change helped
32 butterflies from the same starting noise, through full precision and through ESP-PPQ's simulation of the device's 8-bit arithmetic. The difference is the mean per pixel, out of 255:
Mean difference Colour shift R, G, B First network, 8-bit about 45 strong blue First network, 8-bit with bias correction 39.7 +15, +6, -11 v-prediction, weights rounded in training 11.5 +8, +10, +10 v-prediction, weights and layer outputs rounded in training 7.1 +3, +3, +2 The same, with split layers (the network in the app) 6.8 -2, -1, +2
Bias correction, one of ESP-PPQ's calibration passes, barely helped. The fixes had to go into how the network was trained, not how it was converted.
Full precision on the top two rows, 8-bit underneath, same starting noise: The 8-bit model is exported by ESP-PPQ (quantize.py). It calibrates on the inputs the network really sees: all the sampling steps of 8 butterflies.
Fitting the cache
The first half-image network used plain 3x3 convolutions throughout, 0.48 M parameters. On the board it took 30 seconds a butterfly at 20 steps. ESP-DL can profile each layer (the app prints it when you send p over serial). Five layers took 85% of the time. They ran at about 30 M multiply-adds a second, against 300 to 1,000 M for the rest.
Each of the five had more than 32 KB of weights, and the ESP32-S3 reads them through a 32 KB data cache. Those layers didn't fit, so the weights were fetched again and again from slow external memory.
The fix is from Google's MobileNet: split a big 3x3 convolution in two. A depthwise 3x3 looks at each channel by itself, then a pointwise 1x1 mixes the channels at each pixel:
CACHE_WEIGHTS = 24 * 1024 # bytes of int8 weights a 3x3 layer may have and still run fast
def conv3(cin, cout, sep):
"""A 3x3 conv. With sep, one whose weights would not fit the ESP32-S3's 32 KB data cache is split depthwise then pointwise, as in MobileNet: a 3x3 per channel, then a 1x1 that mixes the channels."""
if not sep or cin * cout * 9 <= CACHE_WEIGHTS:
return Conv(cin, cout, 3, padding=1)
return nn.Sequential(Conv(cin, cin, 3, padding=1, groups=cin), Conv(cin, cout, 1))
For a 96-channel layer, that's 96 x 96 x 9 = 83 KB of weights down to 96 x 9 + 96 x 96 = 10 KB. Only the five big layers are split. The smaller ones stay as plain 3x3s.
Network, 20 steps Parameters Multiply-adds per step Network time Whole butterfly Plain 3x3 layers 0.48 M 176 M 28.1 s 30.6 s Split layers 0.17 M 116 M 4.6 s 6.4 s
The split network does two thirds of the arithmetic, but runs six times faster. Most of the gain is from the cache, not from doing less. And the butterflies are as good: the 8-bit difference is 6.8, against 7.1 for the plain network.
Fewer steps
The network was trained and first run with 20 steps. DDIM (the sampler) can take bigger steps without retraining, so I tried fewer, all in the 8-bit simulation from the same starting noise:
Steps Difference from 20 steps (out of 255) On the board 20 0 6.4 s 10 5.0 3.2 s 7 8.0 5 11.4, slightly softer
The difference at 10 steps is smaller than rounding to 8 bits costs on its own (6.8). So the app uses 10 steps, half the time for butterflies you can't tell apart.
I also tried distillation for 10 steps: training a second network to take one step where the first takes two. It came out grainier in 8 bits than just taking 10 steps with this network, so it isn't used.
On the device
The app (app/src/main.cpp) embeds the 210 KB model in the firmware and runs it with ESP-DL on both cores. Each step it fills the int8 input with the noisy picture and the timestep, runs the network, and takes a DDIM step:
for (int k = 0; k < H * W * 3; k++) {
// v-prediction, DDIM step
float v = qout[k] * sout;
float c0 = fminf(1.0f, fmaxf(-1.0f, sa * x[k] - sb * v));
float eps = (x[k] - sa * c0) / sb;
x0[k] = c0;
x[k] = san * c0 + sbn * eps;
}
c0 is the network's guess at the finished picture. From that it works out the noise, then builds the next, less noisy picture from the two. DDIM with no random noise added each step is deterministic, so the same starting noise always gives the same butterfly. The starting noise comes from the ESP32's hardware random number generator, so every butterfly is different.
The screen shows the guess c0, not the noisy picture. The noisy picture looks like static until the last few steps, but the guess has a shape from the first.
The 64 x 64 butterfly is scaled up 3x with bilinear smoothing to 192 x 192.
Timings at 240 MHz:
- 0.23 s per step for the network, on both cores
- 3.2 s per butterfly, including drawing the screen after every step
- About 30 ms per butterfly for the same network on my Mac
Over serial at 115200, the app sends each finished butterfly as hex, s gets a screenshot, and p prints ESP-DL's per-layer profile.
Limits
64 x 64 pixels only, and every butterfly is exactly symmetrical. No control over what it draws: there's no prompt, only the starting noise. In 8 bits, some butterflies have faint speckle in the white background or a few stray coloured pixels.
Run it
Needs Python 3.11 and uv:
uv venv --python 3.11 .venv && uv pip install --python .venv/bin/python -r requirements.txt
The trained model is in the repo, in runs/h64s-v-qata/. To draw 32 butterflies on your computer:
.venv/bin/python sample.py runs/h64s-v-qata 10
That writes a sheet of them to runs/h64s-v-qata/check-10steps.png. To run it on a CoreS3, from app/ with PlatformIO:
pio run -t upload
The 8-bit model is already in app/model/butterfly.espdl.
Train it yourself
Download the training data (237 MB):
mkdir -p data && curl -L -o data/butterflies.parquet https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset/resolve/main/data/train-00000-of-00001.parquet
Train (about 35 minutes on an Apple silicon Mac), then quantise:
.venv/bin/python train.py data/butterflies.parquet --variant h64s --pred v --qat_steps 5000 --qat_act
.venv/bin/python quantize.py runs/h64s-v-qata w8a8
Copy the quantised network into the app and flash it:
cp runs/h64s-v-qata/model_w8a8.espdl app/model/butterfly.espdl && cd app && pio run -t upload
What I'd tell someone starting out
Use
Comments
No comments yet. Start the discussion.