跳到正文
DEV Community· Max/Wang·· 27 分鐘前AI 評分60

如何以手寫 WebGPU shader 在瀏覽器執行 4x 影片超解像網絡

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

AI 導讀

作者分享以手寫 WebGPU shader 在瀏覽器運行 4x 影片超解像網絡的推理引擎設計。該網絡由 34 層 3×3 卷積構成;推理將畫面切成 384×384 tiles,每邊保留 34 px 上下文,並以雙緩衝處理。

正文

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:

  • fully convolutional, 3×3 convs only, 64 channels wide
  • 34 conv layers, PReLU after each (except the last)
  • no skip connections inside the trunk
  • last layer outputs 48 channels, then PixelShuffle(4) for a native 4x upscale
  • about 2.4 MB of weights in fp16

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.

Why not just use ONNX Runtime Web?

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:

  1. Control over memory. With a plain "conv, conv, conv" chain and no skips, you only ever need two activation buffers (ping-pong). A generic runtime allocates and schedules more conservatively than that.
  2. No readback, one submit per tile. I wanted the whole tile (unpack → 34 convs → pixel shuffle → pack) in a single command encoder and a single compute pass chain, and I wanted to decide exactly when the CPU waits on the GPU.
  3. Fusing the last stage. PixelShuffle, a nearest-neighbour base image added back, and the clamp all fold into one tail kernel.

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

Tensor layout and the conv kernel

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:

  • 16×16 workgroup, one pixel per thread. Each workgroup owns a 16×16 patch of output pixels and all 64 output channels.
  • Accumulators as vec4<f16>. Each thread holds 16 vec4<f16> accumulators (64 channels). It's a lot of registers, but it means each input value read from shared memory is reused across all 64 output channels.
  • Loop over input channels, double-buffered. For each input channel, the workgroup loads an 18×18 halo tile (16×16 plus 1 px border) into workgroup memory, along with the 3×3 weights for that channel across all output channels, packed as vec4<f16>. While computing channel ic, it already loads ic + 1 into the other half of the buffer. One workgroupBarrier() per channel.
  • Fused epilogue. Bias add and PReLU happen in f32 right before the f16 store, so the accumulate stays cheap and the activation stays accurate.

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):

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
}`;
}

f16, with an f32 fallback

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.

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.

Tiling a full frame

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:

  • tile size: 384×384 input
  • context: 34 px per side
  • kept area: (384 − 68)² / 384² ≈ 68 % of the compute is useful

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.

From VideoFrame to VideoFrame, no CPU in the middle

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 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.

Measuring instead of guessing

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:

  1. The knobs interact. Raising PPT raises register pressure; fewer output channels per workgroup lowers it but re-reads the input tile. My first guess did nothing.
  2. A win on one vendor is not a win on another. 1.26× on Apple tells me nothing about NVIDIA/AMD/Intel over D3D12 or Vulkan, which have different occupancy behaviour.

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.

Don't melt the user'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.

Things that bit me

  • Device loss. Listen to device.lost and surface it as a real error; otherwise a driver reset looks like an infinite spinner.
  • Warm-up. The first run on a device includes pipeline compilation. If you time the first frame you'll get a number that's several times the steady state. I warm the engine as soon as a file is chosen (weights, device, pipeline compilation), in parallel with decoding thumbnails.
  • Estimating total time. Tile time × tile count × frame count is a decent ETA, but only if you take it after warm-up.
  • Not everything needs the big network. Cheap paths (a sharpen/FSR-style pass, a tiny model) cover the devices without WebGPU and low-power cases. Pick the engine by device capability, not by one hard threshold.
  • Be honest about the limits. In-browser inference of a model this size is slower than a desktop GPU, makes laptops warm, and is weak on phones. If a job would take 20+ minutes on the user's machine, say so up front.

Try it

If you want to see it run, the engine is behind the free tool at 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.

來源:DEV Community · dev.to