Mental model
ONNX Runtime Web loads an ONNX graph into an InferenceSession, then assigns supported nodes or subgraphs to execution providers such as WebGPU or WebAssembly. Provider boundaries shape latency: each CPU/GPU crossing can copy tensor bytes, so operator support, tensor placement, and session lifetime matter as much as kernel speed.
Learning outcomes
- Trace which ONNX nodes each configured provider claims, then identify the tensor edges that cross between CPU and GPU memory.
- Calculate the byte volume of a boundary tensor from its shape and element type, and estimate its per-request transfer cost.
- Build a reusable inference session that validates names and dimensions and releases caller-owned GPU buffers only after work completes.
Theory
Provider placement and boundary cost
Treat the ONNX graph as a workload description and the execution provider as a placement decision. The graph names operators, shapes, and dependencies; a provider advertises which operators it can execute. ONNX Runtime asks providers to claim compatible subgraphs, respecting their configured priority. A WebGPU provider may own the matrix-heavy sections while WebAssembly runs a remaining operator that lacks a GPU kernel. The execution is still one inference session, but it can move intermediate tensors between device memories.
That partitioning is a correctness boundary as well as a speed boundary. Input and output names must match the exported model, tensor type and dimensions must satisfy its graph, and each crossing must preserve the expected values. A session that initializes successfully does not prove every node ran on the GPU. Inspect provider assignment or profiling output before attributing a speedup to WebGPU.
For a single inference, a useful first model is:
T_infer is total latency in seconds, T_dispatch is host scheduling and command submission time, and T_k is the time for kernel or operator k. B contains tensors that cross between CPU and GPU providers; S_b is each crossing tensor's size in bytes and β_b is its effective transfer rate in bytes per second. This estimate excludes model download and session initialization, which should be reported separately as cold-start costs.
Consider an encoder with an activation shaped [1, 512, 768] in float32. It contains 1 × 512 × 768 × 4 = 1,572,864 bytes, or 1.5 MiB. If a WebGPU region feeds a WASM-only operator and the result returns to WebGPU, two one-way boundaries move about 3 MiB per inference before staging overhead. At 30 inferences per second, those boundaries account for 90 MiB/s of transfer traffic. A compact operator between two large GPU regions can therefore cost more than its arithmetic suggests.
Buffer ownership and session lifetime
By default, ONNX Runtime Web accepts CPU-side tensors and copies inputs into WebGPU memory; results are normally copied back to CPU memory. For a one-shot image classifier, that simple path is often the right trade-off. Repeated transformer steps or a GPU preprocessing pipeline can pay the same transfer cost over and over. In those cases, WebGPU I/O binding can keep input or output tensors on a GPU buffer.
A GPU tensor created with Tensor.fromGpuBuffer refers to a caller-owned buffer. Keep that buffer alive until inference finishes, then call destroy() when the application no longer needs it. A buffer destroyed too early makes the session fail; a buffer retained indefinitely consumes device memory. Session lifetime needs the same discipline: load once for a workload, reuse it, and release it when the model is evicted or the page-level worker shuts down.
The following factory makes provider preference explicit, reuses a session, checks the exported shape, and releases session resources through an explicit close() method:
typescriptimport * as ort from "onnxruntime-web/webgpu";export async function loadRanker(modelUrl: string) {const session = await ort.InferenceSession.create(modelUrl, {executionProviders: ["webgpu", "wasm"],graphOptimizationLevel: "all",});const inputName = session.inputNames[0];const outputName = session.outputNames[0];if (!inputName || !outputName) throw new Error("ranker graph has no I/O");return {async score(features: Float32Array) {if (features.length !== 384) {throw new RangeError("ranker expects 384 float features");}const input = new ort.Tensor("float32", features, [1, 384]);const result = await session.run({ [inputName]: input });const output = result[outputName];if (!output || !Number.isFinite(Number(output.data[0]))) {throw new Error("ranker returned an invalid score");}return Number(output.data[0]);},async close() {await session.release();},};}
The provider list expresses preference; it is not evidence that every node used WebGPU. A browser without a usable adapter, an unsupported operator, or a missing kernel can change the assigned work or fail initialization. For a model whose graph is fully supported and has static shapes, graph capture may reduce repeated host overhead, but it is not a universal switch: shape changes or a CPU fallback can prevent capture. Benchmark cold initialization, warm inference, peak memory, output agreement, and energy on representative browsers.
Trade-offs
WebGPU earns its setup and dispatch cost when dense, repeated work is large enough to amortize it; WASM can win for a small ranker whose GPU path copies a full activation into and out of device memory. A second provider also adds packaging and diagnostic work, but it can keep a model usable on machines without an adapter. Keep both paths only when output tolerance is tested and telemetry can distinguish provider placement from the requested preference.
Failure modes and misconceptions
| Situation | Why it matters | Response |
|---|---|---|
| A large activation crosses providers | Transfer can dominate a small CPU operator | Inspect partitioning and minimize large boundary tensors |
| A GPU buffer is destroyed during a run | The session reads invalid device memory | Make buffer ownership and asynchronous completion explicit |
| A device cannot allocate model buffers | Adapter limits and available memory vary by device | Validate limits and retain a tested WASM path |
| Static-shape graph capture meets dynamic inputs | Capture assumptions no longer hold | Use ordinary execution or bucket inputs into fixed shapes |
The practical failure is treating successful session creation as proof of correct placement or speed. Unsupported operators can trigger fallback, provider crossings can dominate a compact kernel, and a numerical tolerance can change across implementations. Compare the same model, preprocessing, and outputs under both providers, and include output agreement in regression checks.
Decision scenario
A ranking model's WebGPU kernels are 4 ms faster than the WASM path, but profiling finds two 1.5 MiB activation boundaries around CPU-only operators. The one-way crossing volume is already 3 MiB per inference, before any return copies or staging. Measure complete warm inference and output agreement; make WebGPU the default only if those boundary costs still leave a repeatable end-to-end gain. If the copies erase the advantage, keep the WASM path or change the graph partition without removing required model operations.