{"slug": "running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written", "title": "Running a 4x video super-resolution network in the browser with hand-written WebGPU shaders", "summary": "A developer running a small video upscaler site built a hand-written WebGPU inference engine that runs a 34-layer, 3×3 convolutional super-resolution network entirely in the browser, using planar f16 storage buffers, vec4-packed weights, double-buffered halo tiles, and fused bias/PReLU epilogues. The engine falls back to f32 kernels on adapters lacking shader-f16, and tiles frames with 34 px of overlap context to avoid seams at a roughly 32% compute overhead. The developer reports f16 mean error of about 0.3/255 versus an fp32 reference.", "body_md": "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?\n\nThis 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:\n\nThat 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.\n\nI 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:\n\nThe trade-off is real: you own every bug, including driver bugs.\n\nActivations 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.\n\nThe main design decisions:\n\n`vec4<f16>`.` ic`, it already loads `ic + 1` into the other half of the buffer. One `workgroupBarrier()` per channel.\nA 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):\n\n``` js\nfunction convWgsl(OCB: number): string {\n  const G = OCB / 4; // vec4 groups of output channels\n  const accDecl = range(G).map(g => `var a${g} = vec4<f16>(0.0);`).join('\\n');\n  const mac     = range(G).map(g => `a${g} += sW[wBase + ${g * 9}u + wk] * inv;`).join('\\n');\n  return `enable f16;\n@group(0) @binding(0) var<storage,read>       fin  : array<f16>;\n@group(0) @binding(1) var<storage,read_write> fout : array<f16>;\n@group(0) @binding(2) var<storage,read>       Wt   : array<f16>;\n@group(0) @binding(3) var<uniform>            u    : P;\nvar<workgroup> sIn : array<f16, ${2 * HSZ}>;       // double-buffered halo tile\nvar<workgroup> sW  : array<vec4<f16>, ${2 * WSZ}>; // double-buffered weights\n\n@compute @workgroup_size(16,16,1)\nfn main(@builtin(workgroup_id) wid: vec3u,\n        @builtin(local_invocation_index) lidx: u32) {\n  ${accDecl}\n  loadTile(0u, ...);\n  workgroupBarrier();\n  for (var ic = 0u; ic < u.in_c; ic++) {\n    if (ic + 1u < u.in_c) { loadTile(ic + 1u, /* other buffer */ ...); }\n    for (var ky = 0u; ky < 3u; ky++) { for (var kx = 0u; kx < 3u; kx++) {\n      let inv = sIn[sBase + (ly + ky) * HW + (lx + kx)];\n      let wk  = ky * 3u + kx;\n      ${mac}\n    }}\n    workgroupBarrier();\n  }\n  // epilogue: bias + PReLU in f32, store as f16\n}`;\n}\n```\n\nIf 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.\n\n``` js\nconst device = await adapter.requestDevice({\n  requiredFeatures: adapter.features.has('shader-f16') ? ['shader-f16'] : [],\n  requiredLimits: {\n    maxBufferSize: adapter.limits.maxBufferSize,\n    maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,\n  },\n});\n```\n\nRequest 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.\n\nYou 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.\n\nThe 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:\n\nThat 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.\n\nThe path for each frame:\n\n```\nWebCodecs decode → VideoFrame\n  → device.queue.copyExternalImageToTexture(frame)  → rgba8unorm texture\n  → unpack kernel → planar f16 tensor (per tile, with context)\n  → 34 conv dispatches (ping-pong buffers) + tail (pixel shuffle + base + clamp)\n  → pack kernel → output texture\n  → WebGPU canvas → new VideoFrame (zero-copy)\n  → VideoEncoder\n```\n\nEverything 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.\n\nThere'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.\n\nMy 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.\n\nI 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:\n\n| variant | ms / tile | \n|---|---|\n| baseline (1 px/thread) | 151.7 | \n| PPT 2, 1 channel/barrier, 32 out-ch/workgroup | 120.5 ( **1.26×** ) | \n| my first \"should be faster\" guess (PPT 2, 2 ch/barrier, 64 out-ch) | no faster than baseline | \n\nTwo lessons:\n\nSo 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.\n\nThis 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.\n\nAfter 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.\n\n`device.lost` and surface it as a real error; otherwise a driver reset looks like an infinite spinner.\nIf 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.", "url": "https://wpnews.pro/news/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written", "canonical_source": "https://dev.to/maxslashwang/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written-webgpu-shaders-5e8", "published_at": "2026-11-25 11:28:39+00:00", "updated_at": "2026-11-25 11:43:01.768424+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "computer-vision", "ai-infrastructure", "developer-tools"], "entities": ["WebGPU", "WGSL", "ONNX Runtime"], "also_reported_by": [], "takeaway": "Tiling a 34-layer 3×3 conv net with 34 px of halo context per side avoids seams at about 32% extra compute, and f16 WebGPU kernels with vec4-packed weights and double-buffered tiles stay within roughly 0.3/255 mean error of fp32.", "recommendation": {"advice": "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.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written", "markdown": "https://wpnews.pro/news/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written.md", "text": "https://wpnews.pro/news/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written.txt", "jsonld": "https://wpnews.pro/news/running-a-4x-video-super-resolution-network-in-the-browser-with-hand-written.jsonld"}}