Mental model
An edge-to-cloud inference router runs a request in the browser only when the selected model, execution provider, and device profile pass capability and latency checks; it sends data to a server only when policy permits that route. The router returns one result with its route, model revision, and timing, and discards partial local output before invoking cloud inference.
Learning outcomes
- Determine whether a model revision fits a device profile by checking adapter availability, required limits, operator coverage, and measured p95 latency.
- Distinguish an ONNX execution-provider choice inside the browser from an application-level route that transmits a prompt to a server.
- Implement a request budget and privacy rule that yields an edge result, a consented cloud result, or an explicit rejection.
Theory
The edge path begins with a device check, not a promise that the browser supports every GPU operation. The WebGPU API can be missing, requestAdapter can return null, and an adapter's limits can be lower than a model's buffer requirements. A successful adapter request is only one input to admission; the application must also know the model revision, weight format, tensor shapes, and device-specific peak memory.
Transformers.js uses ONNX Runtime Web for browser inference. Its default CPU path runs through WebAssembly, while a caller can request WebGPU. ONNX Runtime documents that WASM supports all ONNX operators, whereas WebGPU supports a subset. A graph can therefore work on WASM but fail or partition differently on WebGPU. Measure the actual graph and inspect runtime diagnostics for CPU fallbacks; a present navigator.gpu property does not prove that the whole model ran on the GPU.
A provider fallback stays on the device: the runtime may execute supported nodes on WebGPU and other nodes on a CPU provider. An edge-to-cloud fallback is a different application decision because it sends request data beyond the browser. Gate that route on the request's privacy classification and an explicit tenant or user permission. Never treat a local timeout as consent to upload the prompt. Return route provenance and model revision, but keep prompt text out of telemetry.
The router can be described as a policy over one request:
Here V_e means the exact model and provider passed the release evaluation for this device class; C_e(x) means the request fits the model's supported input and memory profile; t_e is predicted or measured local latency in milliseconds; D is the remaining request deadline in milliseconds; P_c is explicit permission for this data to leave the device; C_c means the cloud endpoint is reachable; and t_c is the cloud round-trip time in milliseconds. Route choice is not a per-token confidence score. If local eligibility fails and cloud permission is false, return a useful error or offer a user-controlled retry route.
On a measured laptop profile, suppose the WebGPU model's warm p95 is 620 ms and WASM p95 is 1,450 ms. With a 900 ms deadline, the warm WebGPU route qualifies but WASM does not. If WebGPU is unavailable and the request is permitted for cloud processing, a 360 ms cloud response can meet the deadline; if the prompt is confidential, the router must reject or request permission instead of silently forwarding it. Cold model download and compilation need separate budgets because they can take seconds before the first inference begins.
Trade-offs
| Route | Advantage | Cost or limit |
|---|---|---|
| WebGPU in the browser | Keeps input on-device and can accelerate supported tensor operators | Requires a usable adapter, compatible shapes, memory headroom, and a tested low-bit kernel |
| WASM in the browser | Runs on CPU when WebGPU is absent and covers the ONNX operator set | Can exceed interaction deadlines on a phone or for a large model |
| Cloud inference | Can use a larger server model and predictable server hardware | Adds network latency and transfers request data under the service's privacy policy |
Measure cold-load time, warm p50/p95 latency, peak memory, output quality, and provider partitioning by model revision and device class. A smaller model may be a better local route than repeatedly attempting a model that exceeds the device budget. Keep the latency profile separate for a cold cache and a warm cache; a cache hit avoids model download but does not guarantee that GPU pipelines or device memory are ready.
The example's policy.modelProfile is a release-tested record for the pinned model revision. It marks WebGPU operator compatibility and the minimum storage-buffer limit; an adapter that misses that requirement stays on WASM.
Failure modes and misconceptions
WebGPU availability can change between an initial feature check and model creation, and adapter loss can happen during a run. Catch model-load and inference failures and mark that local profile unhealthy until it is revalidated. Do not loop through repeated adapter requests or keep a half-written answer after the route has changed.
A WebGPU execution provider may support only part of a graph. Hidden WASM fallback can make a GPU route slower than a clean CPU route, while unsupported operators can fail outright. Validate real operator coverage and p95 behavior rather than assuming that a model marked WebGPU-compatible will execute every node there.
Connectivity hints are not proof that a cloud service is reachable, and a browser's online flag can be stale. The request itself can time out or fail after the local attempt. Apply the remaining deadline to the remote call, preserve a request identifier for diagnosis, and return an error if no route completes. Do not retry cloud inference indefinitely: it can exceed the interaction budget and duplicate expensive work.
Decision scenario
A browser returns no WebGPU adapter. Its tested WASM profile needs 1,450 ms at p95, but the user request has a 900 ms deadline. The prompt is marked confidential and cloud processing is disabled. The router must not send the text to the server. Reject the request with an explanation that the local profile cannot meet the deadline, or let the user switch to a policy-approved model and budget. If a future request permits cloud processing, retry only within the remaining deadline and report that the server handled it.
Implementation: check, route, and report
typescriptimport { pipeline } from "@huggingface/transformers";const modelId = "onnx-community/Qwen2.5-0.5B-Instruct";const localModels = new Map();async function localProvider(profile) {if (!navigator.gpu || !profile?.webgpuCompatible) return "wasm";try {const adapter = await navigator.gpu.requestAdapter();return adapter && adapter.limits.maxStorageBufferBindingSize >= profile.requiredMaxStorageBufferBindingSize ? "webgpu" : "wasm";} catch { return "wasm"; }}function getModel(provider, revision) {const dtype = provider === "webgpu" ? "q4" : "q8";const key = provider + ":" + modelId + ":" + revision + ":" + dtype;let promise = localModels.get(key);if (!promise) {const options = provider === "webgpu" ? { device: "webgpu", dtype, revision } : { dtype, revision };promise = pipeline("text-generation", modelId, options).catch((error) => {if (localModels.get(key) === promise) localModels.delete(key);throw error;});localModels.set(key, promise);}return { key, promise };}export async function routeInference(prompt, policy) {if (!prompt.trim() || prompt.length > 6000) throw new RangeError("Prompt is outside the input budget");const started = performance.now(), requestId = crypto.randomUUID();const provider = await localProvider(policy.modelProfile); let reason = provider + " profile failed";if (policy.edgeP95Ms[provider] <= policy.deadlineMs) {const cached = getModel(provider, policy.modelRevision);try {const model = await cached.promise;const output = await model(prompt, { max_new_tokens: 128, do_sample: false });const generated = String(output[0]?.generated_text ?? "");const text = generated.startsWith(prompt) ? generated.slice(prompt.length).trim() : generated.trim();if (!text) throw new Error("Local model returned no text");if (performance.now() - started > policy.deadlineMs) throw new Error("Local route exceeded its deadline");return { route: "edge", providerRequested: provider, requestId, text, latencyMs: performance.now() - started };} catch (error) {reason = error instanceof Error ? error.name : "local runtime failure";}}const remainingMs = Math.floor(policy.deadlineMs - (performance.now() - started));if (!policy.cloudAllowed || remainingMs <= 0) throw new Error("No permitted route remains: " + reason);const response = await fetch("/api/inference", {method: "POST",headers: { "content-type": "application/json", "x-request-id": requestId },body: JSON.stringify({ prompt, max_new_tokens: 128 }),signal: AbortSignal.timeout(remainingMs),});if (!response.ok) throw new Error("Cloud inference returned " + response.status);const body = await response.json();if (typeof body.text !== "string" || !body.text.trim()) throw new Error("Cloud returned no text");return { route: "cloud", requestId, text: body.text, latencyMs: performance.now() - started };}