← All posts

WebGPU + Transformers.js: neural nets straight in the browser

Run ML in React without a mandatory server GPU: WebGPU, Transformers.js, ONNX Runtime, OCR and computer vision, WASM fallback, and model-size budgets.

WebGPU + Transformers.js: neural nets straight in the browser
Contents

You photograph a form, a receipt, or an internal sheet and want the text read back. The usual path sends that page across town to a workshop: the browser posts the picture to someone else’s server, a model runs on their GPU, and the answer comes back. It works. You pay in hardware, network delay, privacy, and the fact that the photo left the building.

The other path keeps the tool on the desk. The model downloads into the tab, inference runs on the reader’s GPU through WebGPU, and the server stores results and permissions without having to see the raw image. The first visit brings the tool home. After that you use it here.

Below is how WebGPU, Transformers.js, and ONNX Runtime Web fit together, where that helps OCR and computer vision, and how a React site becomes a client of that system. A giant language model will not fit in the desk drawer. The workshop stays for that job.

Key takeaways

Leave compact work on the desk. Classification, embeddings, object detection, and OCR on a crop stay in the tab. Giant language models and heavy vision nets usually run on the server.

WebGPU is the tab’s GPU socket. Compute shaders and access to the hardware. The model and the runtime sit above it. Transformers.js is the convenient call, on top of ONNX Runtime Web. Acceleration turns on with device: 'webgpu'.

Draw the fallback ladder on day one. WebGPU → WASM → server inference. You cannot promise a GPU to everyone: about 85% support on caniuse as of March 2026.

Split the job into small tools. YOLO finds “where”. OCR reads “what”. Same discipline as in detection engineering and compact CRNN practice.

The page stays on the desk

Server inference gives you a controlled environment and room for large models. The bill is GPU rent, network delay, shipping documents to someone else’s host, and scaling for spikes. For forms, receipts, and internal paperwork, “where did the photo go?” often matters more than “how smart is the model?”

The client path is shorter. The first visit downloads the weights or hits the cache. After that, inference stays local. The server stores results, permissions, and orchestration. It does not have to see the raw image.

The practical question: can an ordinary React site become a client of this system? Yes, if the task fits the model size, the cold start, and WebGPU or WASM support on your audience’s devices.

The GPU in the tab is a socket

A neural net on the desk is thousands of similar steps over numbers. A CPU is good when the work is varied and sequential: one worker walks through a thousand operations in a line. A GPU is good when the same operation can go to a thousand tiny workers at once. The desk tool needs those hands together, so it plugs into the tab’s GPU instead of staying on one CPU.

Before WebGPU, the tab had JavaScript on the CPU, WebAssembly, and WebGL. WebGL is built for pictures on the screen. To run a model there, a runtime has to go through textures and shaders. That is awkward and tight. WebGPU is a more direct way onto a modern GPU, with general-purpose compute. That is what a runtime needs when it runs a model.

Keep the layers apart, or the socket gets mistaken for the tool:

JavaScript
   ↓
ML framework / runtime
   ↓
WebGPU
   ↓
platform GPU API
   ↓
GPU

WebGPU on its own does not classify a photo or read text. It lets a runtime execute a compute graph on the hardware of the person who has the tab open.

A friendly call sits on a portable drawing

Transformers.js (the package @huggingface/transformers) is Hugging Face’s JavaScript library. It runs models in the tab and in Node. Pipelines cover text classification, embeddings, speech recognition, image classification and detection, OCR-style tasks, text generation, and other models exported to ONNX.

The same drawing travels to the desk or the workshop

ONNX (Open Neural Network Exchange) is an open format for a neural-network graph: nodes (operations), tensors, constants. It is not another training framework, and it is not a replacement for PyTorch. Training usually stays in PyTorch or a neighboring stack. You export to ONNX so the same file can run on different engines, at the desk and in the workshop.

ONNX Runtime (ORT) reads that graph and executes it. On a server that is CPU or CUDA. In Node it is the same engine. In the tab it is ONNX Runtime Web, with WASM and WebGPU paths. Transformers.js sits on ONNX Runtime Web: you call a friendly pipeline, and an ONNX graph runs underneath.

The short chain from training to the desk:

Trained model (PyTorch, etc.)
        ↓
   export to ONNX
        ↓
ONNX Runtime (Web / server)
        ↓
   WebGPU / WASM / CUDA …

Without that link, a custom CRNN does not come together in the tab: React does not run a .pt file directly. Export, opset, dynamic axes, and parity with Python are in ONNX: from PyTorch to Runtime.

The first life of the model on the desk is long. Later visits are short:

First run → download files → browser cache → local inference

Weight size hits cold start. Hundreds of megabytes on a phone is a product decision, not a footnote on a demo.

Once the drawing is in place, the roles are:

Layer Job
Transformers.js Pipelines, download, preprocessing
ONNX Runtime Web Execute the model graph
WebGPU Path through the GPU
WASM CPU fallback when the GPU is unavailable

The whole path:

React / JavaScript
        ↓
Transformers.js
        ↓
`ONNX Runtime Web`
        ↓
   WebGPU or WASM
        ↓
     GPU / CPU

One drawing. The room that reads it changes: the tab, or the server.

Three places the work can run

The desk tool is fast when the tab’s GPU can hold it. If the WebGPU socket is missing, the same work can run on the CPU through WASM: wider compatibility, often lower speed. If the model does not fit in the drawer, or it is too slow, the page goes to the workshop — a server GPU, with room for large weights, and with network, cost, and privacy back in the bill.

You pick the place for the task, for the time that 95 out of 100 runs finish within on real audience devices, and for whether the photo is allowed to leave the desk. Fashion is not a reason.

Approach Where it runs Pros Cons
WASM CPU Broad compatibility Often slower
WebGPU Client GPU Faster on suitable hardware Needs browser and driver support
Server GPU Server Strong hardware, large models Cost, network, privacy

The product ladder:

WebGPU → else WASM → if too heavy/slow → Server inference

A “WebGPU only” path cuts people out and breaks a demo on someone else’s laptop. Draw the ladder on the first day, while you are still choosing the tool.

One setting turns the GPU on

The tool is already in the drawer. One setting decides whether it is plugged into the GPU socket. Install the package:

npm install @huggingface/transformers

The shortest example is text classification. The library finds the model card, brings the files, and returns the answer:

import { pipeline } from '@huggingface/transformers';

const classifier = await pipeline(
  'text-classification',
  'Xenova/distilbert-base-uncased-finetuned-sst-2-english',
);

const result = await classifier('Hello world');

After pipeline, the library resolves the model card, downloads the ONNX files, prepares the runtime, picks a path, runs inference, and returns the result. To take the GPU explicitly, pass the same setting into the call:

const pipe = await pipeline(
  'image-classification',
  'onnx-community/mobilenetv4_conv_small.e2400_r224_in1k',
  { device: 'webgpu' },
);

Embeddings and speech recognition turn on the same way — in the Hugging Face WebGPU guide. The line device: 'webgpu' does not promise success. You need support for that access, a working driver, and a model whose operators the runtime can run on that path. Wrap initialization in a check, plus a fallback to WASM or to the server.

The model outlives a single frame

A redrawn frame is a bad reason to go fetch the tool again. Do not create a pipeline on every screen update. Use lazy initialization, one shared service, or a useAIModel() function that loads the model once and reports status: idle → loading → ready → error.

While the weights travel, the page shows progress and stays usable. Coming back to the recognition screen takes the warm instance from the service module and does not download the weights again. A useful chain for the interface:

React UI → useAIModel() → Model Service → Transformers.js → ORT → WebGPU

The service holds the tool. The screen only asks whether it is ready.

Inference and large tensors on the main thread freeze the desk: scrolling stops, clicks disappear, and the person thinks the tab has hung. Move loading and inference into a Web Worker. The main thread sends a message with an ArrayBuffer of the image or an OffscreenCanvas. The worker answers with the result, the timing, and an error code. The same move as other heavy work in the tab — see Web Worker for client compute.

You also need to drop stale work. The person picks another photo while the previous one is still running. The worker should skip an old requestId, or the screen will show the previous file.

Read the receipt on the desk

This link is useful beyond a block of text. A typical vision chain is short: find the place, cut it out, read it or classify it.

Image → preprocessing → detect / crop → classify or OCR → result

Documents, receipts, forms, diagrams, and technical sheets all land here. The classic server path sends the whole file to the workshop. The tab keeps the image on the device:

Browser → Image → Preprocessing → AI model → Text

The data stays put, network delay drops, you do not rent a separate server GPU, and after the cache the work can continue offline. The other side: model size, device requirements, the browser sandbox, and the difficulty of very heavy weights.

For measurement forms, “find the table → find the cell → cut the fragment → compact OCR” beats shipping the whole scan into a giant language model. Same discipline as CRNN on UZT measurements and handwritten digits. The runtime simply moves closer to the desk.

A custom network arrives the same way

A model of your own from PyTorch travels to the desk on the same drawing as a ready-made one:

PyTorch → trained CRNN → export ONNX → ORT Web → (Transformers.js or direct ORT) → WebGPU

Before you promise the same strings, check three things. Every operator exists on the chosen execution provider. Preprocessing in the tab matches Python: normalization, channel order, size. Postprocessing (CTC, argmax) yields the same strings on a control set.

“0.98 in Colab, garbage in the tab” almost always sits in preprocessing or in a different quantization. The WebGPU socket is not the cause.

A detector cuts the page before anyone reads it:

Image → YOLO → boxes → crop → OCR

YOLO answers “where the object is”. Recognition answers “what is inside”. Both models can live locally if they are sized down. A document-vision chain on the desk is a realistic goal for internal tools whose papers must not leave the workstation. How a detector is built is in the YOLO pillar.

The tool has to fit in the drawer

The desk takes OCR on small fragments, classification, object detection, embeddings, compact vision models, speech, local tools, and apps that work offline after the first visit.

It takes poorly to very large language models, huge vision nets, tasks that need a lot of RAM and video memory, operators outside ONNX Runtime support, and models with an unbearable cold start. The drawer is smaller than the workshop, and the delivery makes that obvious:

Server:  10 MB JS + 5 GB model on the server
Browser: 10 MB JS + 500 MB model on the user

On the server, the gigabytes stay in the workshop and a thin program goes to the tab. On the desk, the person pays in bandwidth and disk for the weights themselves. Quantization, compression, cache (Cache Storage / IndexedDB), lazy loading, a CDN, and several small models instead of one giant one soften that bill.

Quantization, roughly, makes the numbers coarser, the file smaller, and the run often faster:

FP32 → FP16 → INT8 → smaller size/memory → often faster

That is a trade of size, speed, and quality. There is no free “shrink without loss”. Measure accuracy on your own validation set after each step.

The door still needs its own lock

Local inference reduces the leak of raw documents to the server where the model runs. That is not absolute safety. The model and its dependencies still download. The browser sandbox limits the blast, and it does not erase the supply chain. A malicious or swapped model file is its own risk. Keep weight sources and integrity under control: hashes and your own CDN.

“Offline first” starts after the tool is already warm in the cache:

React → Local AI Model → WebGPU → GPU
(network may be offline)

A PWA, Cache Storage, and IndexedDB hold both the page and the weights. The two rooms, when the drawing is the same:

Trait In the tab On the server
GPU the user’s the server’s
Data local leaves for the server
Latency potentially low after warm-up depends on the network
Inference cost lower for the service owner the owner pays
Model size limited by the device can be large
Offline possible usually not
Environment control lower higher

The tool on the desk strengthens privacy and offline work. It does not replace a dependency audit or the rules for updating the model. The door of the room still needs its own lock.

Count the first visit apart from the return

It is not enough that the button answered once. Record model size on disk and in memory, load time from the network and from cache, the cold start of the first inference, warm inference, the share of time in preprocessing and postprocessing, the tab’s memory peak, and the share of devices where WebGPU actually came on.

Without a split between the first visit and the return, you speed up the wrong path. Someone who has already been here has the model in Cache Storage. A new person does not, and that cold road from the workshop to the desk is the product.

A lab report:

Model loading (cold network):  2.8 s
Model loading (cache hit):     0.4 s
First inference:               450 ms
Warm inference:                 85 ms
Model size:                    120 MB
WebGPU success rate (lab):      9/10 devices

The lab numbers show the gap between the first delivery of the tool and the work once it is in the drawer.

The usual ways a project breaks sit next to those numbers. People treat Transformers.js as the neural net itself, and WebGPU as a training framework. They ship a model that is too large because it “fits” on the server. They run inference on the interface thread. They leave no WASM fallback. They ignore cold start. They send the whole photo when a crop would do. They call a language model where a detector and recognition are enough. They compare quality in the tab with Python without pinning the quantization version.

A skeleton for a working setup:

React → AI Service → Web Worker → Transformers.js → ORT Web → WebGPU
Fallback: WebGPU → WASM → Server API

A large language model is not every kind of intelligence on this path. For documents, a short chain on the desk often wins:

YOLO → OCR → Classifier → Rules

Put that in place of “image → giant language model → JSON”. A server language model still belongs where you need a broad reasoning model: beside the client path, not in its place. The layers of that stack are in three layers of the LLM stack.

Further along in hardware and formats: a more mature WebGPU, access such as WebNN, SIMD in WASM, quantized and multimodal models, and scenarios that keep data private. What you can use today is device: 'webgpu'. Keep the browser roadmap separate, or the plan becomes a slide show with no delivery date.

Start with one small receipt

The promise “all of the intelligence in the browser” gets checked on one receipt, before the client hears the whole sentence. The tool on the desk should read a single sheet first.

A draft is a short sequence: the photo, a check of the socket, a compact model, the timing, and a fallback.

  1. Load an image and show a preview.
  2. Check navigator.gpu and try device: 'webgpu'.
  3. Load a compact model with a progress indicator.
  4. Preprocess and, if you can, find the document region.
  5. Recognize → JSON on the screen.
  6. Print load time and warm inference.
  7. Add a switch for the WASM fallback.

Target shape:

Image → React → Web Worker → Model → WebGPU → OCR → JSON → UI

That checks the hypothesis on your own devices before you promise the client that the whole workshop has moved onto the desk.

Write the expectations down separately. “Intelligence in the tab” does not mean “no infrastructure”. You still need hosting for the static weights or a CDN, rules for updating models, error reports from the client, and a plan for when warm inference on a weak laptop exceeds the time budget. Those agreements are what separate a demo from a product.

FAQ

Do I still need a server if WebGPU works?

Often yes: for sign-in, storing results, updating models, and heavy inference. The tab covers the sensitive and frequent path. The server keeps control and a backup route.

How is Transformers.js different from ONNX Runtime?

Transformers.js gives you task pipelines and Hugging Face model loading. ONNX Runtime Web executes the graph. A model of your own in ONNX can go to ONNX Runtime directly, without a Transformers.js call.

Is WebGPU always faster than WASM?

On a suitable GPU, and on a net that is heavy to compute, usually yes. On a weak device, or when the download cost is huge, the win can disappear. Measure warm inference on the machines your audience actually uses.

Can I run my own CRNN from PyTorch?

Yes: export to ONNX, check the operators, and match preprocessing with Python. Not every layer and not every custom operator survives the export without extra work.

Is it safe to process passports and medical documents in the browser?

The local path reduces what you send to the inference server. It does not remove cross-site scripting, malicious extensions, or the rules for what stays on disk. That is part of the threat model, not a button that means “safe now”.

Will WebGPU cover every user in 2026?

Support is high, and it is not one hundred percent. Without WASM or a server you knowingly cut the audience. The same rough figure, about 85% on caniuse as of March 2026, leaves people outside.

Further reading

Ideas for later pieces in the series: ONNX: from PyTorch to Runtime, ML frameworks, YOLO in the browser, CRNN on WebGPU, quantization without myths, intelligence that works offline after the first visit.

Conclusion

WebGPU gives the tab computation on the GPU. Transformers.js makes it simpler to run models. ONNX Runtime Web binds the weights to the thing that executes them. Together they keep recognition, object detection, and compact vision on the person’s device: with an honest fallback, a size budget, and a worker around the page.

The receipt tool stays on the desk. You send the page across town to the workshop when the drawer is already too small: heavy models and control stay on the server, and the frequent, sensitive work stays in the tab.

Comments

Loading comments…