# Training a tiny model for the M5Stack CoreS3

> Source: <https://dev.to/justin_mclean_1dd355c2931/training-a-tiny-model-for-the-m5stack-cores3-4849>
> Published: 2026-12-03 02:08:04+00:00

**Recommendation:** Keep embedding lookup tables in flash and expand only the small transformer core to 8 bits in PSRAM when running a tiny LLM on an ESP32-S3, and design a fixed text layout around the device's screen and 256-token context.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

Over the last few weeks I've built five small generative AI apps that run entirely on an M5Stack CoreS3: a recipe writer, a pixel-art sprite maker, a card game inventor, a cocktail maker and a Shakespeare scene writer that types into your computer as a USB keyboard. No cloud, no phone, no Wi-Fi. Each has its own model, from 82 KB to 4 MB, running on the ESP32-S3.

This article walks through how to train one, using Recipe Maker as the worked example, then gives the exact commands to retrain it yourself and to train a model on a subject of your own. You pick a main ingredient and a kind of dish on the touchscreen, and about 25 seconds later you have a recipe nobody has written before. Everything here is in the repo, [esp32-recipe-maker](https://github.com/justinmclean/esp32-recipe-maker), and the model is on Hugging Face at [jmclean/esp32-recipe-maker](https://huggingface.co/jmclean/esp32-recipe-maker).

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](https://github.com/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.

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.

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:

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.

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:

`test_converter.py`. The build script runs the tests first and stops if anything regresses.`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.`check_data.py` counts anything the filters should have removed. It should be zero.
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.

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:

`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.`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.
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.

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:

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.

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

`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.
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 count. The weakest pick is mushroom salad, where the list often leaves out the mushrooms.

`model.bin`, esp32-ai's device format. This rounds every parameter to 4 bits (quantisation), so the model is an eighth of the size. Rounding costs a little accuracy; testing the exported model, as below, shows whether that matters.`model` partition, then the app. The flash is divided into partitions, fixed areas for the app, settings and data. The model goes in once (it's 4 MB, so it's slow to write); after that you can reflash the app as often as you like without touching it:

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

The apps share one partition layout, and each model starts at its own address (offset) in the `model` partition: the recipe model at 0x190000, Bard Lite's at 0xC00000. Flashing one model doesn't overwrite another, so several can be on one CoreS3 at once.

Before flashing anything, I test with `host/recipe.c`. It loads the same `model.bin` and runs the same 8-bit arithmetic and sampling as the device, and only needs a C compiler. That is also how the pick test's numbers can be trusted to match what the device writes.

The repo has the device model, the full-precision weights for fine-tuning, the scripts to rebuild the data and retrain from scratch, and a model card. The model licence follows the data: RecipeNLG is non-commercial, so the model is CC BY-NC 4.0, while the code is MIT. The card also says plainly that the recipes are made up by a tiny model, so check quantities, cooking times and temperatures before you cook one.

Everything below was run on fresh clones on an M3 MacBook Pro (8 cores), and the times are from that run.

You need:

`hf`);` esp32s3-headless` build instead, over serial.

```
git clone https://github.com/slvDev/esp32-ai.git ~/esp32-ai
git clone https://github.com/justinmclean/esp32-recipe-maker.git ~/esp32-recipe-maker
cd ~/esp32-ai && git checkout 52ebcbb && git apply ~/esp32-recipe-maker/training/esp32-ai.patch && uv sync
```

The patch adds the training options this needs: another data folder, the three penalties, starting from saved weights and CPU training. `git status` should show only `research/tinystories/train.py` changed.

```
cd ~/esp32-recipe-maker
hf download SandhyaKilari/RecipeNLG_dataset RecipeNLG_dataset.csv --repo-type dataset --local-dir data
training/prepare_data.sh
```

The download is 2.2 GB. The build took 8.5 minutes, using every core. It runs the converter's tests first, converts and filters 2.2 million recipes, sorts the ingredient lists, tokenises everything with the published tokeniser and then counts anything that should have been removed. The end of the output should look like this, with every count at zero except the cream soups:

```
train 34,903,013 tokens / val 165,909 tokens
191,924 recipes
  double numbered steps: 0
  brand marks: 0
  Fahrenheit: 0
  ...
  cream soups (allowed): 6637, in salads (should be 0): 0
STEPS=500 training/train.sh
```

This trains for 500 steps (2 minutes), exports the model to `firmware/model/model.bin` and runs the pick test (2 more minutes). It overwrites the published model in your clone: `git checkout firmware/model` puts it back.

Don't expect a usable model from 500 steps. Mine put the main ingredient in the list 15 times in 260 and listed an ingredient twice in 178. Run it on the computer to see:

```
cc -O2 -o recipe host/recipe.c -lm && ./recipe pumpkin soup
```

I asked for pumpkin soup and got "Pork Chops With Mushroom and Garlic And Pumpkin", with three cups of rice wine, half a cup of mayonnaise, water listed three times and a method that ends in the microwave. It has the layout and the right sort of words, and nothing more. That is what 500 steps is for: proving that every stage runs before you spend 80 minutes.

```
training/train.sh
```

20,000 steps, about 80 minutes. The pick test at the end should come out close to the published model: about 250 of 260 with the right layout and 240 with the main ingredient in the list. Runs differ a little from one to the next.

This replaces whatever is on the board, partition table included.

```
cd ~/esp32-recipe-maker/firmware
pio run -e m5stack-cores3 -t upload_model
pio run -e m5stack-cores3 -t upload
```

The model took 60 seconds to write and the app 53 seconds to build and flash. Pick on the touchscreen, or open the serial monitor (`pio device monitor`) and type `pumpkin soup`. Mine wrote 130 tokens in 20.1 seconds, 6.5 tokens a second.

Recipes need a big conversion job. The general route is much shorter, and you can try all of it in a few minutes. This example teaches a model to write made-up weather forecasts for Australian cities.

Each example uses the same fixed layout and ends with `<|endoftext|>`:

```
City: Hobart
Season: Winter
Day: Sunday
Forecast: Rain at times. Top 10, low -1. Calm.
<|endoftext|>
```

Here a short program writes them, with simple rules: each city has a usual top for summer and winter, autumn and spring are halfway between, each city has its own chance of rain, the top varies by up to 4 degrees either way, and the low is 8 to 14 degrees under the top.

``` python
import random

# City: (usual top in summer, usual top in winter, chance of rain)
CITIES = {
    "Darwin": (33, 31, 0.5), "Cairns": (31, 26, 0.45), "Brisbane": (29, 21, 0.3),
    "Sydney": (26, 17, 0.3), "Canberra": (28, 12, 0.25), "Melbourne": (25, 14, 0.35),
    "Hobart": (22, 12, 0.4), "Adelaide": (29, 15, 0.25), "Perth": (31, 18, 0.25),
    "Alice Springs": (36, 20, 0.1),
}
SEASONS = ["Summer", "Autumn", "Winter", "Spring"]
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
DRY = ["Sunny.", "Mostly sunny.", "Partly cloudy.", "Clear skies."]
WET = ["Showers.", "A shower or two.", "Rain at times.", "Possible storm."]
WINDS = ["Light winds.", "Winds becoming gusty.", "Fresh southerly change late.", "Calm."]

def usual_top(city, season):
    """Summer and winter as listed; autumn and spring halfway between."""
    summer, winter, _ = CITIES[city]
    return {"Summer": summer, "Winter": winter}.get(season, (summer + winter) // 2)

if __name__ == "__main__":
    rng = random.Random(1)
    with open("forecasts.txt", "w") as f:
        for _ in range(50000):
            city = rng.choice(list(CITIES))
            season = rng.choice(SEASONS)
            top = usual_top(city, season) + rng.randint(-4, 4)
            low = top - rng.randint(8, 14)
            sky = rng.choice(WET if rng.random() < CITIES[city][2] else DRY)
            f.write(f"City: {city}\nSeason: {season}\nDay: {rng.choice(DAYS)}\n"
                    f"Forecast: {sky} Top {top}, low {low}. {rng.choice(WINDS)}\n<|endoftext|>\n")
```

Save it as `make_forecasts.py` in a new `~/forecasts` folder and run it there:

```
mkdir -p ~/forecasts && cd ~/forecasts && python3 make_forecasts.py
```

For your own subject, replace this with your own data in the same shape: one example per document, a fixed layout, `<|endoftext|>` at the end of each.

```
cd ~/esp32-ai
.venv/bin/python ~/esp32-recipe-maker/training/prepare_recipes.py ~/forecasts/forecasts.txt data/forecasts --vocab 1024
```

About a second. It says "recipes" and checks a few recipe words at the end; ignore those. A vocabulary of 1,024 is a ceiling: forecasts use so few words that the tokeniser stopped at 505 tokens, which is fine.

```
ESP32AI_DATA=data/forecasts PYTHONPATH=src .venv/bin/python research/tinystories/train.py --arm ple --vocab 1024 --d-model 96 --n-layers 6 --ple-dim 128 --target-core 560000 --batch-size 16 --seq-len 256 --steps 500 --eval-every 100 --tag forecasts
```

About 70 seconds. Validation loss falls from 6.97 to 0.49. A layout this simple is learnt in about 200 steps.

```
PYTHONPATH=src .venv/bin/python -m research.tinystories.sample --run runs/ple-forecasts-s0.pt --tokenizer data/forecasts/vocab-1024/tokenizer.json --prompt "$(printf 'City: Darwin\nSeason: Winter\nDay: Monday\nForecast:')" --samples 3 --tokens 25
```

Run it as a module (`-m`), as shown; running `sample.py` as a script fails with an import error. It doesn't stop at `<|endoftext|>`, so each sample runs on into the start of another forecast. Mine gave Darwin winter tops of 29 to 35; the same prompt for Hobart gave 12 to 16.

```
PYTHONPATH=src .venv/bin/python -m research.tinystories.export ple-forecasts-s0 --tokenizer data/forecasts/vocab-1024/tokenizer.json
cp artifacts/tinystories/model.bin artifacts/tinystories/tokenizer.json ~/forecasts/
```

That gives a 0.75 MB `model.bin`, which the `cp` above copies to `~/forecasts`. The exporter always writes to `artifacts/tinystories/`, whatever model you export, so the next export (for example `training/train.sh` for Recipe Maker) replaces these files. Keep your own copy somewhere else.

To run it the way the device would, use `host/run.c` from the Recipe Maker repo. It is `host/recipe.c` cut down to take the prompt as token ids, so it works for any subject. It needs `vocab.h` regenerated from your tokeniser:

```
cd ~/esp32-recipe-maker && ~/esp32-ai/.venv/bin/python tools/make_vocab_h.py ~/forecasts/tokenizer.json && cc -O2 -o run host/run.c -lm
python
./run -m ~/forecasts/model.bin -n 3 $(~/esp32-ai/.venv/bin/python -c 'import sys; from tokenizers import Tokenizer; print(*Tokenizer.from_file(sys.argv[1]).encode(sys.argv[2]).ids)' ~/forecasts/tokenizer.json "$(printf 'City: Hobart\nSeason: Winter\nDay: Sunday\nForecast:')")
```

This stops at `<|endoftext|>`, as the device does. Run `git checkout firmware/src/vocab.h` afterwards to put Recipe Maker's back.

Reading samples only tells you so much. Because a program made this data, every forecast can be checked against the rules that made it. I generated 1,000 forecasts, 25 for each city and season, at the device's temperature of 0.7. A short script read each one and checked it:

| Rule | Forecasts that follow it | 
|---|---|
| Layout right | 1,000 of 1,000 | 
| Top within 4 degrees of that city's usual for the season | 908 | 
| Low 8 to 14 degrees under the top | 884 | 
| Sky and wind from the generator's lists | 1,000 | 

Not bad for about a minute of training. Then I counted how often each city got rain. Darwin and Hobart came out right, but Adelaide, Perth and Alice Springs got rain about half as often as they should.

That isn't the model getting rain wrong. It is the sampling temperature. The model gives a probability for every possible next token, and the temperature reshapes those probabilities before one is picked. At 1.0 they are used as the model learnt them. Below 1.0 the likelier choices get likelier still, and above 1.0 the unlikely ones get more of a chance.

So when the model has learnt that Adelaide is dry 75% of the time, sampling at 0.7 pushes that higher still and rain mostly disappears. At 1.0 most cities came within a few points of their real rate. Perth overshot to 39%; with 100 forecasts a city, some of that is just chance:

| City | Chance of rain in the data | Model at 0.7 | Model at 1.0 | 
|---|---|---|---|
| Darwin | 50% | 51% | 51% | 
| Sydney | 30% | 22% | 38% | 
| Adelaide | 25% | 11% | 29% | 
| Perth | 25% | 12% | 39% | 
| Alice Springs | 10% | 5% | 12% | 

The cost of 1.0 is more mistakes: tops within range fell from 908 to 791, and lows from 884 to 812.

Partly. I trained the same model for 2,000 steps instead of 500 (3 minutes 47 seconds) and scored it the same way:

|  | 500 steps | 2,000 steps | 
|---|---|---|
| Top within 4 degrees, at 0.7 | 908 | 998 | 
| Low 8 to 14 under the top, at 0.7 | 884 | 996 | 
| Top within 4 degrees, at 1.0 | 791 | 981 | 
| Adelaide rain at 0.7 (should be 25%) | 11% | 12% | 
| Adelaide rain at 1.0 | 29% | 24% | 
| Perth rain at 1.0 (should be 25%) | 39% | 23% | 

The temperatures are now nearly perfect, and at 1.0 the rain rates are close to the data, with Perth's overshoot gone. But at 0.7 the dry cities are still too dry: Adelaide gets rain 12% of the time, Sydney 17% instead of 30%, Alice Springs 4% instead of 10%.

That is the useful lesson. More training makes the model's probabilities more accurate. It can't undo what the sampling temperature does to them afterwards, because that happens in the app, not in the model. If the app needs the real odds, sample at 1.0 and train long enough that 1.0 doesn't bring mistakes with it.

It is the same trade-off in every app. Recipe Maker samples at 0.7 because a recipe with an odd ingredient is worse than a predictable one, and that is also why recipes drift towards the commonest ingredients. Bard Lite samples at 0.8, where a bit of variety matters more. Whichever you choose, run your tests at the temperature the device uses, or the numbers won't match what people see.

Start from Recipe Maker's firmware. Copy in your `model.bin` and `vocab.h`, change the prompt the app builds (Recipe Maker's prompts are token ids in `firmware/src/picks.h`, made by `tools/make_picks_h.py`) and change the screens to suit. A small model like this one can sit at its own offset in the `model` partition next to the others.

The other apps follow the same ten steps. What changes is what a token is and where the data comes from:

All five projects are open source, with versions that run on a computer and builds for other ESP32-S3 boards with PSRAM:
