Mental model
WebGPU accelerates browser inference by dispatching supported tensor kernels to a GPU through adapter-selected device limits, explicit buffers, WGSL pipelines, and queued commands. A model runtime still has to map operators, shapes, and layouts onto those kernels; unsupported work may run elsewhere. End-to-end gain depends on useful compute outweighing download, compilation, transfer, synchronization, and memory costs.
Think of WebGPU as an explicit command interface to a device, not a model server that accepts a model file and returns predictions. An application first asks navigator.gpu for an adapter. The adapter represents a compatible implementation and reports the limits and optional features available for a device request. requestDevice() consumes that adapter and produces the GPUDevice whose buffers, pipelines, queue, and limits are used by the application. Device creation can fail, the adapter can be absent, and the device can later be lost, so inference needs a fallback or a recoverable error path.
The compute path has four distinct phases. The application creates buffers for inputs, weights, and outputs; builds a WGSL shader module and compute pipeline; binds the buffers to the shader; then records a compute pass into a command encoder. Calling finish() produces a command buffer, and queue.submit() schedules it for execution. JavaScript does not synchronously wait for each instruction. When the result must return to CPU memory, encode a buffer copy into a MAP_READ staging buffer, submit that copy, and await mapAsync(). If the next operation can remain on the GPU, keeping tensors in GPU buffers avoids a costly round trip.
Inference libraries add another layer. ONNX Runtime Web can assign supported graph nodes to its WebGPU execution provider, but graph coverage is operator-, shape-, and release-dependent. If one unsupported node runs through WebAssembly, the model can cross GPU and CPU boundaries several times. A fast matrix multiplication does not guarantee a fast prediction when normalization, sampling, tensor conversion, or readback becomes the new bottleneck. Measure the complete prompt or prediction path and inspect provider placement, rather than timing only one shader.
Learning outcomes
- Given a dense-layer shape and weight precision, calculate its storage bytes and estimate the weight-traffic rate at a stated decode rate.
- Trace adapter selection, device limits, storage bindings, WGSL dispatch, and staging readback for one prediction, identifying the limit checked at each allocation.
- Choose WebGPU, WebAssembly, or remote inference for a device cohort using end-to-end p95 latency, peak memory, and quality error against a reference.
Theory
A dense layer illustrates why transfer planning matters. A row-major matrix with 4,096 input and 4,096 output channels contains 16,777,216 weights. At four bytes per FP32 weight, it occupies 67,108,864 bytes, or 64 MiB, before alignment and runtime allocations. One 4,096-value input and output vector occupy 16 KiB each. The output is small, but repeatedly uploading the matrix for each generated token would move 64 MiB per token. At 20 tokens per second, that is 1.25 GiB/s of weight traffic before activations, staging copies, or other layers. Persistent GPU-resident weights avoid that repeated upload, but require a budget for the device allocation and a strategy for eviction.
For quantized weights, nominal storage begins with Nw × bw / 8 bytes, where Nw is the number of parameters and bw is the packed bits per parameter. Scales, zero points, alignment, dequantization buffers, and temporary activations add to the resident footprint. The simple budget is:
Here, each M is measured in bytes; quantized scale storage is included separately because a four-bit model is not exactly one quarter the memory of the FP32 weights. During autoregressive decoding, the key/value cache can outgrow the weights. Its approximate size is 2 × layers × batch × sequenceLength × kvHeads × headDimension × bytesPerElement, so context length, batch size, and KV precision must be included when checking a browser memory ceiling.
Useful throughput also depends on moving data and dispatching work. For a decode step that reads a matrix of weights, a rough lower bound is weightBytes / effectiveMemoryBandwidth; add shader dispatch, conversion, and synchronization time to estimate token latency. This is not a promise of observed speed: cache reuse and kernel tiling alter traffic, while browser scheduling and thermal throttling alter the effective bandwidth. A benchmark should report model revision, quantization, shape, warmup count, device class, and whether timings include model download and compilation.
Capability selection and execution
navigator.gpu is exposed only in supported browser contexts, and successful adapter acquisition still does not mean that every model fits or that every desired feature exists. Inspect adapter limits before requesting higher device limits; only ask for optional features that the selected adapter actually exposes. The resulting device reports the limits the shader must obey. Buffer binding sizes, workgroup dimensions, storage formats, and shader language features constrain kernel design. Requesting a limit above what the adapter supports rejects device creation rather than making the hardware more capable.
Feature detection should select a whole inference route. If WebGPU is unavailable or the model exceeds the measured device budget, use a supported WebAssembly provider or an explicit remote route according to the product's privacy policy. If WebGPU is available, test that the operator set and tensor shapes stay on the intended provider. A mixed provider graph may be correct but slower when tensors repeatedly cross CPU and GPU memory. Keep a CPU or WASM reference result for numerical and quality comparison; reduced precision can shift logits and alter later generated tokens even if each kernel's local error appears small.
For compute that exceeds a few milliseconds, run orchestration in a Web Worker so shader compilation, model initialization, and result processing do not block interaction. Reuse the device, compiled pipelines, and weight buffers across requests. Make cancellation explicit: an AbortSignal can prevent new work and suppress stale UI updates, but a submitted GPU command is not equivalent to a transaction that can be rolled back. Bound prompt length and concurrency before allocating KV state. When device.lost resolves, discard device-owned buffers and pipelines, then reinitialize or switch routes; retry only after the device and model state are consistent.
Trade-offs
WebGPU can accelerate large supported tensor operations, but its route carries setup and residency costs. Model downloads and shader compilation increase cold-start latency; uploading tensors and reading outputs can erase the gain when work is small or fragmented. Keeping weights and intermediate tensors on the GPU reduces transfers, but the model then competes with the page, other tabs, and KV cache for device memory. GPU execution also shares thermal and power budgets with rendering, which matters more on a phone than on a plugged-in desktop.
| Choice | When it helps | Cost to measure |
|---|---|---|
| WebGPU kernels | Large, supported tensor operations amortize dispatch and setup | Buffer transfers, shader compilation, memory pressure, device loss |
| WASM kernels | Small models, broad operator coverage, or unsupported GPU devices | CPU throughput, thread setup, model package size |
| Remote inference | The model exceeds client memory or the network policy permits service-side execution | Round-trip latency, data handling, and availability |
The right route is per-model and per-device. Compare cold start and warmed p50/p95 under realistic page activity, then include quality drift, memory, model download size, and battery use in the same decision. Preserve the model revision, provider configuration, workload, and coarse device class with each benchmark. Avoid emitting raw adapter identifiers: capability buckets usually provide enough detail to diagnose performance without making hardware a tracking identifier.
Runnable kernel: one dense layer
This small FP32 matrix-vector kernel computes one dense layer with row-major weights. It is useful for checking dispatch, bindings, and readback against a CPU reference; production inference should use a tiled, quantized runtime kernel and keep intermediate tensors on the GPU. The wrapper checks dimensions and binding size, records the compute and readback commands in order, and destroys device resources even when a request fails.
typescriptexport async function runLinearLayer(input: Float32Array, weights: Float32Array, outputWidth: number): Promise<Float32Array> {const inputWidth = input.length;if (!inputWidth || !Number.isInteger(outputWidth) || outputWidth <= 0 || weights.length !== inputWidth * outputWidth) {throw new Error("Expected non-empty input and row-major outputWidth x inputWidth weights");}if (!navigator.gpu) throw new Error("WebGPU is unavailable in this browser context");const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });if (!adapter) throw new Error("No WebGPU adapter is available");const device = await adapter.requestDevice();const outputBytes = outputWidth * Float32Array.BYTES_PER_ELEMENT;const buffers: GPUBuffer[] = [];const makeBuffer = (size: number, usage: GPUBufferUsageFlags) => {const buffer = device.createBuffer({ size, usage });buffers.push(buffer);return buffer;};try {const largestStorageBuffer = Math.max(input.byteLength, weights.byteLength, outputBytes);if (largestStorageBuffer > device.limits.maxStorageBufferBindingSize || largestStorageBuffer > device.limits.maxBufferSize) {throw new Error("A storage buffer exceeds this device's supported size limits");}const x = makeBuffer(input.byteLength, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);const w = makeBuffer(weights.byteLength, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);const y = makeBuffer(outputBytes, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC);const params = makeBuffer(8, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);const readback = makeBuffer(outputBytes, GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST);device.queue.writeBuffer(x, 0, input); device.queue.writeBuffer(w, 0, weights);device.queue.writeBuffer(params, 0, new Uint32Array([inputWidth, outputWidth]));const code = ["struct Params { inputWidth: u32, outputWidth: u32, };","@group(0) @binding(0) var<storage, read> x: array<f32>;\n@group(0) @binding(1) var<storage, read> w: array<f32>;\n@group(0) @binding(2) var<storage, read_write> y: array<f32>;\n@group(0) @binding(3) var<uniform> p: Params;","@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let row = id.x;\n if (row >= p.outputWidth) { return; }\n var sum: f32 = 0.0;"," for (var column = 0u; column < p.inputWidth; column += 1u) {\n sum += w[row * p.inputWidth + column] * x[column];\n }\n y[row] = sum;\n}",].join("\n");const module = device.createShaderModule({ code });const pipeline = await device.createComputePipelineAsync({ layout: "auto", compute: { module, entryPoint: "main" } });const group = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [x, w, y, params].map((buffer, binding) => ({ binding, resource: { buffer } })) });const encoder = device.createCommandEncoder();const pass = encoder.beginComputePass();pass.setPipeline(pipeline); pass.setBindGroup(0, group); pass.dispatchWorkgroups(Math.ceil(outputWidth / 64));pass.end();encoder.copyBufferToBuffer(y, 0, readback, 0, outputBytes);device.queue.submit([encoder.finish()]);await readback.mapAsync(GPUMapMode.READ);const result = new Float32Array(readback.getMappedRange().slice(0));readback.unmap();return result;} finally {buffers.forEach((buffer) => buffer.destroy());device.destroy();}}
Failure modes and misconceptions
A mobile adapter with a 32 MiB maximum storage-buffer binding size cannot bind the 64 MiB FP32 matrix from the worked example as one storage buffer. Asking for a larger device limit does not override the adapter's capability. The application must choose a smaller or quantized representation, split the computation into supported tiles, or select another provider. Splitting is not automatically faster: extra dispatches, intermediate tensors, and dequantization can consume the time saved by GPU arithmetic.
WGSL validation errors often come from mismatched bind-group layouts, a uniform structure with a different byte layout than the host data, or a dispatch that indexes beyond a final partial workgroup. Validate shader compilation during development, keep bounds checks in kernels, and test dimensions that are not multiples of the workgroup size. A valid command buffer also does not guarantee numerically equivalent model output; compare against a CPU reference on representative inputs and inspect downstream quality after reduced-precision kernels.
Provider fragmentation is a performance failure even when the prediction remains correct. If a graph runs a convolution on WebGPU, copies its output to CPU memory for an unsupported operator, then copies the result back for another GPU kernel, transfer and synchronization time can dominate the computation. Inspect the full graph's provider assignment and benchmark the full prediction. A single fast matrix kernel is weak evidence for a faster model.
Device loss can reject a pending map or invalidate buffers and pipelines. Treat device.lost as a route change: stop submitting work, discard old resources, and reinitialize from a verified model artifact or fall back. Cold-start and steady-state results can also mislead in opposite directions. A warm-only test hides download and compilation delay; a one-shot test overweights initialization. Measure both phases and report p50 and p95 under the same workload and page activity.
Decision scenario
A support-chat application handles private ticket text in the browser. Its 4,096 by 4,096 FP32 layer needs 64 MiB for weights before activations or KV cache. A desktop WebGPU canary meets the latency target, but a mobile adapter reports a 32 MiB maximum storage-buffer binding size, and long prompts approach the page's measured memory budget. Do not request an unsupported limit or roll the desktop result across the whole population. Test a smaller or quantized artifact and a tiled kernel against the same mobile cohort, including the complete model graph, long-context peak memory, p95 latency, and output quality. If no candidate fits all limits, route those devices to a measured WASM path or an explicitly approved remote path, then keep the WebGPU rollout scoped to cohorts that pass.