NoteNov 26, 202611 min read
The GPU Super-Resolution Compiler in liberika
Compiling and running neural super-resolution directly inside a video renderer

When adding neural super-resolution to a cross-platform video player, there are two usual paths:
- Embed a general-purpose ML runtime (ONNX Runtime, CoreML, TensorRT, NCNN); or
- Interpret community GLSL user shaders at runtime, the way mpv does for Anime4K or FSRCNNX.
Early in liberika, we looked at both options and ran into practical renderer constraints on each:
- Zero-copy boundaries. Hardware-decoded frames already live on the GPU (
CVPixelBufferon Apple,D3D11VAon Windows,AHardwareBufferon Android,OHNativeBufferon OpenHarmony,VideoFramein browsers). Passing an NV12 luma plane to an external inference SDK often forces extra copies, cross-queue synchronization, or a CPU readback. - Footprint and targets. liberika is an embeddable media kernel targeting desktop, mobile, OpenHarmony, and browser WASM. Bundling a general ML runtime often weighs more than the player itself, and does not carry over cleanly to a browser worker.
- Limits of runtime GLSL shaders. Because mpv render targets output at most a
vec4, a 16-channel convolution gets split into four consecutive passes. Raw GLSL also cannot lower directly onto Apple M5 Metal 4 TensorOps, NVIDIA Vulkancooperative_matrix, or D3D12 SM 6.10 matrix units, and exposing an untrusted shader parser to web JavaScript brings its own crash and security risks.
Instead, we built a small, dedicated GPU super-resolution compiler in pure Rust inside the renderer, with no external ML dependencies. ArtCNN, Anime4K, and mpv hook shaders all lower into one static graph, go through graph optimization and tiling, and compile to six backends: Metal, D3D11, Vulkan CoopMat, D3D12 SM 6.10, native wgpu, and browser WebGPU.
This note covers the graph passes and tiling scheme, GPU backend profiling and tuning, and running the same compiler in browser WebGPU.
1. Luma-Only Inference and One Static DAG
Human vision is much more sensitive to high-frequency luminance ($Y$) detail than chrominance ($Cb/Cr$), and hardware video decoders already emit 4:2:0 NV12 or P010 surfaces where chroma is at half resolution. Running convolutions only on the 1-channel luma plane cuts first-layer compute and memory bandwidth, and prevents the network from introducing color shift or saturation drift.
In the renderer, this maps to two input paths:
- Native YUV renderers (Metal, D3D11, desktop wgpu): sample the zero-copy decoded Y plane directly, output a $2W \times 2H$ upscaled luma texture (or a source-sized $W \times H$ packed
rgba16float2×2 quad), and recombine it with the original chroma before gamut mapping and HDR tone mapping. - RGB input paths (Android pre-converted textures, browser WebGPU
VideoFrame): extract $Y$ in the compute shader using the frame’s luma matrix (for example BT.709 $[0.2126, 0.7152, 0.0722]$), then add only the luma residual during presentation:
When a model trained on full-range luma (InputRange::Full) receives limited-range (16–235) video, the entry and head apply linear normalization and its inverse:
Around this boundary, crates/erika/src/renderer/sr/model.rs defines a platform-neutral static DAG, SrModel:
- Tensor 0 is always the 1-channel luma input, and layers are stored in topological order.
- Each
ConvLayersums one or moreConvInputoperands, each carrying a source tensor index, an element-wise input transform $\phi \in \{\text{Identity}, \text{ReLU}, \text{NegReLU}\}$, an odd kernel width $k \in \{1,3,5,7,9\}$, andOIHWweights. This represents Anime4K’s CReLU halves and dense skip connections without materializing concatenated tensors. - Layers support bias, optional residual addition, activations (
None,ReLU,SiLU, per-channelPReLU), and a 4-channel 2× depth-to-spaceHead(row-major ONNX/Anime4K or column-major FSRCNNX, with an optional clamped bilinear base).
Static mpv shader import. For community Anime4K (
//!HOOK MAIN) and FSRCNNX (//!HOOK LUMA) mpv shaders,mpv.rsparses only topology and numeric weights; no GLSL is executed at runtime. For RGBMAINhooks, the importer treats the input as $R=G=B=Y,\ \alpha=1$, summing the RGB weight columns into a 1-channel luma kernel and folding the constant alpha column into the bias. Separate R/G/B residual heads (as in Anime4K VL/UL) are linearly combined into one 4-channel luma head using BT.709 coefficients.
2. Static Graph Optimization and the 1-Pixel Border
Before any backend emits Metal, HLSL, SPIR-V, or WGSL, fold.rs runs two mathematically exact passes over SrModel.
Sibling Pass Merging
Because mpv shaders output at most 4 channels per pass, a 16- or 32-channel layer arrives split into 4 to 8 consecutive passes. merge_siblings merges consecutive independent layers (up to 256 channels) whenever their remapped input signatures, activation kinds, and residual alignments match. If a merge would leave a downstream residual reading only a slice of a wider tensor, that producer is marked unmergeable and the pass iterates until all residuals align.
On Anime4K UL, sibling merging collapses 22 fragmented passes into 8 layers, reducing GPU dispatches and redundant input loads by 63.6%.
Exact Linear Layer Folding
When a producer layer $p$ has no activation (Activation::None) and its consumers read it only through identity convolutions with $k_c \le 3$ (combined kernel $k = k_p + k_c - 1 \le 9$), the two linear convolutions can be folded algebraically:
Away from the image edge, $\operatorname{pad}$ is the identity, giving a single larger convolution:
Written out across channels and spatial offsets (with $r_p = \lfloor k_p/2\rfloor,\ r_c = \lfloor k_c/2\rfloor,\ r = r_p + r_c$):
In ArtCNN, conv0 ($3\times 3$ linear) folds into conv1 ($3\times 3 \to 5\times 5$), and conv5 ($3\times 3$ linear) folds into conv6 ($3\times 3 \to 5\times 5$). That removes two full-frame feature-map round trips and cuts MACs per pixel by 26.4% to 33.2% across the ArtCNN C4 family.
The chart below shows exact counts from cargo test across the built-in models:
The 1-Pixel Border and 9-Class Weights
If you run $W_{\text{eff}}$ over the entire image and diff the output against the unfolded network, error lines show up along the outermost 1-pixel frame.
This happens because Zero or Clamp padding on the eliminated intermediate tensor breaks shift invariance at the boundary:
- Under
Padding::Zero, an out-of-bounds consumer tap originally saw0, contributing neither the producer’s input nor its bias $b_p$. - Under
Padding::Clamp, an out-of-bounds consumer tap clamped back to tap0, adding its weight onto the center pixel’s producer window.
Once the intermediate tensor is gone, a single $5\times 5$ kernel reaches past the erased boundary into neighboring source pixels.
Some implementations ignore this 1-pixel difference, but in a video player a bright 1-pixel line along letterbox bars or stitched edges is noticeable, and it complicates exact per-pixel verification against a CPU reference.
To keep the optimization exact, we classify each output pixel along row and column into first, interior, and last, giving $3 \times 3 = 9$ border classes (indices 0 through 8, where 4 is the interior and the rest are the four edges and four corners). During folding, each consumer tap $(t_y, t_x)$ is remapped according to the real padding rule:
From this we precompute all 9 exact $(W^{(i)}, b^{(i)})$ sets. On the GPU, the folded layer runs in two steps:
- Interior pass: run class
4across the full image or tile with no border branches. - 1-pixel perimeter ring dispatch: launch a small follow-up dispatch over only the 1-pixel perimeter, using $2W + 2(H - 2)$ threads when $W, H \ge 2$ (and falling back to $W \cdot H$ on degenerate 1-pixel-wide frames).
At 1080p, the perimeter ring is 5,996 pixels out of 2,073,600 (0.289%), so the overhead is negligible. The interior 99.7% stays branch-free, and even small sizes like $2\times 2$ and $3\times 7$ match the unfolded network within fp32 rounding ($< 10^{-4}$).
3. Tiling and Slot Reuse Under VRAM Limits
Holding a full-frame 64-channel fp16 tensor at 4K ($3840\times 2160$) takes nearly 1 GiB, which exceeds mobile memory budgets and WebGPU’s baseline 128 MiB storage buffer binding limit.
Simple tiling treats tile edges like image edges during padding and leaves visible seams. All liberika backends share one receptive-field tiling scheme:
- Backward halo propagation. Starting from
head.tensor($h(t_{\text{head}}) = 0$), walk the graph in reverse topological order to compute how many extra pixels each tensor needs around its core:
Residual reads inherit the output halo. For folded 5-layer ArtCNN C4F16, the input halo is 7 pixels.
- Layer-by-layer region contraction. Each backend picks the largest tile or horizontal band that fits its scratch budget (192–256 MiB on desktop and sidecars, 64–128 MiB on wgpu/WebGPU). Each layer $l$ computes only the tile core expanded by $h(t_l)$, shrinking down to the exact output core at the head. Because overlap halos are computed from real neighboring pixels, tile seams have zero error and tile edges never trigger the global 9-class border fixup.
- Liveness-based slot reuse. Tracking
last_use[t]lets the allocator recycle a tensor’s slot as soon as its last consumer finishes. Five-layer ArtCNN needs two intermediate scratch slots; the fused head writes directly to the output texture.
4. GPU Backend Profiling and Tuning
Below are two issues that showed up in GPU timestamp profiling on an Apple M5 Pro and an RTX 5060 Ti, and how we adjusted the backends for them.
Matrix units vs. scalar kernels, and 8-frame measured selection
The default assumption is that if a GPU has Tensor Cores or Metal 4 TensorOps, the entire network should run on them. Measured timings split sharply by layer width and model size:
- On Apple M5 Pro (Apple10), a single simdgroup executing $32\times N$ tiles via Metal 4
mpp::tensor_ops::matmul2dmeasured about 25 TFLOPS, faster than four simdgroups sharing a 128-row tile (~21 TFLOPS). For narrow layers we use pixel grouping to pack neighboring pixels into the matrix column dimension $N$ toward ~32 columns. Even so, below $C_{\text{out}} = 16$, TensorOps still trailssimdgroup_half8x8, so the Metal backend mixes both kernel tiers inside the same network. - On Windows D3D11, our scalar
cs_5_0generator emits fully unrolled, branch-free HLSL with weights in constant bufferb1indexed by compile-time literals, which drivers lower into hardware FMA constant operands (NVIDIAc[bank][offset], AMD scalar registers). In that kernel, 32-channel output blocks ran 35% slower than 16-channel blocks on an RTX 5060 Ti for ArtCNN C4F32 due to instruction-cache pressure, so we fixed the block width atMAX_OUTPUT_BLOCK = 16. - On wide models like ArtCNN R8F64 (64 channels, 856K MAC/px), Vulkan
GL_KHR_cooperative_matrixand D3D12 SM 6.10 wave32 MMA are much faster than scalar code. On narrow 16-channel networks, once cross-API shared-texture synchronization is counted, the constant-buffer scalar kernel can still come out ahead.
Rather than keeping a hardcoded GPU table, d3d11_sr_select.rs measures at runtime: whenever (model, width, height) changes, each candidate backend runs 8 frames (3 warmup frames plus 5 GPU-timestamped frames) and the lowest median wins. The native wgpu backend uses a similar first-frame background autotuner.
Profiling the 4-channel head, row reuse, and fp16 packing
When we profiled the Windows Vulkan Cooperative Matrix sidecar layer-by-layer on an RTX 5060 Ti at 1080p (ArtCNN C4F32-DN, fp16 matrix accumulation), all hidden 32-channel convolutions combined took 2.79 ms, while the final 4-channel spatial head (combining the 32-channel $5\times 5$ feature branch and 1-channel $5\times 5$ luma branch) plus border fixup took 2.13 ms, about 35% of the 6.00 ms frame.
Because 4 output channels would leave 75% of a $16\times 16$ matrix tile unused, the head already ran on vector ALUs.
We first tried adjacent-row reuse: computing 2 or 4 output rows per tile reduced $B$-fragment loads from 18 to 12 (and 36 to 18 for four rows). The output matched numerically, but hidden-layer register usage jumped from 80 to 112–140, dropping occupancy and making C32 30–45% slower end-to-end, so we discarded it.
Two other changes did improve end-to-end time:
- The feature buffer uses a 16-channel blocked fp16 layout (with $P = WH$):
Changing cooperative loads so adjacent threads read contiguous channels of the same pixel achieved coalesced global access, and writing to padded per-channel shared-memory planes $c(A+1)+p$ ($A = (8+k-1)^2$) avoided bank conflicts. That alone lowered full-network time by 1.6–2.8%.
- Packing four fp16 weights into the first two 32-bit words of each existing 16-byte uniform slot:
reinterpreting them as f16vec4 for fp16 FMAs, and staging fp16 inputs in shared memory halved shared-memory usage from 9,216 B to 4,640 B and reduced head shader bytecode from 90 KB to 63 KB.
Measured on an RTX 5060 Ti at 1080p (full D3D11 → Vulkan → D3D11 GPU span, median of three alternating 15-sample rounds), end-to-end time dropped by 7.4%–8.0% across all four configurations:
Across 124 numerical test cases (solid frames, checkerboards, impulses, gradients, forced 32×16 tiles, and Full/Limited range), worst-case MAE was 0.00059 (against a 0.002 threshold) and max single-pixel error was 0.00343 (against a 0.03 threshold). In production, this path checks the full graph structure and weight hashes rather than trusting a model name string.
5. Compiling the Same Pipeline to Browser WebGPU
Running WebGPU super-resolution in the browser did not require rewriting the shaders in JavaScript. Because model import (mpv.rs, model.rs), graph optimization (fold.rs), and WGSL generation (wgsl.rs) do not depend on OS threads or native graphics APIs, splitting out a wgpu-free SrPlan (sr/plan.rs) and compiling it to wasm32-unknown-unknown lets the browser reuse the desktop compiler directly. It supports ArtCNN C4, the Anime4K family, single-pass fused FSR 1.0 (EASU + RCAS staged in workgroup memory so intermediate results stay off VRAM), and user-uploaded .esr or mpv shaders.
The browser environment did add three constraints that did not come up on native desktop targets:
- Packed 2×2
rgba16floatoutput. Core WebGPU does not guaranteer16floatstorage textures. The neural head packs each source pixel’s 2×2 subpixel quad into one(r, g, b, a)texel at source dimensions $W\times H$, cutting texture write bandwidth in half; the presentation shader reconstructs bilinear luma viasample_packed_lumaand recombines chroma. - Separating shader compilation from playback. First-time
createComputePipelineAsynccan take hundreds of milliseconds. Running it on the same serial worker queue as FFmpeg WASM demuxing and WebCodecs stalls playback when switching modes. Moving SR commands to a dedicated workersrQueueand tagging compiled Rust plans with aplanIdlets playback, decoding, and window resizes keep running on the previous mode while new pipelines compile asynchronously, without pairing a new plan with an old pipeline. - Treating shader text as untrusted input. Exposing a desktop mpv parser to web JavaScript means malformed offsets (
-2147483648,100000), multi-byte UTF-8 next to_texOff(, or crafted.esrheaders claiming 65,535 layers could trap the WASM module and take down the danmaku engine sharing it. Count limits, finite-float checks, UTF-8-safe slicing, and 64-bit device limit checks on 32-bitwasm32all have to be tested as part of the security boundary.
6. Validating Against a 200-Line CPU Reference
With six GPU backends, two graph optimization passes, 19 built-in modes, and custom user shaders, visual inspection is not reliable for catching 1-pixel border shifts or fp16 precision drift. Early on we wrote a ~200-line CPU reference evaluator (reference.rs) that does no tiling and no folding, just pure fp32 nested loops straight from the layer definitions.
Every optimization pass and GPU backend is tested on real hardware against this unfolded reference::run, covering $1\times 1$, $2\times 2$, $3\times 7$, forced multi-tile seams, and both Full and Limited luma ranges. Changes like the 9-class border ring and the packed fp16 head go through numerical verification first, and then GPU timestamps decide whether they stay.
Written from liberika’s super-resolution engine implementation and hardware measurements. See docs/super_resolution.md for the full architectural reference and docs/investigations/sr-gpu-head-2026-11-03/README.md for the complete Vulkan fp16 spatial-head ablation study.