Training a tiny model for the M5Stack CoreS3
DEV Community

Training a tiny model for the M5Stack CoreS3

Why this fits on a microcontroller at all

The CoreS3 has an ESP32-S3 at 240 MHz, 16 MB of flash (slow storage that keeps its contents with the power off) and 8 MB of PSRAM (faster working memory). That is not much for a language model.

A model is a large set of numbers, its parameters (or weights), learnt in training. Writing text means doing arithmetic with all of them for every word piece it writes.

slvDev/esp32-ai has a clever layout for a small chip: most of the parameters are lookup tables, called embeddings, where the model only reads the few rows it needs for the current word piece. Those can stay in flash and be read in place. Only a small core, the transformer that does the real computing, needs the full arithmetic on every step, and that sits in PSRAM.

The recipe model has 8.2 million parameters: 6.3 million in lookup tables for each of its layers (per-layer embeddings), 0.8 million in the table of word pieces (the token embedding), and 1.1 million in the core (6 layers, each 96 numbers wide). Each parameter is stored in 4 bits rather than the usual 32, so the whole model is 4.2 MB, and the core is expanded to 8 bits in PSRAM to run. It writes 6 to 7 tokens a second.

A token is the unit the model reads and writes: a common word, part of a longer word, or a piece of punctuation. "pumpkin" is one token; a rarer word might be two or three.

I didn't change the architecture or the inference code. All my work went into the data, the training options and the checking. That turned out to be the right split.

Step 1: decide what the model writes, and fix its layout

A tiny model can't follow instructions, but it can learn a shape very reliably. So the first job is to design a fixed text layout that carries both the user's choices and the output:

Main: pumpkin
Dish: soup
Title: Roast Pumpkin and Ginger Soup
Ingredients:
- 1 kg pumpkin, peeled and cubed
- 1 onion, chopped
Method:
1. Roast the pumpkin at 200C for 25 minutes.
2. ...
<|endoftext|>

The device sends everything up to Title: and the model writes the rest. The picks go first so the model learns to follow them. <|endoftext|> tells the app when to stop.

Design this around the screen, not the model. The touch picker means no keyboard. The model can only see 256 tokens at a time (its context), prompt included, so recipes have to be short, which suits a 320 x 240 display anyway.

Step 2: find the data, and read the licence

The model only sees about 20 to 80 million tokens in training, so you don't need a huge dataset, but you do need enough examples for every combination of picks. There are two ways to get it:

  • Use an open dataset. I used RecipeNLG, about 2.2 million recipes. Its terms allow non-commercial research and educational use only, so the trained model carries the same restriction (CC BY-NC 4.0). The official site was down, so I used the byte-identical copy on Hugging Face.
  • Generate it with a large model. You get exactly the layout and coverage you want, but check the provider's terms. Several, Anthropic's included, restrict using outputs to train other models.

There's a third way, which Card Maker uses: write a program that makes the data. Its engine plays random rule sets against itself and keeps the good ones. No licence questions at all.

Whatever you choose, convert or generate 200 first and read 30 by hand before doing the rest.

Step 3: clean and convert (this is most of the work)

RecipeNLG is American. I wanted Australian recipes: metric units and standard can sizes, Celsius, Australian names (capsicum, coriander, spring onions, thickened cream) and Australian spelling. The converter, training/convert_recipenlg.py, uses only the standard library and does all of that, and also files each recipe under one of 14 mains and 12 kinds of dish by keyword matching.

Most of the data didn't survive:

  • Dropped because Share From cookbooks.com or kraftrecipes.com 42%
  • No main ingredient from the picker 29%
  • Too long for the 256-token window 9%
  • No proper method, or more than 10 steps 6%
  • Built on US convenience products (cake mixes, cream soups in salads) 5%
  • Other checks (all caps, footnotes, adverts, huge batches) 1%
  • Kept 9%

That still left 191,930 recipes, about 35 million training tokens.

Three habits made this manageable:

  • A test case for every fix. Each time I found a bad recipe in the output (a brand name, crock-pot instructions, a Fahrenheit temperature), I fixed the converter and added a case to test_converter.py. The build script runs the tests first and stops if anything regresses.
  • An audit, not just filters. audit_data.py lists anything that still looks American, for a person to read. It runs on the CPU while the GPU trains, so it never holds anything up.
  • A count of what should be gone. check_data.py counts anything the filters should have removed. It should be zero.

Step 4: check coverage for every pick

A converter run also writes a table of how many recipes there are for every main and dish pair. Pairs with fewer than 50 are too thin to learn from: the model ignores the pick or copies one recipe. The app greys those out. Chocolate soup has no recipes, which is probably for the best.

Generate the app's picker from this table (tools/make_picks_h.py) so the device and the data can't drift apart.

Step 5: make the tokeniser and the training files

The model works on numbers, not letters, so the text has to be cut into tokens and each token given a number. The tokeniser does that. It is learnt from the data itself: byte-level BPE (byte pair encoding) starts from single characters and keeps merging the pairs that appear together most often, so frequent words like "simmer" end up as a single token and rare ones are built from pieces.

prepare_recipes.py learns the tokeniser, turns every recipe into token numbers, and splits them into two files: train.bin, which the model learns from, and val.bin, a small validation set of recipes it never trains on. Checking the model on recipes it has never seen tells you whether it has learnt how recipes go in general, or has just memorised the ones it was shown.

A few things matter here:

  • A small vocabulary. The vocabulary is the list of tokens the tokeniser can use. Recipe Maker has 8,192, where the TinyStories model these tools were built for has 32,768. A narrow subject needs fewer, and the token tables, which have a row for every token, shrink to a quarter. Check that common words (pumpkin, garlic, simmer) come out as one or two tokens. The cocktail model went further, with 2,048 tokens learnt from the drinks, so Chartreuse and Angostura are one token each.
  • Shuffle first. RecipeNLG is grouped by website. Take the last half a percent of it for validation without shuffling and every validation recipe comes from one site, so the check only tells you how well the model does on that site's style.
  • Hold out validation before repeating anything. I wanted more Australian style than the data had, so the 5,496 recipes from Australian websites are copied three times into training. Repeating good examples like this (oversampling) makes the model weight them more. The order matters: pick the validation recipes first, then make the copies, from what is left. Do it the other way round and some of those copies end up in validation, so the model is checked on recipes it has already trained on. It does well on those because it has seen them, and the validation score looks better than the model really is.
  • Keep the tokeniser fixed once the firmware uses it. The device turns token numbers back into text with a table built from the tokeniser (vocab.h). If a data rebuild learnt a new tokeniser, the numbers would mean different words and the device would print nonsense. Later rebuilds reuse the published tokeniser so the numbers still match.

Step 6: train

Training runs on a Mac with PyTorch's mps backend. The final model took about 80 minutes on an M3 MacBook; this size of model needs well under 4 GB.

ESP32AI_DATA=data/recipes PYTHONPATH=src .venv/bin/python research/tinystories/train.py \
  --arm ple --vocab 8192 --d-model 96 --n-layers 6 --ple-dim 128 \
  --target-core 1100000 --batch-size 16 --seq-len 256 --steps 20000 \
  --eval-every 1000 --tag recipes

What the settings mean:

  • --arm ple: the per-layer-embedding layout described above.
  • --d-model 96 --n-layers 6 --ple-dim 128 --target-core 1100000: the model's size. Each layer is 96 numbers wide, there are 6 layers, each layer's lookup table is 128 wide, and the core is sized to about 1.1 million parameters.
  • --vocab 8192: must match the tokeniser.
  • --batch-size 16 --seq-len 256: each training step looks at 16 pieces of text, 256 tokens each, about 4,000 tokens.
  • --steps 20000: how many training steps. 20,000 steps of 4,000 tokens is 82 million tokens, so the model sees the 35 million tokens of recipes a bit over twice.
  • --eval-every 1000: check the validation set every 1,000 steps.

Each step, the model guesses every next token in the batch, the trainer measures how wrong the guesses were (the loss), and it nudges every parameter slightly in the direction that makes the guesses better. Training is that, 20,000 times.

Start with a 500-step run to time it. Mine took 84 seconds, so 5,000 steps was about 12 minutes: short enough to try an idea and look at the result in the same sitting. Run times grew as the model did. All of these are on the same M3 MacBook:

  • Runs Steps Time each First timing run 500 84 seconds Early runs, trying data changes 5,000 11 to 13 minutes With the penalties, then the bigger core 10,000 23 to 39 minutes Final model 20,000 81 minutes

The penalties added a few minutes a run, and doubling the core took a 10,000-step run to 39 minutes. Most of the iterating happened at 10,000 steps, where one idea took about half an hour to test.

One practical warning: don't run two GPU training jobs at once. I tried two and it crashed the Mac. The queue scripts now wait for the GPU to be free.

Step 7: measure what you care about, not the loss

The trainer reports a number called the loss: roughly, how surprised the model is by the real next token, averaged over the text. Lower is better. The validation loss is the same measure on the held-out validation recipes, so it shows how well the model does on recipes it hasn't seen.

Validation loss is a poor guide once the data changes. My first full run had a validation loss of 1.81. The final model, which is much better, has 1.965. In between the tokeniser changed, the data got cleaner and harder to predict, and extra penalties were added, so the numbers across versions aren't comparable. Loss is still useful within one dataset. For Bard Lite it decided when to stop training (see below).

What I needed to know was whether the recipes were right, so I wrote a test for that. pick_test.py writes 20 recipes for each of 13 picks covering every kind of dish, at the device's temperature, and counts:

  • Layout: a title, an ingredient list and a numbered method, ending in time.
  • Main in the list: the main ingredient picked is in the ingredient list, not just the title.
  • Method strays: a method step uses an ingredient the list doesn't have ("add the leeks", with no leeks).
  • Repeats: an ingredient listed twice.

It runs at the device's temperature of 0.7, because temperature changes the results a lot (see What temperature does, in the section on training your own model). Each new model was tested against the one on the device, side by side. Every decision after this point came from that test.

Step 8: iterate on what the test finds

I trained 17 recipe models in under a day. The changes that helped, in order:

  • Sort ingredient lists A to Z and drop repeated lines. Real recipes list "salt" twice more often than you'd think, and the model copied it. A sorted list makes a repeat easy to avoid, because the model only has to check the line before.
  • Unlikelihood penalties. Normal training only teaches the model to copy what the data does. It can't tell the model that listing an ingredient twice is wrong; it just sees that it happens sometimes. An unlikelihood penalty adds a second lesson: at each point in a recipe, it also looks at how likely the model thinks a known-bad next token is, and pushes that down. I added three, in esp32-ai.patch: one against an ingredient line using ingredient words already listed above it (units and numbers are allowed, as real lists repeat those), one against a method step naming an ingredient that isn't in the list, and one against repeating a word within a list inside a method step ("salt, pepper and salt"). Each has a weight, how hard it pushes compared with normal training; the final weights are 3, 3 and 1.
  • A bigger core. Doubling the transformer core from 560,000 to 1.1 million parameters. The device still runs it at 6 to 7 tokens a second.
  • Train longer. 20,000 steps instead of 5,000 to 10,000.

An early 5,000-step model put the main ingredient in the list 140 times in 160. The final model:

  • Recipes Layout right 252 of 260 Main ingredient in the list 240 of 260 (92%) Method uses an ingredient the list lacks 13 of 260 (5%) Ingredient listed twice 13 of 260 (5%)

For comparison, 10.7% of real recipes have a method step naming something not in the list, by the same co

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.