esp32-diffusion / README.md
jmclean's picture
Upload README.md
e1e466d verified
|
Raw History Blame Contribute Delete
6.29 kB
---
license: mit
library_name: pytorch
pipeline_tag: unconditional-image-generation
datasets:
- huggan/smithsonian_butterflies_subset
tags:
- diffusion
- ddim
- unet
- esp32
- esp32-s3
- esp-dl
- microcontroller
- embedded
- edge
- int8
- quantization-aware-training
- butterflies
---
# Model Card for ESP32 Diffusion
A 0.17 M-parameter diffusion model that draws butterflies from pure noise on an ESP32-S3
microcontroller (M5Stack CoreS3), in 8-bit integers, in about 3 seconds, with nothing off
the chip. It uses the same kind of method as Stable Diffusion, at 64 x 64 pixels.
![Butterflies from the model](samples.png)
| Forming, step by step | On the CoreS3 |
|---|---|
| ![Butterflies forming from noise](forming.gif) | ![The app on the CoreS3](app.png) |
## Model Details
### Model Description
A small UNet that removes noise from a picture a step at a time. It draws only the left
half of a butterfly (64 high, 32 wide), and the right half is its mirror image, so it
never has to make the wings match and can be twice as wide for the same work. It predicts
v (a mix of the clean picture and the noise) and runs with a 10-step deterministic DDIM
sampler.
- **Developed by:** Justin McLean
- **Model type:** denoising diffusion UNet, unconditional
- **License:** MIT
- **Inference on the device:** [ESP-DL](https://github.com/espressif/esp-dl) 3.3
- **Quantised with:** [ESP-PPQ](https://github.com/espressif/esp-ppq) 1.3
### Model Sources
- **Repository:** https://github.com/justinmclean/esp32-diffusion
## Uses
### Direct Use
Drawing new 64 x 64 butterflies on an ESP32-S3 board or a computer, for fun and as a
demonstration of generative image models on a microcontroller.
### Out-of-Scope Use
Anything that needs real species. The butterflies are made up: they look like museum
specimens, but their wing patterns are not those of any real butterfly, and the model
knows nothing about biology.
## Bias, Risks, and Limitations
- 64 x 64 pixels only, and every butterfly is exactly symmetrical, by design.
- Colours follow the training photos: mostly browns, yellows and whites, with few blues.
- In 8 bits, some butterflies have faint speckle in the white background or a few stray
coloured pixels.
- No control over what it draws: there is no prompt, only the starting noise.
## How to Get Started with the Model
On an M5Stack CoreS3, from the GitHub repository, copy `butterfly_w8a8.espdl` to
`app/model/butterfly.espdl`, then from the `app/` folder:
```bash
pio run -t upload
```
On a computer, with the repository's Python code:
```python
import torch
from safetensors.torch import load_file
import train
from unet import UNet
model = UNet((24, 48, 96), sep=True)
model.load_state_dict(load_file("butterfly.safetensors"))
model.eval()
x = train.sample(model, 16, 64, 10, "cpu", width=32, pred="v") # 16 left halves
train.save_grid(train.mirror(x), "butterflies.png")
```
## Files
- `butterfly_w8a8.espdl`: the device model, 8-bit weights and activations (210 KB), for
ESP-DL on the ESP32-S3.
- `butterfly.safetensors`: full-precision weights (0.7 MB), for the repository's
`unet.UNet((24, 48, 96), sep=True)`.
## Training Details
### Training Data
1,000 public domain (CC0) butterfly photos from the Smithsonian, via
[huggan/smithsonian_butterflies_subset](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset).
Each was put on a white background, padded to a square and scaled to 64 x 64. The model
learns from left halves, and from right halves mirrored, so 2,000 halves of 64 x 32.
### Training Procedure
#### Training Hyperparameters
- 20,000 steps, batch 64, AdamW, learning rate 2e-3 with a one-cycle schedule (5% warmup),
gradient clipping at 1.0, exponential moving average of the weights at 0.999
- Cosine noise schedule, v-prediction, mean squared error
- **Quantisation-aware training:** for the last 5,000 steps, the weights and every layer's
output are rounded to 8 bits with a power-of-two scale, as ESP-DL does
- **Training regime:** fp32, on the Apple M3 GPU
#### Speeds, Sizes, Times
- 169,731 parameters; 210 KB on the device
- 116 M multiply-adds per step
- 33 minutes of training on an Apple M3 MacBook
- On the ESP32-S3 at 240 MHz: 0.23 s per step on both cores, 3.2 s per butterfly
including drawing the screen
- On the Mac: about 30 ms per butterfly
## Evaluation
### Testing Data, Factors & Metrics
- **8 bits against full precision:** 32 butterflies from the same starting noise, through
full precision and through ESP-PPQ's simulation of the device's 8-bit arithmetic. Mean
absolute difference per pixel, out of 255.
- **Fewer steps:** 16 butterflies in 8 bits from the same noise at 20, 10, 7 and 5 steps,
against 20 steps.
- **Copying:** 128 butterflies, each against its nearest training half (RMS distance).
### Results
| | Result |
|---|---|
| 8-bit against full precision | 6.8 levels out of 255; colour shift R -2, G -1, B +2 |
| 10 steps against 20 | 5.0 levels (7 steps: 8.0, 5 steps: 11.4) |
| Nearest training image, median | 0.31, the same as a real butterfly to its nearest other one |
The closest matches to training images are pale butterflies, close mostly because both
are largely white background; their wing patterns differ.
## Technical Specifications
### Model Architecture and Objective
A UNet with three levels of 24, 48 and 96 channels, each made of residual blocks of two
3x3 convolutions with Swish, stride-2 convolutions to go down, nearest-neighbour
upsampling and skip connections to come back up. The timestep goes in as a fourth input
channel, a constant plane, so the network has one input.
Any 3x3 convolution with more than 24 KB of weights is split into a depthwise 3x3 and a
pointwise 1x1, as in MobileNet. That keeps every layer's weights inside the ESP32-S3's
32 KB data cache: with plain 3x3 convolutions the model took 28 seconds a butterfly at 20
steps, and split it takes 4.6.
The model is trained to predict v = sqrt(a) * noise - sqrt(1 - a) * image, where a is the
cosine schedule's signal level.
### Compute Infrastructure
- **Training:** Apple M3 MacBook (PyTorch, Metal GPU)
- **Inference:** ESP32-S3 (M5Stack CoreS3) with 8 MB PSRAM, or any computer
## Licence
MIT. The training photos are CC0, from the Smithsonian.