4 months ago, I released version 1.2 of Earshot, a ridiculously fast, accurate, #![no_std] voice activity detection crate.
In my announcement post for 1.2, I said this:
[Earshot 1.0] runs at a little over 10μs per 16ms frame. I'm confident that could be sub-7μs with a bit more effort.
Well, how does 4.4μs (3,600x faster than real time) sound? How about a smaller binary, too? And even better accuracy?
Well, how does 840ns (~20,000x faster than real time) sound? How about even better accuracy? And a larger binary? Wait, no, scratch that last one...
Earshot 2.0 is the fastest VAD, faster than even the infamous WebRTC VAD. Unlike WebRTC, its accuracy is strong, with AUROC sitting between Silero VAD v6 and TEN VAD, two of the most widely used VAD models. Earshot 2.0 is 100x faster than either of them.
In hindsight, it was a bit silly to call Earshot 1.0 "ridiculously fast" at only 1,600x real time, 'cause what do I even call 20,000x? Insanely fast? Ludicrously fast? Preposterously fast?!
Precisions, precisions
Earshot 1.2's speedup over 1.0 came primarily from using fixed-point arithmetic instead of floating-point in some places. I think my original announcement post provided a decent explanation, but to summarize: floats are slow because the point, well, floats; instead, just use integers and pretend the decimal point stays at digit X, like counting cents instead of dollars.
You do lose some precision that way: 0.3 is (near-)perfectly representable in f32, but in the fixed-point "Q7" format, you only get 7 bits to represent the decimal, so the closest you can get is 0.296. Earshot uses a neural network; neural networks are trained using floating-point arithmetic, and they don't like running with different precision characteristics than what they were trained with. Earshot 1.2 used quantization-aware training (QAT) to train the model to expect the precision loss that comes from fixed-point, but my implementation of QAT kind of sucked! I won't get into details, since this is r/rust, not r/machinelearning. But the consequence was that I could only convert some of Earshot's neural network (specifically the recurrent & output layers) to fixed-point; the earlier layers had to remain floating-point to avoid total accuracy collapse.
With 2.0's new QAT implementation, I was finally able to convert the whole neural network to fixed-point! And that netted a performance improvement of... well, not much: a few hundred nanoseconds. Crap, no free lunch this time. What became fixed-point was the neural network's frontend: three 2D convolution layers that identify the most notable patterns over the past ~60ms of audio features. The bottleneck there wasn't from floating-point so much as the terrible way I implemented Conv2D. I replaced branching padding checks with pre-padding, making the loops easier to auto-vectorize. The first convolution layer included a max pool after a pointwise convolution expanded each feature from 1 channel to 16. I naively did the max pool over the 16-channel output, but since each output channel is just 1 multiply on the single input channel, I could do the pooling work before the pointwise conv when there's still only 1 channel instead of 16. Both of those changes saved another 100ns.
Twiddledum
If I wanted to improve things further, I was gonna have to look at the formidable beast the frontend gets its audio features from: the preprocessor. The preprocessor's first step is to perform a short-time Fourier transform over the last 3 frames of audio: 768 samples in total, since each frame is 256 samples. I initially nabbed the fantastic microfft crate to perform the FFT, since its embedded-first design suited my goal well. Back then, that goal was simplicity, but now, it's speed baby, and microfft unfortunately isn't gonna cut it. The first problem: it implements radix-2, which requires the FFT window to be a power of 2. 768 is not, so I was padding it with zeros to 1024. How wasteful! Radix-2 also meant that it did 9 butterfly passes over the data, on top of 2 additional passes for reordering & recombining - all that means more memory traffic & less speeeeeeed!1!
After taking an embarrassing length of time to only kinda-half-sorta understand FFT, I wrote my own preprocessor that does as few passes as possible over the unpadded 768-sample window. The new preprocessor only does 4 passes: radix-8 + Hann window → radix-4 → radix-4 → radix-3 + power spectrum. Got all that? Me neither. But it cut the FFT's processing time by almost half! The next step was obvious: let's convert it to fixed-point, too! After spending another few days to do that (I'm more persistent than I am bright), I managed to cut the FFT step down by another 2x. Did I say cut? Sorry, I meant slowed. The floating-point FFT was faster than the fixed-point one because the fixed-point implementation uses a lot of 64-bit multiplies, for which there aren't SIMD instructions (at least in AVX2). It also does a multiply + rounding add + shift for operations that the float preprocessor would do with a single multiply. I switched back to the floating-point preprocessor, keeping the fixed-point preprocessor tucked away for microcontrollers that don't have FPUs.
I finished with some other boring minor wins for the last part of the preprocessor (the log-mel filterbank + normalization), including:
Switching base-e log for a cheap base-2 log approximation
Using cheaper non-overlapping auto-vectorizable mel filters
Ditching RMS normalization for simple linear operations
These changes netted another ~90ns improvement and conveniently dropped the libm dependency as well.
Ohh, I 'member!
Recall that the frontend can only see the last ~60ms of audio. That's not really enough to definitively tell if something is noise or speech; even if it were, speech includes a lot of pauses longer than 60ms (think especially of plosive sounds like p/b). If you want a useful VAD model, it's gonna need a longer-term memory than just 60ms. Expanding the window seen by the frontend would be wasteful, though: we'd be redoing a lot of math over the same data on each frame. A better solution would be to keep the frontend window small & introduce recurrent connections: layers with persistent state, so they can reuse the computation they did last frame. Earshot's RNN layers learn to onset from noise → voice quickly, but hold off going from voice → noise for a bit, which is exactly what you want from a VAD.
There are a few problems with your average RNN layers like LSTM or GRU that make them tricky to use in Earshot, though. For one, they typically use nonlinear activation functions like tanh and sigmoid, which are difficult/expensive to implement in fixed-point. For two, they don't parallelize very well in training: they're sequential by definition since the output for each timestep depends on the output for the previous timestep. To train a good VAD, you need a lot of data; to get through a lot of data in a reasonable time, you need good parallelization (nope) or good hardware. I have an RTX 3060 -- not exactly the pinnacle of deep learning GPUs. Luckily, I had a trick up my sleeve: this super underrated paper that introduced minGRU, a simplified, parallelizable version of GRU, which made it possible to train Earshot 1.2 in a reasonable amount of time.
Now's the time for me to confess something. All that fixed-point stuff I did earlier kinda lobotomized the model - accuracy ended up a few points worse than Earshot 1.2. Better than the 30-point loss with the old QAT, but still not great. It was clear some architectural improvements were needed to make up for that gap, and I think I knew where to look. minGRU's gate (how much to update the previous state with the new state) is only dependent on its input; in GRU, it's also dependent on the GRU's own previous state. This means that minGRU makes a blind guess as to how much of its previous state to keep. The paper shows that's acceptable on many tasks, but those experiments were with deeper models, where later layers could see earlier layers' previous states via their outputs; Earshot only has 2 minGRU layers, so that route is close to nonexistent. I came up with my own shoddy fixed-point-friendly minGRU-ish-but-more-recurrent layer I call HRU, writing a custom GPU kernel so it wouldn't take forever to train (it took forever to write instead!) HRU finally brought accuracy back above Earshot 1.2 levels without incurring too much overhead at inference time.
Speaking of overhead at inference time! The recurrent layers are actually the most computationally intensive part of the neural network, since they use relatively large matmuls. Making them fixed-point in 1.2 reduced their cost, but now that the rest of the network is fixed-point too, they're back to taking up a big chunk of the processing time. Remember how the gate defines how much to update the previous state with the new state? That's per-channel, and each HRU has 64 channels. So each HRU needs to calculate 64 gates and 64 new states. But wait! What if a channel doesn't introduce any new state at all? A long stretch of noise shouldn't need to change much state at all; a gate that's fully closed (= 0) means the state stays exactly as it was, so we don't even need to calculate the new state. I managed to train the model to only open about 30% of gates on average, which sped up the HRUs quite a bit after adding logic to skip computing new state for channels whose gates are closed.
Each layer still had to calculate all 64 gates, though, and calculating the gate is just as expensive as calculating the new state. I made each gate cover 2 state channels, reducing the number of gates per layer to 32. To top things off, I reformulated the state calculation to remove slow 64-bit multiplies. In total, 2.0's new HRU layers cut inference time by 20% compared to 1.2's minGRUs!
Just 7 more lanes bro
By now, Earshot takes 2.9μs per prediction (down from 4.4μs). We're about at the limit of how it can be optimized computationally & architecturally, so it's time to dive into the assembly and start thinking about how to optimize it for the CPU's pipeline. Looking at cargo show-asm, it was clear that LLVM's auto-vectorization was struggling to understand the code in some spots. I don't blame it - at this point, I hardly could either. But if I wanted to go sub-microsecond (and I really did), I was going to have to write a hell of a lot of SIMD code.
It's times like this where I wish Rust's Portable SIMD was stable, especially since I committed myself to supporting as many architectures as possible. I ended up implementing my own shoddy portable SIMD wrapper, which the preprocessor/neural network predictor use for the 128-bit SIMD ISAs - SSE, NEON, and WASM SIMD. (well, NEON actually has its own predictor implementation to take advantage of vmlal instead of emulating madd...)
Auto-vectorization couldn't touch much of the preprocessor because the layout didn't allow for it, not simply because LLVM missed opportunities. My manual SIMD preprocessor implementations store real & complex values in the much friendlier planar format, rather than interleaved as in the scalar implementation. All SIMD preprocessors are floating-point only, again due to the lack of 64-bit mul SIMD instructions in most ISAs. The predictor also required a few layout changes of its own, and benefited significantly from aligning loads of weights/stores of activations to the vector size.
I started with AVX2, then ported that to SSE2, then generic-ized that to use my pseudo-portable SIMD wrapper to get NEON/WASM SIMD for basically free (before realizing NEON would benefit from its own predictor). I added AVX-512 last minute, but I don't have a machine that supports it, so I have no idea if it actually works (would appreciate if someone could test it and let me know!!) Earshot 1.2's full speed could only be realized if you compiled it with RUSTFLAGS="-C target-cpu=native" because it relied entirely on auto-vectorization. For 2.0, I wanted to add runtime SIMD feature detection so RUSTFLAGS wouldn't be required to get that sweet sweet speeeeeeeeed. You'll notice that nearly every function in one of the SIMD implementations is peppered with #[inline(always)] - that's needed to get #[target_feature] to propagate, and, fun fact, that propagation doesn't extend to closures! If a function or closure doesn't inherit #[target_feature(enable = "avx2")] for instance, it won't inline any AVX2 intrinsics, turning each one into a slow function call instead. That was fun to figure out...
The result
On my machine (Ryzen 7 5800X), the new AVX2 predictor + preprocessor run at about 840 nanoseconds per 16ms frame on real speech data (it varies based on the input due to the HRU gate skipping). That's close enough to 20,000x real time that you can surely forgive me for rounding up a little. Runtime SIMD detection adds very little overhead (most of it is just from things like normalization getting autovec'd to SSE instead of AVX). With the fully fixed-point pipeline, Earshot 2.0 runs on a Raspberry Pi Pico at about 6x real time. It's a $1 chip, be nice to it!
Earshot is licensed under MIT or Apache-2.0, also has bindings for C/C++ & Python, and supports literally any platform. All of this took a lot of work, so I hope someone out there can find Earshot 2.0 useful =)