I wanted an image upscaler that runs entirely in the browser: no upload, no API key, works on a phone. This post covers what it took to get Real-ESRGAN running on ONNX Runtime Web with WebGPU and a WebAssembly fallback, and the few details that made the difference between "works on my laptop" and "works on any photo".
The result is live at cv.cm/en/image-upscaler if you want to try it before reading.
Picking a model that fits in a tab
My first attempt used Swin2SR. Quality was fine, but on WebGPU it took seconds per 192 px tile. A 12-megapixel phone photo is a few hundred tiles, so that was a non-starter.
Real-ESRGAN ships two "compact" models (realesr-general-x4v3 for photos and realesr-animevideov3 for anime and line art) built on SRVGGNetCompact. That network is a plain stack of 3×3 convolutions with PReLU, then a PixelShuffle, plus a nearest-neighbour upsample of the input added back as a residual:
- photo model: 32 conv layers, about 1.2M parameters
- anime model: 16 conv layers, about 0.6M parameters
On WebGPU a tile runs in tens of milliseconds. The download is small too:
| Model | fp32 | fp16 |
|---|---|---|
| photo (general-x4v3) | 4.9 MB | 2.4 MB |
| anime (animevideov3) | 2.5 MB | 1.3 MB |
Exporting to ONNX
The released .pth files load straight into a small re-implementation of the architecture (same layer layout, so load_state_dict just works). The export needs dynamic height and width so one model handles any tile size:
torch.onnx.export( model, torch.rand(1, 3, 64, 64), "model.onnx", input_names=["pixel_values"], output_names=["reconstruction"], dynamic_axes={ "pixel_values": {2: "height", 3: "width"}, "reconstruction": {2: "out_height", 3: "out_width"}, }, opset_version=17, ) # fp16 weights, but keep float32 inputs and outputs so the JS side never changes fp16 = float16.convert_float_to_float16(onnx.load("model.onnx"), keep_io_types=True) onnx.save(fp16, "model_fp16.onnx") keep_io_types=True matters: the browser code always feeds a Float32Array and reads one back, whichever file it loaded. The export script also runs both ONNX files through onnxruntime on the CPU against the PyTorch output on a random 96×80 input, so a bad conversion fails loudly instead of producing slightly wrong colours.
Choosing the backend
The worker picks one of three variants once:
async function detectBackend(nav: WorkerNavigator): Promise<"gpu16" | "gpu" | "cpu"> { const gpu = (nav as any).gpu; if (!gpu) return "cpu"; try { const adapter = await gpu.requestAdapter({ powerPreference: "high-performance" }); if (!adapter) return "cpu"; return adapter.features.has("shader-f16") ? "gpu16" : "gpu"; } catch { return "cpu"; } } -
gpu16: WebGPU with the fp16 model (half the download) -
gpu: WebGPU with fp32 when the adapter has noshader-f16 -
cpu: thewasmexecution provider with the fp32 model
The WebAssembly path is only reasonable with threads, and threads need SharedArrayBuffer, which needs cross-origin isolation. The AI pages are served with COOP and COEP: credentialless, and the thread count leaves room for the page:
const cores = navigator.hardwareConcurrency || 4; ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.max(1, Math.min(8, cores - 2)) : 1; The model bytes go through the Cache API, so the second visit doesn't download anything.
Tiles without seams
Running a 4000×3000 image in one go would need a 16000×12000 float output, which is about 2.3 GB for three channels. So the image is processed in tiles: 384 px on the GPU and 192 px on the CPU.
Naive tiling leaves visible seams, because pixels at a tile's edge don't see their neighbours. The fix is to feed each tile with 24 px of context on every side (wider than the network's receptive field), then write back only the core:
const SR_PAD = 24; const ax = Math.max(0, x0 - SR_PAD); // padded tile origin const ay = Math.max(0, y0 - SR_PAD); const tw = Math.min(w, x1 + SR_PAD) - ax; // padded tile size const th = Math.min(h, y1 + SR_PAD) - ay; // ... run the model on [ax, ay, tw, th], then copy only // [(x0 - ax) * 4, (x1 - ax) * 4) × [(y0 - ay) * 4, (y1 - ay) * 4) into the output Because the model has dynamic axes, edge tiles that are smaller than 384 px need no special handling.
2× from a 4× model, without ever building the 4× image
Both models are ×4 only. For a 2× result, the obvious approach is to upscale ×4 and then resize down, but that briefly holds the full ×4 image in memory.
Instead, each 4×4 block of model output is averaged into a 2×2 block while the tile is being written. The full ×4 image never exists, and averaging is also a decent downscale filter:
const shrink = 4 / scale; // 1 for ×4, 2 for ×2 for (let dy = 0; dy < shrink; dy++) for (let dx = 0; dx < shrink; dx++) { const si = (y * shrink + dy) * RW + x * shrink + dx; red += r[si]; green += r[rp + si]; blue += r[2 * rp + si]; } const n = 255 / (shrink * shrink); out[di] = red * n; out[di + 1] = green * n; out[di + 2] = blue * n; The output buffer itself is capped at 16 megapixels. Larger requests are scaled down to fit before upscaling, so a phone doesn't run out of memory halfway through.
What I'd tell someone doing the same
- Pick the architecture for the runtime, not for the leaderboard. A plain conv stack maps well to WebGPU; a transformer with window attention did not, at least for me.
- Ship fp16 only where the GPU says it can run it.
shader-f16is the switch; keep IO in fp32 so the JS doesn't branch. - Pad tiles by more than the receptive field and crop back. It's a few lines and removes every seam.
- Test the export numerically, not just "it loads".
Everything runs in a module worker, and the image never leaves the device. The same setup (WebGPU first, threaded WASM otherwise, models from the Cache API) also runs a depth-map generator and background removal in the same toolkit at cv.cm. Questions about the export or the tiling are welcome in the comments.

