Cantonese Speech to Text in the Browser with WebGPU: Running Qwen3-ASR-0.6B Locally

How we turned a community demo-video request into browser Cantonese speech to text, shrinking Qwen3-ASR-0.6B-Cantonese-HK from 4.40 GB to 1.17 GB INT8 ONNX for local WebGPU and WASM inference.

In our first post, we fine-tuned Koelony's Qwen3-ASR-Cantonese-HK series (Qwen3-ASR-1.7B-Cantonese-HK and Qwen3-ASR-0.6B-Cantonese-HK, Apache-2.0) from the Qwen team's multilingual upstream Qwen3-ASR to transcribe colloquial Hong Kong Cantonese and Cantonese-English code-switching natively (full benchmarks on our ASR model page). Right after we published the weights, people in the community asked for a demo video to hear how the model handled real Hong Kong Cantonese. Rather than cutting a pre-recorded clip that visitors had to take on faith, we tried putting the 0.6B model straight into a website so anyone could open demo.koelony.com and test Cantonese speech to text live with their own voice or audio files, and this post documents what it took to make that work.

Shrinking Qwen3-ASR-0.6B-Cantonese-HK (600M parameters plus a 151,936-token vocabulary) from 4.40 GB FP32 down to 1.17 GB INT8 ONNX (koelony/Qwen3-ASR-0.6B-Cantonese-HK-ONNX) for both the web demo and browser extensions required splitting the graph across three ONNX sessions, fixing a silent encoder attention mismatch in qwen-asr (restoring 20/20 FP32 parity and 17/20 INT8 exact match at 7.75% CER vs 7.62% PyTorch FP32 on the 20-clip FLEURS subset), writing a zero-dependency TypeScript audio frontend, and delivering <= 24 MiB chunks from a commit-pinned Hugging Face repository with a same-origin Cloudflare Workers fallback.

Architecture diagram of the local Qwen3-ASR-0.6B browser inference pipeline using pure TypeScript log-mel extraction, three ONNX Runtime Web sessions in a Web Worker, shared INT8 weights, GPU-resident KV cache, and commit-pinned Hugging Face delivery with Cloudflare Worker fallback
End-to-end browser pipeline for Qwen3-ASR-0.6B-Cantonese-HK (~1.17 GB INT8, 1,165,015,959 bytes): 16 kHz local audio flows through pure-TS Whisper log-mel, a 3-session ONNX Web Worker, commit-pinned Hugging Face chunks with Cloudflare Worker fallback and Cache API storage, and COOP/COEP multi-threaded WASM fallback.

1. Why put 0.6B Cantonese speech to text in the browser

Two practical constraints drove the local browser architecture once we decided to build a live demo instead of a video:

  1. Zero audio leaves the device: microphone input and dropped audio files are decoded via AudioContext at 16 kHz inside the visitor's tab and never touch an API server.
  2. Zero GPU server cost: hosting a public speech demo on cloud GPUs means paying per-second compute for every visitor and queuing requests under traffic spikes. Shifting inference onto the client's WebGPU adapter (or CPU via multi-threaded WASM) turns hosting into static byte delivery.

Between the two Qwen3-ASR-Cantonese-HK checkpoints we released, 1.7B targets desktop apps, while 0.6B fits comfortably inside desktop browser memory budgets while still delivering strong Hong Kong Cantonese and code-switching accuracy across all six public benchmarks. The table below reports the published 0.6B BF16 transformers evaluation (pinned model card revision, greedy decoding, language forced to Cantonese, OpenCC t2s, normalized numbers, spaces removed; browser INT8 ONNX quantization parity is measured separately in Section 3):

Test set (CER %)Upstream Qwen3-ASR 0.6BQwen3-ASR-0.6B-Cantonese-HK (ours)
FLEURS (yue_hant_hk)6.105.70
Common Voice yue6.845.12
Common Voice 23 zh-HK9.556.44
MDCC5.453.29
LegCo8.817.62
MCE (code-switching)15.526.98

Fine-tuning cut MCE Cantonese-English code-switching error by more than half (15.52% down to 6.98%). The remaining challenge was packaging the 0.6B checkpoint into a quantized ONNX bundle so a web browser could load and run it cleanly.

2. Three ONNX sessions, shared weights, and an external FP16 embedding table

In Qwen3-ASR-0.6B, the audio tower is an 18-layer transformer (d_model=896, 14 heads) preceded by three stride-2 Conv2D layers that compress every 100 mel frames into 13 audio tokens and project them to output_dim=1024. The text decoder is a 28-layer Qwen3 causal LM (hidden_size=1024, 16 query heads, 8 KV heads, head_dim=128, vocab_size=151,936, tied word embeddings). Because ASR is audio-only, its interleaved MRoPE reduces to standard 1D RoPE across all three axes.

Exporting everything as a single graph would force autoregressive steps to re-run the audio encoder or waste memory on unused branches. Instead, we split inference across three ONNX sessions:

  • encoder.onnx (216.35 MB, 688 nodes, 111 MatMulNBits ops): runs once per chunk on [1, 128, T] log-mel spectrograms and emits audio_features [1, enc_time, 1024].
  • decoder_init.onnx (0.58 MB graph, 3,403 nodes, 197 MatMulNBits ops): prefill pass. It receives inputs_embeds, scatters audio_features over the audio_pad (151676) span starting at audio_offset=9 (right after the 9-token chat prefix and before the 10-token Cantonese assistant suffix), and returns the initial stacked KV cache [28, 1, 8, seq_len, 128].
  • decoder_step.onnx (0.56 MB graph, 3,328 nodes, 197 MatMulNBits ops): single-token autoregressive loop taking input_embeds [1, 1, 1024] and past_keys / past_values.

Two packaging bugs and surgeries made the biggest size difference:

  1. Deduplicating decoder_weights.data (633.47 MB): During our initial ONNX export, writing decoder_step into the same directory as decoder_init caused scattered onnx__MatMul_* initializer files (373 files, 6.49 GB total) to silently overwrite decoder_init weights because traced node IDs differed between graphs. Exporting each graph to an isolated directory, consolidating decoder_init into one external data file, and SHA-256 deduplicating all 451 external initializers in decoder_step let both browser sessions mount the exact same Uint8Array via externalData: [{ path: "decoder_weights.data", data: files["decoder_weights.data"] }].
  2. Pulling embed_tokens out to JS FP16 and slicing lm_head: Originally decoder_init kept an internal FP32 Gather over embed_tokens.weight (151,936 x 1,024 x 4 bytes = 622,329,856 bytes), duplicating the external embedding file used by decoder_step. We stripped that Gather node, dropped the leading 622,329,856 bytes from decoder_weights.data (shifting all remaining initializer byte offsets down by that exact count), switched decoder_init to accept inputs_embeds, and inserted a Slice node (/lm_head/SliceLast) before lm_head so prefill returns logits [1, 1, 151936] instead of computing logits across the entire prompt sequence.

In the Web Worker (src/asr/worker.ts), embeddings live in embed_tokens.bin as IEEE-754 float16 (311.16 MB / 296.75 MiB). Precomputing a 65,536-entry Float32Array lookup table once at startup keeps runtime row gathering fast and dependency-free:

function f16ToF32(h: number): number {
  const s = (h & 0x8000) >> 15;
  const e = (h & 0x7c00) >> 10;
  const f = h & 0x03ff;
  if (e === 0) return (s ? -1 : 1) * 2 ** -14 * (f / 1024);
  if (e === 31) return f ? Number.NaN : s ? -Infinity : Infinity;
  return (s ? -1 : 1) * 2 ** (e - 15) * (1 + f / 1024);
}

const F16 = new Float32Array(65536).map((_, i) => f16ToF32(i));

function embedRows(ids: number[]): Float32Array {
  const H = 1024;
  const out = new Float32Array(ids.length * H);
  for (let r = 0; r < ids.length; r++) {
    const b = ids[r] * H;
    const o = r * H;
    for (let j = 0; j < H; j++) out[o + j] = F16[emb[b + j]];
  }
  return out;
}

Together with dropping the redundant 11.43 MB tokenizer.json (since vocab.json + tokenizer_config.json suffice for decoding), the shipped web package totals 1,165,015,959 bytes (~1.17 GB / 1.09 GiB):

ArtifactSize (MB)Size (MiB)Parts (<= 24 MiB)Role
decoder_weights.data633.47604.1226Shared INT8 decoder weights (init + step)
embed_tokens.bin311.16296.7513FP16 embedding matrix (151,936 x 1,024)
encoder.onnx216.35206.339INT8 audio encoder (111 MatMulNBits)
vocab.json2.782.651Byte-level BPE decode vocabulary
decoder_init.onnx0.580.551Prefill graph + /lm_head/SliceLast
decoder_step.onnx0.560.541Autoregressive step graph
mel_filters.bin0.100.101Precomputed Slaney filterbank (128 x 201 FP32)
tokenizer_config.json + config.json0.010.012Added tokens and prompt template IDs
Total1,165.021,111.0554~1.17 GB (1.09 GiB)

3. Shrinking 4.40 GB down to 1.17 GB: the FP32 v1 to v2 encoder bug and INT8 vs INT4

Before trusting any quantization pass, we built a 20-clip parity harness against PyTorch FP32 (transformers 4.57.6) on the first 20 clips of FLEURS yue_hant_hk test (258.90 s total audio, clip lengths 7.44 s to 21.06 s, greedy decoding, CER computed after stripping punctuation, symbols, and whitespace without OpenCC folding, measured on an AMD RYZEN AI MAX+ 395 CPU with ONNX Runtime 1.32.0). PyTorch FP32 itself scored 7.62% CER at 0.475 CPU RTF (122.99 s).

Why FP32 v1 only matched PyTorch on 10/20 clips

Our first consolidated FP32 export (4.40 GB / 4.09 GiB) immediately raised a red flag: exact token match against PyTorch was only 10/20 (8.53% CER instead of 7.62%).

Isolating every tensor stage in Python revealed that embed_tokens.bin was bit-identical to PyTorch and MRoPE position_ids matched get_rope_index identically, yet the audio encoder output audio_features diverged on longer clips. Inspecting Qwen3ASRAudioEncoder.forward and Qwen3ASRAudioAttention.forward in qwen-asr uncovered the reason:

  • Qwen3ASRAudioEncoder.forward computes cu_seqlens chunks of window_aftercnn = 13 * 8 = 104 encoder tokens (~8 seconds of audio) and invokes encoder_layer(hidden_states, cu_seqlens).
  • Inside Qwen3ASRAudioAttention.forward, however, cu_seqlens is forwarded as cu_seq_lens_q / cu_seq_lens_k (which only flash_attention_2 reads), while attention_mask remains None.
  • Under PyTorch's default sdpa and eager attention backends, cu_seqlens is ignored completely, so the encoder actually executes full unwindowed bidirectional self-attention across [1, valid_count, d_model].

Our v1 ONNX EncoderWrapper faithfully partitioned tokens into hard ATTN_WINDOW_SIZE = 104 blocks, cutting cross-window attention on every clip exceeding ~8 seconds (19 of the 20 test clips were 9.48 to 21.06 s). Rewriting the wrapper (EncoderWrapperV2) to keep the 100-frame windowed Conv2D stem while removing the 104-token attention window brought ONNX FP32 v2 from 10/20 straight to 20/20 exact token match and 7.62% CER:

class EncoderWrapperV2(nn.Module):
    def forward(self, mel: torch.Tensor) -> torch.Tensor:
        T = mel.shape[2]
        pad_amount = (CONV_WINDOW - T % CONV_WINDOW) % CONV_WINDOW
        mel_padded = F.pad(mel, (0, pad_amount))
        num_conv_windows = mel_padded.shape[2] // CONV_WINDOW

        x = mel_padded.squeeze(0).reshape(128, num_conv_windows, CONV_WINDOW)
        x = x.permute(1, 0, 2).unsqueeze(1)  # [N, 1, 128, 100]
        x = F.gelu(self.conv2d1(x))
        x = F.gelu(self.conv2d2(x))
        x = F.gelu(self.conv2d3(x))

        b, c, f, t = x.shape
        x = self.conv_out(x.permute(0, 3, 1, 2).reshape(b, t, c * f))
        x = x + self.positional_embedding(t).unsqueeze(0)

        # Match Qwen3ASRAudioAttention under sdpa/eager: unwindowed attention over [1, valid_count, d_model]
        valid_count = _get_feat_extract_output_lengths(T)
        x = x.reshape(-1, self.d_model)[:valid_count].unsqueeze(0)
        for layer in self.layers:
            x = _unwindowed_encoder_layer(layer, x, self.scaling, self.num_heads, self.head_dim)
        return self.proj2(self.act(self.proj1(self.ln_post(x))))

Why we rejected INT4 (10.72% CER, 5/20) and chose INT8

Next we tested weight quantization on top of FP32 v2:

  • INT4 RTN (bits=4, block_size=64, accuracy_level=4): Keeping the encoder in FP32 and quantizing decoder weights to INT4 shrank the bundle to 2.04 GB, but CER degraded sharply from 7.62% to 10.72% (+3.10 percentage points) and exact matches collapsed to 5/20. Proper nouns and common characters drifted across clips (for instance 「奢華」 became 「車廈」, 「準確」 became 「盡快」, and 「拉斯-埃斯特雷亞斯」 turned into 「拉斯維加斯特萊亞斯」).
  • INT8 MatMulNBits (bits=8, block_size=64, is_symmetric=True, accuracy_level=4): One ORT quantizer trap waited here: passing RTNWeightOnlyQuantConfig into MatMulNBitsQuantizer silently forced 4-bit quantization even when bits=8 was passed. Dropping algo_config (algo_config=None) and asserting attrs["bits"] == 8 on the emitted MatMulNBits nodes yielded true 8-bit block quantization: 7.24% CER and 18/20 exact match (with FP32 encoder, 2.33 GB).
  • Final INT8 Web Package (1.17 GB): Quantizing the encoder's 111 MatMuls to 8-bit MatMulNBits as well, removing the duplicate 622 MB FP32 embedding copy, converting embed_tokens.bin to FP16, and slicing lm_head produced 7.75% CER (+0.13 pp vs PyTorch's 7.62%), 17/20 exact text and token match, and 0.184 CPU RTF (2.58x faster than PyTorch FP32 CPU). Even on the 3 differing clips, one difference was only a single comma and the other two were single-character foreign transliteration swaps.
VariantSize (GB)CER (%)Exact match vs PyTorchCPU RTFNotes
PyTorch FP32 (reference)N/A7.6220/200.475transformers 4.57.6 CPU baseline
ONNX FP32 v1 (windowed attn)4.408.5310/200.343ATTN_WINDOW_SIZE=104 mismatch vs sdpa/eager
ONNX FP32 v2 (unwindowed attn)4.407.6220/200.340Encoder fixed; exact token parity on all 20 clips
ONNX INT4 decoders + FP32 enc2.0410.725/200.257Rejected (+3.10 pp CER regression)
ONNX INT8 decoders + FP32 enc2.337.2418/200.238True 8-bit MatMulNBits (algo_config=None)
INT8 Web Package (shipped)1.177.7517/200.184INT8 enc + dec, FP16 embed, SliceLast, shared weights

4. WebGPU inference and memory control: GPU-resident KV cache and .dispose()

During autoregressive decoding, decoder_init and decoder_step pass two stacked KV cache tensors shaped [28, 1, 8, seq_len, 128]. Left to default settings, ONNX Runtime Web downloads both present_keys and present_values from GPU buffers back into CPU RAM after every token, then immediately re-uploads them on the next step.

Setting preferredOutputLocation to "gpu-buffer" on both present_keys and present_values keeps the KV cache pinned on the GPU across the entire decoding loop, transferring only the [1, 1, 151936] logits tensor back to JS for greedy argmax. Just as critical, WebGPU GPUBuffer handles inside ort.Tensor do not wait politely for JavaScript garbage collection during a 512-token loop. Calling .dispose?.() on af, logits, and the previous step's pk / pv at every iteration prevents VRAM from growing quadratically and avoids browser tab OOM crashes (src/asr/worker.ts):

const kvGpu: Ort.InferenceSession.SessionOptions =
  backend === "webgpu"
    ? { preferredOutputLocation: { present_keys: "gpu-buffer", present_values: "gpu-buffer" } }
    : {};

// inside transcribeChunk():
af.dispose?.();
let next = argmax(r.logits.data as Float32Array);
r.logits.dispose?.();
let pk: Tensor = r.present_keys;
let pv: Tensor = r.present_values;
let p = ids.length;
const out: number[] = [];

while (!EOS.has(next) && out.length < MAX_NEW_TOKENS) {
  out.push(next);
  if (out.length % 4 === 0) onPartial(out);
  const rr = await S.step.run({
    input_embeds: new ort.Tensor("float32", embedRows([next]), [1, 1, 1024]),
    position_ids: new ort.Tensor("int64", BigInt64Array.from([BigInt(p)]), [1, 1]),
    past_keys: pk,
    past_values: pv,
  });
  pk.dispose?.();
  pv.dispose?.();
  pk = rr.present_keys;
  pv = rr.present_values;
  next = argmax(rr.logits.data as Float32Array);
  rr.logits.dispose?.();
  p++;
}
pk.dispose?.();
pv.dispose?.();

5. Zero-dependency TypeScript frontend and in-browser regression tests

To keep the UI bundle small and prevent subtle preprocessing drift from PyTorch, the entire audio frontend and token decoder (src/asr/lib.ts) are zero-dependency TypeScript ports whose arithmetic matches Python:

  • 128-bin Whisper Log-Mel (logMel): Whisper uses SR=16000, NFFT=400, HOP=160, NMEL=128, and NBIN=201. Because 400 = 2^4 * 5^2 is not a power of two (and zero-padding to 512 shifts frequency bins), makeFFT(400) implements a mixed-radix recursive complex FFT in Float64Array with precomputed twiddle tables, Hann windowing, 200-sample reflect padding (center=True), and the precomputed Slaney filterbank mel_filters.bin (102.9 KB). Across clip 00 of FLEURS, maximum absolute difference against PyTorch log_mel_spectrogram stays around 2e-5 (verified < 1e-4 in test/lib.test.ts).
  • Byte-level BPE decode (decodeTokens): Reconstructing GPT-2/Qwen bytesToUnicode() plus added_tokens_decoder takes ~30 lines of TypeScript using vocab.json (2.78 MB) and tokenizer_config.json, eliminating the 11.43 MB tokenizer.json. All 20 reference token sequences decode identically to Python AutoTokenizer.
  • 30-second quiet-point chunking (splitChunks): Recordings over 30 s scan a +/- 5 s window around each 30 s target using a 0.1 s sliding |wav| amplitude sum and split at the quietest sample, zero-padding any trailing fragment shorter than 0.5 s.
  • Repetition guard (fixRepetitions): Direct port of qwen_asr's detect_and_fix_repetitions(threshold=20) collapsing both single-character runs (> 20) and repeating multi-character patterns (1 to 20 chars repeated >= 20 times).

Finally, visiting ?selftest=3 (or ?selftest=20&backend=wasm) triggers an end-to-end browser self-test inside Demo.tsx: it checks melMaxDiff against /test/mel_ref_00.bin, runs full worker transcription on the FLEURS yue_hant_hk reference WAVs, verifies word-for-word parity against Python pt_text, and exposes metrics on window.__hkasr.selftest for headless Chromium verification.

6. Hugging Face delivery, Cloudflare Worker fallback, isolation headers, and honest limits

Shipping a 1.17 GB browser model across both a web demo (demo.koelony.com) and browser extensions means keeping downloads fast, cache-friendly, and resilient without relying on a single static host. Cloudflare Workers caps static assets at 25 MiB per file, and even the WebAssembly runtime (ort-wasm-simd-threaded.asyncify.wasm, ~28 MiB) exceeds that limit. Our deployment solves model hosting, fallback, and runtime isolation across src/asr/loader.ts, worker/index.ts, and scripts/vite-plugin-ort.ts:

  1. Commit-pinned Hugging Face primary + same-origin Cloudflare fallback + Cache API: Every file over 24 MiB (encoder.onnx, decoder_weights.data, embed_tokens.bin) is split into <= 24 MiB (25,165,824-byte) parts (54 parts total) and published as koelony/Qwen3-ASR-0.6B-Cantonese-HK-ONNX. Keeping <= 24 MiB chunks gives browsers live per-part progress, single-part retries, and full compatibility with Cloudflare Workers' 25 MiB cap for the fallback mirror. In public/models.json, demo.koelony.com points hfUrl to an immutable 40-character Hugging Face commit SHA (resolve/<sha>/, enforced at deploy time via REQUIRE_PINNED_HF_SHA=1 in scripts/check-dist.ts), so the web demo and browser extensions can share one public package. src/asr/loader.ts caps concurrent fetches (DEFAULT_PART_CONCURRENCY = 3), retries 408/429/5xx, network errors, and truncated bodies with exponential backoff (Retry-After aware), and automatically switches to the same-origin Cloudflare MODELS service binding (/models/*) if Hugging Face fails. Cache API entries in caches.open("hkasr-yue-0.6b-int8") are always keyed by the canonical same-origin part URL so existing visitor caches stay valid and primary/fallback sources never duplicate storage.
  2. COOP / COEP / CORP for multi-threaded WASM fallback and cross-origin CORS: wrangler.jsonc sets run_worker_first: true so worker/index.ts attaches cross-origin isolation headers to every HTML, /assets/*, /models/*, and /ort/*.wasm response. That flips crossOriginIsolated === true and unlocks SharedArrayBuffer, allowing the WASM fallback to scale up to Math.min(8, navigator.hardwareConcurrency || 4) SIMD threads instead of falling back to 1 thread. Because the page runs under Cross-Origin-Embedder-Policy: require-corp, src/asr/loader.ts fetches cross-origin Hugging Face and Xet CDN (*.hf.co) parts with { mode: "cors", credentials: "omit" }, matching Hugging Face's Access-Control-Allow-Origin headers so the browser admits every cross-origin chunk without blocking it.
  3. Isolating and pinning onnxruntime-web 1.31.1: Because ort.webgpu.min.mjs dynamically loads ort-wasm-simd-threaded.asyncify.mjs and .wasm by unhashed filename, vite.config.ts excludes onnxruntime-web from pre-bundling, scripts/vite-plugin-ort.ts emits the two .mjs files unhashed into dist/ort/ and fails the build if ORT_VERSION in wrangler.jsonc drifts from package.json, scripts/check-dist.ts blocks any .onnx/.wasm/.data or > 24 MiB file in dist/, and worker/index.ts proxies /ort/*.wasm from jsDelivr with edge caching and isolation headers:
export const SECURITY_HEADERS: Record<string, string> = {
  "Cross-Origin-Opener-Policy": "same-origin",
  "Cross-Origin-Embedder-Policy": "require-corp",
  "Cross-Origin-Resource-Policy": "same-origin",
  "X-Content-Type-Options": "nosniff",
  "Referrer-Policy": "strict-origin-when-cross-origin",
};

// Inside fetch() for /ort/*.wasm (~28 MiB, over Workers' 25 MiB static asset cap):
const name = p.slice("/ort/".length);
if (!/^[\w.-]+\.wasm$/.test(name)) return plain(404, "not found", env);
const src = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${env.ORT_VERSION}/dist/${name}`;
const res = await fetch(src, { cf: { cacheEverything: true, cacheTtl: 30 * 86400 } } as RequestInit);
return finish(new Response(req.method === "HEAD" ? null : res.body, res), env, {
  "Content-Type": "application/wasm",
  "Cache-Control": "public, max-age=86400",
});