On-Device Voice AI: Running Piper ONNX and WebLLM in the Browser

On-Device Voice AI: Running Piper ONNX and WebLLM in the Browser

Picture a field technician standing in a basement plant room with one bar of signal. She holds up a tablet and asks it, out loud, which breaker feeds the cold-storage compressor. The assistant on the screen is a cloud voice agent: the audio is captured, uploaded, transcribed on a server, answered by a large model, synthesized on another server, and streamed back. With one bar of signal the round trip takes eight seconds, then the connection drops mid-sentence. She walks upstairs to ask again, and the assistant has no memory that she asked.

The same product, rebuilt so that everything runs inside the browser tab, behaves differently. A small quantized language model sits in GPU memory, a compact neural voice runs on the CPU through WebAssembly, and a voice activity detector decides when she has stopped talking. Nothing leaves the device, so there is nothing to lose to a bad network and nothing to leak to a vendor. This article walks through how that stack works with WebLLM for the language model and Piper exported to ONNX for the voice, where the real costs hide, and when you should not do this at all.

1. What one spoken turn actually costs

A voice assistant is a pipeline, and users judge it by one number: the gap between the moment they stop speaking and the moment they hear the first syllable of the reply. Everything you build is in service of shrinking that gap. For a spoken turn the pipeline has six stages. Voice activity detection decides the user has finished. Speech recognition turns the audio into text. The language model reads the prompt and produces tokens. A chunker cuts the token stream into speakable pieces. The synthesizer turns a piece into audio samples. The audio output schedules those samples for playback.

Two stages dominate. The first is the language model's prefill, where it reads the whole prompt (system instructions, conversation history, the new question) before emitting anything. Prefill cost grows with prompt length, so a short system prompt matters more on a phone than on a data-center GPU. The second is time to first audio from the synthesizer, which depends on how much text you hand it. Handing it a full paragraph delays the first sound; handing it the first sentence lets playback start while the model is still writing the second.

The on-device design changes the shape of the budget rather than only its size. A cloud pipeline pays network round trips at every hop, and those round trips vary wildly on mobile networks. A local pipeline pays no network cost but pays in compute you do not control, because the user's hardware is the server. A flagship laptop and a four-year-old budget phone are the same deployment target, and your latency distribution is the union of both. Plan for the slow end of that range, and treat anything the fast end gives you as bonus.

2. WebLLM: a language model in a GPU tab

WebLLM, from the MLC project, compiles transformer models ahead of time into WebGPU compute shaders and a small runtime, so a browser can run them with no native install. The model weights are quantized (commonly to 4 bits per weight with 16-bit activations, which is what an identifier like q4f16_1 in a model ID refers to) and split into shards that the page downloads once and keeps in browser storage. The API deliberately mimics the OpenAI chat-completions interface, so code written against a cloud endpoint ports with small changes.

Autoregressive decoding is memory-bandwidth-bound: every generated token requires reading essentially all of the model's weights from memory. That gives you a useful rule of thumb. Tokens per second is roughly the memory bandwidth available to the GPU divided by the model's size in bytes. A 1B-parameter model at 4 bits is on the order of a gigabyte or less, which is why such models feel snappy even on integrated GPUs, while a 7B-8B model at 4 bits is several gigabytes and starts to hurt on modest hardware. Quantization is not a free lunch. It trades some accuracy for size, and smaller models degrade faster, particularly in languages that were thin in their training data.

The f16 trap

Many prebuilt WebLLM variants use 16-bit floats in the shaders, which requires the WebGPU shader-f16 feature. Not every browser and GPU combination exposes it. The project publishes parallel builds with 32-bit float activations (q4f32_1) for those devices. A production page checks the adapter's features at startup and picks the matching build instead of failing with an opaque shader error. The f32 builds use more memory and run slower, so keep your latency budget honest for them.

Run it off the main thread

Generation is heavy and long-lived. If it runs on the main thread, the page's UI, the audio scheduling and the microphone processing all compete with it, and you hear it as stutter. WebLLM ships a web-worker engine that keeps the model in a dedicated worker and exposes the same interface through message passing. Use it from the first prototype, because moving to a worker later changes your error handling and your cancellation story.

3. Piper: from text to waveform in a few dozen megabytes

Piper is a neural text-to-speech system built on the VITS architecture, an end-to-end model that maps a sequence of phoneme identifiers directly to a waveform. Voices are exported as ONNX files together with a JSON config. Their size is modest, typically tens of megabytes for the common quality tiers, and they run faster than real time on an ordinary CPU, which is why Piper became the default choice for embedded and offline speech. Voices come in tiers (x_low, low, medium, high) that trade naturalness against size and speed, and the sample rate differs by tier.

The model does not read characters. A front end first converts text to phonemes, and Piper uses the espeak-ng phonemizer for that. The config's phoneme_id_map then maps each phoneme symbol to an integer, with special symbols for beginning of sentence, end of sentence and padding. The network consumes that integer sequence plus three scale parameters from the config: a noise scale, a length scale and a noise width. The length scale is the knob that controls speaking rate. Raising it slows the voice; lowering it speeds it up. The output is a float waveform at the voice's native sample rate.

In a browser, two things make this practical. ONNX Runtime Web runs the graph on WebAssembly with SIMD, and optionally on WebGPU. The espeak-ng phonemizer also has to run client-side, usually as a WebAssembly build, and it is the part people forget. A page that runs the voice model locally but calls a server for phonemes has not become private, only slower.

Check the language support before you commit. Piper's voice catalog is uneven across languages, and quality varies a lot between voices even inside one language. Vietnamese has a few community voices, but they differ in recording quality, tone handling and sample rate. Listen to every candidate on your actual domain vocabulary (product names, numbers, units) before you build around one, and re-check the current catalog because it changes.

4. Wiring the pipeline: a streaming sketch

The key design move is overlapping the stages. The model streams tokens; you accumulate them until a sentence boundary; you synthesize that sentence while the model keeps writing; and you queue the resulting audio so playback is gapless. The sketch below shows that loop with WebLLM and an already-loaded Piper session. It leaves out the phonemizer call, which is whatever espeak-ng build you ship, and it assumes the engine and session were created once at startup.

import { CreateMLCEngine } from "@mlc-ai/web-llm";
import * as ort from "onnxruntime-web";

const SENTENCE_END = /([.!?…]+["')\]]?)\s+/;

export async function createVoiceRuntime({ modelId, voiceUrl, voiceConfig, phonemize }) {
  // The language model: weights are downloaded once, then served from browser storage.
  const engine = await CreateMLCEngine(modelId, {
    initProgressCallback: (p) => console.log("llm load:", p.text),
  });

  // The voice: one ONNX session, reused for every sentence.
  const session = await ort.InferenceSession.create(voiceUrl, {
    executionProviders: ["wasm"],
  });

  const ctx = new AudioContext({ sampleRate: voiceConfig.audio.sample_rate });
  let playhead = 0;
  const live = new Set();

  function toIds(phonemes) {
    const map = voiceConfig.phoneme_id_map;
    const ids = [...map["^"]];
    for (const p of phonemes) {
      if (map[p]) ids.push(...map[p], ...map["_"]);
    }
    ids.push(...map["$"]);
    return ids;
  }

  async function speak(sentence) {
    const ids = toIds(await phonemize(sentence));
    const { noise_scale, length_scale, noise_w } = voiceConfig.inference;
    const feeds = {
      input: new ort.Tensor("int64", BigInt64Array.from(ids, (n) => BigInt(n)), [1, ids.length]),
      input_lengths: new ort.Tensor("int64", BigInt64Array.from([BigInt(ids.length)]), [1]),
      scales: new ort.Tensor("float32", Float32Array.from([noise_scale, length_scale, noise_w]), [3]),
    };
    const out = await session.run(feeds);
    const samples = out.output.data; // Float32Array of mono PCM

    const buf = ctx.createBuffer(1, samples.length, voiceConfig.audio.sample_rate);
    buf.copyToChannel(samples, 0);
    const src = ctx.createBufferSource();
    src.buffer = buf;
    src.connect(ctx.destination);
    playhead = Math.max(playhead, ctx.currentTime + 0.02);
    src.start(playhead);
    playhead += buf.duration;
    live.add(src);
    src.onended = () => live.delete(src);
  }

  async function answer(messages) {
    const stream = await engine.chat.completions.create({
      messages, stream: true, temperature: 0.6, max_tokens: 220,
    });
    let buffer = "";
    for await (const chunk of stream) {
      buffer += chunk.choices[0]?.delta?.content ?? "";
      let m;
      while ((m = buffer.match(SENTENCE_END))) {
        const end = m.index + m[0].length;
        await speak(buffer.slice(0, end).trim());
        buffer = buffer.slice(end);
      }
    }
    if (buffer.trim()) await speak(buffer.trim());
  }

  function bargeIn() {
    engine.interruptGenerate();           // stop the model
    for (const s of live) s.stop();       // stop queued audio
    live.clear();
    playhead = 0;
  }

  return { answer, bargeIn };
}

Three details in that sketch carry weight. The sentence regex requires whitespace after the punctuation, so decimals like 3.5 do not split, but abbreviations such as "Dr. Lee" still will, so a real deployment adds an abbreviation list or a minimum chunk length. The playhead variable schedules each buffer to start exactly when the previous one ends, which is what makes sentence-by-sentence synthesis sound like continuous speech. And bargeIn stops both the generator and every audio source that has been queued, because stopping only one leaves the assistant talking over the user.

5. Turn-taking: VAD, echo and interruption

Most of what makes a voice assistant feel good is not the models. It is turn-taking. Voice activity detection (VAD) answers two questions: has the user started speaking, and have they finished. Silero VAD is a small ONNX model that runs comfortably in a browser audio worklet, and libraries exist that wrap it. The tuning knob that matters is the end-of-speech silence threshold. Set it short and the assistant cuts people off during a thinking pause; set it long and every reply feels sluggish. A threshold in the high hundreds of milliseconds is a common starting point, and the right value depends on your users and your language, so make it configurable and test with real speakers.

Echo is the next trap. If the speaker output reaches the microphone, the assistant hears itself, transcribes its own sentence, and answers that. The browser's built-in acoustic echo cancellation, requested through the echoCancellation constraint on getUserMedia, handles most laptop and headset cases, but it behaves differently across devices and is weakest with loud speakers close to the mic. Test on the loudspeaker configuration your users will really use. A conservative fallback is half-duplex mode: ignore the microphone while the assistant speaks, at the cost of losing barge-in.

Barge-in itself is a state machine problem. States are idle, listening, thinking and speaking. A user speech-start event in the speaking state must cancel generation, flush queued audio, and move to listening, in that order and without waiting on any asynchronous work. Write that transition as a single synchronous function and test it directly. The most common bug in homemade voice agents is a late audio buffer that plays after the user has already interrupted.

For the recognition stage, you have choices with different privacy properties. The browser's built-in speech recognition API is convenient, but in several browsers it sends audio to a remote service, which defeats the point of an on-device design. Running a Whisper-family model through a WebGPU-enabled runtime keeps audio local at the cost of another model download and more GPU memory contention with the language model. Decide this explicitly, and describe it truthfully in your privacy notice.

6. Failure modes you will meet in production

The first failure is the download. A first visit must fetch the language model shards, the voice file, the phonemizer and the runtime, which together can be on the order of a gigabyte for a small model. That is a product decision as much as an engineering one. Show real progress, make the download resumable, ask the browser for persistent storage so the cache is not evicted under disk pressure, and keep the app useful (text input, say) while voice assets load. Evicted caches are common on mobile, so the second visit is not guaranteed to be fast.

The second failure is memory. The language model, the KV cache, the ONNX session and the audio buffers all live in the same tab, and browsers kill tabs that grow too large, mobile browsers aggressively. The KV cache grows with conversation length, so cap the context window you configure and trim history by summarizing or dropping old turns. If WebLLM reports a device-lost or out-of-memory error, your handler should fall back to a smaller model rather than crash the session.

The third failure is the device lottery. WebGPU support has broadened across browsers but is not universal, and driver bugs still produce device-specific crashes. Detect support up front (navigator.gpu, then requesting an adapter), choose a model tier from the adapter's limits, and keep a tested degraded path. Thermal throttling is real as well: a phone that runs a model smoothly for ten seconds may halve its speed after a minute of continuous use, so test sustained conversations rather than single turns.

The fourth failure is cross-origin isolation. Multi-threaded WebAssembly relies on shared memory, which browsers only enable on pages served with the right cross-origin isolation headers. Without them, ONNX Runtime Web silently falls back to a single thread and your synthesis speed drops. Serve the page with the isolation headers, and make sure third-party scripts you embed still work under those restrictions.

7. On-device or cloud: choosing honestly

On-device is not automatically better. It wins on privacy, offline operation, per-conversation marginal cost (zero) and latency when the network is poor. It loses on model quality, on language coverage, on first-load cost, and on the engineering burden of supporting a wide hardware range. The table compares them on qualitative properties; no numbers, because the real ones depend on your device mix and models.

Property Fully on-device (WebLLM + Piper) Cloud pipeline Hybrid (local speech, cloud model)
Audio leaves the device No Yes Text only, if recognition is local
Works offline Yes, after first load No Partly (speech yes, answers no)
Answer quality ceiling Limited by small quantized models Highest available Highest available
Cost per extra conversation None to you; battery and heat to the user Metered per request Metered for the model only
First-visit cost Large download Small Moderate
Hardware variance risk High Low Moderate
Typical fit Kiosks, field tools, privacy-sensitive notes, demos Open-ended assistants, complex reasoning Consumer apps wanting private audio and strong answers

The hybrid column deserves attention because it is often the best compromise: transcribe and synthesize locally so raw audio never leaves the device, and send only text to a stronger remote model when the question needs it. Even then, tell users what is sent. Text can be as sensitive as audio.

When not to do this

  • The task needs strong multi-step reasoning, long documents or reliable tool use. A 1B-3B quantized model will disappoint.
  • Your users are on low-end phones or old browsers and you cannot test them. The long tail will dominate your support queue.
  • Your language has no good open voice. A robotic voice in the user's language is worse than a good cloud voice.
  • You need audit logs of every utterance for compliance. Local-only processing makes that harder, not easier.

8. A worked example: sizing the field-technician assistant

Return to the plant room. The requirement is narrow: answer questions about a fixed set of equipment manuals, hands-free, offline, in a noisy room. Walk through the decisions in order.

  1. Scope the model's job. The assistant does not need broad world knowledge. It needs to read a retrieved manual passage and restate the relevant line. That is a task a small model can do, so a 1B-3B quantized model is plausible, with retrieval doing the knowledge work.
  2. Retrieve locally. Ship an embedding index of the manuals with the app, query it before generation, and put only the top passages in the prompt. A short prompt keeps prefill cheap.
  3. Constrain the output. Instruct the model to answer in one or two short sentences and to say "I don't know" when the passage does not contain the answer. Short answers mean short synthesis and a faster perceived response.
  4. Pick the voice. A medium-tier Piper voice in the user's language, auditioned on real breaker labels and part numbers, since numbers and codes are where small voices stumble.
  5. Handle noise. A noisy room needs a headset microphone, conservative VAD thresholds, and a visible transcript so she can see what the assistant heard.
  6. Pre-cache. Install the app as a PWA, request persistent storage, and load models during setup on good Wi-Fi, not in the plant room.
  7. Measure on the device. Record time from end of speech to first audio on the actual tablet, over a full shift, including thermal behavior. Set a target and fail the build when it regresses.
Verification before you ship. A voice demo that works on your laptop proves almost nothing. Test the full loop on the slowest device you intend to support, with real background noise and real vocabulary, and write the pass/fail latency target down before you run the test, not after.

9. Common mistakes and what to do on Monday

Mistakes that recur

  • Synthesizing the whole reply at once. It delays first audio by the length of the entire generation. Chunk by sentence.
  • Loading models on the main thread. The page freezes during load and stutters during use.
  • Ignoring cancellation. Interrupting the user's turn without cancelling the generator wastes battery and produces late audio.
  • Trusting a single test device. Latency and stability vary enough across GPUs that one machine proves nothing.
  • Leaving a cloud call in the loop. A remote phonemizer, a remote font or telemetry that includes transcripts quietly breaks the privacy promise.
  • Unbounded history. The KV cache and prefill time both grow with it. Trim.

Decision checklist

  • Is the task simple enough for a small quantized model, with retrieval supplying facts?
  • Is there a Piper voice you have listened to in your language, on your vocabulary?
  • Do you have a feature-detected fallback for browsers without WebGPU or shader-f16?
  • Is every network dependency (phonemizer, runtime, model host) either local or disclosed?
  • Do you have a measured time-to-first-audio target on your slowest supported device?

What to do on Monday

  1. Build the smallest loop: a text box, a WebLLM engine in a worker, sentence chunking, and Piper playback. Skip the microphone for now.
  2. Log the time from submit to first audio, and look at the distribution across two or three different devices.
  3. Add VAD and barge-in as a tested state machine, then add speech recognition.
  4. Only then decide whether the quality ceiling of small models is acceptable, or whether a hybrid design is the right call.

Short FAQ

Is it really private? Only if every stage is local, including the phonemizer and recognition, and only if you ship no analytics that capture transcripts. Audit the network tab during a conversation to prove it.

Can it work on a phone? Often yes for small models on recent hardware, but memory limits, thermal throttling and storage eviction make it the hardest target. Treat desktop as the baseline and phones as a tested tier.

Do I need WebGPU for the voice? No. Piper's ONNX voices run acceptably on WebAssembly, which is why the voice side works in far more browsers than the language-model side.