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.
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:
- Zero audio leaves the device: microphone input and dropped audio files are decoded via
AudioContextat 16 kHz inside the visitor's tab and never touch an API server. - 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.6B | Qwen3-ASR-0.6B-Cantonese-HK (ours) |
|---|---|---|
FLEURS (yue_hant_hk) | 6.10 | 5.70 |
| Common Voice yue | 6.84 | 5.12 |
| Common Voice 23 zh-HK | 9.55 | 6.44 |
| MDCC | 5.45 | 3.29 |
| LegCo | 8.81 | 7.62 |
| MCE (code-switching) | 15.52 | 6.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, 111MatMulNBitsops): runs once per chunk on[1, 128, T]log-mel spectrograms and emitsaudio_features [1, enc_time, 1024].decoder_init.onnx(0.58 MB graph, 3,403 nodes, 197MatMulNBitsops): prefill pass. It receivesinputs_embeds, scattersaudio_featuresover theaudio_pad(151676) span starting ataudio_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, 197MatMulNBitsops): single-token autoregressive loop takinginput_embeds [1, 1, 1024]andpast_keys/past_values.
Two packaging bugs and surgeries made the biggest size difference:
- Deduplicating
decoder_weights.data(633.47 MB): During our initial ONNX export, writingdecoder_stepinto the same directory asdecoder_initcaused scatteredonnx__MatMul_*initializer files (373 files, 6.49 GB total) to silently overwritedecoder_initweights because traced node IDs differed between graphs. Exporting each graph to an isolated directory, consolidatingdecoder_initinto one external data file, and SHA-256 deduplicating all 451 external initializers indecoder_steplet both browser sessions mount the exact sameUint8ArrayviaexternalData: [{ path: "decoder_weights.data", data: files["decoder_weights.data"] }]. - Pulling
embed_tokensout to JS FP16 and slicinglm_head: Originallydecoder_initkept an internal FP32Gatheroverembed_tokens.weight(151,936 x 1,024 x 4 bytes = 622,329,856 bytes), duplicating the external embedding file used bydecoder_step. We stripped thatGathernode, dropped the leading 622,329,856 bytes fromdecoder_weights.data(shifting all remaining initializer byte offsets down by that exact count), switcheddecoder_initto acceptinputs_embeds, and inserted aSlicenode (/lm_head/SliceLast) beforelm_headso prefill returnslogits [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):
| Artifact | Size (MB) | Size (MiB) | Parts (<= 24 MiB) | Role |
|---|---|---|---|---|
decoder_weights.data | 633.47 | 604.12 | 26 | Shared INT8 decoder weights (init + step) |
embed_tokens.bin | 311.16 | 296.75 | 13 | FP16 embedding matrix (151,936 x 1,024) |
encoder.onnx | 216.35 | 206.33 | 9 | INT8 audio encoder (111 MatMulNBits) |
vocab.json | 2.78 | 2.65 | 1 | Byte-level BPE decode vocabulary |
decoder_init.onnx | 0.58 | 0.55 | 1 | Prefill graph + /lm_head/SliceLast |
decoder_step.onnx | 0.56 | 0.54 | 1 | Autoregressive step graph |
mel_filters.bin | 0.10 | 0.10 | 1 | Precomputed Slaney filterbank (128 x 201 FP32) |
tokenizer_config.json + config.json | 0.01 | 0.01 | 2 | Added tokens and prompt template IDs |
| Total | 1,165.02 | 1,111.05 | 54 | ~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.forwardcomputescu_seqlenschunks ofwindow_aftercnn = 13 * 8 = 104encoder tokens (~8 seconds of audio) and invokesencoder_layer(hidden_states, cu_seqlens).- Inside
Qwen3ASRAudioAttention.forward, however,cu_seqlensis forwarded ascu_seq_lens_q/cu_seq_lens_k(which onlyflash_attention_2reads), whileattention_maskremainsNone. - Under PyTorch's default
sdpaandeagerattention backends,cu_seqlensis 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: passingRTNWeightOnlyQuantConfigintoMatMulNBitsQuantizersilently forced 4-bit quantization even whenbits=8was passed. Droppingalgo_config(algo_config=None) and assertingattrs["bits"] == 8on the emittedMatMulNBitsnodes 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-bitMatMulNBitsas well, removing the duplicate 622 MB FP32 embedding copy, convertingembed_tokens.binto FP16, and slicinglm_headproduced 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.
| Variant | Size (GB) | CER (%) | Exact match vs PyTorch | CPU RTF | Notes |
|---|---|---|---|---|---|
| PyTorch FP32 (reference) | N/A | 7.62 | 20/20 | 0.475 | transformers 4.57.6 CPU baseline |
| ONNX FP32 v1 (windowed attn) | 4.40 | 8.53 | 10/20 | 0.343 | ATTN_WINDOW_SIZE=104 mismatch vs sdpa/eager |
| ONNX FP32 v2 (unwindowed attn) | 4.40 | 7.62 | 20/20 | 0.340 | Encoder fixed; exact token parity on all 20 clips |
| ONNX INT4 decoders + FP32 enc | 2.04 | 10.72 | 5/20 | 0.257 | Rejected (+3.10 pp CER regression) |
| ONNX INT8 decoders + FP32 enc | 2.33 | 7.24 | 18/20 | 0.238 | True 8-bit MatMulNBits (algo_config=None) |
| INT8 Web Package (shipped) | 1.17 | 7.75 | 17/20 | 0.184 | INT8 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 usesSR=16000,NFFT=400,HOP=160,NMEL=128, andNBIN=201. Because400 = 2^4 * 5^2is not a power of two (and zero-padding to 512 shifts frequency bins),makeFFT(400)implements a mixed-radix recursive complex FFT inFloat64Arraywith precomputed twiddle tables, Hann windowing, 200-sample reflect padding (center=True), and the precomputed Slaney filterbankmel_filters.bin(102.9 KB). Across clip 00 of FLEURS, maximum absolute difference against PyTorchlog_mel_spectrogramstays around2e-5(verified< 1e-4intest/lib.test.ts). - Byte-level BPE decode (
decodeTokens): Reconstructing GPT-2/QwenbytesToUnicode()plusadded_tokens_decodertakes ~30 lines of TypeScript usingvocab.json(2.78 MB) andtokenizer_config.json, eliminating the 11.43 MBtokenizer.json. All 20 reference token sequences decode identically to PythonAutoTokenizer. - 30-second quiet-point chunking (
splitChunks): Recordings over 30 s scan a+/- 5 swindow around each 30 s target using a0.1 ssliding|wav|amplitude sum and split at the quietest sample, zero-padding any trailing fragment shorter than0.5 s. - Repetition guard (
fixRepetitions): Direct port ofqwen_asr'sdetect_and_fix_repetitions(threshold=20)collapsing both single-character runs (> 20) and repeating multi-character patterns (1to20chars repeated>= 20times).
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:
- 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 askoelony/Qwen3-ASR-0.6B-Cantonese-HK-ONNX. Keeping<= 24 MiBchunks gives browsers live per-part progress, single-part retries, and full compatibility with Cloudflare Workers' 25 MiB cap for the fallback mirror. Inpublic/models.json,demo.koelony.compointshfUrlto an immutable 40-character Hugging Face commit SHA (resolve/<sha>/, enforced at deploy time viaREQUIRE_PINNED_HF_SHA=1inscripts/check-dist.ts), so the web demo and browser extensions can share one public package.src/asr/loader.tscaps concurrent fetches (DEFAULT_PART_CONCURRENCY = 3), retries408/429/5xx, network errors, and truncated bodies with exponential backoff (Retry-Afteraware), and automatically switches to the same-origin CloudflareMODELSservice binding (/models/*) if Hugging Face fails. Cache API entries incaches.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. COOP / COEP / CORPfor multi-threaded WASM fallback and cross-origin CORS:wrangler.jsoncsetsrun_worker_first: truesoworker/index.tsattaches cross-origin isolation headers to every HTML,/assets/*,/models/*, and/ort/*.wasmresponse. That flipscrossOriginIsolated === trueand unlocksSharedArrayBuffer, allowing the WASM fallback to scale up toMath.min(8, navigator.hardwareConcurrency || 4)SIMD threads instead of falling back to 1 thread. Because the page runs underCross-Origin-Embedder-Policy: require-corp,src/asr/loader.tsfetches cross-origin Hugging Face and Xet CDN (*.hf.co) parts with{ mode: "cors", credentials: "omit" }, matching Hugging Face'sAccess-Control-Allow-Originheaders so the browser admits every cross-origin chunk without blocking it.- Isolating and pinning
onnxruntime-web 1.31.1: Becauseort.webgpu.min.mjsdynamically loadsort-wasm-simd-threaded.asyncify.mjsand.wasmby unhashed filename,vite.config.tsexcludesonnxruntime-webfrom pre-bundling,scripts/vite-plugin-ort.tsemits the two.mjsfiles unhashed intodist/ort/and fails the build ifORT_VERSIONinwrangler.jsoncdrifts frompackage.json,scripts/check-dist.tsblocks any.onnx/.wasm/.dataor> 24 MiBfile indist/, andworker/index.tsproxies/ort/*.wasmfrom 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",
});