Skip to content
WebAI

What Transformers.js, ONNX Runtime Web and WebGPU each do in a browser

The demos here run on several stacks at once: Transformers.js pipelines, raw onnxruntime-web sessions, MediaPipe Tasks and a few libraries that compile a whole task to WASM. One page can use three of them together. Here is which layer does what, and how we pick a stack for a new task.

Open any demo on this site and the browser does roughly the same thing: download weights, turn an image or an audio clip into tensors, run one forward pass, draw the result back onto a canvas. For that one forward pass we have used five or six different setups. Some pages hand ONNX weights to Transformers.js, some open an onnxruntime-web session and assemble the inputs themselves, and some ship an SDK that someone else compiled to WASM. Deployment blocked us a few times, over things unrelated to model accuracy that decided whether the page loaded at all.

These pieces sit at different layers

Before comparing Transformers.js, ONNX and WebGPU side by side, it helps to notice they are not the same kind of thing. ONNX defines how weights are stored and what operators are called. onnxruntime-web is the thing that reads that file and executes it. Transformers.js wraps a task pipeline on top. WebGPU and WebAssembly only supply compute and know nothing about models. All four layers show up across the forty-odd demos here.

LayerExamplesWhat it doesHere
Model formatONNX, GGUF, TFLiteWeight serialisation and operator namesAlmost everything is ONNX
Inference runtimeonnxruntime-web, XNNPACK, TVMLoads the graph, dispatches operators to CPU or GPUORT wasm and webgpu execution providers
Task-level wrapperTransformers.js, MediaPipe Tasks, TensorFlow.jsPacks pre-processing, inference and post-processing into one callpipeline() and FaceLandmarker
Browser hardware APIWebAssembly, WebGPU, WebNNSupplies compute, does not parse modelsnumThreads, device and execution providers land here
The stack by layer, with what this site uses in the last column

When we pick one, the first questions are whether an ONNX export already exists, who writes the pre- and post-processing, and which chip the target browser can reach. Speed comes last, because the same weights on WASM and WebGPU are one configuration change apart.

Transformers.js owns the whole pipeline

One pipeline() call covers downloading weights, picking the tokenizer or processor, running inference and turning logits into labels. The project pins @huggingface/transformers 4.3.x. Its runtime is about 30 MB of ESM and is imported only on the first run. Each (repo, dtype, device) combination stays in an in-memory Map while the files live in Cache Storage, so opening the same model a second time reports zero downloaded bytes in the results panel.

Two things have to be pinned by hand. The onnxruntime-web WASM binaries, a couple dozen MB, need env.backends.onnx.wasm.wasmPaths pointed at a directory we host; leave it unset and they come from the jsDelivr CDN, which is slow from China. The model hub is similar: when huggingface.co is unreachable we probe once and switch to hf-mirror.com, otherwise the page sits on "downloading weights" forever with no error.

A trimmed version of how we load a pipeline
const mod = await import('@huggingface/transformers');
mod.env.allowLocalModels = false;
mod.env.backends.onnx.wasm.wasmPaths = '/ort/';

const device = navigator.gpu ? 'webgpu' : 'wasm';
const dtype = device === 'webgpu' ? 'fp16' : 'q8';
const pipe = await mod.pipeline('image-classification', repo, { device, dtype });
const scores = await pipe(image);

The wrapper also gets in the way sometimes. On the background-removal demo, the generic pipeline multiplies the mask by 255 and casts to uint8 before resizing. When the sigmoid output does not reach either end of 0..1, the subject turns semi-transparent. RMBG-1.4 ships a config that declares Segformer and BiRefNet declares swin, so the pipeline resolves to the wrong architecture class. We pinned both to plain ONNX graphs with model_type: 'custom' and 'birefnet', then wrote the sigmoid, min-max, guided filter and colour decontamination ourselves. That demo still bypasses the generic pipeline.

When we skip the pipeline and run the ONNX graph

Silero VAD, MI-GAN inpainting, HT-Demucs source separation and both matting models open an ORT session directly. What they share is that the output needs interpreting: speech ranges, a soft alpha, separated waveforms, none of which is a top-1 label. We measured the Silero v5 graph with onnxruntime-node first. input is [1, 576], which is 64 samples of history plus 512 new ones (32 ms at 16 kHz); the LSTM state is [2, 1, 128] and has to be fed back from stateN every frame; there is also an int64 scalar sr. Feed it 512 samples as the older tutorials do and the probability sits at 0.001 the whole way through.

A raw session and the Silero v5 input contract
import * as ort from 'onnxruntime-web/wasm';

ort.env.wasm.numThreads = 1;   // no COOP/COEP on this host, single thread only
ort.env.wasm.wasmPaths = '/ort/';

const session = await ort.InferenceSession.create(bytes, {
  executionProviders: ['wasm'],
  graphOptimizationLevel: 'disabled', // the optimiser aborts on large exported graphs
});

let state = new ort.Tensor('float32', new Float32Array(256), [2, 1, 128]);
const sr = new ort.Tensor('int64', BigInt64Array.from([16000n]), []);
const res = await session.run({
  input: new ort.Tensor('float32', frame576, [1, 576]),
  state,
  sr,
});
state = res.stateN; // reuse on the next frame

Switching to WebGPU is an import path and an execution provider array. A few notes in the official docs matter more than the benchmarks: for very light models the WASM binary is smaller, graph capture needs static shapes with every kernel on WebGPU, and GPU-resident tensors must be disposed by hand or memory keeps climbing.

Same weights, WebGPU execution provider
import * as ort from 'onnxruntime-web/webgpu';

const session = await ort.InferenceSession.create(bytes, {
  executionProviders: ['webgpu', 'wasm'],
});

What happens after device: 'webgpu'

The device: 'webgpu' option in Transformers.js and the webgpu execution provider in ORT both end up at the same navigator.gpu. The difference is who supplies the operator kernels. ORT maps ONNX operators to prebuilt WGSL kernels. WebLLM and MLC-LLM compile the model ahead of time with TVM into artifacts their web runtime consumes, then add an OpenAI-shaped chat API and XGrammar-constrained decoding for token-by-token generation. Their engine runs in a Web Worker, so decoding does not block the UI.

Do not copy the headline numbers. The Transformers.js v3 announcement quotes up to 100x over WASM, a ceiling measured on small encoders. The MLC paper reports about 41.1 tokens/s for Llama-3.1-8B and 71.1 for Phi-3.5-mini on an M3 Max with Chrome Canary 133 and WebLLM 0.2.75, which is one machine and figures from the vendor itself. Our results panel reports the bytes actually downloaded and the backend that worked, and makes no speed claim.

On real hardware the more common failure is that the GPU cannot build the graph. attemptLadder has four steps: the preferred device and dtype, the same device at q8 when a driver cannot compile the fp16 graph, wasm at q8 so a 90 MB fp16 download does not land on a CPU pipeline, and finally a smaller model. BiRefNet-lite-512 is marked webgpuOnly and falls all the way back to the q8 weights of RMBG-1.4. GPU failures are remembered so the same session stops retrying them.

The fallback ladder, simplified from real.ts
const gpu = !!navigator.gpu;
const steps = [
  { device: gpu ? 'webgpu' : 'wasm' },
  ...(gpu ? [
    { device: 'webgpu', dtype: 'q8' },
    { device: 'wasm', dtype: 'q8' },
  ] : []),
  { repo: 'briaai/RMBG-1.4', dtype: 'q8' },
];
for (const step of steps) {
  try { return await load(step); }
  catch (e) { if (isGpuFailure(e)) rememberGpuFailure(step); }
}

WebAssembly is the layer we use most

Every browser has WASM and SIMD is available, so most demos here end up on it. Alongside the ORT wasm provider there are libraries that compile a whole task: Tesseract.js, PaddleOCR.js and EasyOCR.js for OCR, RNNoise for denoising, and MediaPipe Tasks for face, pose, hand and object landmarks through XNNPACK. Each brings its own task-level API and its own WASM assets, which is convenient until you need an output shape it does not offer.

Deployment trips over files before compute. An SDK that ships worker assets has to be same-origin, so PaddleOCR is hosted with the page rather than on object storage. EdgeOne Pages assigns MIME types by extension: .mjs comes back as application/octet-stream and .ts as video/mp2t. Chrome validates MIME types strictly for ES modules and module workers, so every dynamically loaded SDK is packaged as .js, and the worker files Turbopack emits under their source extension get renamed in postbuild along with the chunk references. There is a quieter one too: without COOP/COEP the page is not cross-origin isolated, SharedArrayBuffer is unavailable, ORT stays single-threaded and those pthread worker branches are dead code. That is why numThreads = 1 appears above.

A few stacks we did not ship

  • TensorFlow.js has its own model format and layers API with WebGL and WebGPU backends. It fits a project that trains in JS from the start; starting from ONNX weights on the Hub means another conversion
  • wllama compiles llama.cpp to WASM and runs GGUF weights directly, SIMD on CPU, the broadest model compatibility and no GPU acceleration
  • WebNN is the whole-graph API aimed at NPUs, already an execution provider in ORT, but still behind a flag or an Origin Trial in Chrome and Edge. There is a separate post on it
  • Recent Chrome versions ship Gemini Nano, exposed through APIs such as window.LanguageModel, so no weights to download at all, at the cost of limited devices and a model you cannot swap

How we decide for a new task

TaskStackWhy
Classification, embeddings, ASR, translationTransformers.js pipeline with ONNX weightsOne call covers the tokenizer and post-processing; device and dtype are one line each
Matting, VAD, source separation, inpaintingRaw onnxruntime-web sessionSoft alpha, speech ranges and sigmoid on logits all need custom handling
Face, pose, hand and object landmarksMediaPipe TasksTask API and WASM assets ready to use, steady frame rates
OCR and denoisingTesseract.js / PaddleOCR.js / RNNoiseMature tasks, no reason to rebuild their pre-processing
Chat generationNot shipped here; WebLLM or MLC fits betterSeveral GB on first load is too long for a demo page
Always-on low-power inferenceWebNN execution provider, see the dedicated postWaiting on implementations outside Chromium
Where several of our tasks ended up

These stacks coexist here. One page can take landmarks from MediaPipe, run classification through Transformers.js and compute an alpha in a raw ORT session. For a new task we check the catalogue first for an ONNX export and a task-level pipeline, and only open a session directly when the output needs its own interpretation. The results panel shows which backend ran and how many bytes were downloaded, which is more reliable than any comparison table.

All posts →

← Back to all posts