NoteNov 26, 202611 min read

The GPU Super-Resolution Compiler in liberika

Compiling and running neural super-resolution directly inside a video renderer

Sakiko Shinokawa

When adding neural super-resolution to a cross-platform video player, there are two usual paths:

  1. Embed a general-purpose ML runtime (ONNX Runtime, CoreML, TensorRT, NCNN); or
  2. 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 (CVPixelBuffer on Apple, D3D11VA on Windows, AHardwareBuffer on Android, OHNativeBuffer on OpenHarmony, VideoFrame in 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 Vulkan cooperative_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 rgba16float 2×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:
$$\mathbf{RGB}_{\text{out}} = \operatorname{clamp}\Big(\mathbf{RGB} + (Y_{\text{sr}} - Y),\; 0,\; 1\Big)$$

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:

$$y_{\text{in}} = (y_{\text{raw}} - o) \cdot s, \qquad o = \frac{16}{255},\quad s = \frac{255}{219}$$

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 ConvLayer sums one or more ConvInput operands, 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\}$, and OIHW weights. 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-channel PReLU), and a 4-channel 2× depth-to-space Head (row-major ONNX/Anime4K or column-major FSRCNNX, with an optional clamped bilinear base).
Zero-copy GPU decoder frames · no CPU readback CVPixelBuffer D3D11VA AHardwareBuffer OHNativeBuffer VideoFrame Pure-Rust compiler · no ML runtime · the same code builds to WASM Static import ArtCNN · Anime4K mpv GLSL parsed, never executed One IR SrModel static DAG one luma channel in 2× depth-to-space Exact graph opt. siblings 22 → 8 folding −26–33% 9 border classes Tiling plan halo propagation budgeted tiles liveness slot reuse Windows: 8 measured frames pick the fastest per (model, W, H) Metal TensorOps D3D11 cs_5_0 FMA Vulkan CoopMat D3D12 SM 6.10 wgpu WGSL FP16 WebGPU WASM Luma recombination and present YUV: replace the Y plane · RGB: add the luma residual CPU reference.rs unfolded fp32 ground truth for all six backends
The liberika super-resolution compiler, end to end. Decoded frames stay on the GPU. A pure-Rust compiler imports three model families into one static graph, applies exact graph optimisations and tiling, emits six backends, and recombines luma at presentation. Every backend is checked against the unfolded CPU reference.

Static mpv shader import. For community Anime4K (//!HOOK MAIN) and FSRCNNX (//!HOOK LUMA) mpv shaders, mpv.rs parses only topology and numeric weights; no GLSL is executed at runtime. For RGB MAIN hooks, 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:

$$y = W_c * \big(\operatorname{pad}(W_p * x + b_p)\big) + b_c$$

Away from the image edge, $\operatorname{pad}$ is the identity, giving a single larger convolution:

$$W_{\text{eff}} = W_c * W_p, \qquad b_{\text{eff}} = b_c + W_c * b_p$$

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

$$W_{\text{eff}}[o, c, \Delta y + r, \Delta x + r] = \sum_{m=0}^{C_{\text{mid}}-1} \sum_{\substack{t_y + p_y = \Delta y \\ t_x + p_x = \Delta x}} W_c[o, m, t_y + r_c, t_x + r_c] \cdot W_p[m, c, p_y + r_p, p_x + r_p]$$

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.

Wc3×3 consumer ∗ Wp3×3 producer, no activation = 1 2 3 2 1 2 4 6 4 2 3 6 9 6 3 2 4 6 4 2 1 2 3 2 1 Weff5×5 folded kernel paths 1 2 3 4 6 9 The intermediate tensor disappears: two full-frame passes become one, with one fewer read and write. Each number counts the (t_c, t_p) pairs landing on that input offset: the terms W_c ∗ W_p sums there.
Two linear convolutions fold into one. When the producer has no activation, $W_c * W_p$ gives a single $5\times 5$ kernel; each number counts the paths that land on that input offset, and brighter cells sum more terms.

The chart below shows exact counts from cargo test across the built-in models:

ArtCNN: MACs per pixel indexed to the unoptimised model 60% 70% 80% 90% 100% artcnn_c4f16 artcnn_c4f16: 12,240 MAC/px artcnn_c4f16: 9,012 MAC/px (-26.4%) −26.4% 12,240 → 9,012 · 7 → 5 layers artcnn_c4f32 artcnn_c4f32: 47,520 MAC/px artcnn_c4f32: 31,748 MAC/px (-33.2%) −33.2% 47,520 → 31,748 · 7 → 5 layers artcnn_r8f64 artcnn_r8f64: 924,480 MAC/px artcnn_r8f64: 856,548 MAC/px (-7.3%) −7.3% 924,480 → 856,548 · 27 → 25 layers Anime4K: GPU passes sibling merging, same MACs 0 8 16 24 anime4k_l anime4k_l: 7 passes anime4k_l: 4 passes (-42.9%) 7 → 4 anime4k_vl anime4k_vl: 15 passes anime4k_vl: 8 passes (-46.7%) 15 → 8 anime4k_ul anime4k_ul: 22 passes anime4k_ul: 8 passes (-63.6%) 22 → 8 before after numbers from cargo test over the built-in models
What the graph passes buy. ArtCNN gains from linear folding, which removes MACs; Anime4K gains from sibling merging, which removes passes at the same MAC count.

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 saw 0, contributing neither the producer’s input nor its bias $b_p$.
  • Under Padding::Clamp, an out-of-bounds consumer tap clamped back to tap 0, 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:

$$e(t, \text{cls}) = \begin{cases} t & \text{inside image} \\ \varnothing & \text{outside under } \texttt{Zero} \\ 0 & \text{outside under } \texttt{Clamp} \end{cases}$$

From this we precompute all 9 exact $(W^{(i)}, b^{(i)})$ sets. On the GPU, the folded layer runs in two steps:

  1. Interior pass: run class 4 across the full image or tile with no border branches.
  2. 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}$).

Nine border classes 0 1 1 1 1 1 1 1 2 3 4 4 4 4 4 4 4 5 3 4 4 4 4 4 4 4 5 3 4 4 4 4 4 4 4 5 3 4 4 4 4 4 4 4 5 6 7 7 7 7 7 7 7 8 class 4: interior, branch-free classes 1/3/5/7: edges classes 0/2/6/8: corners 1080p ring: 5,996 px, 0.289% of the frame After folding, what should an edge tap read? Zero padding out-of-range taps read 0, bias too Clamp padding out-of-range taps clamp inward The folded kernel has no intermediate tensor, so an out-of-range tap reads the wrong input. Nine weight sets plus one small ring pass stay exact.
Nine border classes and the 1-pixel ring. Once folded, the intermediate tensor is gone and out-of-range taps read the wrong neighbours. Nine weight sets follow the real padding; the interior runs branch-free and one small dispatch rewrites the ring.

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:

  1. 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:
$$h(t_{\text{in}}) = \max\!\left(h(t_{\text{in}}),\; h(t_{\text{out}}) + \left\lfloor \frac{k}{2} \right\rfloor\right)$$

Residual reads inherit the output halo. For folded 5-layer ArtCNN C4F16, the input halo is 7 pixels.

  1. 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.
  2. 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.
Computed span of two neighbouring tiles t0 h=7 t1 h=5 t2 h=4 t3 h=3 t4 h=2 out h=0 tile seam: zero error tile A tile B Each layer computes its core plus h(t); overlaps read real neighbours, not padding. Slot reuse (ArtCNN, 5 layers) L1 L2 L3 L4 Head slot 0 t1 t3 slot 1 t2 t4 output 2× A slot returns once its tensor is last read: two intermediate slots; the head writes the output.
Seam-free tiling and slot reuse. Neighbouring tiles shrink by their halo at every layer; overlaps read real pixels and the output cores meet exactly at the seam. Tensors give back their slot once read, so five-layer ArtCNN needs two intermediate slots.

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::matmul2d measured 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 trails simdgroup_half8x8, so the Metal backend mixes both kernel tiers inside the same network.
  • On Windows D3D11, our scalar cs_5_0 generator emits fully unrolled, branch-free HLSL with weights in constant buffer b1 indexed by compile-time literals, which drivers lower into hardware FMA constant operands (NVIDIA c[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 at MAX_OUTPUT_BLOCK = 16.
  • On wide models like ArtCNN R8F64 (64 channels, 856K MAC/px), Vulkan GL_KHR_cooperative_matrix and 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.

Don't guess by GPU model: pick by GPU timestamps Schematic: each candidate runs 8 frames, 3 warm-up, then the median of 5 timestamps 1 2 3 4 5 6 7 8 warm-up timed D3D11 scalar median Vulkan CoopMat median D3D12 Linalg median Lock the fastest until model, width or height changes The wgpu backend autotunes the same way in the background after the first frame.
Measured backend selection (schematic). No hardcoded GPU list: whenever the model or resolution changes, each candidate runs 8 frames and the median of the last 5 GPU timestamps picks the fastest.

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:

  1. The feature buffer uses a 16-channel blocked fp16 layout (with $P = WH$):
$$I(c, p) = 16 P \lfloor c / 16 \rfloor + 16 p + (c \bmod 16)$$

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

  1. Packing four fp16 weights into the first two 32-bit words of each existing 16-byte uniform slot:
$$u_0 = h(w_0) \mid (h(w_1) \ll 16), \qquad u_1 = h(w_2) \mid (h(w_3) \ll 16)$$

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:

Where the 6.00 ms go ArtCNN C4F32-DN · fp16 matrix accumulation · RTX 5060 Ti · 1080p 32-channel middle layers: 2.79 ms 32-channel middle layers 2.79 ms · 46.5% 4-channel head and edges: 2.13 ms 4-channel head and edges 2.13 ms · 35.5% other: 1.08 ms other 1.08 ms · 18.0% Packed fp16 spatial head end-to-end, D3D11 → Vulkan → D3D11, median of three 15-sample rounds 3 ms 4 ms 5 ms 6 ms 7 ms ArtCNN C4F16-DN fp32 C4F16-DN fp32: 3.624 ms C4F16-DN fp32: 3.354 ms 3.624 → 3.354 −7.44% ArtCNN C4F32-DN fp32 C4F32-DN fp32: 7.214 ms C4F32-DN fp32: 6.662 ms 7.214 → 6.662 −7.65% ArtCNN C4F16-DN fp16 C4F16-DN fp16: 3.384 ms C4F16-DN fp16: 3.114 ms 3.384 → 3.114 −7.98% ArtCNN C4F32-DN fp16 C4F32-DN fp16: 6.387 ms C4F32-DN fp16: 5.875 ms 6.387 → 5.875 −8.02% original head fp16 head
What the 4-channel head costs, and the packed fp16 head. Top: the head and border fix-up take 2.13 ms of ArtCNN C4F32-DN’s 6.00 ms. Bottom: packed fp16 weights and shared inputs cut end-to-end time by 7.4–8.0% in 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 rgba16float output. Core WebGPU does not guarantee r16float storage 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 via sample_packed_luma and recombines chroma.
  • Separating shader compilation from playback. First-time createComputePipelineAsync can 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 worker srQueue and tagging compiled Rust plans with a planId lets 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 .esr headers 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-bit wasm32 all 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.

Discussion