I've been working on TapirUpscale, a browser-based video upscaler that runs on the user's own GPU.
For two of its AI models, I ended up writing the inference engine directly in WGSL. The nice thing about these models is that their architecture is simple enough to make this practical.
I thought I'd share how the engine works, some of the kernel optimizations I tried, and a few things I learned along the way.
The models
I'm using two SRVGGNetCompact models from Real-ESRGAN by xinntao (BSD-3-Clause).
| Model | 3×3 conv layers | Weights | FP16 file size | MACs per input pixel |
|---|---|---|---|---|
realesr-animevideov3 | 18 | 621,424 | ~1.2 MB | ~0.62 M |
realesr-general-x4v3 | 34 | 1,213,296 | ~2.4 MB | ~1.2 M |
Both models have essentially the same architecture. The first convolution takes 3 channels to 64, followed by a series of 64-to-64 convolutions with PReLU activations. The final convolution produces 48 channels.
PixelShuffle rearranges those 48 channels into a 4× RGB image, and a nearest-neighbor upscaled version of the input is added to the result.
No attention, pooling, or strided convolutions. Just a straightforward chain of layers, which makes it fairly easy to write a specialized inference engine for it.
A small inference engine
The engine consists of four compute pipelines:
- Input conversion from
f32to the activation type. - Convolution with fused bias and PReLU.
- A variant of the same convolution pipeline for the final layer, without PReLU.
- PixelShuffle, residual addition, and clamping.
All the model weights are packed into a single flat FP16 storage buffer. A small metadata table holds the channel counts and weight offsets for each layer.
Since there are no intermediate skip connections, I only need two 64-channel activation buffers. Each layer reads from one and writes to the other, alternating between them as inference progresses.
Each tile runs in a single command encoder and compute pass, with one queue submission and no CPU readback.
I also made the engine follow the interface of an ONNX Runtime InferenceSession: GPU tensor in, GPU tensor out. That let me plug it into my existing tiling pipeline without having to rewrite the rest of the application.
Writing the convolution kernel
The original kernel uses a 16×16 workgroup, with each thread responsible for one spatial pixel.
For the 64-channel layers, each thread accumulates all 64 output channels using 16 vec4<f16> registers. The outer loop goes over input channels rather than output channels.
Here's a simplified sketch of the loop:
for (var ic = 0u; ic < u.in_c; ic++) { // Cooperatively load the next input channel into the spare buffer. // Compute the 3x3 convolution for the current input channel: // acc[g] += weight[g][tap] * input[tap]; // vec4 * scalar workgroupBarrier(); } // Add bias, apply PReLU, and write the output. The workgroup uses two sets of shared buffers, each holding an 18×18 input patch (a 16×16 tile plus a one-pixel border) and the corresponding weights.
The idea is to prepare the next input channel while computing on the current one, then swap buffers.
By my calculation, this takes around 3.6 KB of workgroup memory in FP16, or 7.2 KB in FP32. Both are comfortably below WebGPU's default 16 KB workgroup storage limit.
A more complicated kernel isn't necessarily faster
I wanted to see whether register tiling could improve performance, so I wrote another version of the kernel with three configurable parameters:
- How many pixels each thread processes.
- How many input channels are processed between barriers.
- How many output channels each workgroup handles.
Here are the results from my Apple GPU (Metal 3), using FP16, a 320×320 tile, and the 34-layer model.
| Kernel | Pixels/thread | Channels/barrier | Outputs/workgroup | Time per tile |
|---|---|---|---|---|
| Original | 1 | 1 | 64 | 151.7 ms |
| Tiled | 2 | 2 | 64 | 153.9 ms |
| Tiled | 2 | 1 | 32 | 120.5 ms |
| Tiled | 2 | 2 | 32 | 122.3 ms |
The first configuration I tried was actually a little slower than the original. Reducing the number of output channels per workgroup to 32 gave me a much better result: 120.5 ms instead of 151.7 ms, or about a 1.26× speedup.
I haven't benchmarked these variants on NVIDIA, AMD, or Intel GPUs yet, so I still ship the original kernel everywhere. I don't want to assume an optimization that works on my machine will also work well on someone else's.
Tiling and receptive fields
Running the entire frame through the network at once would require large intermediate activation buffers, so I split it into smaller tiles.
The tricky part is deciding how much context each tile needs. Without enough surrounding pixels, the output near tile boundaries can differ from full-frame inference.
For these models, the calculation is straightforward: each 3×3 convolution expands the receptive field by one pixel in every direction. The 18-layer model therefore needs 18 pixels of context on each side, and the 34-layer model needs 34.
With enough context, I can discard the overlapping borders and keep only the valid center of each tile. No blending is needed.
| Model | Max tile size | Context per side | Area kept | FP16 buffers per tile |
|---|---|---|---|---|
| 18-layer model | 320×320 | 18 px | ~79% | ~60 MB |
| 34-layer model | 384×384 | 34 px | ~68% | ~80 MB |
These percentages are for interior tiles. Tiles along the edges of the frame keep more of their area.
I tested the 34-layer model against full-frame inference using ONNX Runtime on the CPU:
| Context per side | Observed difference |
|---|---|
| 34 px | Identical |
| 33 px | 0.0001/255 |
| 30 px | 0.0044/255 |
The full theoretical receptive field is more conservative than the differences I observed in practice, at least for the inputs I tested.
One other detail: the app's 2× mode still runs the native 4× model and then box-downsamples the result by a factor of two. As a result, 2× and 4× take roughly the same amount of GPU inference time.
Keeping video frames on the GPU
Inference is only one part of video upscaling. I also wanted to avoid reading the processed frames back to CPU memory just to send them to the video encoder.
The pipeline looks like this:
Decoded VideoFrame -> GPU texture -> Planar GPU buffer -> Tiled Real-ESRGAN inference -> GPU texture -> Sharpening -> WebGPU OffscreenCanvas -> VideoFrame -> Encoder Mediabunny handles the media side of the pipeline.
On the main output path, I create a new VideoFrame from the WebGPU OffscreenCanvas and pass it to the encoder without an explicit CPU readback. There's also a readback path as a fallback.
In the app, I currently use these neural networks for input videos up to 720p. Higher-resolution sources use an FSR path instead.
FP16 support and correctness
When the WebGPU adapter supports shader-f16, the engine runs in FP16. Otherwise, I generate FP32 versions of the same shaders by replacing the types in the WGSL source. The FP32 path uses more memory and is slower.
There's no WASM fallback for these models. If WebGPU isn't available, they won't run.
To check correctness, I compared the 34-layer model running through my FP32 kernels on SwiftShader against ONNX Runtime CPU. I used real video frames at 61×45 and 128×96. The maximum observed error was 0.17/255.
One important limitation: SwiftShader doesn't support shader-f16, so this comparison only validates the FP32 path. I haven't established the same numerical error bound for the FP16 implementation.
Leaving some GPU time for the rest of the browser
One issue with running heavy GPU workloads in a browser is that the user might want to do something else while a video is being processed.
Submitting tiles continuously can make the rest of the browser feel sluggish. I added a simple throttling mechanism: after each tile, the worker waits for the GPU work to finish and then sleeps for a fraction of the elapsed time.
await device.queue.onSubmittedWorkDone(); const busy = performance.now() - mark; const idle = Math.min(busy * IDLE_RATIO, 120); // ms if (idle >= 2) { await new Promise(resolve => setTimeout(resolve, idle)); } mark = performance.now(); I currently use an idle ratio of 0.35 for the 18-layer model and 0.15 for the 34-layer model.
With a ratio of 0.15, roughly 13% of the combined busy and idle time is spent sleeping, assuming the delay isn't capped or skipped. It's a simple way to trade some throughput for a more responsive browser.
Final thoughts
Writing an inference engine from scratch would be a lot more work for a general-purpose neural network. For a model like SRVGGNetCompact, though, it turned out to be quite manageable.
The biggest thing I took away from this was how important it is to benchmark on actual hardware. A kernel that looks more efficient on paper can end up being slower, and results from one GPU family aren't necessarily representative of others. The same applies to correctness testing across different precision paths.
The 18-layer model is currently running in the anime video upscaler on TapirUpscale if you'd like to try it in your browser.
I'm particularly interested in how it behaves on NVIDIA, AMD, and Intel GPUs. If you're working on something similar with WebGPU, I'd love to hear about your experience with convolution kernels and cross-GPU performance.
This article was drafted with AI assistance and then edited by me.
