Speech Model Export
“A model that runs in a Jupyter notebook is an experiment. A model that runs on an iPhone is a product.”
TL;DR
Exporting speech models for edge deployment is harder than image models because streaming audio requires explicit state management between inference calls. The key pattern is transforming model signatures to accept and return hidden states (h, c) as explicit I/O ports, making the client application responsible for the state loop. LSTMs export cleanly to ONNX while Transformer attention caches take more work. Quantization-Aware Training is essential for INT8 deployment on mobile CPUs, and runtimes like TFLite, CoreML, and SNPE target specific hardware. This connects to speech pipeline dependencies for end-to-end system design and privacy-preserving speech for on-device inference requirements.

1. Problem Statement
Speech models are uniquely difficult to export compared to Image models.
- Image: Input
[1, 3, 224, 224]. Static. - Speech: Input is Infinite (Streaming Audio).
- State: Streaming models (RNNs, and Transformers with key/value caches) maintain “memory” of the past sounds.
The Problem: How do you export a PyTorch model such that it can run on a Raspberry Pi or Android phone, processing audio in 30ms chunks, while maintaining the Hidden State correctly between chunks?
2. Fundamentals: Batch vs. Streaming
Batch Inference (Offline)
The user uploads a 1-minute file. We process the whole file at once. This is easy to export. It’s just a big matrix multiplication.
Streaming Inference (Online)
The user talks live. We must show text as they speak. We process audio in small “frames” (e.g., 20ms). Challenge: The network needs to know what happened in the previous frame to understand the current frame.
- Input:
Current_Audio + Previous_State - Output:
Current_Text + New_State
3. Architecture: The Stateful Export Pattern
When exporting a streaming speech model (like a Transducer or LSTM), we transform the model signature.
Original (Training) Signature:
def forward(full_audio):
return text
Exported (Inference) Signature:
def forward(audio_chunk, h_state, c_state):
# Process small chunk using history
output, new_h, new_c = lstm_cell(audio_chunk, h_state, c_state)
return output, new_h, new_c
The Client Application (iOS App) becomes responsible for holding the new_h and passing it back into the model on the next loop.
4. Model Selection for Edge
| Architecture | Exportability | Streaming Latency | Size |
|---|---|---|---|
| Conformer (Transformer) | Harder. Attention key/value caches and convolution caches must be exported as state (toolkits such as sherpa-onnx do this for streaming Zipformer/Conformer transducers). | Medium | Large |
| LSTM / RNN-T | Easy. State is just two vectors (h, c). | Lowest | Small |
| QuartzNet (CNN) | Easy. “State” is just the left-padding buffer. | Low | Medium |
For ultra-low latency edge devices (Wake Word detection), Depthwise Separable CNNs or LSTMs are still preferred over heavy Transformers.
5. Implementation: Exporting a Streaming LSTM to ONNX
We must define a wrapper class that exposes the state as input/output.
import torch
import torch.nn as nn
class StreamingLSTM(nn.Module):
def __init__(self, input_dim, hidden_dim):
super().__init__()
self.lstm = nn.LSTMCell(input_dim, hidden_dim)
self.fc = nn.Linear(hidden_dim, 10) # Output chars
def forward(self, x_chunk, h_prev, c_prev):
# x_chunk: [Batch, Features] - One frame
h_new, c_new = self.lstm(x_chunk, (h_prev, c_prev))
output = self.fc(h_new)
return output, h_new, c_new
# 1. Instantiate
model = StreamingLSTM(input_dim=80, hidden_dim=256)
model.eval()
# 2. Creating Dummy Inputs for Tracing
dummy_input = torch.randn(1, 80)
dummy_h = torch.zeros(1, 256)
dummy_c = torch.zeros(1, 256)
# 3. Export to ONNX
torch.onnx.export(
model,
(dummy_input, dummy_h, dummy_c), # Tuple of inputs
"streaming_asr.onnx",
input_names=["audio_chunk", "h_in", "c_in"],
output_names=["logits", "h_out", "c_out"],
opset_version=12
)
Now, the Android developer sees an ONNX function asking for h_in. They don’t need to know what an LSTM is. They just know they need to pass h_out back into h_in.
6. Training Considerations
- Quantization Aware Training (QAT):
If deploying to INT8 (common for Phones/DSP), simulate quantization during training. Post-training INT8 quantization can cost noticeable accuracy on speech models, especially recurrent ones whose activations span wide ranges.
- Use
torch.ao.quantization.prepare_qat(eager mode), or thetorchaolibrary, where PyTorch’s newer quantization work lives.
- Use
7. Production Deployment: The Runtime
On the device, we rely on specialized runtimes:
- LiteRT (formerly TensorFlow Lite, Google): Standard for Android. Highly optimized for ARM CPUs, with GPU and NPU delegates.
- Core ML (Apple): Schedules work across the CPU, GPU and Neural Engine on Apple devices. Convert from PyTorch with
coremltools(its ONNX converter is no longer supported). - SNPE / Qualcomm AI Engine Direct (QNN): Runs on the Hexagon DSP/NPU. Extremely low power (can run continuously for wake words).
8. Streaming Real-Time Logic (Client Side)
The client code loop looks like this (Pseudo-C++):
// Initialize Logic
State h = zeros();
State c = zeros();
while (is_recording) {
// 1. Read 20ms from Microphone
AudioBuffer chunk = Microphone.read(320_samples);
// 2. Compute log-Mel features (2 frames at a 10ms hop; run the model once per frame)
Tensor features = ComputeLogMel(chunk);
// 3. Run Inference
auto result = Model.run(features, h, c);
// 4. Update State for next loop
h = result.h_out;
c = result.c_out;
// 5. Decode text
String text = CTCDecode(result.logits);
Display(text);
}
9. Quality Metrics
- Real-Time Factor (RTF):
Processing_Time / Audio_Duration.- RTF < 1.0 is required.
- Target RTF: 0.1 (Process 1 sec of audio in 0.1 sec).
- Model Size: Small enough for your app’s download budget. Apple asks users before cellular downloads over 200MB, and many teams download models after install.
- Power Consumption: mW per inference.
10. Common Failure Modes
- State Drift: Models are trained on utterances of a few seconds, then deployed on streams that run for minutes. The recurrent state
hcan drift into regions never seen in training, and precision differences between Training (GPU, FP32) and Inference (DSP, FP16/INT8) make it worse. Output degrades into gibberish.- Fix: Reset state during detected silence, and train on long or concatenated utterances.
- Buffer Overrun (falling behind): The model is too slow. Audio accumulates in the input buffer faster than we process it. Latency grows without bound.
- Fix: Drop frames (bad) or use a smaller model (Quantization).
11. Unified Streaming and Non-Streaming Models
Dual-mode ASR (Yu et al., ICLR 2021) and WeNet’s U2 dynamic-chunk training let one set of weights run either with full context or with limited chunks.
- Full context: batch mode (higher accuracy).
- Limited chunks plus cached state: streaming mode (low latency).
For deployment you typically export two graphs from the same weights, or one graph that takes the chunk size and cache tensors as inputs.
12. Key Takeaways
- Explicit State: Export hidden states as explicit I/O ports in your model graph.
- Quantize for Edge: Mobile CPUs need INT8 for speed and battery life.
- Client Loop Responsibility: The application code “owns” the memory (state loop). The model is just a pure function transition.
- Buffer Management: Handling raw audio buffers (ring buffers) is a large share of the work in Speech deployment.
FAQ
Why is exporting speech models harder than exporting image models?
Image models have fixed-size static inputs (e.g., [1, 3, 224, 224]), making export straightforward. Speech models process potentially infinite streaming audio and must maintain hidden state (memory of past sounds) between inference calls. The model signature must be transformed to explicitly accept previous state as input and return new state as output, shifting state management responsibility to the client application code.
How do you export a streaming LSTM model to ONNX?
Create a wrapper class that exposes the LSTM hidden state (h, c) as explicit function parameters rather than internal state. Use torch.onnx.export with dummy inputs for the audio chunk and both state tensors, naming the I/O ports clearly (audio_chunk, h_in, c_in, logits, h_out, c_out). The client developer then simply passes h_out from each call back as h_in on the next inference loop, without needing to understand LSTM internals.
What is Quantization Aware Training and why is it important for speech models?
QAT simulates INT8 quantization during training (for example with torch.ao.quantization.prepare_qat), so the model learns to be robust to reduced precision. Post-training quantization can cost noticeable accuracy on speech models, especially recurrent ones whose activations span wide ranges. QAT recovers most of that loss while enabling fast INT8 inference that meets the battery life and speed requirements of mobile CPUs and DSPs.
What causes state drift in deployed streaming speech models?
State drift occurs when a recurrent state runs far longer in deployment than in training: models see utterances of a few seconds during training, then minutes of continuous audio on device. The state can wander into regions the model never learned, and precision differences between training (GPU, FP32) and inference (mobile DSP, FP16 or INT8) make it worse. The usual mitigations are resetting the hidden state during detected silence and training on long or concatenated utterances.