Wake Word on an MCU

A microcontroller hears 16,000 samples a second all day. Every 20 ms it turns the newest ones into 40 numbers, scores them, and sleeps. One threshold sets how often it wakes by mistake.

Pick a sound, then drag the threshold. Watch the 40-band picture of the sound roll past, the score climb, and the processor wake and sleep underneath. Then we build every box in that pipeline, in firmware terms, from zero.

You need a feel for what a sample is (one number that says how far the air pressure moved) and a little C. We build the rest from zero. It follows fixed-point DSP on a Cortex-M and the sensor-to-feature pipeline.

Built from primary sources, none of them slides: Warden, Speech Commands (2018); Zhang et al., Hello Edge (2017); the TensorFlow Lite Micro micro_speech example; Apple, Hey Siri (2017); the CMSIS-DSP MFCC docs; and the STM32L476 product page. The full list is in the Field Guide.

Listen for the wake sweep

0.45

A model, not real silicon. The keyword is a rising whistle sweep from 600 to 2,400 Hz in 0.6 s, so a toy template matcher can stand in for a trained network; your spoken voice will not trigger it, but a rising whistle into My mic will. The front end is real: 16 kHz, 480-sample Hann window, 320-sample hop, 512-point FFT, 40 mel bands, log. Power uses ST's headline 100 µA/MHz run figure for the STM32L476 at 80 MHz; the cycle counts and the idle current are illustrative.

Chapter 0

A Battery That Never Stops Listening

See why a speaker on a shelf cannot send its microphone to the cloud, and what it must do on the chip instead

A small speaker sits on your kitchen shelf. You say a short phrase, and it lights up. You did not press a button. It was listening the whole time, and it decided on its own that you meant it.

Now think about what “listening the whole time” costs. The microphone never rests. The chip behind it must look at every moment of sound, and 99.99% of those moments hold nothing useful: a fridge hum, a tap running, a person talking to someone else. The device has to ignore all of it, cheaply, and still catch the one phrase that matters.

Why not just send the sound to a server?

A server could run a huge speech model without any trouble. So why not stream everything up and let it decide? Do the arithmetic first. A sample is one number that records how far the air pressure moved at one instant. A typical voice recording takes 16,000 samples per second, and each sample uses 16 bits (2 bytes). That is 32,000 bytes every second.

Over one hour, that is 115.2 megabytes (32,000 × 3,600). Over one day, it is about 2.76 gigabytes (115.2 × 24 = 2,764.8 megabytes). One shelf speaker would upload that much, in a home that mostly sounds like nothing. Multiply by millions of homes.

Pete Warden, who built the Speech Commands dataset for this exact job, gives the same answer in plain words. Sending audio data over the web from all devices all the time would be very costly to maintain and would increase the privacy risks. So the first detection step must run on the device. The server only hears the sound after the device has decided that someone is talking to it.

Stream everything, or upload on wake

Two bars on a log scale: bytes uploaded in one day. The warm bar streams the microphone all day. The teal bar uploads 3 seconds of sound after each wake event. Drag the number of wake events.

20

Exact arithmetic for 16 kHz, 16-bit, mono audio: 32,000 bytes per second. The 3 second upload per event is illustrative. A false accept counts as an event too: it uploads sound nobody meant to share.

Look at the teal bar when you drag the slider to 200. Even 200 events a day send under 20 megabytes, far less than the warm bar. Every wrong event still costs privacy, so the detector has to be right about when to wake.

What the chip has to be

Warden lists what a keyword spotting model needs, and the list reads like a firmware spec. It must be small and light on compute. It must run in a very energy-efficient way. Most of its input is silence or background noise, so false positives on that must be rare. Most speech it hears has nothing to do with the voice interface, so it must not trigger on random talk. And the unit of recognition is a single word or short phrase, not a whole sentence.

That last point is a gift. Recognising any sentence in any language needs a giant model. Recognising one short phrase, or ten of them, needs a small one. This lesson is about the small one. We follow the sound from the microphone to a yes or no, in the order that the firmware runs.

The plan has four parts. First, a front end turns raw samples into a compact picture of the sound: that picture is the log-mel spectrogram, a grid of 40 numbers per 20 milliseconds. Second, a tiny neural network scores the picture. Third, a decision rule turns a stream of scores into a wake or no wake. Fourth, the chip duty cycles: it sleeps between jobs, so the average power stays small.

Each part has a trap. The front end can disagree with the one used in training. The score can fire on a TV. The decision can be late. The sleep can be too shallow to matter. We meet each one with a number, a measurement, and a fix.

The road

  1. From microphone to decision: the whole pipeline, with the shape and rate of data at every stage.
  2. Cutting sound into frames: windows, hops, and the FFT.
  3. Mel bands and the log: why 40 numbers are enough.
  4. A network that fits in 40 kilobytes: the classifier, in int8.
  5. From clips to a stream: ring buffers, smoothing, and the decision rule.
  6. Wrong wakes and missed words: false accepts per hour.
  7. Sleeping between hops: duty cycling and the power budget.
  8. A cascade of cheaper ears: a tiny always-on stage that wakes a bigger one.
  9. Making the chip agree with Python: parity, overflow, and testing.
  10. Field guide: numbers, code, sources.
Why does a wake word detector run on the device instead of on a server?

Chapter 1

From Microphone to Decision

Follow one 20 millisecond slice of sound through ten stages and watch 32,000 bytes a second shrink to a single yes or no

Picture a conveyor belt in a bakery. Dough goes in at one end. At each station, a worker shapes it, and the pile gets smaller and more useful. At the far end, one finished loaf drops into a basket.

A wake word detector is that belt. Raw sound goes in at one end. At each station the firmware reduces it to something smaller that still carries the answer. At the end, one bit comes out: wake, or do not wake. Before we study each station, we walk the whole belt once, and we write down two things at every step: the shape of the data (how many numbers, in what grid) and its rate (how many bytes per second).

The heartbeat: a 20 ms block

The belt does not run sample by sample. It runs in blocks. The microphone interface, an I2S port or a PDM front end (the previous audio lessons, digital audio on the wire and DMA ping-pong), writes samples into memory by DMA, with no CPU work. The buffer has two halves. While DMA fills one half, the CPU may work on the other half.

We choose each half to hold 320 samples. At 16,000 samples per second, that is 20 milliseconds of sound (320 / 16,000 = 0.020 s). So every 20 ms the DMA controller raises an interrupt and says: this half is full. That interrupt is the heartbeat of the whole system. Fifty times a second the firmware wakes, handles one block, and goes back to sleep.

The TensorFlow Lite Micro micro_speech example uses the same numbers: 16 kHz audio, a 30 ms window, and a 20 ms stride between windows, which gives 49 spectrogram slices of 40 filterbank channels for one second of sound. The model input is 49 × 40. We adopt exactly these numbers, because they are an honest, working choice.

Ten stations

Use the slider below to stand at each station. Read the shape and the rate, and watch how the belt narrows. The widths of the bars are drawn on a log scale, so each step of width is a factor of ten.

Stand at a station

Each bar is one stage; its width is bytes per second on a log scale. Drag the slider to choose a stage and read its shape, its rate, and who does the work.

4

Rates are exact for the numbers in the text (16 kHz, 16-bit samples, 320-sample hop, 480-sample window, 512-point FFT, 40 mel bands). The float32 stages are a choice: a fixed-point build stores them in 2 or 4 bytes anyway. The 10 inferences per second figure comes from Hello Edge; Chapter 5 shows how a stream decides when to run the network.

Here is the belt in words, with the arithmetic. You will meet each number again.

  1. Microphone to PCM. The mic delivers 16,000 samples a second, 2 bytes each: 32,000 bytes a second. The data is a list of int16 values.
  2. DMA half buffer. 320 samples = 640 bytes per block, 50 blocks a second. DMA does this with no CPU.
  3. Window. The CPU takes the newest 480 samples: the 320 just arrived plus the last 160 from the previous block. Overlap is how we keep a smooth picture. Each sample is read 1.5 times (480 / 320). A bell-shaped weighting (Chapter 2) is applied.
  4. FFT. A 512-point transform turns 480 samples (padded with zeros) into 257 numbers: how much power sits at each frequency, in steps of 31.25 Hz.
  5. Mel bands. 257 numbers become 40, by adding up groups of neighbours with triangular weights (Chapter 3).
  6. Log. Each of the 40 numbers is compressed by a logarithm, so a whisper and a shout both fit.
  7. Quantise to int8. 40 bytes per block, 2,000 bytes a second. The belt carries 16 times fewer bytes than at the start (32,000 / 2,000).
  8. Feature ring. The newest 49 blocks, kept as a 49 × 40 grid: 1,960 bytes. This is one second of sound as a small picture.
  9. Network. The picture goes in, and 12 scores come out, one per class (Chapter 4).
  10. Decide. Smooth the scores, compare to a threshold, apply a quiet period. One bit leaves (Chapter 5).

The firmware skeleton

Now write the skeleton in C. Read the interrupt first. It does almost nothing: it records which half is ready and returns. The main loop sleeps until something happens, then does the whole belt for one block.

c  (STM32L476, HAL; mono 16 kHz PCM already arriving by DMA)
#define HOP   320                       /* 20 ms at 16 kHz */
static int16_t dma_buf[2 * HOP];         /* ping-pong: 2 x 640 bytes */
static volatile int16_t *ready;           /* which half is full, or NULL */
static volatile uint32_t overruns;

void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *h) { if (ready) overruns++; ready = &dma_buf[0]; }
void HAL_I2S_RxCpltCallback    (I2S_HandleTypeDef *h) { if (ready) overruns++; ready = &dma_buf[HOP]; }

int main(void) {
    board_init(); frontend_init(); kws_init();
    HAL_I2S_Receive_DMA(&hi2s2, (uint16_t *)dma_buf, 2 * HOP);
    for (;;) {
        __disable_irq();
        if (!ready) __WFI();               /* sleep; a pending interrupt still wakes the core */
        __enable_irq();
        if (!ready) continue;
        int16_t *blk = (int16_t *)ready;  ready = NULL;
        gpio_high(DBG_PIN);                  /* scope this pin: it is the CPU-busy time */
        frontend_push(blk, HOP);               /* window, FFT, mel, log, int8 -> feature ring */
        kws_step(feature_ring);                /* network, smoothing, decision */
        gpio_low(DBG_PIN);
    }
}

Three details matter. First, __WFI() is the Arm “wait for interrupt” instruction: the core stops fetching and waits. Hello Edge puts its chip in WFI for the time left between inferences. Second, the check and the sleep sit inside a disabled-interrupt window, so an interrupt cannot slip in between the check and the sleep and leave you sleeping with a full buffer. A pending interrupt wakes the core even while interrupts are masked. Third, overruns counts blocks that arrived before the last one was handled.

When the belt jams

The deadline is simple: the work for one block must finish before the next half fills, 20 ms later. If it does not, the symptom is odd and quiet. The detector still runs, but now and then a block is skipped, the spectrogram has a hole, and the score dips just when the user speaks. Nothing crashes.

You measure it, you do not guess it. Raise a GPIO pin at the top of the work and lower it at the bottom, then look at the pin on a scope or logic analyser. The high pulses should repeat every 20 ms and last well under 20 ms. Also log overruns over an hour: it must stay at zero. If the pulse nears 20 ms, shrink the work (a smaller network, Chapter 4), raise the clock, or add a third buffer so one slow block does not stack onto the next.

A wake word firmware uses 320-sample DMA half buffers at 16 kHz. How often does the CPU have to finish a block, and what happens if it is late?

Chapter 2

Cutting Sound Into Frames

Slice a stream into short overlapping windows, taper each one, and use the FFT to see which pitches it holds

Imagine you hum a rising note, from low to high. If I hand you the whole recording and ask “which pitch is in it?”, you cannot give one answer. The pitch changed. You need to ask the question in small pieces: “which pitch in this tenth of a second?”

That is the first job of the front end. Speech changes quickly, but over a very short time it holds nearly still. So we cut the stream into short pieces called frames and ask what pitches each piece holds. The tool that answers is the FFT, the fast Fourier transform: a quick way to split a short piece of sound into its pure tones and say how strong each one is.

Window and hop

Two numbers describe the cutting. The window is how much sound one frame looks at. The hop (also called the stride) is how far the window slides forward between frames. Our window is 480 samples: 30 ms. Our hop is 320 samples: 20 ms. Because the window is longer than the hop, neighbouring windows overlap by 160 samples (10 ms).

Why overlap? A syllable can start in the middle of a window. If windows did not overlap, such a start could be cut into two weak halves. With overlap, every moment of sound appears in at least one window near its centre.

Now count the frames in one second. The first window needs 480 samples. Each later window needs 320 more. So the number of frames is (16,000 − 480) / 320 + 1 = 48.5, and we keep the whole frames only: 49. That is the 49 in the 49 × 40 picture. Hello Edge reaches the same 49 with a 40 ms window and the same 20 ms stride.

Why we taper the window

The FFT has a hidden assumption. It treats its 480 samples as one cycle of a signal that repeats forever. But the end of our slice does not match its start. At the seam, the repeated signal jumps, and a jump sounds like a click. A click holds every pitch, so it spreads fake energy across the whole spectrum. This is spectral leakage.

The cure is to fade each slice in and out. We multiply the samples by a smooth bell-shaped curve that is zero at both ends. The common choice is the Hann window.

w[n]
The weight for sample number n. It is 0 at the first and last sample, and 1 in the middle.
n
The position inside the window: 0, 1, 2, up to N − 1.
N
The window length in samples. For us N = 480.

w[0] = 0.5 − 0.5 · cos(0) = 0    w[239.5] = 0.5 − 0.5 · cos(π) = 1 (the middle, between samples 239 and 240)

The price is small. A Hann window makes each spectral line a little wider (its main lobe spans four bins where a plain cut spans two), but it removes the fake energy far from the line. For a detector that reads the broad shape of a spectrum, that is a good deal.

From 480 samples to 257 numbers

The FFT works best on lengths that are powers of two. 480 is not one, so we add 32 zeros at the end and use 512 points. Zero padding does not add information. It only makes the output grid finer. The result is 257 values (512 / 2 + 1), because a real signal has a mirror-image second half that we can drop. Each value is a complex number; we keep its power, the real part squared plus the imaginary part squared.

Δf
The gap between neighbouring FFT bins, in hertz.
fs
The sample rate: 16,000 samples a second.
Nfft
The FFT length: 512 points.

Δf = 16,000 / 512 = 31.25 Hz, so bin 32 sits at 1,000 Hz and bin 256 at 8,000 Hz (half the sample rate)

An FFT of 512 points does about (512 / 2) × log2(512) = 256 × 9 = 2,304 small steps called butterflies. A transform built for real input does roughly half that. That is why one FFT per 20 ms is easy for an Arm Cortex-M4, and why doing the same job by the slow textbook method would not be. The ideas behind the FFT are in the FFT chapter of CLRS and in discrete signals; the fixed-point version for a Cortex-M is in fixed-point DSP on an MCU.

A longer window sees pitch, a shorter one sees time

You cannot have both. A long window holds many wave cycles, so it measures pitch finely, but it blurs anything that moves during the window. A short window follows fast changes, but it holds few cycles, so each line is fat. The width of a line is about one over the window length in seconds: 30 ms gives about 33 Hz.

Trade time against pitch

This is the rising sweep from the hero, 600 to 2,400 Hz in 0.6 s. The dashed line is its true pitch. Move the window length and see the picture smear or sharpen.

30 ms

Computed live in your browser from the same synthetic sweep, with a Hann window, a 320-sample hop and a 1,024-point FFT so that long windows fit; the firmware uses 512 points. Frequency width is estimated as 1 / window length.

Our choice, 30 ms, sits in the middle for speech. Phones last roughly 50 to 200 ms, and the sounds inside them change in tens of milliseconds, so a 30 ms window follows them without fattening the lines too much.

The window that does not match

Here is the trap. You train a model on features made by a Python library, then write your own C front end. The picture looks right. The accuracy is poor. The cause is often a tiny mismatch: a Hann window built with N instead of N − 1 in the formula (NumPy’s hanning uses N − 1, SciPy’s default “hann” window is periodic and uses N), a different pad length, or a different frame offset.

Measure it. Feed one saved sound file to both. Print the first frame’s power values from each side and subtract. If the largest gap is not close to zero, find out why before you touch the model. Chapter 9 turns this into a test.

Why does the front end multiply each 480-sample slice by a Hann window before the FFT?

Chapter 3

Mel Bands and the Log

Squeeze 257 power values into 40 bands that match how we hear, then compress their loudness with a logarithm

Play two notes on a piano, one at 200 Hz and one at 300 Hz. They sound far apart. Now play 5,200 Hz and 5,300 Hz. Both are 100 Hz apart again, but you can barely tell them apart. Our ears care about ratios of pitch at high frequencies, not equal steps in hertz.

The FFT gives us 257 numbers in equal 31.25 Hz steps. That is too fine at the top and too coarse at the bottom, and it is far more numbers than a tiny network needs. We want fewer numbers, spaced the way hearing spaces them. That is the mel scale, and the bands we build on it are mel bands.

The mel scale

The mel scale stretches low pitches and squeezes high ones. One common formula is below. It was fitted to listening tests, not derived from physics, so treat it as a good ruler.

mel
The pitch on the mel ruler. The constants 2595 and 700 make 1,000 Hz land at 1,000 mel.
f
The frequency in hertz.

1,000 Hz → 2595 × log10(2.4286) = 1,000 mel    2,000 Hz → 1,521 mel    4,000 Hz → 2595 × log10(6.7143) = 2,146 mel

See what happened. The first 1,000 Hz span 1,000 mel. The next 1,000 Hz, from 1,000 to 2,000, add only 521 mel. And the 2,000 Hz from 2,000 to 4,000 add only 625. Low pitches get more room.

Building 40 triangles

Our build uses 40 bands between 125 Hz and 7,500 Hz (our choice; the band edges are a design decision, so write them down). Those edges are 185.2 and 2,773.3 mel. We cut that stretch into 41 equal mel steps of 63.13 mel and turn the 42 points into hertz. Each band is a triangle: it rises from one point to the next and falls to the one after, so triangles overlap with their neighbours.

The result: band 0 covers 125 to 223 Hz, only 98 Hz wide, and gives non-zero weight to 3 FFT bins. Band 39 covers 6,631 to 7,500 Hz, 869 Hz wide, and gives non-zero weight to 27 bins. Each band adds up the FFT powers inside its triangle, weighted by the triangle. In code that is a sparse multiply: a list of start bins and short weight lists, so the whole step costs about as many multiply-adds as there are weights, a few hundred.

Drop a tone into the bands

The tone has a weak overtone at three times its pitch, 40 dB quieter. Slide the pitch. Top: the triangles that catch it. Bottom: the 40 band values. Switch the spacing and the bar scale and see what you lose.

1000 Hz

Real computation: a 0.5-amplitude sine plus a 0.005-amplitude overtone at 3 times its pitch, a 480-sample Hann window, a 512-point FFT, 40 triangles from 125 to 7,500 Hz. Bar heights use the same rule the firmware uses, 10 log10(power + a tiny floor).

Turn on Raw power bars. The tone fills one or two bars. The overtone is 40 dB quieter, which is a power ratio of 10,000, so its bar is too short to see. Switch to Log bars and the overtone appears. That is the next step, and it matters a great deal.

Why take the log

Loudness spans a huge range. A 16-bit sample covers about 96 dB, a power ratio of billions. A network that sees raw powers would spend all its attention on the few loud bands and ignore the rest. Our ears do the opposite: they hear loudness on a log scale, roughly. So we convert each band to decibels (dB): ten times the base-10 logarithm of the power.

dB
The band value the network sees.
E
The summed power in one mel band.
ε
A tiny floor. Without it, digital silence gives log of 0, which is minus infinity.

power ratio 10,000 → 10 × log10(10,000) = 40 dB; a doubling of power is only 3 dB

The log has a second gift. Make the whole sound louder by a fixed factor and every band moves by the same number of dB. After we subtract the average, the picture is unchanged. The detector then cares less about how far you stand from the microphone. (Chapter 9 shows where this gift breaks.)

MFCC, the older cousin

Many tutorials go one step further. They apply a discrete cosine transform to the 40 log values and keep the first 13 or so. The result is the MFCC, the mel-frequency cepstral coefficients. The transform makes the numbers less correlated and packs the shape of the spectrum into the first few. Hello Edge uses 40 MFCC features per frame. The CMSIS-DSP library offers the whole chain, window, FFT, mel, log and DCT, in one call for 16-bit fixed-point input:

c  (CMSIS-DSP, from the arm_mfcc_q15 documentation)
arm_mfcc_instance_q15 mfcc;
/* fftLen, nbMelFilters, nbDctOutputs, then the DCT, filter and window tables you generate offline */
arm_status s = arm_mfcc_init_q15(&mfcc, 512, 40, 13, dct_coefs, filter_pos, filter_len, filter_coefs, window_coefs);

q15_t  frame[512];            /* 480 samples + zeros; the call modifies it in place */
q15_t  out[13];               /* results come out in q8.7 format */
q31_t  tmp[2 * 512];         /* scratch of complex values; the docs give exact sizes */
arm_mfcc_q15(&mfcc, frame, out, tmp);

Q15 means a 16-bit number with 15 bits after the binary point, so it covers −1 up to just under +1; 0.5 is stored as 16,384. The docs warn that saturation can occur if the FFT length is large and the number of mel filters is small, because sums overflow the range. We study that in Chapter 9. Our lesson uses log-mel directly, which skips the DCT; many small models do the same, because a convolutional network can learn its own mixing.

When the front ends disagree

The mel step has its own traps. Libraries disagree: librosa’s default mel scale is the Slaney variant (linear below 1 kHz, log above), not the formula above, and it scales each triangle by its width. A band edge off by a few hertz moves energy between neighbours. The symptom is the same as in Chapter 2: the model scores well in Python and poorly on the chip. Measure by dumping 40 values for a 1 kHz test tone from both sides.

The floor ε is a second trap. A quiet room gives tiny powers, so ε sets what the quiet room looks like to the network. If training used one ε and firmware another, the quiet background shifts by tens of dB. Fix it by writing ε into the shared feature spec, the same file that holds 16,000, 480, 320, 512, 40, 125 and 7,500.

A tone has an overtone whose power is one ten-thousandth of the tone’s. What does a log (dB) feature do for it?

Chapter 4

A Network That Fits in 40 Kilobytes

Turn a 49 by 40 picture of sound into 12 scores with a small int8 network, and count what that costs the chip

Think of a judge at a talent show who has three seconds to look at a picture and call a name. The picture is the log-mel grid from the last chapter: 49 columns of time, 40 rows of pitch, one second of sound. The name is one of twelve: ten command words, silence, or unknown.

A neural network is that judge. It is a stack of simple steps. Each step takes numbers in, multiplies them by stored numbers called weights, adds the products up, and passes the result on. Training sets the weights so the right name wins. On the chip, we only run it: we never train there.

The data the network learned from

Warden’s Speech Commands set was built for exactly this job. Version 2 has 105,829 utterances of 35 words. Each is a one-second (or shorter) clip, stored as 16-bit mono PCM at 16 kHz, recorded by thousands of people on ordinary devices, so it carries real background noise. The Hello Edge study used the earlier release of 65,000 clips and 30 keywords. It trained the network to pick one of ten words (“yes”, “no”, “up”, “down”, “left”, “right”, “on”, “off”, “stop”, “go”), or silence, or unknown, which stands for the 20 other words. That is 12 outputs.

The convolution and its cheaper cousin

A convolution is a small stamp, say 3 × 3 numbers, slid over the picture. At each spot it multiplies stamp and picture, adds up, and writes one number. Stamps learn to spot small patterns: a rising edge, a burst, a flat hum. Stack many stamps and many layers, and the network finds bigger patterns, such as the shape of a word.

A normal convolution is costly because every stamp looks at every input channel. A depthwise separable convolution, the trick behind MobileNet, splits the job in two. One thin stamp per channel looks at space only. Then a 1 × 1 step mixes channels. Count the multiply-adds per output position with 64 input channels, 64 output channels and a 3 × 3 stamp:

normal: 3 × 3 × 64 × 64 = 36,864    separable: 3 × 3 × 64 + 64 × 64 = 576 + 4,096 = 4,672    ratio = 36,864 / 4,672 = 7.9

Nearly eight times fewer. Hello Edge built a network of such layers, a DS-CNN, and found it won on a small chip. Their three size classes, S, M and L, cap memory at 80, 200 and 500 KB and operations per inference at 6, 20 and 80 million, assuming 10 inferences per second and 8-bit numbers. Their best models at each class:

ClassDS-CNN accuracyMemoryOperations
S (80 KB, 6 MOps)94.4%38.6 KB5.4 million
M (200 KB, 20 MOps)94.9%189.2 KB19.8 million
L (500 KB, 80 MOps)95.4%497.6 KB56.9 million

Read the first row twice. The small model uses less than half of its 80 KB allowance and still scores 94.4%. A plain deep network (DNN) of the same 80 KB class reaches only 84.6%.

Why int8

Those memory numbers assume int8: each weight and each intermediate value is one signed byte, not a 4-byte float. Hello Edge reports that this costs no accuracy for the models it tested, even without retraining. The mapping is a simple ruler: real value = scale × integer. If weights lie in −1.27 to 1.27, take scale 0.01. Then 0.534 becomes 53, and 53 stands for 0.53, an error of 0.004. Bytes shrink four times, and the chip’s integer multiply-accumulate instructions run it fast. The full method is in quantization I and quantization II; the firmware side, with overflow and requantisation, is in int8 in firmware.

What it costs the chip

Two budgets matter. Flash holds the weights (read only, cheap). RAM holds the working numbers while the network runs, a block that TensorFlow Lite Micro calls the tensor arena. Hello Edge’s deployed demo (a DNN on a Cortex-M7 board, the STM32F746G-DISCO) fit in about 70 KB in total: roughly 66 KB of weights, 1 KB of activations, and 2 KB for audio and features. And the TensorFlow Lite Micro micro_speech model is under 20 KB.

Time is the other budget. Run the network 10 times a second, so each inference gets at most 100 ms. How long does it take? Divide operations by what the chip does per second. The chip’s clock gives cycles per second; the kernel code decides how many operations finish per cycle. Plain loops manage under one. Arm’s CMSIS-NN kernels use SIMD instructions on Cortex-M4 and M7 to pack several 8-bit multiply-adds in one instruction. Try it:

Fit a model to a clock

Each dot is one model from the Hello Edge study. The purple ring marks the DS-CNN. Choose a size class, then set the clock and how many operations the code retires per cycle.

80 MHz
1.0

Accuracy, memory and operations are the Hello Edge study’s (Table 5, 8-bit weights and activations). Operations per cycle is a knob, not a measurement: scalar C is often below 1, SIMD kernels can be higher. Time = operations / (operations per cycle x clock), at 10 inferences a second as in the paper.

Set the class to S, the clock to 80 MHz and one operation per cycle. The DS-CNN needs 5.4 million operations, which takes 67.5 ms of every 100 ms. The chip is awake two thirds of the time, just to run the model. Now double the operations per cycle: 33.8 ms. Pick M at the same settings and the answer reads 247.5 ms per 100 ms. It cannot keep up. The model must fit the clock, not just the memory.

Where it breaks

Symptom: the board resets, or AllocateTensors() reports an error, right after you add a bigger model. Cause: the arena is too small for the model’s working buffers. Measure: ask the interpreter how much it used (arena_used_bytes()) with a generous arena, then trim to that plus a small margin. Fix: a smaller model, a different layer order, or more RAM. A second symptom is a model that runs but is late. Measure with the cycle counter around Invoke(), not with a stopwatch on a guess.

c++  (TensorFlow Lite Micro; API details vary between versions)
constexpr int kArena = 16 * 1024;                       // start generous, then trim to arena_used_bytes()
alignas(16) static uint8_t arena[kArena];

const tflite::Model *model = tflite::GetModel(g_kws_model);   // the weights, in flash
static tflite::MicroMutableOpResolver<5> ops;
ops.AddConv2D(); ops.AddDepthwiseConv2D(); ops.AddAveragePool2D();
ops.AddFullyConnected(); ops.AddSoftmax();
static tflite::MicroInterpreter interp(model, ops, arena, kArena);
if (interp.AllocateTensors() != kTfLiteOk) fatal("arena too small");

TfLiteTensor *in = interp.input(0);                  // int8 [1, 49, 40, 1]
memcpy(in->data.int8, feature_ring, 49 * 40);       // the 1,960-byte picture
uint32_t t0 = DWT->CYCCNT;
interp.Invoke();
uint32_t cycles = DWT->CYCCNT - t0;                    // log this
TfLiteTensor *out = interp.output(0);                // int8 [1, 12]: one score per class
A DS-CNN needs 5.4 million operations per inference, 10 inferences a second, on an 80 MHz chip doing 1 operation per cycle. What share of the time is the chip busy with the model?

Chapter 5

From Clips to a Stream

Turn a model that judges tidy one-second clips into a detector that works on sound that never stops

In the lab, a test clip starts exactly when the word starts. In your kitchen, nothing starts on cue. The word could begin at any instant, and the microphone keeps running before and after it. The model was trained on neat one-second clips. The chip must face a river.

The fix is a sliding window. Every 20 ms the chip takes the newest one second of features and asks the network what it sees. The window slides along the stream, and sooner or later one position lines up with the word well enough for a high score. Warden describes the same problem for his dataset: models in products get a continuous stream and do not know when words start and end, whereas the usual accuracy test aligns every clip to its start.

The feature ring

Sliding costs memory traffic. Recomputing the whole 49 × 40 grid every hop would repeat 48 rows of work that has already been done. So the firmware keeps a ring buffer of feature rows: an array of 49 rows plus one number, head, that says where the oldest row sits. A new row overwrites the oldest and head moves one step. Nothing else moves.

When the network needs its input, it wants the rows in time order, oldest first. Copy the rows from head to the end, then the rows from the start up to head. That is two copies of 1,960 bytes in all, which costs microseconds, and it is much cheaper than recomputing 48 rows of FFTs.

c  (feature ring and the decision, int8 features and a 0..255 wake score)
#define ROWS 49
#define COLS 40
static int8_t  ring[ROWS][COLS];
static uint8_t head;                                     /* index of the oldest row */

void feature_push(const int8_t row[COLS]) { memcpy(ring[head], row, COLS); head = (head + 1) % ROWS; }
void feature_copy(int8_t *dst) {                       /* oldest row first, for the network */
    uint8_t n1 = ROWS - head;
    memcpy(dst,               ring[head], n1   * COLS);
    memcpy(dst + n1 * COLS,   ring[0],  head * COLS);
}

#define SM     4                                  /* smoothing: average of the last 4 scores = 80 ms */
#define QUIET  25                                 /* refractory: 25 hops = 0.5 s of silence after a wake */
static uint8_t  hist[SM]; static uint8_t hi; static uint16_t sum; static uint8_t quiet;
bool decide(uint8_t score, uint8_t thresh) {
    sum += score; sum -= hist[hi]; hist[hi] = score; hi = (hi + 1) % SM;
    if (quiet) { quiet--; return false; }
    if (sum >= (uint16_t)SM * thresh) { quiet = QUIET; return true; }
    return false;
}

Why smooth the scores

A network scores each window on its own, and the numbers flicker. One hop it says 0.8, the next 0.2, the next 0.7, even on a steady sound. If you fire the moment one score passes the threshold, noise alone will sometimes cause it. If you demand a high score and nothing less, you will miss words that score 0.8, 0.2, 0.7.

The cure is to average the last few scores. A real word raises many windows in a row, so its average stays high. A random spike lifts one window, and the average barely moves. The price is delay: an average over S hops lags the true rise by about (S − 1) / 2 hops, so S = 4 adds about 30 ms.

Add one more rule: after a wake, stay quiet for a short while. Without it, one word keeps the score above the threshold for ten hops and fires ten times. Warden’s reference code has a rule of this kind, and his scoring tool counts a recognition as correct if it lands within a time tolerance of the true word, 750 ms by default.

Smooth the score, then decide

Left of the dotted line the stream holds the wake sweep (true event, in the green band). Right of it, the look-alike sweep. Thin line: the jittery raw score. Thick line: the average. Move both sliders.

6 hops
0.45

The scores come from this page’s own front end and template matcher on a 4.8 s stream. Jitter of up to +/-0.25 per hop is added, seeded and the same every visit, to mimic the frame-to-frame flicker of a small network; it is illustrative. The quiet period is fixed at 25 hops (0.5 s).

Try this: set smoothing to 1 hop and the threshold to 0.20. The detector fires eight times, six of them on noise. Raise smoothing to 6 hops: the noise fires vanish, and two remain, the true word and the look-alike sweep. Now raise the threshold to 0.45: the look-alike goes too. Push smoothing to 12 hops and the true word itself fades out, because the average spreads its short peak over many hops. Smoothing and threshold are two knobs on one trade, and Chapter 6 puts a number on that trade.

Choosing when to run the network

The front end runs on every 20 ms hop, 50 times a second. The network need not. Hello Edge runs 10 inferences a second, so one inference per five hops, and puts the chip in WFI sleep for the rest. That saves four fifths of the network cost. The price: the best-aligned window can be up to 100 ms from the true word, a small loss. Pick the inference rate from the budget in Chapter 4 and the latency you can accept.

When the stream and the clip disagree

Symptom: the model scores 95% on the test set, but in the living room it misses words, or fires too late. Cause: the test set is aligned to the word, and the stream is not. Another cause is a quiet period that is too short or too long. Measure: record a ten-minute stream with known word times, run the firmware on it, and count three things: matched words, wrong words, and fires with no word. Warden does exactly this on a 10-minute streaming test file: his baseline reports 49.0% matched, 46.0% correct, 3.0% wrong and 0.0% false positives. Fix: tune smoothing, threshold and the quiet period against that stream, not against the clip set.

A detector fires ten times on one spoken word, one fire per hop. Which two changes fix this, and what does the second cost?

Chapter 6

Wrong Wakes and Missed Words

Measure a detector in false accepts per hour, see why one a week is hard to prove, and set the threshold with your eyes open

It is evening. A television in the next room plays a talk show. Your speaker lights up. Nobody said anything to it. A minute later it lights up again. By the third time you unplug it.

Now flip the story. You walk in, say the phrase clearly, and nothing happens. You say it louder. Nothing. You give up and press the button. Both stories are failures of the same detector, set at the wrong point on one dial.

Two ways to be wrong

A false accept is a wake when nobody said the word. A false reject (or miss) is no wake when somebody did. They pull against each other through the threshold. Raise the threshold and false accepts drop, but more true words fall below the bar. Lower it and the reverse happens.

The two are not measured the same way. A miss is a fraction of the words spoken: out of 100 wake words, 5 missed is 5%. A false accept needs a different yardstick, because there is no list of “things nobody said” to take a fraction of. Apple’s write-up on “Hey Siri” uses false accepts per hour of listening, and says the team needed test data large enough to estimate rates as low as one a week. Warden also stresses that most of what a device hears is silence or speech aimed at someone else, so false positives on those must be minimised.

Counting decisions

Take our detector at 10 inferences a second. In one hour it makes 10 × 3,600 = 36,000 decisions. To false accept only once a week (168 hours) it may be wrong on at most 1 of 36,000 × 168 = 6,048,000 decisions. That is a per-decision error of about 0.000 000 165, or 1.65 × 10−7.

Suppose the scores of non-wake sounds follow a bell curve with some centre and width. Then the bar must sit about 5.1 widths above the centre to reach 1.65 × 10−7. That is far out in the tail, where a bell curve and reality part ways: real scores have fat tails, because real sound contains odd cases such as a kettle, a song, a cough that sounds like a syllable. So treat the bell curve below as a teaching toy, not a forecast.

Set the bar, read the cost

Top: score curves, grey for everything that is not the wake word, teal for spoken wake words, with your threshold. Bottom: the trade, misses against false accepts per hour on a log scale. The dot is your setting. Drag the threshold, then make the world noisier.

0.50
x1.00

Illustrative. Non-wake scores: a bell curve centred at 0.10 with width 0.08; wake scores: centred at 0.70 with width 0.12; the noise slider multiplies both widths. Decisions per hour = 10 per second x 3,600 = 36,000, treated as independent; real windows are correlated, and real tails are fatter than a bell curve. The calculation is exact for these curves.

Start at the threshold 0.50 and noise x1.00. About 4.8% of wake words are missed. False accepts come once every four days or so. Good enough? Slide the noise to x1.50. The curves widen and overlap, and the same threshold now false accepts about 15 times an hour. You can buy back the false accepts only by missing more words. The only real cure is to pull the curves apart, with a better model, better features, or a second stage (Chapter 8).

How long must you listen to know?

Here is the cruel part. Suppose you leave a prototype listening to recorded television for 100 hours and it never fires. Have you shown it false accepts less than once a week? No. A simple rule of thumb says: if you see zero events in n hours, the rate could still be as high as about 3 / n per hour at 95% confidence (the “rule of three”). With n = 100 that is 0.03 an hour: once every 33 hours. To bound the rate by one per 168 hours you need n = 3 × 168 = 504 hours, three weeks of audio, with the kind of sound the product will actually meet.

So test data is a product in itself. It needs hours of talk radio, television, music, kitchen noise, other people’s speech that is close to the wake phrase in sound, and many voices and rooms.

A second chance

Apple describes a trick for the miss side. The detector has two thresholds: the normal one, and a lower one that does not wake the device. A score between the two moves the detector into a more sensitive state for a few seconds. If you repeat the phrase in that window, the lower bar is enough. You get fewer misses without opening the front door to false accepts.

Symptom, measurement, fix

Symptom: the device wakes during television at night. Measure: play 24 hours of recorded television and talk radio at room level, count the pulses on a GPIO that fires on each decision, and log the score and two seconds of features around each one. Divide the count by 24. Fix: in the order of cost: raise the threshold and see what it costs in misses; add the look-alike sounds the log shows to the training set as negatives; lengthen the phrase, because a longer phrase has fewer accidental matches; add a second stage that rechecks every fire.

A prototype runs 100 hours on recorded television and never fires. What can you honestly claim?

Chapter 7

Sleeping Between Hops

Work out the average current of a chip that wakes 50 times a second, and find the three levers that matter

A tortoise and a hare both cross the same field. The hare sprints, then naps. The tortoise plods the whole time. Which one burns more food? It depends on how hungry each mode is, and on how long each one runs. A chip that listens all day is a hare that naps 50 times a second. To know its battery life, you need to know its sprint, its nap, and the share of time in each.

Average current, in one line

A battery does not care about the shape of the current. It only counts the total charge drawn. A current measured in milliamps (mA), drawn for some seconds, is a charge. So the number to know is the average current: the total charge in one repeat of the cycle, divided by the cycle length.

Iavg
The average current over one cycle, in milliamps. It sets battery life.
Σ Ii · ti
Add up, for each state i (running, sleeping, microphone on), its current times the time spent in it.
T
The cycle length. Ours is 100 ms: five feature hops and one inference.

The numbers for one chip

Take the STM32L476, the Cortex-M4 chip on the Nucleo-L476RG. ST’s product page gives headline figures: a run-mode current of 100 µA per MHz with the internal linear regulator, 39 µA per MHz with the switching regulator (SMPS) at 3.3 V, and 1.1 µA in its Stop 2 mode. These are marketing summaries under favourable test conditions; the datasheet’s electrical tables hold the exact conditions, so check them before you design with them. At 80 MHz the linear regulator gives 80 × 100 µA = 8.0 mA while the CPU runs.

How much work is there per cycle of 100 ms? Hello Edge measured one full inference, with memory copy, feature extraction and network, at about 12 ms on a 216 MHz Cortex-M7 at 10 inferences a second. That is 12 ms × 216 MHz = 2.6 million cycles per 100 ms. If we assume our Cortex-M4 spends the same cycles (a rough assumption; the cores differ), then at 80 MHz the work takes 2.6 M / 80 MHz = 32.5 ms of each 100 ms. The chip is awake 32.5% of the time.

run: 0.325 × 8.0 mA = 2.60 mA    idle (illustrative 0.4 mA): 0.675 × 0.4 = 0.27 mA    microphone and the rest (illustrative): 0.30 mA    total = 3.17 mA

A 220 mAh coin cell (an illustrative size) would last 220 / 3.17 = 69 hours. Under three days. That is why this first design is not a wearable. Play with the levers:

Pull the power levers

Yellow blocks are the processor running; the thin floor is idle plus the microphone. Change the clock, the regulator, the work per cycle, the idle floor and the battery. Watch the average, not the peak.

80 MHz
2.6 M cycles
0.40 mA

A model, not a measurement. Run current = clock x the ST headline figure for the L476 (100 µA/MHz linear, 39 µA/MHz SMPS, to be checked in the datasheet). The 2.6 M cycles per 100 ms is derived from Hello Edge (12 ms at 216 MHz) and assumed equal on the M4. Idle floor, the 0.30 mA for the microphone and the rest, and the three battery sizes are illustrative. A real coin cell would also sag under 8 mA pulses.

Three levers, and one that is a trap

Set the clock to 20 MHz and watch the average. The yellow blocks get long, and the run part of the average barely changes. Here is why. The charge for a job is cycles × (charge per cycle). Charge per cycle is the run current in µA per MHz, a fixed property of the chip, here 100 µA / 1 MHz = 1 × 10−10 coulomb per cycle. So 2.6 M cycles always cost 2.6 × 106 × 10−10 = 260 µC, whatever the clock. Slowing the clock only spreads the same charge over more time. It changes nothing unless the idle floor is bigger than the run cost.

So the levers are these.

  1. Fewer cycles. A smaller model, SIMD kernels, a leaner front end. Halve the cycles and you halve the run part.
  2. Cheaper cycles. The switching regulator turns 100 µA/MHz into 39. Same work, 2.6 times less charge.
  3. A lower floor. Idle plus microphone were 0.57 mA in our example, nearly as much as the SMPS run part (1.0 mA). Once cycles are cheap, the floor dominates.

The trap is to tune only the one you can see. Try the switching regulator, then 1.2 M cycles of work, then a 0.1 mA idle floor, with the clock at 80 MHz. The average drops from 3.2 mA to about 0.85 mA, and a 1,000 mAh pair of AAA cells lasts 49 days instead of 13.

What “sleep” means in code

The idle floor depends on which sleep mode you can use. In the Arm “Sleep” mode of the L4 family the core clock stops and peripherals can keep running, so DMA keeps filling the audio buffer while the core naps. Deeper modes such as Stop 2 reach the 1.1 µA headline figure, but they stop most clocks. Which audio peripherals can stay alive there is a question for the reference manual, not for a guess: it decides whether your design can reach microamps or must settle for the milliamp floor.

c  (idle without the 1 kHz tick)
for (;;) {
    __disable_irq();
    if (!ready) {
        HAL_SuspendTick();      /* SysTick would wake the core every 1 ms, 50 times per hop */
        __WFI();                /* the DMA half-complete interrupt wakes us at 20 ms */
        HAL_ResumeTick();
    }
    __enable_irq();
    /* ... handle the block as in Chapter 1 ... */
}

Symptom: your measured idle current is several times what the datasheet promised. Measure: look at the current trace on a profiler. A regular tick every millisecond is the SysTick interrupt waking the core. Also check whether a debug probe is attached: a debugger can keep clocks running in low-power modes. Fix: suspend the tick or run tickless, and measure with the probe detached.

A chip draws 100 µA per MHz while running. A job takes 2.6 million cycles. Which statement is true when you cut the clock from 80 MHz to 20 MHz?

Chapter 8

A Cascade of Cheaper Ears

Let a tiny always-on stage say “maybe” cheaply, and wake a bigger stage only to say “yes” or “no”

Think of airport security. At the door, a guard glances at everyone. It takes a second, and the guard waves nearly everyone through to a desk with a long line. At the desk, an officer checks each passport with great care. Nobody would staff the door with the careful officer, because the line would never end. Nobody would let the guard decide alone, because the guard sometimes waves the wrong person through.

A cascade works the same way. A cheap first stage looks at everything, all day, and accepts anything that might be the wake word. A costly second stage looks only at what the first stage accepted, and decides with much more care. Most of the time, the costly stage sleeps.

The stages

  1. Stage 0, the gate. Is anything louder than the room’s noise floor? A few additions on the mel energies answer this, for a few hundred cycles. If the room is silent, nothing runs after it. This is a voice activity check in its simplest form.
  2. Stage 1, the tiny network. A very small model on the lowest-power processor in the product. It must almost never miss, and it may false accept a lot.
  3. Stage 2, the careful network. A bigger model on a bigger core, woken only when stage 1 fires. It must reject the false accepts.
  4. Stage 3, the server. The recogniser in the cloud, which hears the sound only after stage 2 agrees. It can still say “that was not the wake word”.

Apple describes exactly this in its “Hey Siri” write-up. On an iPhone, the always-on processor (AOP) runs the first detector, and it uses a small share of that processor’s limited power. When the first-pass score passes its threshold, the motion coprocessor wakes the main processor, which re-analyses the same sound with a larger network. The server can send a cancellation if its own recogniser does not hear the phrase. In the first versions with the AOP, the first pass was a network of 5 layers with 32 units each, and the second pass was 5 layers with 192 units each.

How much cheaper is cheap?

Count the weights between hidden layers. Five layers have four links between them. Each link is a square grid of numbers, units by units. At 32 units: 4 × 32 × 32 = 4,096 weights. At 192 units: 4 × 192 × 192 = 147,456. The ratio is (192 / 32)2 = 36. The second pass has 36 times the work in those links, and the same factor in the multiply-adds per frame. (Input and output layers add more, and Apple does not give those sizes here, so 36 is for the middle only.) Stage 1 can therefore run all day for the price of a small fraction of stage 2.

Now add up the energy. The average current of the cascade is the always-on part plus the wake part:

Icascade
The average current of the whole cascade, in milliamps.
I1
The always-on part: microphone, front end and the tiny network (gated by stage 0).
r
How many times an hour stage 1 wakes stage 2: the true wakes plus the false accepts of stage 1.
q2
The charge stage 2 uses for one check, in millicoulombs (mA times seconds). Dividing by 3,600 spreads it over an hour.

Build a cascade

The grey bar is a big model that listens all day. The coloured bar is the cascade. Turn the stage 1 false accept rate up, and watch the wake cost grow. Then make stage 2 stricter.

32 / h
20 mC
0.2%

Illustrative numbers, not Apple’s or any product’s: the front end and microphone draw 0.15 mA, the tiny network 0.35 mA when it runs, a check on the big core costs the charge shown (for example 40 mA for 0.5 s is 20 mC), 2 true wakes an hour, and a big always-on model draws 12 mA. Errors of the two stages are treated as independent; in practice a sound that fools one often fools the other. Only the 36 times ratio and the 5 x 32 and 5 x 192 layer sizes come from the Apple write-up.

With the defaults, the cascade draws about 0.4 mA, and stage 2 lets through 0.06 false accepts an hour to the user. The big always-on model would draw 12 mA, about 27 times more. Now push stage 1 to 500 false accepts an hour: the wake part alone climbs above 2.7 mA, and the cascade loses much of its edge. A cascade works only when stage 1 is cheap and quiet enough.

Two thresholds, two jobs

Set the first stage’s bar low, so it almost never misses: whatever it lets through, the second stage can throw out. Set the second stage’s bar high, so the user almost never sees a false accept. The end-to-end miss rate is about the sum of the two miss rates, because a word must pass both. The end-to-end false accept rate is the first stage’s rate times the share the second stage lets through, if the two stages err independently. They usually do not, so measure the pair together on your 500 hours of audio from Chapter 6, never stage by stage.

Apple adds one more layer on top: when the user turns on personalisation, the second-pass detector’s output is also compared with five stored samples of the user’s own voice, against another threshold. A third gate costs one more comparison and rejects other people’s voices.

When the cascade backfires

Symptom: stage 1 looks cheap on the bench, but in the field the battery drains in a day or two. Cause: in a noisy home, stage 1 fires hundreds of times an hour, and every fire wakes the big core. Measure: toggle a GPIO at every stage 1 fire and another when stage 2 says yes, then read both counts over an hour, and record the current with a profiler: each wake appears as a tall pulse. Fix: raise stage 1’s threshold a little (see the miss cost in Chapter 6), train stage 1 on hard negatives from real homes, or make stage 2 cheaper, for instance a short burst at a lower clock.

Why can the first stage of a cascade be a much smaller network than the one a single-stage detector would need?

Chapter 9

Making the Chip Agree With Python

Find the quiet bugs where the firmware’s numbers drift from the training numbers, and build the test that catches them

A student practises piano on a keyboard in the living room. On exam day the piano is in another hall. The keys are heavier, the room rings longer, and the student plays badly. The notes are the same. The instrument is not.

Your network is that student. It learned from features made by Python code on a laptop. On the chip it receives features made by C code on a different instrument: different arithmetic, different rounding, a different microphone. If the features differ, the network is playing on a piano it never practised. Nothing crashes. The accuracy just falls.

The bug has a name

This is called training-serving skew: the model sees one kind of input in training and another in use. The causes in this lesson are all small. The window formula (Chapter 2) and the mel scale and floor (Chapter 3). The order of the rows in the grid. A feature scaled to int8 with a different range. A sample rate that is 16,000 on paper but slightly off in reality because the two clocks disagree (the lesson on DMA and clock drift covers that). And the arithmetic itself, which we now meet.

What a short word length does

The firmware does not use 64-bit floats. It stores samples as 16-bit integers, or fewer. The step between two neighbouring values is the quantisation step: for B bits the full range −1 to +1 holds 2B levels, so the step is 2 / 2B. Each sample gets rounded to the nearest level, which adds a small error, quantisation noise. A loud sound drowns that noise. A quiet sound does not.

Worked example. With B = 8 the step is 2 / 256 = 0.0078. A quiet word whose peaks are 0.01 of full scale (−40 dBFS) spans just two or three levels. Its shape is crushed into steps. With B = 16 the step is 0.000 031, and the same word spans over 300 levels.

The other end hurts too. A sound that is too loud for the range is clipped: peaks are cut flat, which creates harmonics that were never in the air. And inside the front end, fixed-point sums can overflow if they are not scaled with care. The CMSIS-DSP MFCC documentation warns that saturation can occur when the FFT length is large and the number of mel filters is small.

Sweep the level, change the bits

The grey line is the score in floating point. The purple line is the score when the samples are rounded to B bits and clipped at full scale. The red zone is where the score falls below the threshold of 0.45 and the word is missed. Pick a word length, then drag the level.

-24 dB

Computed live with this page’s front end on the wake sweep plus a small fixed microphone noise (peaks near −62 dBFS). Level 0 dB means the sweep peaks near −5 dBFS; the other levels scale it. Rounding and clipping are applied to the samples before the front end. Real firmware also rounds inside the FFT and the mel step, which this model does not.

Read the picture. With 16 bits the purple line hugs the grey one from −54 dB up to 0 dB. The score is nearly independent of level, which is the log’s gift from Chapter 3. Drop to 8 bits: below about −24 dB the score collapses. Move the level to +12 dB and every word length bends down together, because the clipped peaks add harmonics. So the log protects you from level only inside a window: above the quantisation noise and below clipping.

The parity test

You cannot find these bugs by reading code. You find them by comparing numbers. The method has three rules.

  1. Compile the real firmware front end for your laptop. The same C file, built with a desktop compiler, fed from a WAV file. If it only builds for the chip, you cannot test it in a loop of seconds.
  2. Compare frame by frame against the Python reference. The same file goes through both. Subtract the 40 values per frame. Report the biggest gap in dB.
  3. Then compare on the chip. Put the same samples into the DMA buffer from flash, so the microphone is out of the loop. Print the frames over UART. The host build and the chip must agree to the last bit, because both run the same C; if they do not, the compiler, the FPU or an overflow is the cause.
python  (golden-vector test; the reference is the training code, the other file is printed by the firmware build)
import numpy as np
ref = logmel_reference("golden/yes_0.wav")            # shape (T, 40), the code that made the training set
fw  = np.loadtxt("build/yes_0_frames.txt")             # shape (T, 40), from the firmware front end
gap = np.abs(ref - fw).max(axis=1)                     # worst band in each frame, in dB
assert ref.shape == fw.shape, (ref.shape, fw.shape)
assert gap[2:-2].max() < 1.0, f"worst frame gap {gap.max():.2f} dB"   # skip the edge frames

Pick the tolerance with care. One quantisation step of the int8 feature is the smallest difference the network can even see; a gap above that is a real mismatch. Keep a few golden files: a tone, silence, a loud clip that clips, a quiet clip, and a recorded word. Each catches a different bug. Add them to the build so every change runs them. The firmware side of this habit is in testing firmware; the network side, parity of int8 against float, is in int8 in firmware.

Symptom, measurement, fix

Symptom: the detector works at arm’s length and fails across the room. Measure: play one recording at a series of levels, from −40 dB to 0 dB in 6 dB steps, into the board and plot the peak score. A curve that falls off early shows a noise floor or a word length problem; a curve that falls at the top shows clipping. Fix: add analog gain before the converter (the codec lesson on gain staging), use more bits, or raise the level of the signal path before it is rounded, never after. An automatic gain control can help, but it changes the features, so train with it on.

When the model itself changes, repeat the whole test. Shipping a new model by over-the-air update (the bootloader and update lessons) without the golden files is how a wake word that worked yesterday stops working for everyone today.

The detector works when you stand close and fails across the room. The same C code passes its host tests. What is the best first measurement?

Chapter 10

Field Guide: The Wake Word Pipeline on One Page

Review the numbers, the checklist and the core code, then see where to go next and which sources stand behind each claim

You now know every box between the microphone and the wake. Go back to the instrument at the top and name each part: the spectrogram is Chapters 2 and 3, the score is Chapter 4, the dashed line and the green and red marks are Chapters 5 and 6, and the yellow bars underneath are Chapter 7.

The one-paragraph summary

An always-on detector turns a stream of 16,000 samples a second into one feature row every 20 ms: window 480 samples, Hann taper, 512-point FFT, 40 mel bands, log. It keeps the newest 49 rows as a 49 × 40 int8 picture and scores it with a small network about 10 times a second. It smooths the scores, applies a threshold and a quiet period, and fires. Its quality is false accepts per hour and missed words; its cost is average current. A cascade lets a tiny stage listen all day and wake a bigger one. Parity tests against the training code keep it honest.

The numbers that matter

WhatNumberWhere it comes from
Raw audio rate16,000 samples/s × 2 B = 32,000 B/s; 115.2 MB/hArithmetic; 16 kHz 16-bit mono as in Speech Commands
Window, hop, FFT480 (30 ms), 320 (20 ms), 512 points, 31.25 Hz binsmicro_speech README (30 ms, 20 ms); 512 is our zero-padded choice
Features per second of sound49 frames × 40 bands = 1,960 valuesmicro_speech README; Hello Edge (40 MFCC, 49 frames)
Mel scale2595 · log10(1 + f/700); 1,000 Hz = 1,000 melStandard formula; our 40 bands span 125 to 7,500 Hz
Best small modelDS-CNN S: 94.4%, 38.6 KB, 5.4 M opsHello Edge, Table 5, 8-bit
Deployed demo~12 ms per inference at 10 per second; ~70 KBHello Edge, STM32F746G-DISCO (Cortex-M7), CMSIS-NN
Dataset105,829 utterances, 35 words, 1 s, 16 kHzWarden, Speech Commands v2
Decisions per hour36,000; one false accept a week = 1.65 × 10−7 per decisionArithmetic at 10 inferences a second
Proof of a rate by silence0 events in n hours bounds the rate near 3 / n; 504 h for one a weekRule of three (95%)
Chip power (L476)100 µA/MHz (linear), 39 µA/MHz (SMPS), 1.1 µA Stop 2ST product page headlines; confirm in datasheet DS10198
Cascade sizes5×32 first pass, 5×192 second pass; 36 times the middle weightsApple, Hey Siri (2017); ratio is arithmetic

The checklist

The core as code

This is the whole front end in C, with the CMSIS-DSP floating point FFT for clarity. A fixed-point build swaps the transform and the log; the shape stays the same. Every line is a stage from Chapter 1.

c  (one feature row per 20 ms; assumes arm_math.h, a Hann table and a sparse mel table built offline from the shared spec)
#define FS 16000
#define WIN 480
#define HOP 320
#define NFFT 512
#define NB 40

static int16_t win[WIN];                                  /* the newest 30 ms */
static float   buf[NFFT], spec[NFFT], pwr[NFFT / 2 + 1];
extern const float hann[WIN];                            /* 0.5 - 0.5 cos(2 pi n / (N-1)), as in training */
extern const mel_row_t mel[NB];                          /* { start_bin, length, weights[] } per band */
static arm_rfft_fast_instance_f32 rfft;                    /* arm_rfft_fast_init_f32(&rfft, NFFT) once at boot */

void frontend_push(const int16_t *blk, int n) {
    memmove(win, win + HOP, (WIN - HOP) * sizeof(int16_t));   /* keep the last 160 samples */
    memcpy(win + (WIN - HOP), blk, HOP * sizeof(int16_t));   /* append the 320 new ones */
    for (int i = 0; i < NFFT; i++) buf[i] = i < WIN ? (win[i] / 32768.0f) * hann[i] : 0.0f;
    arm_rfft_fast_f32(&rfft, buf, spec, 0);                  /* packed output: spec[0], spec[1] hold DC and Nyquist */
    arm_cmplx_mag_squared_f32(spec, pwr, NFFT / 2);       /* power per bin; patch bin 0 and bin 256 by hand */
    int8_t row[NB];
    for (int b = 0; b < NB; b++) {
        float e = 0.0f;
        for (int j = 0; j < mel[b].len; j++) e += mel[b].w[j] * pwr[mel[b].start + j];
        float db = 10.0f * log10f(e + 1e-9f);               /* the floor is part of the spec */
        row[b] = (int8_t)fminf(127.0f, fmaxf(-128.0f, roundf((db - DB_OFFSET) / DB_STEP)));
    }
    feature_push(row);                                   /* Chapter 5: into the ring */
}

Where this sits

This lesson is the audio track’s last stop. The microphone and the clocks are in digital audio on the wire and DMA ping-pong. The gain stage is in codecs and the analog front end. The fixed-point FFT is in fixed-point DSP on an MCU. The general pattern of windows, features and ring buffers, for sound and for motion, is in the sensor-to-feature pipeline. The network side is in a network on a Cortex-M and profile, budget and ship.

Keep going

Sources

No slides were used. Each claim comes from one of these, opened and read for this lesson. Items that came from a vendor summary rather than an electrical table are marked.

  1. P. Warden, “Speech Commands: A Dataset for Limited-Vocabulary Speech Recognition”, 2018: 105,829 utterances of 35 words, 16 kHz 16-bit one-second clips, the design requirements, the streaming metrics, the 750 ms tolerance and the baseline streaming result.
  2. Y. Zhang, N. Suda, L. Lai, V. Chandra, “Hello Edge: Keyword Spotting on Microcontrollers”, 2017: 40 MFCC features, 49 frames, the model comparison table, the S, M, L classes, the 8-bit result and the STM32F746G-DISCO deployment (12 ms per inference, 10 per second, about 70 KB, WFI sleep).
  3. TensorFlow Lite Micro, micro_speech example README: 16 kHz, 30 ms window, 20 ms stride, 40 channels, 49 slices, a model under 20 kB.
  4. Apple Machine Learning Journal, “Hey Siri: An On-device DNN-powered Voice Trigger for Apple’s Personal Assistant”, 2017: the always-on processor, two passes, 5×32 and 5×192 units, false accepts per hour, the second-chance threshold, personalisation.
  5. Arm, CMSIS-DSP MFCC (Q15) documentation: the init and run signatures, the q8.7 output, the saturation warning.
  6. STMicroelectronics, STM32L476 product page (headline run and Stop 2 currents; vendor summary, not the electrical tables; confirm in datasheet DS10198 before design use).
  7. C. Banbury et al., “MLPerf Tiny Benchmark”, 2021: keyword spotting is one of its four tasks; accuracy, latency and energy are its metrics.

Not verified, and marked as assumptions in the page: the cycle count on a Cortex-M4 equals the Cortex-M7 figure; which peripherals stay alive in Stop 2; every toy number labelled illustrative (the idle and microphone currents, the battery sizes, the cascade currents and the score curves). The devices are models running in your browser, not silicon.

The takeaway. A wake word detector is a pipeline with a budget at every stage: 20 ms to finish a block, 100 ms to finish an inference, a few parts in ten million to be wrong, and a few milliamps to stay alive. You measure each with a pin, a counter or a meter, and you test every change against the same golden numbers.
Your detector scores 94% on the aligned test set, the average current is 3 mA, and it false accepts 15 times an hour on television. Which fix attacks the biggest problem first?

Now press Teach and explain the belt out loud, from memory: what each stage turns into what, how many bytes move, why the log helps and where it fails, how a threshold becomes false accepts per hour, and how the chip sleeps. Then go back to the instrument and break it on purpose.

Wake Word on an MCU, Firmware from Zero to Expertise
Hello Edge · Speech Commands · Hey Siri · Back to microLearning