I wanted to understand transformers beyond calling a model API. Buying an ESP32-S3 gave that goal a concrete constraint: build a model that continues children’s stories in Brazilian Portuguese, with inference running on the board itself.
The result is Historinhas, a 28.87M-parameter model trained from scratch. To understand its design, we will follow the path from the original Transformer to Gemma’s memory-saving embeddings, then trace Portuguese text through training, quantization, and deployment. A token is a text unit, often a word fragment, and each generation step predicts one more.
The figures below come from the V3 training and release records. Host verification and physical-device performance are different evidence: this article reports the former, not a newly reproduced hardware benchmark.
Why the ESP32-S3?
“ESP32” names a family, not one interchangeable chip. The relevant differences are:[1–3]
| Chip | CPU | Internal SRAM | Why it matters here |
|---|---|---|---|
| Original ESP32 | Xtensa LX6, with single-/dual-core variants, up to 240 MHz | 520 KB | Supports external RAM, but not the S3’s dedicated vector-instruction capability. |
| ESP32-C3 | Single-core RISC-V, up to 160 MHz | 400 KB, including 16 KB used for cache | A different CPU and tighter on-chip memory budget. |
| ESP32-S3 | Dual-core Xtensa LX7, up to 240 MHz | 512 KB | Dedicated SIMD instructions and suitable external-memory configurations. |
SIMD means applying one instruction to multiple numerical values, useful for the dot products behind neural networks. It does not turn the S3 into a GPU. Notice also that the S3 does not have more internal SRAM than the original ESP32.
My target is specifically an N16R8 board: 16 MB flash and 8 MB PSRAM. Those capacities are not universal ESP32-S3 specifications. Flash retains the firmware and model after power-off; PSRAM is external working memory; internal SRAM is the scarce on-chip working space.
This is a simplified diagram of our implementation, not an official Espressif cache hierarchy. The full 512 KB is not an application-only allowance: firmware, stacks, and system allocations also consume SRAM.
From the original Transformer to Gemma
The Transformer in Attention Is All You Need was designed for sequence-to-sequence tasks such as translation. Its encoder reads the source sentence with bidirectional self-attention; its decoder generates the translation using masked self-attention plus cross-attention to the encoder’s output. The encoder represents the input; the decoder predicts an output sequence conditioned on that representation.[11]
Attention operates on learned queries, keys, and values (Q, K, V). A query is compared with keys to produce weights for combining values. Multiple attention heads learn different such combinations. Feed-forward layers then transform each position’s representation, while residual connections preserve a running information path between layers. The original base model used additive sinusoidal position encodings, ReLU feed-forward networks, and LayerNorm after its residual additions.[11]
Why we do not need an encoder
Story continuation is naturally one sequence, not a source sentence and a separate translation. Given Era uma vez, we predict the next token, append it, and repeat. The prefix already provides the conditioning information through causal self-attention: each position can attend to earlier positions, but not to future tokens.
A separate encoder and encoder–decoder cross-attention would add parameters, memory traffic, and implementation work without being required for this objective. Decoder-only is therefore a task-aligned choice, not a claim that encoders are obsolete. Encoder–decoder models remain useful when input and output have distinct roles; multimodal systems may also use encoders for images or audio. Nor should a transformer encoder be confused with the tokenizer’s encoder, which merely converts text into token IDs.
During training, the causal mask lets us predict many next-token targets in parallel without leaking their future context. During generation, predictions are sequential. The output head produces logits, the unnormalized scores over the vocabulary; sampling turns those scores into the next token.
What changed in modern language models?
Many contemporary generative models retain this decoder-only backbone but change its components and scale. Common choices include rotary position embeddings (RoPE), which rotate Q and K according to position; RMSNorm, which rescales activations without LayerNorm’s mean subtraction; and gated feed-forward networks such as SwiGLU. These are specific design choices, not a definition that every modern model must satisfy.
At the frontier, architectures also vary in how they reduce inference cost. Mixture-of-experts (MoE) routes tokens to subsets of feed-forward networks; attention variants reduce the amount of historical state stored during generation. DeepSeek-V3 is one documented example, combining MoE with Multi-head Latent Attention. Its report also describes large-scale pretraining and subsequent supervised and reinforcement-learning stages.[13] Proprietary frontier systems do not necessarily disclose enough detail for a component-by-component comparison.
Gemma is Google’s family of open-weight models, not an alternative to the Transformer principle and not the same product as Gemini. Its variants explore different deployment budgets. The mobile-oriented Gemma 3n introduced per-layer embeddings (PLE) alongside other efficiency mechanisms; the smaller Gemma 4 variants also use PLE, and our source follows their PLE construction.[4][12] We borrow the PLE idea, not Google’s pretrained knowledge or its entire architecture.
| Design question | Original Transformer | Contemporary model examples | Historinhas |
|---|---|---|---|
| How is text generated? | Decoder conditioned on a separate encoder | Often a causal decoder; multimodal frontends vary | Causal decoder for a story prefix |
| How is position represented? | Sinusoids added to embeddings | RoPE and other model-specific schemes | Standard RoPE |
| How is the block updated? | Post-residual LayerNorm; ReLU feed-forward | Often RMSNorm and gated feed-forward blocks | Pre-attention/FFN RMSNorm; SwiGLU |
| Where does additional capacity go? | Dense attention and feed-forward weights | Wider dense layers, routed experts, or specialized mechanisms | Small dense core plus token-indexed PLE tables |
| What makes it useful? | Translation training | Architecture, much larger data/compute, and often post-training | Short Portuguese-story pretraining only |
A block diagram alone does not explain frontier capability. Our model has no instruction tuning, alignment stage, broad knowledge-training claim, or reasoning evaluation. Sharing architectural ingredients does not imply sharing those capabilities.
PLE: more token-specific capacity without a wider core
A standard embedding table maps a token ID to its initial vector. Later layers refine that vector in the residual stream, the running representation carried through the network. PLE adds a second route: each token receives a small, dedicated conditioning vector for every layer.
The motivation is memory efficiency on devices with unequal memory tiers. Google’s Gemma 3n guide explains that per-layer embedding parameters can be handled outside constrained accelerator memory while the core transformer remains resident there.[12] On our microcontroller there is no separate GPU VRAM, but the useful distinction survives: large sparse tables can stay in flash while repeatedly used dense weights live in PSRAM.
The same architecture diagram used in our model cards.[9][10] Open full-size. The lower panel distinguishes the FP32 research release from INT4/INT8 device storage and computation.
Follow one token through the PLE branch
- Look up its ordinary embedding. A token ID selects a 96-value row. This initializes the residual stream and also feeds a learned projection into six slices of 128 values, normalized separately for each layer.
- Look up its layer-specific information. The same ID selects one row from the PLE table: six more slices of 128 values. The entire vocabulary table is stored, but only the selected row is read for this token.
- Combine the two paths. For each layer, our code combines the normalized projection with the corresponding table slice, scaled by the square root of 128, and divides the sum by the square root of two. Those factors are part of the implemented numerical convention, not an extra learned language feature.
- Gate the update using context. After attention and the feed-forward update, the layer projects its current 96-value hidden state to 128 values and applies GELU. It multiplies that gate elementwise by the layer’s PLE vector, projects back to 96 values, normalizes, and adds the result to the residual stream.
The distinction in step four matters. The table lookup and input-embedding projection are token-dependent, not context-dependent in this implementation: the same token gets the same prepared PLE vectors. The hidden-state gate depends on the preceding context, so the injected update can differ between two occurrences of that token. The GELU gate is not a probability constrained to zero through one.
PLE is also not retrieval of text, an external knowledge base, or an MoE router. It retrieves learned numerical vectors by token ID. It reduces the need to widen the always-active core, but it does not eliminate table storage, training cost, or memory bandwidth. Whether the extra table improves quality must be tested against matched baselines; architecture alone is not a result.
Our adaptation and its consequences
This is a model trained from scratch, not a compressed Gemma checkpoint or a fine-tune of Google’s weights. We retained the PLE mechanism and built a much smaller, text-only decoder around it:
| Deployment-target setting | Value |
|---|---|
| Decoder layers / attention heads | 6 / 4 |
| Hidden width / feed-forward width | 96 / 66 |
| PLE width per layer | 128 |
| Vocabulary | 32,768 |
| Training context | 256 tokens |
| Dense core, excluding output head | 558,368 parameters |
| Shared input embedding / output head | 3,145,728 parameters |
| PLE lookup table | 25,165,824 parameters |
These counts match the V3 release record: 28,869,920 unique trainable parameters, counting the tied weights once.[9] Most parameters live in the lookup table; total parameter count therefore says little about per-token compute on its own.
We retain ordinary causal multi-head attention, RoPE, RMSNorm, and SwiGLU, but not the Gemma family’s complete efficiency stack. There is no multimodal encoder, alternating local/global attention, cross-layer KV sharing, or AltUp, the mechanism used by Gemma 3n to update a wider representation while computing over a smaller active part.[12]
Those omissions keep the implementation inspectable, but they are not free optimizations: independent attention layers retain their own history, and our model does not inherit Gemma’s long-context or multimodal behavior. Reducing the core to 96 dimensions and the feed-forward width to 66 is a severe representational bottleneck; PLE adds token-specific information, not a substitute for unlimited contextual computation. The input embedding and output head share weights to avoid storing a duplicate vocabulary matrix.
The repository includes baseline and ablation arms for testing whether PLE earns its storage budget. We do not claim superiority over those alternatives without matched results.
There is still a bandwidth bill: the output head must score the vocabulary on every step. Tying it to the input embedding saves storage, not that scan.
Making the whole pipeline Brazilian Portuguese
The language comes from the data and tokenization, not a flag inside attention. We train exclusively on the texto field of Boakpe/historinhas on Hugging Face, a Portuguese children’s-story corpus.[5]
Preparation pins the source revision and checksum, normalizes line endings, and splits documents deterministically into training and validation sets. The tokenizer is trained only on the training split, so validation documents do not help construct its vocabulary.
We use UTF-8 ByteLevel BPE: text starts as bytes, and learned merges combine common sequences into tokens. This handles accents such as ã, ç, and é without reducing Portuguese to an ASCII approximation. Unlike a word-level dictionary, byte coverage also permits encoding unfamiliar words, potentially with more tokens.
The deployment-specific change is disabling regex pre-tokenization. Python and firmware apply BPE to the complete prompt byte sequence, avoiding a Unicode regex engine on the microcontroller. The firmware validates UTF-8, and host tests compare its token IDs with the Hugging Face tokenizer implementation. The checkpoint and tokenizer must stay paired: matching vocabulary size alone does not guarantee matching token meanings.
Tokenizer diagram from our model cards.[9][10] Open full-size.
The <|endoftext|> token separates training documents and signals completion during generation. Training on stories narrows the task deliberately; it does not create a general Portuguese assistant.
Training: about three hours, not on the microcontroller
Training runs on a computer, not on the ESP32. The documented Intel-laptop profile uses twelve CPU threads, 10,000 optimizer steps, batches of 16, and sequences of 256 tokens. That schedule processes 40,960,000 token positions, including possible repeated sampling. This is not 40.96 million unique corpus tokens.
The completed V3 run (ple-historinhas-intel-v3-s0, seed 0) records 10,943.55 seconds (about 3 hours and 2 minutes) of training wall time. It used AdamW, a peak learning rate of 0.001, 200 warmup steps, cosine decay, and gradient clipping at 1.0. The exact processor model was not preserved; the twelve-thread laptop command is a documented profile, not proof of the release run’s complete hardware configuration.[9]
The recovered, hash-verified preparation manifest records 1,249,051 training documents and 174,056,772 training tokens, plus 6,189 validation documents and 860,822 validation tokens. The run’s 40.96 million sampled token positions are not a full traversal of that training corpus. Validation ran every 250 steps over 40 sampled batches; these are not full-validation-corpus evaluations.
More training can improve predictions while the model is still learning useful patterns. It also costs wall time, and improvement eventually slows. If training loss keeps falling while validation loss rises, additional training is fitting the training data rather than improving held-out prediction. The learning curve, not the step count alone, should decide whether more time is worthwhile.
Quantization: int4 on flash, int8 for computation
Quantization represents weights with fewer bits. Our exporter applies post-training, symmetric group-wise int4 quantization, packing two codes per byte and storing FP16 scales for groups of up to 128 values. Small normalization weights remain FP32. This is not quantization-aware training.
Moving a weight from FP32 to int4 reduces its raw code storage by eight times, but scales, metadata, and unquantized tensors make the complete file larger than the ideal four-bits-per-parameter calculation. Our V3 model.bin is 14,912,348 bytes (14.22 MiB), including its header and quantization metadata.[10]
The runtime uses a separate optimization: at startup it stages the dense core and output head as int8 in PSRAM, while leaving the PLE table in memory-mapped flash. The firmware enables int8 activation computation, keeps hot scratch buffers and normalization vectors in internal SRAM, and stores its FP32 KV cache and logits in PSRAM.
Storage precision and compute precision are therefore different decisions. Quantization can also change predictions, so we need separate checks for:
- Full-precision versus exported int4 validation loss: the weight-quantization cost.
- Python versus C logits for the same quantized weights: implementation correctness.
- Portable versus staged int8 inference: the additional numerical cost of the optimized path.
The INT4 release records a passing portable-C versus dequantized-PyTorch golden check, with maximum absolute logit difference 0.00001 at printed precision, plus passing int8 staging/dispatch checks. These are recorded host results, not tests rerun for this article. They establish implementation consistency for their test cases, not preservation of FP32 perplexity or an end-to-end device-quality benchmark.[10]
Perplexity: 74.08, and what that means
Perplexity measures how surprising held-out text is to a model. For each correct next token, we take the negative log probability, average across evaluated predictions, and exponentiate:
cross-entropy = mean(-ln P(correct next token | preceding context))
perplexity = exp(cross-entropy)
Lower is better under the same evaluation conditions. For intuition, a cross-entropy of 3 corresponds to perplexity about 20.09; a cross-entropy of 2 corresponds to about 7.39. Perplexity is not a percentage, a count of grammatical errors, or a guarantee of coherent stories. It can be interpreted as an effective average prediction uncertainty, not a literal number of equally likely candidates at every position.[6]
Our result and the training-time trade-off
The original V3 training record reports FP32 validation cross-entropy of 4.30514 nats/token and perplexity of 74.0793 at the final 10,000-step checkpoint. Its best recorded loss equals its final loss. This is a historical sampled-validation result, not a fresh evaluation of the uploaded safetensors.[9]
| Point in the V3 training history | Validation perplexity |
|---|---|
| Logged step 1,000 | 348.77 |
| Logged step 2,500 | 146.45 |
| Logged step 5,000 | 95.60 |
| Logged step 7,500 | 79.42 |
| Final evaluation, 10,000 completed updates | 74.08 |
Values are calculated as exp(val) from the release’s training_metrics.json; intermediate labels preserve the trainer’s logged step indices. From logged step 5,000 to completion, perplexity fell by about 22.5%. There were still gains, but they became smaller toward the end. Because the learning rate was also decaying, this curve does not isolate model capacity from optimization schedule, and the record does not provide per-evaluation timestamps for an improvement-per-hour calculation.
A separate earlier V2 run ended at 5,000 steps with perplexity 101.66. That is not the V3 midpoint above, and must not be substituted for it. Additional steps helped in the observed V3 run; we cannot extrapolate that another three hours would produce a similar reduction.
| Release / path | Validation perplexity | What is established |
|---|---|---|
| V3 original FP32 | 74.08 | Historical sampled-validation training result |
| V3 packed INT4 | Not measured | Export and golden-logit consistency checks |
| Staged INT8 device path | Not measured | Host staging/dispatch checks, not end-to-end quality |
The score 74.08 belongs to FP32, not to the INT4 binary. Neither quantization quality loss nor human-rated story quality was measured for this release.[10]
Does “low perplexity” mean competitive with larger models?
Published examples give context, not a shared leaderboard. OpenAI reported 18.34 on WikiText-2 for its largest GPT-2; the SqueezeLLM authors measured 5.68 on WikiText-2 for their 16-bit LLaMA-7B baseline.[7][8] OpenAI’s report also uses benchmark-specific normalization conventions, adding another reason not to equate those values with our tokenizer-token score.
These figures do not support describing 74.08 as a frontier-level low perplexity; nor would matching their numbers establish comparable capability. Children’s stories are a narrower distribution than general web text. Different tokenizers, vocabulary sizes, evaluation units, context windows, and validation corpora all affect perplexity.[6]
For this experiment, the meaningful result is the improvement within the same V3 protocol, achieved in about three hours, not parity with a larger model. Further work should measure the quality cost of INT4, inspect generated stories, and compare matched baselines before spending more training time.
Deployment and practical limits
The deployment pipeline exports a checkpoint and its exact tokenizer, builds tokenizer assets, runs conformance and available golden-logit checks, verifies int8 staging, compiles the firmware, and flashes the model and application. The model partition is defined once in partitions.csv: offset 0x190000, capacity 0xE60000 (about 14.38 MiB). The V3 binary fits with 160,932 bytes of model-partition headroom; that margin is not spare PSRAM or the board’s total free flash.
Deployment diagram from the INT4 model card.[10] Partition sizes are not to scale. Open full-size.
After boot, prompts arrive over a 115200-baud serial console. Generation runs locally; it does not call a remote inference API. The firmware prints the loaded model’s size and fingerprint so they can be checked against the deployment receipt.
Memory still limits the conversation. The KV cache retains earlier attention keys and values so generation does not have to recompute the entire prefix at every step. For the documented 256-token configuration, the FP32 KV cache alone requires 1,179,648 bytes (1.125 MiB): two tensors × six layers × 256 positions × 96 values × four bytes. The firmware reserves room for up to 200 generated tokens, leaving at most 56 prompt tokens in that configuration, with a separate 512-byte input limit.
Short context, a very narrow dense core, story-domain training, quantization error, and vocabulary-scoring bandwidth all constrain the result. We should expect repetition, inconsistent narratives, and limited knowledge outside the corpus, rather than reliable reasoning or factual answers. Actual tokens per second and successful hardware deployment still need their recorded measurements.
The experiment’s main lesson is architectural: count what is read on every token, what is looked up once, and what grows with context. Those are different budgets, even when all three are described casually as “model memory.”
Code and references
- Project code: e-valente/esp32-historinhas.
- Original FP32 model: e-valente/historinhas-29M-pt-BR.
- ESP32 INT4 model: e-valente/historinhas-29M-pt-BR-INT4. Both models and their model cards are public and can be accessed without authentication.
- Training dataset: Boakpe/historinhas.
- Espressif: ESP32-S3 datasheet and S3 overview.
- Espressif: original ESP32 datasheet.
- Espressif: ESP32-C3 datasheet.
- Hugging Face: Gemma 4 architecture, including PLE. Consulted to explain the implemented mechanism; current documentation may include later additions.
- Boakpe/historinhas dataset card.
- Hugging Face: perplexity of fixed-length models.
- OpenAI: Language Models are Unsupervised Multitask Learners, Table 3.
- SqueezeLLM: Dense-and-Sparse Quantization, Table 1.
- Historinhas FP32 model card and
training_metrics.json, Hub revision7588065534f47bfbce11a067907b59ba53ada06a; publicly accessible without authentication. - Historinhas INT4 model card and
verification.json, Hub revisionb10f860ee0db5c38b0ef4f8ccdd440febfb5a43c; publicly accessible without authentication. - Vaswani et al., Attention Is All You Need, sections 3.1–3.5.
- Google, Introducing Gemma 3n: The developer guide, June 26, 2025; PLE memory placement and architecture overview.
- DeepSeek-AI, DeepSeek-V3 Technical Report, architecture and training overview; a documented modern example, not a claim about undisclosed current frontier architectures.