# Training a Neural Network on the ESP32-S3

An [ESP32-S3](https://www.espressif.com/en/products/socs/esp32-s3) can do more than execute a neural network trained elsewhere. A sufficiently small model can learn directly on the microcontroller, updating its own weights from locally collected examples. The interesting constraint is the complete training footprint: parameters, gradients, optimizer state, and examples all compete with the rest of the firmware for limited memory.

A compact signal classifier makes that possibility concrete. A plain C implementation trains a 1,756-parameter network in about 18 seconds using both cores, while a second experiment learns a few microphone sound categories in under a second. **The benefit is adaptation at the sensor, not beating a laptop at training.** Understanding the data representation and memory layout explains both why these examples work and why their results should not be generalized to larger models.

<iframe class="aspect-video h-auto" width="100%" height="315" src="https://www.youtube.com/embed/v4AX5Uz23Go" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

## Learning changes the microcontroller's job

Many embedded machine learning systems perform inference only. A computer trains the model, firmware receives the resulting parameters, and the device computes predictions. This is useful when the training distribution is known in advance, but it cannot automatically adapt the classifier to a new installation or an individual user's examples.

On-device training adds the missing feedback loop. The device evaluates its prediction against a label, computes how each weight contributed to the error, and updates those weights. That requires backpropagation and an optimizer in addition to the forward pass used for inference.

The [on-device training project](https://github.com/andrisgauracs/s3-ondevice-training) keeps that loop small enough to inspect. Its synthetic signal classifier distinguishes sine, square, chirp, and noise inputs. The model contains layers with 32, 32, 16, 8, and 4 values, ending in four output scores.

![The small signal classifier maps 32 inputs through three intermediate layers to four signal scores](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/a35ba612-a8a6-4fc4-71f0-ec4101bc9900/lg2x =1920x1080)

The 1,756 trainable parameters occupy roughly 7 KB as 32-bit floating-point values. This is a small dense classifier, rather than a compressed language model or a general audio recognition system. Its size makes ordinary arithmetic on a microcontroller practical without a graphics processor.

The narrow task is an advantage. The input has a fixed shape, the output has four known categories, and the training workload is bounded. Those properties make it possible to account for memory and execution time before expanding the firmware into an open-ended learning system.

## The training footprint extends beyond the weights

Weights alone give a misleading estimate of training memory. Backpropagation needs gradients, and the Adam optimizer maintains two additional values for each parameter: moving estimates of the gradient and its squared magnitude. The four parameter-sized arrays together occupy about 28 KB in this implementation.

![Weights, gradients, and Adam's two state arrays total about 28 KB before the training examples](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/134081a3-58d3-4391-7d68-23ded1826000/md2x =1920x1080)

The displayed training-data budget adds approximately 128 KB. That is a property of this implementation's data representation, not a rule that any matrix with 4,096 examples and 32 inputs will occupy 128 KB. A dense float32 copy of every input would require substantially more space. Representation choices belong in a memory budget alongside the network topology.

The selected ESP32-S3 board has 8 MB of external pseudo-static RAM, or PSRAM, in addition to its internal memory. External capacity does not make every access equally fast. Keeping frequently accessed weights and working arrays in internal memory helps the arithmetic loop avoid slower memory traffic.

This is a useful embedded distinction: fitting in memory and fitting in fast memory are separate constraints. A design may have enough total RAM yet still spend too much time moving data to sustain its intended training or inference rate. The operating system, display, microphone buffers, task stacks, and communication code also need space; the full silicon memory specification is not the application's free working budget.

The implementation uses a compact plain C training loop rather than relying on TensorFlow Lite for this experiment. The same source can be compiled on a host computer, which makes numerical comparisons easier. Shared code does not prove every target behaves identically, but it reduces the chance that two completely different implementations are being compared accidentally.

## The hardware is a complete learning loop

The experimental setup combines the development board, an INMP441 microphone, a 1.28-inch round display, and a button on a breadboard. The display makes training state visible, while the button provides a simple way to collect labeled examples for the sound task.

![The board, microphone, round display, and button form the local training setup](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/fc63d888-0fe2-4967-939f-e87144717f00/lg2x =1920x1080)

These peripherals are not merely presentation details. A model that adapts locally still needs a source of trustworthy labels. In this setup, a person chooses a sound category and records examples. In a deployed sensor, labels might come from a maintenance action, a known machine state, or a supervised calibration period. Without that mechanism, collecting more data does not automatically teach the model the right distinction.

The microphone task also shows why firmware scheduling matters. Audio capture cannot simply wait indefinitely while training monopolizes the device. A production design needs explicit boundaries between collection, feature extraction, training, and inference, including a policy for what happens when the input arrives faster than it can be processed.

The synthetic experiment avoids some of those complications by generating its own examples at boot. Its Python counterpart produces the same data bit for bit, allowing the board and laptop reference to learn from identical inputs. That controls an important variable: a difference in accuracy is less likely to come from accidentally training on different datasets.

## Accuracy needs a held-out measurement

The signal model trains for 80 full-batch updates over 4,096 examples. The display visualizes the model's current classifications as colored cells. As the weights improve, the four signal regions become more consistent.

The important reported result is 84.8% accuracy on test examples the model did not train on. The laptop reference reaches the same test accuracy on the matched data. A higher percentage shown during training describes a different population and should not replace that held-out figure.

![The board reports 84.8% held-out test accuracy alongside the one-core and two-core training times](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/2f2af63f-e811-453c-b495-2170692afe00/orig =1920x1080)

This distinction becomes even more important with tiny personalized datasets. A classifier can learn its stored examples very well while failing on a quieter sound, a different distance, or another background. Training accuracy answers whether optimization fits the available examples. Test accuracy asks whether the learned pattern extends beyond them.

Matching the host's accuracy supports the claim that training on the microcontroller can produce a comparable result for this particular network and dataset. It does not establish accuracy across unrelated tasks, nor does it show that a small signal model has acquired general sound understanding. The evidence is strongest when the conclusion stays close to the experiment.

## Two cores accelerate the same update

On one core, the 80 updates take about 35.1 seconds. Using both cores reduces that to approximately 18.0 seconds, a 1.95-fold speedup. The implementation splits the 4,096 examples into two groups of 2,048 and accumulates gradients independently before combining them for the optimizer update.

![Two cores process separate halves of the batch and combine gradients before a single Adam update](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/52744355-1aa6-43d4-7ab7-108eb10fb700/lg1x =1920x1080)

The synchronization point is essential. Each worker computes a contribution to the same batch gradient; the optimizer then applies one combined update. Running two unrelated optimization histories and averaging their final weights would be a different algorithm. Likewise, changing the number or size of updates would make the timing comparison harder to interpret.

The near-twofold improvement is credible for a workload with enough independent arithmetic and modest coordination overhead. It is not a general guarantee for embedded multithreading. Shared memory contention, tiny batches, peripheral interrupts, or an uneven split can reduce the benefit.

A NumPy laptop reference completes the comparable training in approximately 0.08 seconds. Dividing 18 seconds by that figure gives roughly 225, so the host remains hundreds of times faster. The microcontroller's value is that an 18-second calibration can happen where the data originates, without a training computer being present.

For a device adapting occasionally, that may be an acceptable pause. For a control loop requiring continuous responses, it may not be. Training latency should therefore be evaluated against the application's schedule rather than only against another processor's throughput.

## Fast inference follows from a bounded model

Once trained, the signal classifier produces a reported 20,488 decisions per second. The corresponding estimate is about 6.9 processor cycles per multiply-add operation. An earlier reference experiment listed 36 cycles for the ESP32-S3.

![The implementation's estimated cycles per multiply-add are lower than the earlier reference figure](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/04d29022-8f98-4e21-6128-5806882e5b00/orig =1920x1080)

The implementation does not use the chip's special vector instructions for this result. Compiler optimization and keeping hot data in fast internal memory are plausible contributors. However, the comparison does not isolate those factors independently, so it should not be treated as proof that one setting alone creates the whole improvement.

Throughput also needs a clear boundary. A forward pass over already prepared inputs is different from a complete sensor decision that includes acquisition, signal processing, display updates, and power management. A system can classify features quickly while spending most of its time waiting for enough audio to arrive.

This explains why a half-second recording window can coexist with thousands of classifications per second. The arithmetic loop is fast, but the input has its own time scale. For an interactive sound trigger, end-to-end latency includes both.

## Audio features make local personalization tractable

The sound experiment learns three categories: a normal clap, a finger clap, and a tap on the table. It begins from random weights and uses ten recorded examples per category. Instead of feeding raw microphone samples into the classifier, firmware detects a sound above the background and captures about half a second of audio.

That recording becomes a compact time-frequency representation containing 161 values. The representation compresses the input while retaining information about when energy appears at different frequencies. This is the feature extraction stage that makes the small classifier's job manageable.

![The captured sound becomes 161 time-frequency and loudness values for the classifier](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/df7dc2a1-058f-4467-cb2f-ce8bb0422200/md1x =1920x1080)

The trigger and the classifier solve different problems. The trigger decides when an event is worth recording. The network decides which learned category best matches its features. A poor trigger can clip the beginning of a sound or include too much unrelated noise, limiting accuracy regardless of how well the neural network trains.

With only 30 real recordings, memorization is a concern. During training, the system varies examples through small shifts in time and added noise. These transformations encourage some tolerance for changes that should preserve the label.

![Time shifts and noise create variations of the small collection of recorded sound examples](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/89a979d5-4824-4d78-9aca-1a216dc39000/public =1920x1080)

Augmentation does not create independent evidence of generalization. Variations derived from one recording remain related to that recording. A useful held-out evaluation needs genuinely separate captures, ideally collected at different distances and under different background conditions.

The small sound model completes 40 epochs in about 0.9 seconds. Its display reaches 100% training accuracy, but the observed confusion between similar claps is a reminder that fitting the examples is not the same as robust recognition.

![The sound model completes 40 epochs in about 0.9 seconds and reports training accuracy](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/4d5f1b1c-fd31-45ca-f03f-9e8e58602b00/lg2x =1920x1080)

A deployable classifier also needs behavior for unfamiliar sounds. Choosing the largest score among three categories always produces a winner, even when none is appropriate. A rejection threshold, explicit unknown examples, and a way to recover a previously useful model can be more valuable than another decimal place of training accuracy.

## Final thoughts

Small neural networks can train on an ESP32-S3 when the task, feature representation, and optimizer state fit the device's real memory budget. The signal experiment demonstrates matched host and device accuracy with practical two-core training time. The audio experiment shows how local labels and compact features can personalize behavior quickly.

**Local adaptation is the useful capability; broad model training remains outside this experiment's scope.** For personalized triggers and narrow sensor classifiers, that capability can remove a round trip to a training server. Reliable deployment still depends on held-out examples, background variation, bounded execution time, and a safe response when the input does not belong to any learned category.
