Making tiny models faster and better on the ESP32-S3
Making tiny models faster and better on the ESP32-S3 Over the last few weeks I've written about five small language models that run on an M5Stack CoreS3: Recipe Maker, Bard Lite, Sprite Maker, Card Maker and Cocktail M
Making tiny models faster and better on the ESP32-S3
Over the last few weeks I've written about five small language models that run on an M5Stack CoreS3: Recipe Maker, Bard Lite, Sprite Maker, Card Maker and Cocktail Maker (a sibling of Recipe Maker). All five use the same model layout and the same inference code, from slvDev/esp32-ai.
The sixth is different: a diffusion model that draws butterflies, a convolutional network run by Espressif's ESP-DL. It had its own speed problem, and the fix explains something about the language models too.
The shared code made the language models worth going back to. Anything that made it faster made all five faster, so the changes went into the library, my fork justinmclean/esp32-ai, rather than into each app. This post covers what changed, what each change bought, and the things I measured that didn't help.
Here's where the apps ended up:
| App | Before | After |
|---|---|---|
| Bard Lite | 7.2 tokens a second | 23 tokens a second |
| Recipe Maker | 6.2 tokens a second | 17 tokens a second |
| Cocktail Maker | 7.8 tokens a second | 24 tokens a second (26.9 without a screen) |
| Sprite Maker | 18.4 seconds a sprite | 7.1 seconds a sprite |
| Card Maker | 0.12 to 0.35 seconds a rule set | 0.06 seconds |
| Diffusion | 30.6 seconds a butterfly | 3.2 seconds |
Two of them also got better, not just faster. A short fine-tune on their 4-bit weights put the main ingredient you pick into 236 of 260 test recipes, up from 220, and made 76% of sprites look like the character asked for, up from 66%.
The models
All five are transformers in slvDev's per-layer embedding layout. As well as the usual table that turns each token into a vector of numbers, every layer gets its own small table, looked up by the same token. Those tables hold most of the parameters, but each token only reads one row of each, straight from flash, so they cost almost no time. The work happens in a small core of ordinary transformer layers: for Bard Lite, Recipe Maker and Cocktail Maker that's 1.1 million parameters (6 layers, 96 numbers wide). Sprite Maker's core is 5 layers, 128 wide. Card Maker's whole model is 82 KB.
Each token, the core does a series of matrix-vector multiplies: a grid of 4-bit weights times a vector of activations (the numbers flowing through the model). That's almost all the time.
The basics: 4-bit weights
A model is trained with 32-bit floating-point weights. Recipe Maker's model has 8.2 million of them, which is 33 MB as floats. The CoreS3 has 16 MB of flash and 8 MB of PSRAM, so the weights have to shrink before they'll even fit.
Quantising means storing each weight as a small whole number plus a shared scale, and multiplying back when it's used. These models use 4 bits a weight: a whole number from -7 to 7. Every group of 128 weights along a row shares one 16-bit scale, chosen so the biggest weight in the group lands on 7 or -7. Here's the rounding from the training code:
@torch.no_grad()
def fake_int4(w):
x = w.float().reshape(-1, w.shape[-1])
out = torch.empty_like(x)
for a in range(0, x.shape[1], QAT_GROUP):
seg = x[:, a:a + QAT_GROUP]
sc = (seg.abs().amax(dim=1, keepdim=True) / 7).clamp_min(1e-8).half().float()
out[:, a:a + QAT_GROUP] = torch.clamp(torch.round(seg / sc), -7, 7) * sc
return out.reshape(w.shape).to(w.dtype)
A worked example with a group of four. Take the weights 0.21, -0.07, 0.35 and -0.50. The biggest is 0.50, so the scale is 0.50 / 7 = 0.0714. Dividing by the scale gives 2.94, -0.98, 4.90 and -7, which round to 3, -1, 5 and -7. Those are what's stored. On the board they come back as 3 x 0.0714 = 0.214, then -0.071, 0.357 and -0.500: close to the originals, but not equal.
Two 4-bit weights fit in a byte, and the scale adds 16 bits for every 128 weights, so each weight costs about 4.1 bits instead of 32. Recipe Maker's model is 4.2 MB on the board, and Bard Lite's is 1.5 MB.
Smaller is also faster. The core's weights are read from PSRAM for every token, and 4-bit weights are an eighth as many bytes to read.
The price is accuracy, because every weight is a little off. I measure that with held-out loss: how surprised the model is, on average, by the next token of text it never trained on (the cross-entropy, in nats; lower is better). The difference between the full-precision model's loss and the 4-bit model's loss is what rounding cost. That number comes back later in the post, because one of the models was losing far more than the others.
Where the time went
I timed Bard Lite on the CoreS3 before changing anything:
| Per token | Time |
|---|---|
| Running the model | 95 ms |
| Redrawing the scene on screen | 37 ms |
| Picking the token | 4 ms |
So the model was the target. Here's what each change did to the model's time per token on Bard Lite's model, with no screen drawing. The first row is from a typical 200-token scene; the rest are averaged over all 256 positions of the context:
| Build | ms/token |
|---|---|
llm.h alone, as the apps shipped |
95 |
| Vector kernels, one core | 61.8 |
| + quantised attention cache | 53.0 |
| + second core | 50.2 |
| + 176 KB of weights in internal RAM | 44.2 |
Vector instructions
The ESP32-S3 has a small set of vector instructions (Espressif calls them PIE): 128-bit registers that multiply sixteen 8-bit numbers at once and add the results into a 40-bit accumulator. llm.h is plain C, so it never used them.
msb-msb/esp32-ai had kernels (small hand-written assembly routines) for this, for rows of 96 and 128 weights. They're the core of llm_s3_dot.S in my fork, with a general version added for any row length. The trick is getting 4-bit weights into 8-bit lanes without unpacking them one by one. Each byte holds two weights. Masking the byte with 0xF0 keeps the high weight where it is, which reads as an 8-bit number exactly 16 times too big. Shifting the byte left by 4 first does the same for the low weight. Both are 16 times too big, so the sum is too, and one shift right by 4 at the end divides it back exactly. From the comment in the assembly, where ACCX is the accumulator:
* With M = 0xF0 in every byte:
* (w & M) read as int8 = 16 * hi
* ((w << 4) & M) read as int8 = 16 * lo
* so ACCX = 16 * dot exactly, and out[r] = ACCX >> 4.
The vector unit multiplies 8-bit numbers, so the activations have to be 8-bit too. Before each matrix multiply, the input vector is rounded to 8 bits, with one scale for the whole vector, the same way the weights are rounded. llm.h already had that as an option (LLM_INT8_ACT), so I could check what it costs on a computer first. On Bard Lite's model, held-out loss moved from 4.0104 to 4.0107.
The kernels plug into hooks llm.h already had, so llm.h itself didn't change. An app adds one call after loading:
#include "llm_s3.h"
#include "llm.h"
llm_load(model_bytes, &model);
// NULL: repacked weights go in PSRAM; 1: use both cores; up to 96 KB of weights in internal RAM
int n = llm_s3_init(&model, NULL, 1, 96 * 1024);
if (n < 0) { /* the plain C code still runs, just slower */ }
At start-up llm_s3_init repacks every weight into the kernels' layout, then runs every row of every tensor through both the vector path and the plain C path and compares them bit for bit. If anything differs, it leaves the model alone. That check runs on every boot, so a kernel bug shows up as a slower app, not wrong output.
That took Bard's model from 95 to 61.8 ms a token.
A smaller attention cache
Attention is how a transformer looks back at earlier tokens. For each token it stores a key (what this token offers) and a value (what to pass on) in every layer. Every new token compares itself with all the stored keys (one dot product each) and blends the stored values according to how well they matched. It does this in several heads at once, each working on its own slice of the numbers: Bard Lite has 4 heads of 24 numbers each. The store of keys and values is the attention cache, and it's read in full for every token, so the later in the context, the slower each token gets.
llm.h kept the cache as 32-bit floats. slvDev/esp32-ai#24, by barkinsarikartal, stores keys as 8-bit numbers and values as 16-bit, each with its own scale per token and head. Comparing with the keys and blending the values then run on the vector unit too. On Bard's model the last quarter of the context went from 85 to 68 ms a token, and held-out loss moved by at most 0.002 on any of the five models.
Turning it on is a build flag, -DLLM_KV_QUANT, plus one call that gives the cache its memory:
llm_kv_quant_bind(&model, &s,
ps_malloc(llm_kv_main_bytes(&model)),
ps_malloc(llm_kv_key_bytes(&model)),
malloc(llm_kv_hot_bytes(&model)));
This matters most for Sprite Maker, because it always pays for the slowest part. The cache grows by one entry per token, and each new token reads every entry before it, so the later the token, the slower it is. A Bard Lite scene often stops before the end of its 256-token context. A sprite never does: it's 16 x 16 pixels, one token each, so every sprite writes all 256 tokens, including the slowest last quarter.
It also shrinks the cache. Sprite Maker's model stores a key and a value of 128 numbers per token in each of its 5 layers. As 32-bit floats that's 1.3 MB for a full sprite. With 8-bit keys and 16-bit values it's 0.5 MB.
The second core
The ESP32-S3 has two cores, and the apps used one. Before the vector kernels, splitting each matrix multiply across both cores saved about 20%. With the kernels, a worker task on the second core takes half the rows of every multiply of 128 rows or more, and half the attention heads. That saved much less: 53.0 to 50.2 ms on Bard's model.
Internal RAM
The weights live in PSRAM, an external memory chip that's much slower than the ESP32-S3's own 512 KB of internal RAM. Every weight is read once per token, so each byte moved inside saves the same time: about 1 ms a token for every 32 KB on Bard's model.
The catch is that the app needs internal RAM too, for its stack and its screen. So llm_s3_init takes a budget. Bard Lite gives it a fixed 176 KB, which left 41 KB free and ran normally, and took it from 50.2 to 44.2 ms. Recipe Maker, Cocktail Maker and Sprite Maker work the budget out at start-up, keeping 48 KB back:
size_t free_sram = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
size_t budget = free_sram > SRAM_RESERVE ? free_sram - SRAM_RESERVE : 0;
int n = llm_s3_init(&model, NULL, 1, budget);
Cocktail Maker has a build that holds two models at once (Recipe Maker's and its own), and it splits the budget between them. Card Maker's rule sets take 0.06 seconds already, so it moves nothing.
Fitting the 32 KB data cache
The ESP32-S3 reads PSRAM through a 32 KB data cache. Whether that helps depends on how often each weight is used.
The diffusion model is a convolutional network with 8-bit weights. Its first version used plain 3x3 convolutions throughout and took 30 seconds a butterfly. ESP-DL can profile each layer, and five layers took 85% of the time, running 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. A convolution uses each weight at every pixel, so weights that don't fit the cache are fetched from PSRAM again and again.
The fix is from Google's MobileNet: split each big 3x3 convolution into a depthwise 3x3, which looks at each channel by itself, then a pointwise 1x1, which mixes the channels at each pixel. Only layers too big for the cache are split. The limit is 24 KB rather than 32, to leave room in the cache for the image data the layer is working on:
CACHE_WEIGHTS = 24 * 1024 # bytes of int8 weights a 3x3 layer may have and still run fast
def conv3(cin, cout, sep):
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 83 KB of weights down to 10 KB:
| 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 |
Two thirds of the arithmetic, six times faster: most of the gain is the cache, not doing less. A diffusion model starts from noise and removes a little of it each step, running the whole network every time. Taking 10 steps instead of 20 halved the time again, to 3.2 seconds. The 10-step butterflies differ from the 20-step ones by less than rounding to 8 bits changes them on its own. conv3 and the rest of the diffusion model's ESP-DL helpers are now in the library too, as src/espdl.py.
The language models are the opposite case. Writing one token uses each weight exactly once, so there's nothing for the cache to keep. That's why moving weights into internal RAM pays off byte for byte: every weight read from PSRAM costs the same, and the cache can't hide any of it.
Sharing keys and values between heads
A model with 4 attention heads stores 4 keys and 4 values per position per layer. With multi-query attention, all 4 query heads share one key and one value, so the cache is a quarter of the size and attention reads a quarter as much. It has to be trained that way: --kv-heads 1. To keep the comparison fair, the parameters saved in attention go to the feed-forward layers (the other half of each transformer layer) instead.
I trained Bard's model each way three times, each from a different random starting point (a seed), and measured them on the board with both cores and the smaller cache:
| Key/value heads | Held-out loss, 4-bit, mean of 3 seeds | ms/token | Last quarter of the context |
|---|---|---|---|
| 4 (the default) | 4.018 | 51.5 | 61.7 |
| 2 | 4.028 | 48.5 | 59.3 |
| 1 | 4.011 | 43.4 | 48.0 |
The loss moved by up to 0.13 between seeds of the same setting, far more than between settings, so sharing cost nothing I could measure. That's why there are three runs of each: with one each, I could have shown any of the three winning.
Those were trained from scratch. To use it in an app without retraining, a shipped model can be converted: average its 4 key heads into 1 and its 4 value heads into 1, as in Google's grouped-query attention paper (Ainslie and others, 2023), then fine-tune briefly so the rest of the model adapts. Straight after averaging, Bard Lite's held-out loss jumped from 3.99 to 5.16. After an 800-step fine-tune on the 4-bit weights it was 4.001, against 3.997 for the same fine-tune with all 4 heads kept. On the board, with the screen as it was drawn then, Bard Lite went from 13.1 to 14.2 tokens a second.
Loss isn't the whole story, though. I had the converted model write 60 scenes and counted how many it ended itself, by writing the end-of-text token, rather than running into the 256-token limit. It ended 47. The shipped model ended 58. That could have been the extra 800 steps rather than the heads, since Bard's training stops at 1,600 steps because held-out loss starts rising after that. But the same 800-step fine-tune with all 4 heads kept ended 59, so it was the conversion.
Training a one-head Bard from scratch with the shipped recipe, and the shipped feed-forward width so it stays as fast, didn't fix it. Over three seeds its held-out loss was about 0.03 worse than three seeds of the 4-head recipe (4.040 against 4.013), and it ended 50 to 56 scenes out of 60. Then the 4-head recipe itself turned out to be just as variable: one of its seeds ended only 48. So a model that ends 47 isn't outside what the shipped recipe can produce. The seed that shipped happened to be a good one.
With the faster screen drawing (below), the speed difference is bigger. Over 10 scenes on the board, the converted one-head model ran at 36.9 ms a token, 27.1 tokens a second, against 44.3 ms, 22.6 tokens a second, with 4 heads. That's about 20% faster, in exchange for scenes that run to the limit a little more often.
I kept 4 heads. A 200-token scene already appears in about 9 seconds, far faster than anyone reads it, so 7.4 seconds wouldn't be noticed. A scene cut off mid-speech one time in five would be.
Sprite Maker should gain more, since every sprite runs through all 256 positions, including the slow last quarter. It did: converted to one head, it drew a sprite in 3.9 seconds instead of 7.1 on the board. Quality fell much further, though. After a 1,500-step fine-tune on the 4-bit weights, held-out loss was 1.330 against 1.298, and the classifier recognised 68% of sprites as their character, against 76% for the shipped model. The same fine-tune with all 4 heads kept scored 1.296 and 80%, so the drop is the heads, not the extra training. The one-head model's loss stopped improving after 500 steps. Sprite Maker learns its basics from 1.4 million sprites before it's fine-tuned on the characters, and 58,000 character sprites (mirrored copies included) can't put back what averaging the heads took out. Doing it properly means going back to that first stage, which is a longer job than a fine-tune.
Skipping work on the prompt
Every app starts by feeding the model a prompt. For Recipe Maker that's the picks, such as Main: Chicken, Dish: Curry, about 10 tokens. The model reads them one token at a time, the same way it writes, so each prompt token goes through the whole model.
The last step of the model is the output layer. It turns the model's final numbers into a score for every token in the vocabulary, and the next token is picked from those scores. While reading a prompt, those scores aren't needed: the next token is already known, because it's the next token of the prompt. Only the last prompt token's scores matter, as they pick the first new token.
llm_forward_prompt skips the output layer for every prompt token but the last. Everything else runs as before, so the model ends up in exactly the same state. How much that saves depends on the vocabulary. Recipe Maker has 8,192 tokens, and its output layer does 0.8 million multiply-adds a token against 1.1 million for the rest of the model, so skipping it saves about 40% of the work per prompt token. A 10-token prompt went from 851 to 565 ms.
Picking tokens faster
Picking each token used top-k sampling: keep the 40 most likely tokens and choose among them at random. The apps kept a list of the best 40 so far, and for each of the 2,048 tokens in Bard Lite's vocabulary searched all 40 for the weakest one to replace. llm_sample_top_k keeps them in a heap, which finds the weakest at once, and picking a token went from 3.6 ms to 0.29 ms.
Drawing only what changed
With the model down to about 44 ms a token, the 37 ms redraw was nearly half of Bard Lite's time. The app shows the scene word-wrapped, with older lines scrolling off the top. For every token it wrapped the whole scene again, cleared a 240 x 240 pixel image in PSRAM, drew every line into it, and sent the whole image to the display. At 2 bytes a pixel that's 115 KB, and the display's 40 MHz bus takes about 23 ms to carry it.
Almost none of that changed from one token to the next. A token adds a few letters to the last line, and a line that a newline or a wrap has ended never changes again. So the app now keeps the finished lines, re-wraps only the unfinished last one, and remembers what each row of the screen shows. It draws only the rows that differ, each in a one-row image (240 x 16 pixels, 7.5 KB) in internal RAM. Usually that's one row a token. When a new line scrolls the text up, every row changes and all of them are drawn, but that happens once a line, not once a token.
Bard Lite went from 76.6 to 42.0 ms a token on the board, 13.1 to 23.8 tokens a second over five scenes. The model hadn't changed, and the screen looks the same.
Recipe Maker and Cocktail Maker draw differently. They keep the whole recipe in one tall image in PSRAM (1,400 rows), so a finished one can be scrolled by dragging. Each token redrew its line into that image, which is cheap, but then did two expensive things. It cleared the image from the current line all the way to the bottom, up to 440 KB of PSRAM writes, and it sent the whole visible view to the display, about 70 KB. Everything below the text is already black, so now only the rows the current line drew last time are cleared. While the view hasn't scrolled, only the rows that changed are sent. Once the recipe is taller than the screen, each new line scrolls the view and the whole view is sent, again once a line rather than once a token.
| App | Before | After |
|---|---|---|
| Bard Lite | 76.6 ms a token | 42.0 ms |
| Cocktail Maker | 90.6 ms a token | 41.3 ms |
| Recipe Maker | 103.9 ms a token | 59.4 ms |
Each is timed on the board over the same requests before and after: 5 scenes for Bard Lite, 12 drinks and 12 recipes for the others. Recipe Maker gains least in proportion because its model is the slowest of the three: its 8,192-token vocabulary makes the output layer bigger. Cocktail Maker now runs at 24.2 tokens a second against 26.9 in the build with no screen at all, so drawing costs it about 4 ms a token.
Better, not just faster: training on 4-bit weights
Back to the rounding from the start of the post. How much it costs depends on the model. Here's the added held-out loss on each model's own test text:
| Model | Added by rounding to 4 bits |
|---|---|
| Bard Lite | 0.003 |
| Card Maker | 0.010 |
| Sprite Maker | 0.035 |
| Recipe Maker | 0.112 |
Bard Lite loses almost nothing because it was trained with quantisation-aware training (QAT): for its last 300 steps, every forward and backward pass ran on the weights rounded exactly as the export rounds them, while the updates went to the full-precision weights. The model learns weights that still work after rounding.
if qat: # forward and backward on the 4-bit weights, update the full ones
full = [p.data.clone() for p in qat_ps]
for p in qat_ps:
p.data.copy_(fake_int4(p.data))
logits, loss = model(x, y)
...
loss.backward()
if qat:
for p, f in zip(qat_ps, full):
p.data.copy_(f)
Recipe Maker was trained without it, and lost the most. I didn't retrain it from scratch. I fine-tuned the shipped model for 1,000 steps, every one of them on the 4-bit weights, at a tenth of the original learning rate. That took 5 minutes on an M3 MacBook:
| Recipe Maker | Shipped | After the QAT fine-tune |
|---|---|---|
| Added by rounding | 0.112 | 0.004 |
| Held-out loss on the board | 2.050 | 1.976 |
| Main ingredient in the list (of 260) | 220 | 236 |
| An ingredient listed twice | 20 | 7 |
| Method uses an ingredient not in the list | 21 | 20 |
The recipe counts come from the app's pick test: 20 recipes for each of 13 picks, written with the 4-bit weights. 3,000 steps did no better than 1,000.
Sprite Maker was the other model trained without QAT. It lost less to rounding than Recipe Maker, but the same fine-tune, 500 steps this time, fixed that too:
| Sprite Maker | Shipped | After the QAT fine-tune |
|---|---|---|
| Added by rounding | 0.035 | 0.009 |
| Held-out loss on the board | 1.315 | 1.298 |
| Sprites that look like the character asked for | 66% | 76% |
| Copies of training sprites (of 1,875) | 0 | 0 |
The third row comes from the app's own check: a small classifier, trained on real sprites, judges whether each generated knight looks like a knight. It's right 87% of the time on real sprites, so that's the ceiling. Robots went from 56% to 81%, ninjas from 65% to 85% and frogs from 62% to 82%. A small change in loss made a big difference to those scores. 1,500 steps did no better than 500.
What didn't help
GPTQ. Snikitha-V/ple-esp32-28.9M rounds weights with GPTQ, which picks each rounded weight to cancel the error of the ones before it, using sample inputs. I tried it on four of the models:
| Model | Full precision | Plain rounding | GPTQ |
|---|---|---|---|
| Bard Lite (trained with QAT) | 3.9897 | 3.9921 | 3.9957 |
| Card Maker | 1.7723 | 1.7824 | 1.7889 |
| Sprite Maker | 1.2797 | 1.3148 | 1.2986 |
| Recipe Maker | 1.9520 | 2.0611 | 2.0429 |
It recovered about half of Sprite Maker's rounding loss and a sixth of Recipe Maker's, and made the other two slightly worse. QAT did better on Recipe Maker and matched it on Sprite Maker (1.2977 against 1.2986). QAT also changes only the training: the exporter still rounds each weight to the nearest 4-bit value, as before. GPTQ would have needed a new export step that runs sample inputs through the model and adjusts the weights as it rounds them. So I left GPTQ out.
Smaller groups. Rounding groups of 32 weights instead of 128 gives each weight a better-fitting scale. It took Recipe Maker's rounding loss from 0.110 to 0.086, at 0.38 MB more flash. QAT took it to 0.004.
Rounding the activations once. Each matrix multiply rounds its input vector to 8 bits. Where two multiplies take the same input, that rounding is done twice. In these models only two do (the feed-forward gate and up projections), so rounding once would save about 0.05% of the time. Not worth the code.
The output scores in internal RAM. I tried putting the buffer that holds the output layer's scores in internal RAM instead of PSRAM. It made no difference I could measure, so it stayed out, and the internal RAM went to weights instead, where every 32 KB is worth a millisecond.
Dropout and distillation on Bard Lite. Bard Lite's training text is small: 1.5 million tokens of Shakespeare, and training reads it about four times over. By the end, its loss on the training text was 3.26 against 3.99 on held-out text. A gap like that means the model is partly memorising, and two common fixes for it are dropout and distillation.
Dropout switches off a random part of the model at every training step, so it can't lean on any one path through it. Distillation (Hinton and others, 2015) trains the small model to match a bigger, already trained model's whole set of scores for the next token, not just the one right answer. I trained a teacher twice as wide with 8 layers, then trained Bard Lite three times each with dropout of 0.1, with the teacher, and with both. Held-out loss on the 4-bit weights:
| Bard Lite | Mean of 3 runs | The 3 runs |
|---|---|---|
| Neither (the baseline) | 3.953 | 3.941, 3.942, 3.977 |
| Dropout | 4.007 | 3.987, 4.019, 4.016 |
| Distillation | 3.960 | 3.953, 3.964, 3.962 |
| Both | 3.990 | 3.968, 3.998, 4.004 |
| The teacher, for reference | 3.882 |
Dropout made every run worse than every baseline run. It also slows learning, because each step trains only part of the model, and Bard Lite trains for just 1,600 steps. Here that cost more than the memorising did. Dropout usually pays off in longer training, where the held-out loss would otherwise start rising, and Bard Lite's was still falling when training stopped.
Distillation landed within the spread of the baseline runs, so it made no difference I can measure. The teacher is the reason: it was only 0.07 better than Bard Lite. A bigger model can't get much more out of 1.5 million tokens than a small one, so it had little extra to pass on. Distillation needs a teacher that's clearly better, which needs more data than Bard Lite has. Recipe Maker may be a better fit: its training text is 34.9 million tokens, 23 times Bard Lite's, which is enough for a bigger teacher to pull clearly ahead. I haven't tried it yet. Training that teacher takes several hours.
Three bits, or three weights to a byte. If 4 bits works, why not fewer? I tried 3 bits, 2 bits, and packing three weights into each byte: two 3-bit and one 2-bit, with a separate scale for the 2-bit ones. Each got the same 800-step QAT fine-tune from the shipped Bard Lite model:
| Bard Lite | Weights | Held-out loss before QAT | After QAT |
|---|---|---|---|
| 4 bits | 1.48 MB | 3.992 | 3.997 |
| 3 bits | 1.12 MB | 4.104 | 4.013 |
| 3 + 3 + 2 to a byte | 1.05 MB | 4.467 | 4.057 |
| 2 bits (-1, 0 or 1) | 0.76 MB | 7.002 | 4.308 |
QAT won back most of the loss, but not all of it. Packing three to a byte still cost 0.060, more than the spread between training runs, to save 0.43 MB of flash that wasn't short. It would also need new vector kernels to unpack, and only then might it be faster. I stopped there.
Not every experiment pays
As you can see, a lot of this didn't help. Dropout and distillation on Bard Lite took ten training runs, about an hour, and made nothing better. GPTQ, smaller groups and fewer bits all took time to set up and measure, and none went into the apps. The Recipe Maker teacher I'd need to test distillation properly would take about four hours to train before it could tell me anything.
That time isn't wasted if it answers a question, but it's worth asking up front whether the answer could matter. Before a long run, it's worth checking the cheap things first: whether the model is short of data (then a bigger teacher won't help), whether it's still improving when training stops (then dropout won't help), and whether the saving is something the board is actually short of (flash wasn't). The speed in this post came from measuring where the time went. Training paid off only where it fixed a measured problem: Recipe Maker and Sprite Maker losing quality to rounding.
What I'd tell someone starting out
- Time it on the board before changing anything, and again after. The screen took 37 ms of Bard's 136 ms a token at the start, which told me how much a faster model could ever help. Once the model was faster, the same 37 ms was the biggest cost left.
- Check every speed-up for quality on a computer first.
host_verify/ppl.cruns the device's C code over held-out text, so I knew what 8-bit activations and the smaller cache cost before flashing anything. - Make the fast path prove itself. The bit-for-bit self-test at boot means the vector kernels can't silently change the output.
- Train on the weights you'll ship. QAT is a few lines in the training loop and recovered almost all of Recipe Maker's rounding loss in a 5-minute fine-tune.
- Use more than one seed. Seeds of the same model differed by up to 0.13 in loss, more than any setting I compared.
- Know how often each weight is used. A convolution reuses its weights at every pixel, so fit them in the 32 KB cache. A language model uses each weight once per token, so the cache can't help and internal RAM can.
Links
-
justinmclean/esp32-ai, the fork with everything in this post;
runtime/README.mdcovers using it in your own app - slvDev/esp32-ai, the original model layout and inference code
- msb-msb/esp32-ai, the vector kernels
- slvDev/esp32-ai#24, the quantised attention cache
- Snikitha-V/ple-esp32-28.9M, the GPTQ export I compared against
- esp32-diffusion, the butterfly model
- The apps: esp32-bard-lite, esp32-recipe-maker, esp32-cocktail-maker, esp32-sprite-maker, esp32-card-maker
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.