Studying Bicubic++: AI Super-Resolution in WebGL Without WebGPU
WebGPU is a great API for running neural networks directly in the browser. But what happens when a user's device doesn't support it?
One alternative worth researching is WebGL as an inference backend for lightweight super-resolution models. Bicubic++ is a particularly interesting case to study: its architecture is small and designed for speed.
This article looks at how the network is built, then works through a question: instead of relying on a general-purpose inference runtime, could the entire network run on hand-written fragment shaders?
Upscale your video now
Free in your browser, or on a cloud GPU with Pro.
- No sign-up
- No watermark
- Up to 4K
Why Bicubic++?
Bicubic++ is a lightweight super-resolution network presented at the CVPR 2023 NTIRE workshop, where it won the ×3 track of the real-time super-resolution challenge.
Unlike larger models such as Real-ESRGAN, Bicubic++ prioritizes computational efficiency while still improving image quality beyond traditional bicubic interpolation.
Some interesting architectural choices include:
- Reducing spatial dimensions before feature extraction.
- Using a small number of standard convolutional layers.
- Removing convolution biases to reduce inference overhead.
- Using residual connections.
- Reconstructing high-resolution images through depth-to-space operations.
The authors reported an inference time of approximately 1.17 ms on an RTX 3090 for 720p input and 4K output using FP16.
That's a native GPU benchmark, not a browser benchmark, but it demonstrates why this type of architecture is worth exploring.
WebGL is more than a graphics API
WebGL doesn't expose compute shaders like WebGPU does.
However, fragment shaders are perfectly capable of performing mathematical operations that have nothing to do with rendering graphics.
Instead of rendering colors to the screen, we can render numerical results into floating-point textures.
The mapping between neural network operations and WebGL looks something like this:
| Neural network | WebGL |
|---|---|
| Tensor | Floating-point texture |
| Model weights | Weight texture |
| Convolution | Fragment shader |
| Activation function | GLSL operation |
| Residual connection | Texture addition |
| Intermediate output | Framebuffer attachment |
| Inference graph | Sequence of rendering passes |
A neural network effectively becomes a multi-pass rendering pipeline.
1. Exporting the model weights
The first step is extracting trained parameters from a PyTorch model.
There's no need to bring the entire PyTorch runtime into the browser.
For a relatively simple network, we can export its weights as binary files and implement the architecture directly in JavaScript and GLSL.
import json
import numpy as np
metadata = {}
for name, tensor in model.state_dict().items():
array = tensor.detach().cpu().numpy()
array = array.astype(np.float32)
filename = f"{name}.bin"
array.tofile(filename)
metadata[name] = {
"shape": list(array.shape),
"file": filename
}
with open("weights.json", "w") as f:
json.dump(metadata, f)
The exported files contain the numerical parameters required for inference.
For production, we could pack all weights into a single binary file to reduce HTTP requests and simplify initialization.
We could also convert weights to FP16 before exporting to reduce download size and GPU memory usage.
2. Representing tensors as textures
Unlike WebGPU, WebGL doesn't provide arbitrary storage buffers for compute operations.
Instead, we can represent neural network tensors using textures.
An RGBA texture conveniently stores four feature channels per texel.
For example, a feature map with 32 channels can be divided into eight RGBA channel groups.
Channels 0 - 3 -> RGBA group 0
Channels 4 - 7 -> RGBA group 1
Channels 8 - 11 -> RGBA group 2
...
Channels 28 - 31 -> RGBA group 7
These groups can be stored in separate textures, texture arrays, or a larger texture atlas.
First, we need to check whether the device supports floating-point render targets.
const gl = canvas.getContext("webgl2");
if (!gl) {
throw new Error("WebGL2 is not supported");
}
if (!gl.getExtension("EXT_color_buffer_float")) {
throw new Error("Float render targets unavailable");
}
We can then allocate floating-point textures for intermediate feature maps.
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texStorage2D(
gl.TEXTURE_2D,
1,
gl.RGBA16F,
width,
height
);
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_MIN_FILTER,
gl.NEAREST
);
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_MAG_FILTER,
gl.NEAREST
);
Using RGBA16F rather than RGBA32F reduces memory consumption and potentially improves memory bandwidth.
Of course, the actual numerical accuracy and framebuffer compatibility need to be tested on the target devices.
3. Implementing convolution with fragment shaders
A convolution layer computes each output value using a local neighborhood of input features and a set of learned weights.
This maps naturally onto fragment shaders.
Each fragment invocation calculates an output texel. The shader reads the input feature map, multiplies the values by the corresponding weights, and accumulates the result.
Here is a simplified implementation of a 3x3 convolution for four input channels and one output channel.
#version 300 es
precision highp float;
uniform sampler2D uInput;
uniform sampler2D uWeights;
out vec4 fragColor;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 size = textureSize(uInput, 0);
float result = 0.0;
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
ivec2 q = p + ivec2(x, y);
if (
q.x < 0 || q.y < 0 ||
q.x >= size.x || q.y >= size.y
) {
continue;
}
vec4 inputValue = texelFetch(
uInput, q, 0
);
vec4 weight = texelFetch(
uWeights,
ivec2(x + 1, y + 1),
0
);
result += dot(inputValue, weight);
}
}
fragColor = vec4(result, 0.0, 0.0, 0.0);
}
A production implementation would extend this kernel to accumulate across all input channel groups and calculate four output channels simultaneously.
GLSL's vector operations are particularly useful here.
We can use vec4, mat4, and dot() to express multiple channel operations without manually handling every scalar multiplication.
Since the network architecture is known in advance, we can also generate specialized shaders for individual layers instead of writing a generic convolution kernel.
4. Fuse convolution and activation
Every additional rendering pass introduces overhead and requires reading and writing intermediate textures.
If a convolution is immediately followed by an activation function, there's little reason to implement them as separate passes.
For example, Leaky ReLU can be applied directly to the convolution result.
vec4 leakyRelu(vec4 x, float alpha) {
return max(x, x * alpha);
}
The final output becomes:
fragColor = leakyRelu(result, uAlpha);
Here, result represents a vector of four accumulated output channels, and uAlpha must match the model's activation parameter.
This eliminates an additional texture read, texture write, and draw call.
For lightweight networks, reducing rendering passes can be just as important as reducing arithmetic operations.
5. Keep computation at a lower resolution
One of the most interesting ideas behind Bicubic++ is reducing spatial dimensions before performing most of its feature extraction.
Consider an input image with dimensions H x W.
Reducing both spatial dimensions by a factor of two gives us:
Original feature map:
H x W
Reduced feature map:
(H / 2) x (W / 2)
The number of spatial positions is reduced to one quarter.
This doesn't mean the entire network automatically becomes four times faster, but it significantly reduces the spatial workload of subsequent convolutional layers.
The downsampling operation can be implemented directly as a strided convolution.
ivec2 inputPosition =
ivec2(gl_FragCoord.xy) * 2;
The convolution kernel then samples the corresponding input neighborhood.
Instead of processing a large feature map throughout the network, most computation happens at a smaller resolution.
This is particularly attractive for video processing, where inference may need to run thousands of times.
6. Implementing residual connections
Residual connections are relatively straightforward in WebGL.
We simply read two corresponding feature values and add them together.
#version 300 es
precision highp float;
uniform sampler2D uInput;
uniform sampler2D uResidual;
out vec4 fragColor;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec4 inputValue = texelFetch(uInput, p, 0);
vec4 residual = texelFetch(uResidual, p, 0);
fragColor = inputValue + residual;
}
Depending on the architecture, this addition can also be fused into the preceding convolution shader.
The main requirement is keeping the original feature texture alive until the residual operation is complete.
This is where understanding the execution graph becomes useful.
Rather than allocating a new texture for every layer, we can reuse intermediate textures as soon as their previous contents are no longer needed.
7. Implementing Pixel Shuffle
Pixel Shuffle, also known as depth-to-space, rearranges channels from a low-resolution feature map into spatial positions in a higher-resolution image.
Unlike convolution, it doesn't require multiply-accumulate operations.
Consider a simple x2 Pixel Shuffle operation.
Input tensor: H x W x 12
Output tensor: 2H x 2W x 3
For every output pixel, the shader calculates its corresponding input coordinate and feature channel.
Using the standard PyTorch Pixel Shuffle channel ordering:
ivec2 source = outputPosition / scale;
ivec2 offset = outputPosition % scale;
int channel =
outputChannel * scale * scale +
offset.y * scale +
offset.x;
We can then determine which RGBA group contains the required value.
int group = channel / 4;
int component = channel % 4;
This turns spatial reconstruction into a texture-addressing operation rather than an expensive convolution at the final output resolution.
In the published x3 Bicubic++ architecture, the internal spatial resolution is reduced by a factor of two, so the final depth-to-space operation uses a factor of six.
Input: H x W x 3
Reduced spatial: H/2 x W/2
Before shuffle: H/2 x W/2 x 108
Pixel Shuffle: x6
Output: 3H x 3W x 3
Most of the neural network's computation therefore happens before the final high-resolution image is constructed.
8. Building the inference pipeline
Once the required operators are implemented, inference becomes a sequence of rendering passes.
A simplified execution graph looks like this:
Input image texture
|
v
Strided convolution
|
v
Low-resolution features
|
+------------------+
| |
v |
Convolution layers |
| |
v |
Residual addition <-------+
|
v
Reconstruction convolution
|
v
Pixel Shuffle
|
v
Upscaled image texture
Each layer renders its output into a framebuffer-backed texture, which becomes the input for a subsequent layer.
The exact execution graph, activation functions, padding, and weight layout must match the original trained model.
For intermediate layers, a ping-pong texture strategy can help reduce memory allocations.
Pass 1: Texture A -> Texture B
Pass 2: Texture B -> Texture A
Pass 3: Texture A -> Texture B
Pass 4: Texture B -> Texture A
Additional textures are required when the architecture contains residual connections or when tensor dimensions change.
Most importantly, we must avoid reading from a texture while simultaneously rendering into that same texture.
9. Optimizing for video inference
Processing a single image is relatively straightforward.
Processing an entire video is a different problem.
A five-minute video at 30 FPS contains 9,000 frames. Even small inefficiencies become significant when repeated thousands of times.
Some optimizations worth considering:
Compile shaders only once
Shader compilation can be expensive, especially on older devices.
All model shaders should be compiled during initialization and reused across frames.
Upload weights only once
Model weights remain constant throughout inference.
There's no reason to upload them again for every video frame.
Reuse textures and framebuffers
Repeated GPU resource allocation creates unnecessary overhead.
Allocate intermediate textures when the video resolution changes, not when the next frame arrives.
Avoid GPU-to-CPU transfers
One of the most expensive operations in WebGL-based inference can be:
gl.readPixels(...)
This may force synchronization between the CPU and GPU.
Whenever possible, intermediate results should remain on the GPU.
The final output can be rendered directly into a canvas and passed into a compatible video encoding pipeline.
Use overlapping tiles for large frames
Older GPUs may have limited texture sizes and available memory.
Instead of processing an entire frame at once, we can divide it into overlapping tiles.
+----------+----------+
| Tile 1 | Tile 2 |
| <----> |
+----------+----------+
| Tile 3 | Tile 4 |
+----------+----------+
The overlapping region must account for the network's receptive field. Otherwise, visible seams may appear between tiles.
Tile boundaries must also remain aligned with the model's downsampling stride and Pixel Shuffle layout.
10. WebGPU first, WebGL as a fallback
Rather than replacing WebGPU, WebGL can serve as an alternative inference backend.
async function selectBackend() {
if (navigator.gpu) {
try {
const adapter =
await navigator.gpu.requestAdapter();
if (adapter) {
const device =
await adapter.requestDevice();
return {
type: "webgpu",
device
};
}
} catch {
// Try WebGL2 instead.
}
}
const canvas = document.createElement("canvas");
const gl = canvas.getContext("webgl2");
if (
gl &&
gl.getExtension("EXT_color_buffer_float")
) {
return {
type: "webgl2",
gl
};
}
return {
type: "cpu"
};
}
The CPU path could use traditional interpolation or a lightweight WASM implementation.
The resulting architecture would look like this:
Browser
|
Capability detection
|
+----------+----------+
| | |
WebGPU WebGL2 WASM
| | |
+----------+----------+
|
Upscaled output
Modern devices can benefit from WebGPU, while older devices still have another potential GPU-accelerated path.
However, API availability alone doesn't guarantee good performance.
A small inference benchmark during initialization may provide a better indication of which backend should be selected.
11. Verifying numerical correctness
Before optimizing performance, it's important to verify that the WebGL implementation produces the expected results.
I would start by comparing intermediate outputs against PyTorch using identical input tensors.
difference = np.abs(
pytorch_output - webgl_output
)
print("Mean error:", difference.mean())
print("Maximum error:", difference.max())
Some common sources of numerical differences include:
- Incorrect weight layouts.
- Incorrect padding.
- RGB channel ordering.
- Texture coordinate orientation.
- Pixel Shuffle channel ordering.
- FP16 rounding.
- Incorrect activation parameters.
Testing individual operators before testing the complete network makes these problems much easier to identify.
Once the FP32 implementation is correct, we can experiment with FP16 intermediate textures and measure the resulting quality difference.
A note on licensing
The official Bicubic++ repository is published under the CC BY-NC-SA 4.0 license.
The license includes a non-commercial clause, so read its terms before using the official code or pretrained weights for anything beyond research.
This article is a technical study: it uses Bicubic++ as a reference for exploring how lightweight super-resolution architectures can be mapped onto WebGL.
Final thoughts
WebGPU is undoubtedly a better fit for general-purpose GPU computing.
But WebGL is far from obsolete.
For small neural networks with predictable architectures, hand-written fragment shaders offer an interesting alternative to compute shaders.
What makes architectures like Bicubic++ particularly interesting is that efficiency isn't something added after training. It's part of the network design itself.
Instead of asking how we can make a large AI model run on weaker hardware, perhaps we should spend more time exploring models that were designed for weaker hardware in the first place.
Not every AI application needs a massive neural network.
Sometimes, a small model and a few well-optimized shaders are enough.
References
Got a video to sharpen?
Free in your browser, or on a cloud GPU with Pro.
- No sign-up
- No watermark
- Up to 4K