Parallel image reduction in WebGPU using workgroup memory
A guide to parallel image reduction in WebGPU using workgroup storage buffers, with compute pipeline setup, limits, and verification steps.
29 Oct 2025, 23:22 UTC

If you've ever tried to apply a blur, sharpen, or other kernel filter to a large image directly in a web browser, you've likely hit a CPU performance wall. Pixel-wise operations on megapixel-resolution images can freeze the main thread, especially on mobile devices. WebGPU compute pipelines with workgroup memory provide a path around this bottleneck, but the implementation detail that makes or breaks the performance gain is how you organize threads and memory within a threadgroup.
Useful takeaway
For any browser that exposes WebGPU compute support, a reduction pipeline that stores per-threadgroup data in a workgroup storage buffer can process a full-resolution image reduction in a fraction of the time a CPU loop would take, as long as the threadgroup size respects the device's maxWorkgroupSize limit and memory barriers are placed where the shader expects them.
Mechanism: workgroup-memory parallel reduction
WebGPU compute shaders run in groups of workitems called a threadgroup. Each threadgroup has a small, fast-access memory region — the workgroup storage buffer — that all workitems in the group can read and write during a single dispatch call. A parallel reduction typical of image filtering proceeds in two phases: first, each workitem loads one pixel (or a small tile) into the shared buffer, then a series of intra-threadgroup adds folds the tile down to a single value. The folded result is then written to a global output buffer, and the next threadgroup processes the next tile.
The JS side creates a GPUComputePipeline that references a compute shader declaring this buffer, encodes commands via GPUCommandEncoder.beginComputePass(), and dispatches using GPUComputePass.dispatchWorkgroups() with threadgroup counts calculated from the image dimensions and the chosen workgroup size.
Compute shader (WGSL)
// 1D parallel reduction using workgroup storage buffer
@group(0) @binding(0) var<private> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;
@workgroup_size(64) var<private> wg_buf: array<f32, 256>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let idx = id.x;
// load one element from the input texture buffer into the workgroup buffer
wg_buf[idx] = input[idx];
// ensure all workitems in the threadgroup have written before proceeding
barrier();
// reduction loop — halving the active count each iteration
let size = workgroup_size.x;
for (var s = size >> 1; s > 0; s >>= 1) {
if (idx < s) {
wg_buf[idx] += wg_buf[idx + s];
}
barrier();
}
// first workitem writes the threadgroup's reduced sum to the global output
if (idx == 0) {
output[global_invocation_id.x / 64] = wg_buf[0];
}
}
JavaScript pipeline setup
// assume `device` is a valid GPUDevice acquired from a canvas context
const inputArray = new Float32Array(width * height); // populated from image data
const outputArray = new Float32Array(Math.ceil(width * height / 64)); // one reduced value per threadgroup
const inputBuffer = device.createBuffer({
size: inputArray.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST
});
const outputBuffer = device.createBuffer({
size: outputArray.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
});
// bind the buffers into a bind group (layout must match the shader's @binding indices)
const bindGroup = device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: inputBuffer } }
]
});
// encode the compute pass
const commandEncoder = device.createCommandEncoder();
const computePass = commandEncoder.beginComputePass();
computePass.setPipeline(computePipeline);
computePass.setBindGroup(0, bindGroup);
// dispatch: 64 workitems per threadgroup, so ceil(totalPixels / 64) threadgroups
const threadgroupCount = Math.ceil(inputArray.length / 64);
computePass.dispatchWorkgroups(threadgroupCount, 1, 1);
computePass.end();
// submit to the GPU queue
const gpuCommands = commandEncoder.finish();
device.queue.submit([gpuCommands]);
// read back the result
outputBuffer.mapAsync(GPUMapMode.READ, 0, outputArray.byteLength, () => {
const reducedValues = new Float32Array(outputBuffer.getMappedRange());
console.log('GPU reduced output:', reducedValues);
});
Placeholders such as width, height, and the WGSL shader string should be replaced with actual values from your canvas size and image data. The dispatchWorkgroups call uses a threadgroup count derived from the total number of pixels divided by the chosen workgroup size (64 in this example). If the pixel count is not a multiple of 64, trailing workitems will read uninitialized memory unless the shader handles bounds checking.
Limits and common mistakes
- Workgroup size: The
@workgroup_sizeannotation in WGSL must not exceed the device'smaxWorkgroupSize, typically 256. Choosing a size that does not divide the image dimensions evenly can leave trailing workitems that read uninitialized memory; add a bounds check in the shader if your image dimensions are not a power of two. - Binding groups: If the shader expects a buffer at binding index 0 but the JS code binds it at index 1, pipeline creation throws a validation error. Double-check that
GPUBindGroupentries match the@bindingannotations exactly. - Memory barriers: The
barrier()instruction in WGSL is the only way to guarantee that all workitems in a threadgroup have finished writing before another workitem reads the result. Omitting it leads to stale reads and incorrect reduction values. - Feature flag variability: Not every browser that supports WebGPU exposes the
computefeature flag. Before attempting to create a compute pipeline, querynavigator.gpu?.featureStats?.computeordevice.features.has('compute'). If the flag is absent, the device either does not support compute shaders or requires a different feature request path. - Integer vs float reduction: The example uses
f32; reducing integer data requires a different shader pattern or conversion, as WebGPU compute shaders handle integer types with additional constraints.
Practical verification
After the dispatch completes, read back the output buffer and compare it against a CPU reference implementation that applies the same reduction kernel. A element-by-element match confirms the pipeline is correct. In the browser console, you can check compute support with:
if (navigator.gpu && navigator.gpu.featureStats?.compute) {
console.log('WebGPU compute is available');
}
When running the dispatch, inspect the GPU queue for submission errors using device.queue.onerror or the browser's WebGPU debugging tools (usually accessible via chrome://gpu or Firefox's about:devtools toolbox). If the output buffer contains NaN or unexpected values, verify that the workgroup size divides the input size evenly, that every barrier() in the shader is paired with a read after the dispatch, and that the input buffer contains valid floating-point values.
For a full end-to-end test, copy the input pixel data to a GPUBuffer, run the dispatch as shown, read back the result, and compare it to a simple CPU loop that sums tiles of 64 pixels. Matching results give confidence that the workgroup memory setup, barrier placement, and dispatch configuration are all correct.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.