Mental model
WebAssembly runs validated instructions over linear memory through the browser's CPU runtime; WebGPU submits compute work to an adapter-backed GPU device. The faster choice depends on the whole path: model support, startup, dispatch, tensor copies, memory pressure, and workload size. A small operation can be quicker on WASM even when the GPU kernel itself is faster.
Learning outcomes
- Profile cold startup and warm p50/p95 latency for the same model, input tensors, and browser device.
- Estimate provider-boundary bytes from tensor shape and element size before blaming an individual kernel.
- Select a fallback policy that checks adapter availability, preserves output tolerance, and records which backend actually ran.
Theory
Runtime execution models
Use WASM as a portable baseline, not as a promise of identical speed on every browser. It can run near-native compiled code within a sandbox and offers SIMD instructions; threaded configurations may require shared memory and cross-origin isolation. It is attractive for small models, CPU-friendly operators, or devices where browser GPU access is unavailable. ONNX Runtime Web documents WASM support for all ONNX operators in its current web runtime.
WebGPU exposes an adapter, a device with supported limits and features, buffers, shader pipelines, and an asynchronous queue. It suits parallel operations such as large matrix multiplies when enough work can be batched into GPU commands. Getting an adapter is only a capability probe: device creation may still fail, requested limits can be unavailable, and the GPU may be shared with graphics or other tabs. ONNX Runtime Web documents WebGPU support for only a subset of operators, so a model can be split between providers.
Compare the complete inference path
For repeated inference, estimate:
All terms are milliseconds per inference after dividing T_setup by N, the number of calls that reuse the initialized runtime. T_dispatch is host-side command and synchronization overhead, T_kernel is backend execution time, and each CPU/GPU crossing i moves B_i bytes at effective rate β_i bytes per millisecond. Choose WebGPU only when its total path beats the measured WASM path while meeting memory, accuracy, and energy limits.
Suppose a laptop measures a small model at 6 ms per warm WASM inference. On the same input, WebGPU needs 2 ms for kernels, 1.5 ms for dispatch, and 3 ms for staging a 1.5 MiB input and a 1.5 MiB result; its 6.5 ms total is slower. A larger batched encoder might take 84 ms on WASM and 18 ms of GPU work plus 4.5 ms of overhead, finishing in 22.5 ms. These are measured examples, not portable benchmarks: report the device, browser, batch, shape, model precision, and whether compilation and download are included.
Cold start can change the product decision. If WebGPU initialization takes 140 ms and the model runs only 20 times, setup contributes 7 ms per call when amortized across that short session. A long-running worker that serves hundreds of requests spreads the same cost much further. Measure both first-use latency and warm percentiles instead of combining them into one average.
Session selection and fallback
This session factory fetches the model once so a failed GPU initialization can retry with the same bytes on WASM. It does not interpret adapter presence as a speed guarantee; production code should choose its preferred path from device-level measurements and can record which session was opened.
typescripttype Backend = "webgpu" | "wasm";export async function openModel(modelUrl: string) {const response = await fetch(modelUrl);if (!response.ok) throw new Error("model download failed");const modelBytes = new Uint8Array(await response.arrayBuffer());const adapter = await navigator.gpu?.requestAdapter({powerPreference: "high-performance",});if (adapter) {try {const gpuOrt = await import("onnxruntime-web/webgpu");const session = await gpuOrt.InferenceSession.create(modelBytes, {executionProviders: ["webgpu", "wasm"],});return { backend: "webgpu" as Backend, session };} catch (error) {console.warn("WebGPU initialization failed; trying WASM", error);}}const wasmOrt = await import("onnxruntime-web");const session = await wasmOrt.InferenceSession.create(modelBytes, {executionProviders: ["wasm"],});return { backend: "wasm" as Backend, session };}
requestAdapter() may resolve to null, and an adapter's limits describe what can be requested rather than an unlimited memory pool. A WebGPU session can fail when the browser denies device creation or cannot allocate the model's buffers. Keep this fallback visible in telemetry; otherwise a successful page load can conceal that every request is running on the slower CPU path.
WASM also has non-obvious constraints. More worker threads do not guarantee more throughput: contention with the UI, cache effects, and shared-memory setup can outweigh parallel work. If multithreading is enabled, verify the deployment's cross-origin isolation requirements and measure on mobile devices where CPU cores and memory bandwidth are constrained. Conversely, a GPU can be power-efficient for large batches but costly for repeated tiny dispatches; thermal throttling can make a long benchmark diverge from its first minute.
Trade-offs
| Workload property | WASM path | WebGPU path | What to measure |
|---|---|---|---|
| Small operators and one-shot tasks | Avoids GPU command and readback overhead | Dispatch can cost more than the kernel | Cold and warm end-to-end latency |
| Large dense layers or batched images | CPU throughput may become the limit | Parallel GPU work can amortize dispatch | Throughput at realistic batch and shape |
| Operator coverage | Broad ONNX coverage in ONNX Runtime Web | Supported operators only; partitions may fall back | Provider assignment and crossing tensor sizes |
| Memory placement | Linear memory in the browser process | Separate device buffers and limits | Peak process memory and device allocation failures |
WASM avoids a GPU command queue and often suits tiny or one-shot work. WebGPU pays additional setup and dispatch, then can win on large parallel layers or repeated batches. A fallback provider preserves coverage when a kernel is unavailable, but copies between provider-owned memory can erase the gain. Keep both backends only when their full paths meet the product's latency, memory, accuracy, and energy targets.
Failure modes and misconceptions
Adapter detection is not device creation: requestAdapter() can return null, and requestDevice() can fail when requested features or limits are unavailable. A WebGPU provider may also leave unsupported ONNX operators on WASM, adding activation transfers at every partition boundary. Test provider placement and fallback rate instead of recording only the backend the application requested.
WASM threading has deployment constraints as well. Shared memory requires an isolated browser context; without the expected cross-origin isolation, a threaded build may not initialize. Increasing worker count can also contend with rendering and application JavaScript, especially on mobile CPUs. GPU thermal throttling can turn an initially fast run into a slower long-session tail. Benchmark sustained workloads and treat missing adapter, allocation failure, unsupported operators, and degraded sustained throughput as separate cases.
Run the same preprocessed tensors through both implementations. Compare output error against the application's tolerance, include odd dimensions and empty batches where the model allows them, and test a device with no adapter. Track startup, warm p50 and p95, peak memory, energy per request, and fallback rate by browser and device class.
Decision scenario
A mobile browser app runs a small classifier only twice per visit. WASM takes 6 ms per warm call. The measured WebGPU path takes 2 ms in kernels, 1.5 ms in dispatch, and 3 ms in transfers, or 6.5 ms per warm call, plus 120 ms of session initialization. Even before accounting for model download, two WebGPU calls take about 133 ms against 12 ms of WASM work. Prefer WASM for this short visit; reconsider WebGPU for sustained or larger workloads only after end-to-end measurements show a latency or energy benefit without output regressions.