# Running a 4x video super-resolution network in the browser with hand-written WebGPU shaders

> Source: <https://dev.to/maxslashwang/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written-webgpu-shaders-5e8>
> Published: 2026-11-25 11:28:39+00:00

**Recommendation:** When running deep conv nets in WebGPU, request the adapter's max buffer limits, pack weights as vec4<f16>, double-buffer halo tiles, and tile with receptive-field-sized overlap to eliminate seams.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

I run a small video upscaler site. The free tier does the whole job on the visitor's GPU, so the interesting engineering problem is: how do you push an entire video through a 34-layer convolutional network in a browser tab without freezing the machine?

This post is about the inference engine. I'm leaving the specific network out on purpose; what matters is the shape of it, because the shape is what dictates the kernel design:

That works out to roughly 1.2 million multiply-accumulates per *input* pixel. A single 1080p frame is 2 million pixels. Multiply by 30 fps. It's a lot of math, and it all has to happen in compute shaders.

I did, at first. ORT's WebGPU backend is good and I still use it for a couple of smaller models. For this one I ended up writing the engine by hand, for three reasons:

The trade-off is real: you own every bug, including driver bugs.

Activations are planar CHW in `array<f16>` storage buffers. Each conv kernel is a 3×3, zero-padded, with the bias and PReLU fused into the epilogue.

The main design decisions:

`vec4<f16>`.` ic`, it already loads `ic + 1` into the other half of the buffer. One `workgroupBarrier()` per channel.
A trimmed version of the generator (I build the WGSL as a string so the channel-group count is a compile-time constant and the loops fully unroll):

``` js
function convWgsl(OCB: number): string {
  const G = OCB / 4; // vec4 groups of output channels
  const accDecl = range(G).map(g => `var a${g} = vec4<f16>(0.0);`).join('\n');
  const mac     = range(G).map(g => `a${g} += sW[wBase + ${g * 9}u + wk] * inv;`).join('\n');
  return `enable f16;
@group(0) @binding(0) var<storage,read>       fin  : array<f16>;
@group(0) @binding(1) var<storage,read_write> fout : array<f16>;
@group(0) @binding(2) var<storage,read>       Wt   : array<f16>;
@group(0) @binding(3) var<uniform>            u    : P;
var<workgroup> sIn : array<f16, ${2 * HSZ}>;       // double-buffered halo tile
var<workgroup> sW  : array<vec4<f16>, ${2 * WSZ}>; // double-buffered weights

@compute @workgroup_size(16,16,1)
fn main(@builtin(workgroup_id) wid: vec3u,
        @builtin(local_invocation_index) lidx: u32) {
  ${accDecl}
  loadTile(0u, ...);
  workgroupBarrier();
  for (var ic = 0u; ic < u.in_c; ic++) {
    if (ic + 1u < u.in_c) { loadTile(ic + 1u, /* other buffer */ ...); }
    for (var ky = 0u; ky < 3u; ky++) { for (var kx = 0u; kx < 3u; kx++) {
      let inv = sIn[sBase + (ly + ky) * HW + (lx + kx)];
      let wk  = ky * 3u + kx;
      ${mac}
    }}
    workgroupBarrier();
  }
  // epilogue: bias + PReLU in f32, store as f16
}`;
}
```

If the adapter exposes `shader-f16`, everything (weights, activations, accumulators) runs in half precision. Against an fp32 reference the mean error is about 0.3/255, which I can't see in output. For adapters without the feature, the same kernels are generated with `f32`. That roughly doubles memory and is slower, but it works on any WebGPU adapter.

``` js
const device = await adapter.requestDevice({
  requiredFeatures: adapter.features.has('shader-f16') ? ['shader-f16'] : [],
  requiredLimits: {
    maxBufferSize: adapter.limits.maxBufferSize,
    maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
  },
});
```

Request the adapter's max limits explicitly. The defaults (128 MiB storage binding) are too small once you have 64 channels × a big tile × 4 bytes.

You can't run a 1080p frame through 64 channels × 34 layers in one go: the intermediate buffers alone would be hundreds of MB. So frames are cut into tiles.

The catch is the receptive field. 34 stacked 3×3 convs means each output pixel depends on input pixels up to **34 px away**. If you cut tiles with no overlap, you get visible seams. So each tile carries 34 px of context on every side, and only the centre is kept:

That 32 % overhead is the price of seamless output. Bigger tiles waste less but need more memory, so tile size is a trade-off between wasted compute and buffer size.

The path for each frame:

```
WebCodecs decode → VideoFrame
  → device.queue.copyExternalImageToTexture(frame)  → rgba8unorm texture
  → unpack kernel → planar f16 tensor (per tile, with context)
  → 34 conv dispatches (ping-pong buffers) + tail (pixel shuffle + base + clamp)
  → pack kernel → output texture
  → WebGPU canvas → new VideoFrame (zero-copy)
  → VideoEncoder
```

Everything for one tile is a single command encoder, a single submit, and nothing is read back. I use [mediabunny](https://github.com/Vanilagy/mediabunny) for demux/mux and the WebCodecs plumbing, so the only thing I had to write was the middle part.

There's a readback fallback (`copyTextureToBuffer` + `mapAsync`) for browsers where the canvas → `VideoFrame` path doesn't work. It's slower, and it bit me once: if two frames are in flight and share a staging buffer, you get `mapAsync: Buffer already mapped`. Frames through the readback path have to be strictly serial.

My first optimisation was the obvious one: register-tile it. Have each thread compute 2 horizontally adjacent pixels (PPT = 2) so each weight read from shared memory is reused twice, and process several input channels per barrier.

I wrote a bench page that builds 13 kernel variants on the visitor's own GPU, checks each against the baseline on a small tile (this catches f16/driver problems), and times 320×320 and 384×384 tiles. Results on Apple Metal, f16, 320×320 tile:

| variant | ms / tile | 
|---|---|
| baseline (1 px/thread) | 151.7 | 
| PPT 2, 1 channel/barrier, 32 out-ch/workgroup | 120.5 ( **1.26×** ) | 
| my first "should be faster" guess (PPT 2, 2 ch/barrier, 64 out-ch) | no faster than baseline | 

Two lessons:

So the shipped default is still the simple kernel everywhere. The faster one is gated behind a vendor allow-list that currently contains only `apple`, and I'll add vendors once the bench page shows a gain on them. Not exciting, but I'd rather ship a slower kernel than a "faster" one that regresses on someone's laptop.

This one is easy to forget when you're staring at a benchmark: a browser tab that saturates the GPU makes the *whole machine* laggy, and thin laptops thermal-throttle after a minute or two anyway.

After each tile I `await device.queue.onSubmittedWorkDone()`, measure how long the GPU was busy, and sleep for a fraction of that. The current ratio makes the tab idle on purpose for about 13 % of wall-clock time. It costs throughput, but the page stays scrollable, other tabs stay responsive, and sustained speed ends up closer to burst speed because the chip isn't hitting its thermal ceiling.

`device.lost` and surface it as a real error; otherwise a driver reset looks like an infinite spinner.
If you want to see it run, the engine is behind the free tool at [tapirupscale.com](https://tapirupscale.com): drop in a short clip and compare one frame before committing to the whole file. I'm happy to answer questions about the kernel layout, and I'd especially like to hear if you've got faster conv layouts for 64-channel 3×3 on non-Apple GPUs.
