Small Language Models on Microcontrollers: Memory Budgets, Quantization, KV Cache and What Fits in Kilobytes
In November 2026 a hobbyist shipped TINY 2.1, a 367,000-parameter question-answering transformer that runs from a floppy disk on a 486DX or Pentium PC under MS-DOS. Its README says it needs about 540 KB of free conventional memory. That machine has less usable RAM than a mid-range Cortex-M7. So the old question has turned into an engineering one: how much of a language models on microcontrollers story is real, and how much is a demo? The answer comes down to arithmetic you can do before you train anything. You need bytes per parameter in flash, bytes per token of KV cache in SRAM, and multiply-accumulates (MACs) per generated token. This post works through that arithmetic with real model configurations, real published throughput and the real operator coverage of today’s runtimes. You will leave with a budget calculator, a KV ring buffer in C, and a clear sense of which tasks a kilobyte-scale transformer can handle and which it cannot.
What this covers: flash and RAM budgets, quantization formats, the KV cache formula, vocabulary cost, Cortex-M and Ethos-U throughput, runtime support, realistic use cases, a hybrid design and OTA security.
Context and Background
The case for language models on microcontrollers starts with a 2023 result showing that a coherent model could be tiny. Ronen Eldan and Yuanzhi Li’s TinyStories paper (arXiv 2305.07759) trained on a synthetic corpus of children’s stories. They showed that models with under 10 million total parameters, some with a single transformer block, could produce fluent and consistent short stories. Their point of comparison is telling. They note that roughly 125M-parameter models such as GPT-2 small rarely produce coherent English beyond a few words on general web text. Narrow the data distribution and you can shrink the model by more than an order of magnitude.
Andrej Karpathy’s llama2.c turned that result into something you can port. It is a single-file C inference loop for a Llama-2-style architecture, plus a family of TinyStories checkpoints. The smallest is stories260K: dimension 64, 5 layers, 8 query heads, 4 key/value heads, a 512-token custom vocabulary and a 512-token context. The “original” stories15M uses dimension 288, 6 layers, 6 heads, the 32,000-token Llama 2 vocabulary and a 256-token context. These two configurations are the closest thing the field has to reference workloads, so this post uses them throughout.
The embedded community ported them almost at once. One public ESP32-S3 port, esp32-llm, reports about 30 tokens/s for the fp32 260K model and about 12 tokens/s for a 3.3M-parameter int8 model. The author notes that the second figure is close to a computed memory-bandwidth ceiling of 13.1 tokens/s. In August 2026 another ESP32-S3 project ran a 28.9M-parameter, 4-bit model at about 9.9 tokens/s by keeping a 25M-parameter embedding table in flash.
Meanwhile the conventional TinyML stack has matured around CNNs, as covered in our TFLite Micro int8 and CMSIS-NN tutorial. The open question for language models on microcontrollers is how much of that tooling transfers to autoregressive transformers. Those models add two things CNNs never needed. The first is state that grows with every token, the KV cache. The second is a vocabulary-sized output layer.
The Memory Math of Language Models on Microcontrollers
Direct answer: A language model fits on a microcontroller when three budgets close at once. Quantized weights must fit in flash. The KV cache plus activation buffers must fit in on-chip SRAM. Per-token MACs and weight bytes must fit your latency target. In practice that means roughly 0.25 to 4 million parameters, int8 or int4 weights, a vocabulary under a few thousand tokens and a context of 128 to 512 tokens.

Figure 1: Where each part of a tiny transformer lives on a typical MCU. Weights stream from flash, while state that changes per token stays in SRAM.
Figure 1 shows the basic split. Flash, the read-only storage that is often executed in place, holds the quantized weights, the tokenizer’s string table and the runtime code. SRAM holds whatever changes per token: activation vectors, the attention-score scratch, the logits buffer and the KV cache. PSRAM is external pseudo-static RAM on a QSPI or octal-SPI bus. It is common on ESP32-S3 boards and acts as a slow overflow tier. Its bandwidth, not the CPU, usually sets your token rate.
Budget one: weights in flash
Flash cost is parameters times bytes per parameter, plus quantization metadata. The table below is computed directly from parameter counts. Int8 assumes one fp32 scale per output row, which adds well under 1 percent. Int4 assumes groups of 32 weights, each with an fp16 scale, which works out to 0.5625 bytes per parameter. Ternary is shown two ways: packed at 2 bits per weight, which is the practical case, and at the information-theoretic 1.58 bits.
| Model (params) | fp32 | fp16 | int8 | int4 (g32) | ternary 2-bit | ternary 1.58-bit |
|---|---|---|---|---|---|---|
| stories260K (≈260K) | 1,016 KiB | 508 KiB | 254 KiB | 143 KiB | 64 KiB | 50 KiB |
| TINY 2.1 (367K) | 1,434 KiB | 717 KiB | 358 KiB | 202 KiB | 90 KiB | 71 KiB |
| 1M-class (illustrative, below) | 3,968 KiB | 1,984 KiB | 992 KiB | 558 KiB | 248 KiB | 196 KiB |
| 3.3M | 12.6 MiB | 6.3 MiB | 3.1 MiB | 1.8 MiB | 806 KiB | 637 KiB |
| stories15M (≈15.2M) | 57.9 MiB | 29.0 MiB | 14.5 MiB | 8.1 MiB | 3.6 MiB | 2.9 MiB |
| 28.9M | 110 MiB | 55 MiB | 27.6 MiB | 15.5 MiB | 6.9 MiB | 5.4 MiB |
Two published sizes check the arithmetic. The stories260K.bin checkpoint on Hugging Face is 1.06 MB in fp32, which matches about 1,016 KiB. TINY 2.1 reports 380 KB total for program plus 8-bit per-row-scaled weights. That fits 358 KiB of weights plus a small Turbo C executable. The 28.9M ESP32-S3 model reports 14.9 MB at 4-bit, about 0.52 bytes per parameter. That implies a larger group size or less scale overhead than my g32 assumption.
What does this mean for real parts? An STM32H743 has up to 2 MB of internal flash, so a 1M-class int8 model fits with room for firmware. stories15M does not fit at int8. It needs external QSPI flash, or int4 plus a much smaller vocabulary. Ternary weights, popularized by BitNet b1.58 (Ma et al., 2024), cut flash by 4x against int8. However, they must be trained in, not applied after training. No mainstream MCU runtime ships a ternary GEMV kernel today, so you would write your own.
Budget two: the KV cache and activations in SRAM
The KV cache stores each layer’s key and value vectors for every past position. Attention can then reuse them instead of recomputing them. Its size is:
KV bytes = layers × kv_heads × d_head × seq_len × 2 × bytes_per_element
The factor of 2 covers keys and values. Here kv_heads is the number of key/value heads, which is smaller than the query-head count under grouped-query attention (GQA). Our deep dive on MLA vs GQA vs MQA KV cache compression covers those variants at datacenter scale. The same formula decides your fate at kilobyte scale.
Worked numbers, computed from the published configurations:
| Model | Layers | KV heads × d_head | Context | fp32 KV | fp16 KV | int8 KV |
|---|---|---|---|---|---|---|
| stories260K | 5 | 4 × 8 | 512 | 640 KiB | 320 KiB | 160 KiB |
| stories260K | 5 | 4 × 8 | 128 | 160 KiB | 80 KiB | 40 KiB |
| 1M-class (illustrative) | 4 | 4 × 32 | 256 | 1,024 KiB | 512 KiB | 256 KiB |
| 1M-class with GQA | 4 | 2 × 32 | 256 | 512 KiB | 256 KiB | 128 KiB |
| stories15M | 6 | 6 × 48 | 256 | 3,456 KiB | 1,728 KiB | 864 KiB |
| stories15M | 6 | 6 × 48 | 128 | 1,728 KiB | 864 KiB | 432 KiB |
This is the central claim of the post, and most write-ups on language models on microcontrollers miss it. At microcontroller scale, the KV cache routinely costs as much as the weights, or more. stories260K needs 254 KiB of int8 weights but 640 KiB of fp32 KV at full context. The weights fit an RP2350’s 520 KB of SRAM. The naive KV cache does not. Weights can live in flash, which is cheap and plentiful. The KV cache must be writable and fast, so it competes for the scarcest resource on the chip.
Activation buffers add a smaller amount. In a llama2.c-style decode loop you hold three model-width vectors, two FFN-width vectors, the query, an attention-score row per head and the logits vector. For stories15M that is about 36,000 floats, or 141 KiB in fp32. Of that, 125 KiB is the 32,000-entry logits buffer alone. For stories260K the total is about 20 KiB, and for the 1M-class design about 11.5 KiB.
Budget three: MACs and bytes per token
Decoding one token is essentially a matrix-vector multiply (GEMV) over every non-embedding weight. Then comes attention over the cache, then the classifier. Attention costs about 2 × layers × d_model × t MACs at position t, covering QK scores and the weighted sum of V. The classifier costs vocab × d_model MACs. Using the published shapes:
| Model | Non-embedding MACs | Attention MACs (at t) | Classifier MACs | Total per token | Classifier share |
|---|---|---|---|---|---|
| stories260K | 226,560 | 163,840 (t=256) | 32,768 | ≈423K | 8% |
| 1M-class | 950,272 | 131,072 (t=128) | 65,536 | ≈1.15M | 6% |
| stories15M | 5,971,968 | 442,368 (t=128) | 9,216,000 | ≈15.6M | 59% |
Two non-obvious facts drop out. First, in a model as narrow as stories260K, attention over a 256-token context costs almost as much as all the weight matmuls combined. Context length is a compute cost as well as a memory cost. Second, in stories15M the classifier over a 32,000-token vocabulary is 59 percent of the work. The vocabulary is the model.
Deeper Analysis: Vocabulary, Throughput, Runtimes and Code
Why vocabulary size dominates tiny models
The embedding table and the classifier are both vocab × d_model. llama2.c’s stories models tie them by sharing one matrix. For stories15M that matrix is 32,000 × 288 = 9.2M parameters, or 61 percent of the 15.2M total. The other 39 percent is the actual transformer. Swap in a 512-token vocabulary and the same table shrinks to 147K parameters. That is how stories260K exists at all.
Small vocabularies are not free. A 512-token SentencePiece vocabulary, or a character-level model like TINY 2.1, splits text into more tokens than a 32K BPE vocabulary. Each character-level step costs a full forward pass, and the KV cache grows per token, not per word. If your average word needs four tokens instead of 1.3, you pay about 3x in latency and KV for the same sentence. Our explainer on BPE, SentencePiece and tiktoken tokenization covers how merge tables set that ratio. On an MCU the sweet spot is usually a domain-trained vocabulary of 256 to 4,096 tokens. It is small enough that the classifier stays cheap, and large enough that common command words become single tokens.
There is also a tokenizer storage cost. The vocabulary strings and merge scores for 512 tokens took about 6 KB in the published tok512.bin. A 32K vocabulary takes hundreds of kilobytes, which competes with weights for flash.
Decode dataflow on a Cortex-M

Figure 2: The per-token decode loop. Every weight byte is read once per token, and the KV ring grows by one slot per layer.
Figure 2 traces one generated token. The token id selects an embedding row, which is a gather, not a matmul. Each layer applies RMSNorm, then the Q, K and V projections as int8 GEMVs. It writes K and V into the current ring-buffer slot and scores the query against every cached key. A fixed-point softmax follows, then a weighted sum of cached values and the SwiGLU feed-forward block. After the last layer comes the classifier, then an optional grammar mask that zeroes illegal tokens, then argmax or sampling. The chosen id feeds back as the next input.
The loop is dominated by streaming weights, so throughput has two ceilings. Take the minimum of the two:
- Compute ceiling = clock × effective MACs per cycle ÷ MACs per token
- Bandwidth ceiling = effective weight bandwidth ÷ weight bytes per token
The esp32-llm port gives a real anchor for the bandwidth term. Its 3.3M int8 model reached about 12 tokens/s against a stated 13.1 tokens/s memory limit. That implies roughly 43 MB/s of effective PSRAM bandwidth (3.3 MB × 13.1 per second, my derivation). At that bandwidth, int8 stories15M streams about 15 MB per token and tops out near 3 tokens/s whatever the CPU does. That is why the 28.9M ESP32 project moved most of its parameters into an embedding table. Only about 6 rows, around 450 bytes, are read from flash per token. The technique borrows Gemma 3n’s per-layer embeddings, which trade parameter count for bandwidth.
Throughput estimates on Cortex-M4, M7, M55 and Ethos-U
The table below is illustrative. It shows compute ceilings for the 1M-class int8 model at about 1.15M MACs per token. The effective MACs-per-cycle values are my engineering assumptions, not measurements. Cortex-M4’s DSP extension has dual 16-bit MAC instructions such as SMLAD, but int8 GEMV kernels lose cycles to unpacking and loads. Helium (MVE) on Cortex-M55 processes 16 int8 lanes per 128-bit instruction across two beats. That gives a peak of about 8 int8 MACs per cycle by my derivation, and real kernels reach less.
| Core (example clock) | Assumed effective MAC/cycle | Compute ceiling, 1M-class int8 | Likely real limiter |
|---|---|---|---|
| Cortex-M4 @ 168 MHz | ~1 | ~146 tok/s | Compute |
| Cortex-M7 @ 480 MHz (STM32H743) | ~2 | ~835 tok/s | Flash wait states, cache misses |
| Cortex-M55 @ 400 MHz, Helium | ~4 | ~1,390 tok/s | SRAM/MRAM bandwidth |
| Ethos-U85, 256 MACs @ 1 GHz class | far higher | bandwidth-bound | Weight streaming over AXI |
Treat these as upper bounds. Ten tokens/s is already faster than most users read a terse status line, so the practical question is rarely raw speed. It is whether the model fits at all, and whether it says anything useful. For the NPU row, Arm’s Ethos-U85 announcement gives the facts that matter. It scales from 128 to 2,048 MACs per cycle, which is 256 GOPS to 4 TOPS at 1 GHz. It adds native TRANSPOSE, GATHER and MATMUL support aimed at transformers, and carries 29 to 267 KB of internal SRAM. Our Ethos-U85 and Cortex-M85 architecture breakdown goes deeper. Decode is GEMV with batch size one, so an NPU spends most of its time waiting on weights. It helps prefill and long prompts more than token-by-token generation.
For calibration against a known number, llama2.c reports about 110 tokens/s for stories15M on an M1 MacBook Air. That is an application processor with orders of magnitude more bandwidth than any MCU.
Runtime support, verified November 2026
Operator coverage is where many plans for language models on microcontrollers fail, so here is the state of each runtime as documented today.
ExecuTorch Cortex-M backend. The ExecuTorch 1.5 Cortex-M backend docs describe it as an operator library, not a delegate, with status Beta. It covers CMSIS-NN kernels for linear, batch matmul, softmax, add, mul, permute and convolutions. It supports symmetric int8 only (8-bit weights, 8-bit activations). Int4 weights and int16 activations are “not yet integrated.” The validated models are all CNNs or MLPs, such as DS-CNN, MobileNet and ResNet-8. The October 2026 PyTorch blog lists attention operators and layer normalization under “What’s next.” The same blog reports an ExecuTorch core runtime under 20 KiB of flash and 15 to 37 KiB of code with selective build. Planning is ahead-of-time with no heap allocator. A tiny transformer will therefore export, but norms and attention plumbing fall back to portable fp32 kernels. Profile before you commit. On M55, M85 and Corstone platforms, the EthosUPartitioner offloads supported ops to Ethos-U55, U65 or U85 through Vela. For the phone-class side of the same project, see ExecuTorch 1.5 on-device LLM serving.
LiteRT for Microcontrollers (TFLite Micro). The current tflite-micro main branch’s MicroMutableOpResolver exposes AddBatchMatMul, AddEmbeddingLookup, AddGather, AddTranspose, AddSoftmax, AddRsqrt, AddMean and AddFullyConnected. Those are enough building blocks to express a small transformer graph, including RMSNorm decomposed into mean and rsqrt. The CMSIS-NN kernel directory includes batch_matmul, fully_connected, softmax and transpose. TFLM has no first-class stateful KV-cache abstraction. You either export a fixed-context graph that recomputes attention, or manage KV tensors as variable buffers yourself.
CMSIS-NN. The library’s README lists Batch Matmul in int8 and int16 across the pure C, DSP and MVE paths. Fully Connected also has an int4-weight, int8-activation variant on all three. Experimental fp16 and fp32 APIs exist, aimed mainly at Helium cores. Int4 weights are available at the kernel level even where frameworks have not wired them up.
microTVM. On the Apache TVM forum in November 2024, maintainers said the legacy micro flow would be phased out. It remains available in 0.18.0 and earlier and is not actively maintained. Do not start a new project on it.
NNoM. The documentation lists conv, dense, RNN/GRU, pooling and softmax layers with an optional CMSIS-NN backend. It mentions no attention layers. It is a fine choice for CNN keyword models, not for transformers.
In practice, most working demos of language models on microcontrollers today, including the ESP32 ports and TINY 2.1, are hand-written C loops derived from llama2.c. Frameworks are catching up but are not there yet.
A memory-budget calculator
Run this before you train. It encodes the three budgets above, using llama2.c’s activation layout.
# mcu_lm_budget.py - first-order flash/RAM/compute budget for a tiny decoder
from dataclasses import dataclass
@dataclass
class Cfg:
dim: int; n_layers: int; n_heads: int; n_kv_heads: int
hidden: int; vocab: int; seq: int; tied: bool = True
BYTES = {"fp32": 4.0, "fp16": 2.0, "int8": 1.0, "int4_g32": 0.5 + 2/32, "tern2": 0.25}
def params(c: Cfg):
dh = c.dim // c.n_heads
kv = c.n_kv_heads * dh
attn = c.dim*c.dim*2 + c.dim*kv*2 # wq, wo, wk, wv
ffn = 3 * c.dim * c.hidden # SwiGLU w1, w2, w3
emb = c.vocab * c.dim * (1 if c.tied else 2)
norms = c.dim * (2*c.n_layers + 1)
return (attn + ffn) * c.n_layers, emb, norms
def budget(c: Cfg, wfmt="int8", kvfmt="int8", act_bytes=4):
body, emb, norms = params(c)
dh = c.dim // c.n_heads
flash = (body + emb) * BYTES[wfmt] + norms * 4
kv = c.n_layers * c.n_kv_heads * dh * c.seq * 2 * BYTES[kvfmt]
act = (3*c.dim + 2*c.hidden + c.dim + c.n_heads*c.seq + c.vocab) * act_bytes
macs = body + 2*c.n_layers*c.dim*c.seq + c.vocab*c.dim # worst case t = seq
return dict(params=body+emb+norms, flash_KiB=flash/1024,
kv_KiB=kv/1024, act_KiB=act/1024,
sram_KiB=(kv+act)/1024, macs_per_tok=macs)
if __name__ == "__main__":
s260k = Cfg(64, 5, 8, 4, 172, 512, 512)
s15m = Cfg(288, 6, 6, 6, 768, 32000, 256)
one_m = Cfg(128, 4, 4, 4, 448, 512, 256)
for name, c in [("260K", s260k), ("15M", s15m), ("1M", one_m)]:
print(name, {k: round(v, 1) for k, v in budget(c).items()})
For stories260K this prints about 260K parameters, 256 KiB of int8 flash (norms stay fp32), 160 KiB of int8 KV and about 180 KiB of SRAM in total. The 172-wide FFN is derived from llama2.c’s sizing rule and reproduces the published 260K count. For stories15M at full context it prints about 864 KiB of KV plus 141 KiB of activations, which already exceeds the STM32H743’s 864 KB of user SRAM. Halve the context to 128 and the total drops to about 570 KiB, which fits.
A KV-cache ring buffer with int8 storage
A ring buffer bounds KV memory to a fixed window. Once the window fills, the oldest position is overwritten, which gives sliding-window attention. The sketch below stores K and V as int8 with one scale per head-vector. It computes int8 dot products for the attention scores. Treat it as a correct reference shape, not a tuned kernel.
#include <stdint.h>
#include <math.h>
#define N_LAYERS 4
#define N_KV_HEADS 4
#define D_HEAD 32
#define WINDOW 128
typedef struct {
int8_t k[N_LAYERS][WINDOW][N_KV_HEADS][D_HEAD];
int8_t v[N_LAYERS][WINDOW][N_KV_HEADS][D_HEAD];
float ks[N_LAYERS][WINDOW][N_KV_HEADS]; /* per-vector scales */
float vs[N_LAYERS][WINDOW][N_KV_HEADS];
uint32_t pos; /* tokens seen so far */
} kv_ring_t; /* ~144 KiB for this config */
static void quant_vec(const float *x, int n, float *scale) {
float amax = 1e-8f;
for (int i = 0; i < n; i++) { float a = fabsf(x[i]); if (a > amax) amax = a; }
*scale = amax / 127.0f;
}
void kv_append(kv_ring_t *kv, int layer, int h, const float *k, const float *v) {
uint32_t slot = kv->pos % WINDOW;
float s;
quant_vec(k, D_HEAD, &s); kv->ks[layer][slot][h] = s;
for (int i = 0; i < D_HEAD; i++) kv->k[layer][slot][h][i] = (int8_t)lrintf(k[i] / s);
quant_vec(v, D_HEAD, &s); kv->vs[layer][slot][h] = s;
for (int i = 0; i < D_HEAD; i++) kv->v[layer][slot][h][i] = (int8_t)lrintf(v[i] / s);
}
/* q_i8 is the query quantized with scale qs; out receives D_HEAD floats */
void kv_attend(const kv_ring_t *kv, int layer, int h,
const int8_t *q_i8, float qs, float *scores, float *out) {
uint32_t n = kv->pos < WINDOW ? kv->pos : WINDOW;
float inv_sqrt_d = 1.0f / sqrtf((float)D_HEAD), mx = -INFINITY, sum = 0.0f;
for (uint32_t t = 0; t < n; t++) {
int32_t acc = 0; /* int8 x int8 -> int32 */
for (int i = 0; i < D_HEAD; i++) acc += (int32_t)q_i8[i] * kv->k[layer][t][h][i];
scores[t] = acc * qs * kv->ks[layer][t][h] * inv_sqrt_d;
if (scores[t] > mx) mx = scores[t];
}
for (uint32_t t = 0; t < n; t++) { scores[t] = expf(scores[t] - mx); sum += scores[t]; }
for (int i = 0; i < D_HEAD; i++) out[i] = 0.0f;
for (uint32_t t = 0; t < n; t++) {
float w = scores[t] / sum * kv->vs[layer][t][h];
for (int i = 0; i < D_HEAD; i++) out[i] += w * kv->v[layer][t][h][i];
}
}
/* Caller increments kv->pos once per token after all layers append.
With RoPE, rotate k BEFORE kv_append so positions stay absolute. */
Three design notes. The inner QK loop is exactly the pattern CMSIS-NN’s DSP and MVE paths accelerate. You can replace it with arm_dot_prod_s8-style intrinsics or a batch-matmul call over the whole window. Order does not matter for softmax, so the ring does not need unrolling. Positional information comes from RoPE (rotary position embeddings) applied before caching. Finally, float scales and expf keep the sketch readable. A fully fixed-point version would use CMSIS-NN’s s8 softmax with a requantization multiplier and shift.
What These Models Can and Cannot Do

Figure 3: A go/no-go flow for putting a generative model on an MCU. Most paths end at a classifier, a smaller context or a hybrid design.
Figure 3 encodes the decision order I recommend. The first question is not “does it fit?” It is whether the output is a closed set of labels. If it is, a generator is the wrong tool. A keyword or intent classifier, such as the DS-CNN in our keyword spotting on microcontrollers pipeline, does the job in tens of kilobytes. The ExecuTorch blog’s DS-CNN measurement shows 26 KiB of peak RAM and 5.8 ms per inference on a Cortex-M55. No generative model competes with that.
Generation earns its place when the output has structure but no fixed enumeration. A tiny language model running on a microcontroller can realistically do the following:
- Slot filling into a template. “Set zone 3 to 21 degrees after 6” becomes
{zone:3, setpoint:21, after:"18:00"}. The model emits a short structured string, and a grammar mask applied to the logits before argmax guarantees it parses. - Constrained command generation. Map free-text operator notes to a small command language for a PLC gateway, with a few dozen tokens of output.
- Narrow-domain question answering from memorized facts. This is what TINY 2.1 does. Its README says it was trained on about 3,500 facts, each asked in many wordings, and answers outside that set are confidently invented.
- Templated status narration. Turn a sensor dictionary into a one-line human-readable summary for a display.
What they cannot do is equally clear from the evidence. TinyStories-class models write fluent text within their training distribution. They do not follow instructions, reason over multiple steps, or carry facts they were not trained on. The 28.9M ESP32 model’s own write-up says it cannot follow instructions, answer questions or write code. Retrieval is impractical because the context is too short to hold retrieved passages. Safety filtering on-device is effectively absent.
Constrained decoding is the most valuable technique here, and it is cheap. Apply a boolean mask over the vocabulary at each step, derived from a small finite-state machine for your output grammar. With a 512-token vocabulary the mask is 64 bytes and costs one pass over the logits. The model then only has to rank legal continuations, which is a far easier job than producing well-formed output unaided.
Trade-offs, Gotchas, and What Goes Wrong
Quantization error compounds in small models. Large models tolerate int4 because redundancy absorbs noise. A 64-wide model has little redundancy, and per-tensor int8 on the classifier can flip argmax decisions. Use per-row or per-group scales. Keep RMSNorm weights in fp32, as llama2.c’s runq.c does. Quantize the KV cache per vector, not per tensor. Our INT4 vs INT8 vs FP8 on edge NPUs comparison covers the error budgets.
XIP flash is not free bandwidth. Execute-in-place from QSPI flash can look fine in microbenchmarks. Then it collapses when weights, code and the tokenizer all thrash a 16 to 64 KB cache. The ExecuTorch blog’s Renesas RA8D1 demo cut latency from 191 ms to 24 ms, about 8x, mostly by placing hot weights in DTCM and enabling the instruction cache. Memory placement is the optimization.
Sliding windows forget. A ring-buffer KV cache bounds memory but silently drops early context. For slot filling that is fine. For anything that refers back to the start of a long prompt, it is a correctness bug. Size the window to the longest prompt plus output you actually accept, and reject longer inputs.
Prefill is the hidden latency. Generation speed figures usually report decode. A 100-token prompt runs 100 forward passes before the first output token unless your runtime batches prefill as GEMM. Most hand-written MCU loops do not. For an interactive device, measure time-to-first-token.
Model and tokenizer drift. Weights and tokenizer are a matched pair. An OTA that updates one without the other produces fluent garbage, and nothing crashes, so monitoring will not catch it. Version and sign them together.
Benchmarks are mostly anecdotes. No MLPerf Tiny category exists for autoregressive language models on microcontrollers. The tokens/s figures in this post are project self-reports or my labelled estimates. They are not comparable across boards, clocks or memory configurations.
Hybrid Design and Secure Weight Updates

Figure 4: The hybrid pattern. The MCU handles confident, structured requests locally, escalates the rest to a site gateway, and accepts only signed model updates.
For most products, the right architecture is not “LLM on MCU” or “LLM in the cloud.” It is both, with a confidence gate. Figure 4 shows the pattern. The MCU model handles the narrow, frequent, latency-sensitive cases, such as known commands with clear slots. When the top token probability or a sequence-level score falls below a threshold, the device forwards the raw input to a gateway. That gateway runs a 1-4B-parameter small language model, as described in our SLM edge architecture guide. It works offline for common cases and degrades gracefully for the rest. It also produces labelled escalations that become next quarter’s fine-tuning data for the tiny model.
The weights are firmware, so treat them that way. Store the model in an A/B partition next to the application image. Verify a signature over the combined blob of weights, tokenizer and config hash at boot, using the same secure-boot chain that protects code. MCUboot or a vendor root of trust are the usual options. Use delta updates: an int8 fine-tune changes most bytes, but a LoRA-style adapter merged at build time can be shipped as a much smaller diff. Keep the previous slot bootable for rollback. If the hardware supports it, put the weights region behind read-protection. A 1 MB model trained on proprietary command logs is an extractable asset, so treat its confidentiality as part of the threat model.
Practical Recommendations
For language models on microcontrollers, start from the task, not the model. If the output fits a label set, ship a classifier and stop. If it needs structure, write the output grammar first, then size a model whose vocabulary covers that grammar’s tokens plus the input domain. Train the tokenizer on your domain. A 512 to 2,048-token vocabulary usually beats a borrowed 32K one on every MCU metric.
Do the budget arithmetic before training. Pick the context window from real prompt lengths. Compute KV at int8 with GQA. Confirm that KV plus activations fit on-chip SRAM with 30 percent headroom for the stack, drivers and the rest of your firmware. Weights can go to flash or PSRAM, but measure that bandwidth on the actual board. The ESP32 numbers suggest tens of MB/s, not hundreds.
Choose a runtime with open eyes. If you need ExecuTorch’s toolchain and Ethos-U offload, plan for attention and norms running on portable kernels until the backend’s roadmap lands. If you need a result this quarter, a llama2.c-derived C loop with CMSIS-NN GEMV calls is the proven path. Pick a Cortex-M55 or M85 part when latency matters. A Cortex-M7 with 1 MB of SRAM is the practical floor for anything above 1M parameters. The RISC-V vs Arm Cortex-M ecosystem comparison covers the vector-extension options on the other side.
Checklist:
- Output is structured but not a closed label set, otherwise use a classifier.
- Domain tokenizer at 4,096 tokens or fewer; tokens per word measured.
- Flash ≥ weights + tokenizer + firmware, at int8 or int4 with per-group scales.
- SRAM ≥ int8 KV + activations + logits, with 30 percent headroom.
- Grammar-constrained decoding on every output.
- Time-to-first-token measured, not just decode tokens/s.
- Weights, tokenizer and config signed as one blob, A/B slots, rollback tested.
- Confidence gate and gateway fallback for everything else.
Frequently Asked Questions
Can you run an LLM on a microcontroller?
Yes, if “LLM” means a language model of roughly 0.25 to a few million parameters. Public projects run llama2.c-derived models on the ESP32-S3: a 260K fp32 model at about 30 tokens/s and a 3.3M int8 model at about 12 tokens/s. A 28.9M 4-bit model reached about 9.9 tokens/s using flash-resident embeddings. These models produce fluent text in a narrow domain. They cannot follow general instructions like ChatGPT-class models. Billion-parameter models do not fit any microcontroller’s memory.
How much RAM does a tiny transformer need?
Add the KV cache and the activation buffers. The KV cache is layers × KV heads × head dimension × context × 2 × bytes per element. For stories260K at a 512-token context that is 640 KiB in fp32 or 160 KiB in int8. Activations add about 20 KiB. For stories15M at a 128-token context, int8 KV plus fp32 activations total about 570 KiB. That fits an STM32H743’s 864 KB of user SRAM, but not at 256 tokens of context.
What is the smallest language model that produces coherent text?
The TinyStories paper showed that models under 10 million parameters, including some with a single transformer block, produce fluent and consistent short stories when trained on a simplified, synthetic children’s-story corpus. Karpathy’s stories260K has 260K parameters, a 512-token vocabulary and five layers, and still produces recognizable story fragments. Coherence depends heavily on how narrow the training distribution is. On general web text, models of this size do not produce coherent English beyond a few words.
Does ExecuTorch support transformers on Cortex-M?
Partially. ExecuTorch 1.5’s Cortex-M backend is Beta and int8-only. It provides CMSIS-NN kernels for linear, batch matmul and softmax, which cover much of a transformer. However, its validated models are CNNs, and the October 2026 PyTorch and Arm blog lists attention operators and layer normalization as future work. A small transformer will export, with unsupported pieces falling back to portable fp32 kernels. On Ethos-U parts, supported operators can be partitioned to the NPU via Vela. Profile carefully before relying on it.
Is int4 or ternary quantization worth it on an MCU?
Int4 roughly halves flash against int8. CMSIS-NN already provides int4-weight, int8-activation fully connected kernels on C, DSP and MVE paths, although ExecuTorch’s Cortex-M backend has not integrated them yet. Ternary weights cut flash by about 4x against int8 but must be trained in, BitNet-style. You would also have to write your own kernel. On small models, aggressive quantization costs more quality than on large ones, so validate the task accuracy, not just perplexity.
Why does vocabulary size matter so much for tiny models?
The embedding table and output classifier both scale with vocab × model width. In stories15M, the 32,000-token vocabulary accounts for 61 percent of parameters and 59 percent of per-token MACs. Its fp32 logits buffer alone is 125 KiB of RAM. A 512-token vocabulary shrinks all three dramatically. The trade-off is that text splits into more tokens, which raises KV memory and latency per sentence. A domain-trained vocabulary of a few thousand tokens is usually the balance point.
Further Reading
- Keyword spotting on microcontrollers with MFCC features and DS-CNN: the classifier you should reach for before a generator.
- LLM tokenization explained: BPE, SentencePiece and tiktoken: how vocabulary design sets tokens per word.
- RISC-V for IoT microcontrollers: ESP32-C series vs Arm Cortex-M: choosing the silicon and vector extensions.
- KV cache optimization for LLM inference: the same memory problem at datacenter scale.
- Arm Ethos-U85 and Cortex-M85 TinyML NPU architecture: what the NPU tier adds.
- External: TinyStories, Eldan and Li, arXiv 2305.07759; ExecuTorch Arm Cortex-M backend documentation; Bringing ExecuTorch to Arm Cortex-M CPUs (PyTorch blog); CMSIS-NN repository; TINY 2.1 repository.
By Riju — about
