Skip to main content

KNIFE-009 – v10 / v10L: a PyTorch CNN on the bird's ESP32-S3 (to explore)

danger

Problematic breadboard and PCB design - Not ready nor used, proper dedicated breadboard KNIFEs are KNIFE-018 and onwards.

📅 2026-10-12 · stav: backlog · priorita: vysoká · ✍️ Ondrej Špánik

Question. Can the whistle detector from KNIFE-008 be replaced by a convolutional neural network (CNN) that we design and train in PyTorch, and can that network run directly on the bird's own microcontroller?

Short answer. Not directly: a microcontroller has no Python and no PyTorch runtime, and only 512 KB of on-chip RAM. But the usual way works: train in PyTorch on a PC, export the network, quantize it to 8-bit integers and run it with an embedded inference library on the ESP32-S3. A whistle classifier is small enough for that by a wide margin (6-60 thousand parameters, under 3 million multiply-accumulates per second of audio, see the budget below). Two maintained paths exist for Espressif chips: ESP-DL (Espressif's own, PyTorch/ONNX in via the ESP-PPQ quantizer) and TensorFlow Lite Micro (esp-tflite-micro, PyTorch in via Google's ai-edge-torch or ONNX). Everything below is a plan to explore: nothing here has been trained, converted or run yet.

1. Which chip: the colleague's "AT8089" and why v10 stays on the ESP32​

  • A colleague worked with a chip noted as "AT8089". No part with that number turned up in a search. The closest match is Microchip's (formerly Atmel's) AT89 family, 8-bit 8051 microcontrollers, e.g. AT89C51: 4 KB flash, 128 bytes of RAM, up to 24 MHz. Even the smallest network below (model A) needs about 9.6 kB of RAM for its activations, about 75 times the AT89C51's 128 bytes, and its 5.8 kB of weights do not fit the 4 KB flash, so an AT89 could at most be a helper, never the CNN.
  • Decision (2026-10-12): keep the ESP32 for v10, and use the ESP32-S3 variant: 2 x Xtensa LX7 at 240 MHz, 512 KB SRAM, vector instructions that Espressif's ESP-NN / ESP-DL libraries use for int8 convolutions, and on the board we buy, 8 MB flash + 2 MB PSRAM ("N8R2").
  • To do: get the exact part number of the colleague's chip (a photo of its marking is enough). If it turns out to be a capable part (an MCU with an NPU, a Cortex-M4/M7 or similar), it can be compared against the ESP32-S3 with the same model and the same tests from section 8.

Why the S3 and not the plain ESP32 of v9: Espressif's own TFLite Micro benchmark (Person Detection, time of one invoke()):

Chipwithout ESP-NNwith ESP-NNclock
ESP324084 ms380 ms240 MHz
ESP32-S32300 ms54 ms240 MHz
ESP32-P41395 ms73 ms360 MHz
ESP32-C33355 ms426 ms160 MHz

The S3 is about 7x faster than the ESP32 with the optimized kernels, and ESP-DL's fastest kernels target the S3 and P4 (on the plain ESP32, ESP-DL falls back to plain C operators). techfun.sk sells an ESP32-S3 N8R2 dev board for EUR 9.65.

2. The boards: v10 and v10L​

LELEK_board_v10.fzz (battery) and LELEK_board_v10L.fzz (5 V from the dev board's USB) are v9 / v9L unchanged (same nets, same PCB, same Q1 switch in the DFPlayer Pro's ground, sound = button held AND whistle). The CNN is software; the board only had to give the microcontroller clean access to the microphone and the player switch, which v9 already does. The changes:

v9 / v9Lv10 / v10L
Dev boardany ESP32 (you have one)ESP32-S3 N8R2, techfun.sk EUR 9.65
MIC (MAX9814 OUT)GPIO34 (ADC1)GPIO4 (ADC1 channel 3)
CTRL (Q1 gate)GPIO25GPIO5 (S3 strapping pins 0, 3, 45, 46 avoided)
Dev board current in the simulation50 mA100 mA (CNN at 240 MHz, Wi-Fi off; an estimate)
v10 cell current, listening / playing0.06 / 0.17 A0.10 / 0.21 A (cell rated 0.25 A)
Checks11/11, 12/12 nets11/11, 12/12 nets; breadboard = schematic; ngspice OK

Kept on purpose: the MAX9814 analog microphone (sold by techfun.sk; no I2S MEMS microphone such as the INMP441 is listed there) and 8 kHz sampling: a whistle lives at about 0.5-4 kHz, so 8 kHz (0-4 kHz band) is enough and halves the input size against the 16 kHz that speech models use. v9's whistle.ino runs on the S3 with MIC_PIN 4, CTRL_PIN 5 until the CNN firmware exists, so v10 is never worse than v9.

v10 (battery) schematic, breadboard and PCB

v10 schematic

v10 breadboard

v10 PCB

v10L (USB) schematic, breadboard and PCB

v10L schematic

v10L breadboard

v10L PCB

3. Why a CNN at all (what it has to beat)​

v9's Goertzel detector is cheap and explainable, and in the Python tests it already rejects noise, speech-like sound, claps and the bird's own churr. Its known weakness is any steady tone in the band: an oven beep, a phone, a kettle whistle all count as "whistle". A CNN looks at a whole second of spectrogram, so it can learn what a human whistle looks like (onset, slight pitch wobble, breath noise, no harmonics stack like a buzzer) and what a beep looks like. That is the measurable reason to do this: fewer false triggers at the same hit rate. If a CNN cannot beat the Goertzel detector on the same recordings (section 8), the Goertzel detector stays.

4. The pipeline​

  1. Record real audio through the real microphone, ideally already inside the wooden bird (the wood and the sound hole change the sound): the ESP32-S3 streams raw 8 kHz ADC samples over USB serial to a PC script that saves WAV files.
  2. Features: 1 s windows, 256-sample frames (32 ms) without overlap -> 31 frames; 32 log-mel bands over 0-4 kHz -> a 1 x 32 x 31 "image" per window. Computed the same way on the PC (for training) and on the board (for inference).
  3. Train a small CNN in PyTorch on those images (section 5), with float32 weights.
  4. Export the trained model (ONNX via torch.onnx.export, or torch.export for ai-edge-torch).
  5. Quantize to int8 with a calibration set of real recordings (post-training quantization); if accuracy drops, quantization-aware training.
  6. Deploy: the quantized model goes into the firmware as a C array (TFLite Micro) or an .espdl file in flash (ESP-DL); the firmware computes the features, runs the network every 256 ms on the last 1 s, and drives CTRL as whistle.ino does today.
  7. Evaluate float vs int8 on the PC, then on the board (section 8).

The step most likely to go wrong silently is 2: if the board computes its log-mel features even slightly differently from the PC (FFT scaling, window, mel filter edges, log offset), the network sees inputs it was never trained on. Plan: write the feature code once in C, compile it for the PC too (ctypes or a small CLI) and train on its output, so both sides use literally the same code; check with a test vector that the board and the PC produce the same 32 x 31 numbers.

5. How big a network: the budget​

ml/cnn_budget.py (in ST-017-MOTHERBOARD) counts parameters, multiply-accumulates (MACs) and peak activation memory for three candidates on the 1 x 32 x 31 input:

ModelLayersParams (= int8 bytes)MACs per inferenceActivations peak
A tiny, 2 classesconv3x3 8 -> pool -> conv 16 -> pool -> conv 32 -> global avg -> FC 25 954 (5.8 kB)0.61 M~9.6 kB
B small, 4 classesconv 16 -> pool -> 32 -> pool -> 64 -> pool -> 64 -> gap -> FC 460 484 (59.1 kB)2.72 M~19.2 kB
C DS-CNN style, 4 classesstrided conv 32 + 5 depthwise-separable blocks (32-64) -> gap -> FC 418 788 (18.3 kB)1.01 M~16.0 kB

All three fit the S3's internal SRAM with room to spare (the 2 MB PSRAM is not needed for these). Running one inference every 256 ms means 4 inferences per second, i.e. 2.4-11 M MACs per second. The actual time per inference has to be measured on the board; the benchmark above (54 ms for Person Detection with ESP-NN) is a much larger image model and only says the S3 is in the right league. Start with A (whistle / not whistle); move to C if A confuses whistles with beeps; B is the "if all else fails" size.

Layers to stick to, because every runtime supports them and they quantize well: Conv2d (3x3, also depthwise), ReLU, MaxPool / AvgPool, global average pooling, Linear. Fold BatchNorm into the convolutions before export; leave Softmax out of the exported graph (take the larger logit on the board). No LSTM/GRU, no attention.

6. The ways from PyTorch to the board​

PathHowRuns onProsCons / to check
ESP-DL (Espressif)PyTorch -> ONNX -> ESP-PPQ (pip install esp-ppq) quantizes with calibration data and writes .espdl (FlatBuffers) -> ESP-DL C++ APIESP32-S3, ESP32-P4 (optimized); ESP32 with plain C operatorsEspressif's own path for exactly this chip; int8 (w8a8), int16 (w16a16) and mixed w8a16 per layer; Conv2D / DepthwiseConv2D dual-core on the S3Needs ESP-IDF 5.3 or newer (not the Arduino IDE the v9 firmware uses); check each layer against ESP-DL's operator list
TensorFlow Lite Micro (esp-tflite-micro)PyTorch -> ai-edge-torch (torch.export based; PT2E quantization for int8) -> .tflite -> C array; or PyTorch -> ONNX -> onnx2tf -> full-int8 .tfliteESP32, S3, P4, C3 (ESP-NN kernels)Widely used (micro_speech keyword spotting is the same kind of problem); benchmarks aboveInt8 conversion from PyTorch is the fiddly part: the ONNX route adds layout Transposes and conversion errors are common; ai-edge-torch's int8 output has to be checked against TFLM's supported ops
Edge Impulse "bring your own model"Upload the ONNX export; it quantizes and generates a C++ library with DSP + modelESP32 family, Arduino library exportLeast glue code, includes MFCC/mel DSP blocksA hosted service; check its current ESP32-S3 support and licence terms before relying on it
Hand-written int8Export model A's ~6 k weights as C arrays and write the 3 convolutions, pooling and FC by hand (or call ESP-NN's functions)anything, also ArduinoFull control, tiny, no framework; fits the current Arduino firmwareOwn quantization code to get right; only sensible for model A
ExecuTorch (PyTorch's own on-device runtime)torch.export -> ExecuTorch programCortex-M / Ethos-U and Cadence DSP backendsNative PyTorch pathNo ESP32 / Xtensa LX7 backend found (search 2026-10-12): not a path today; recheck later

Recommended order to explore: (1) ESP-DL with model A (Espressif's path for the chip we chose), (2) TFLite Micro with the same model as the cross-check and fallback, (3) hand-written int8 for model A if the Arduino firmware should stay (ESP-DL needs ESP-IDF; Arduino can run as an ESP-IDF component if needed).

"Use PyTorch directly on the board" in the literal sense (MicroPython, a libtorch build) is not realistic on a 512 KB microcontroller; the PyTorch model stays the source of truth on the PC, and every board model is generated from it by a script, never edited by hand.

7. Data to collect​

Proposed first data set (numbers are a plan, not measurements):

ClassWhatTarget
whistledifferent people, pitches, short/long, near/far, in the bird300+ windows
beep / toneoven, phone, kettle, a 1-3 kHz tone from a phone app200+ (the Goertzel detector's weak spot)
speech / musictalking, singing, radio, the churr itself300+
noise / silenceroom noise, handling the bird, pressing the button, claps300+

Rules: split by recording session, not by window, so the test set has sessions the network never heard; keep a separate set recorded later in the real enclosure; record the button's click and the bird's own churr as negatives.

8. How to judge it (proposed)​

  • On the PC, float and int8: hit rate on whistles, false triggers per hour on long negative recordings (TV, kitchen, conversation), and the same numbers for v9's Goertzel detector on the same files (firmware/whistle/whistle_sim.py).
  • On the board: time per inference, RAM and flash used, current at 3.3 V (v10: the cell is rated 0.25 A and the simulation already shows 0.21 A while playing), time from the end of the whistle to CTRL.
  • Accept the CNN when: hit rate at least the Goertzel detector's, at least 5x fewer false triggers on beeps, inference under 100 ms, and the v10 cell current measured under its rating.

9. Open questions and next steps​

  • Exact name of the colleague's chip; if capable, run the same model and tests on it.
  • Build v10L first (USB power, no battery risk) with the ESP32-S3 and v9's whistle.ino (pins 4 / 5) as the baseline.
  • Recording firmware + PC script (8 kHz raw over USB serial), then collect section 7's data set.
  • Feature code in C shared by the PC and the board; test vector check.
  • Train model A in PyTorch; float and int8 results against the Goertzel baseline.
  • Convert with ESP-PPQ / ESP-DL (ESP-IDF 5.3+); measure on the board. Then the same with TFLite Micro.
  • Measure the ESP32-S3's real current (v10 battery margin) and boot time on each press.
  • Decide: CNN, Goertzel, or both (Goertzel as a cheap wake-up, CNN to confirm).

Sources (read 2026-10-12): espressif/esp-dl, ESP-DL user guide, espressif/esp-tflite-micro, AI Edge Torch announcement, ExecuTorch on Arm microcontrollers, PyTorch -> TFLite on ESP32 example, Atmel AT89 series, techfun.sk ESP32-S3 N8R2.


← KNIFE-008 · ↩️ Všetky KNIFE príspevky · KNIFE-010 →