GPU computing: tiles, barriers and data movement
GPU 计算基础
Implement a bounded tiled matrix product in real WebGPU and distinguish device correctness from performance claims.
gpu-computingThirty-five outputs, sixty-four invocations
Multiplying a 7×9 matrix by a 9×5 matrix produces 35 numbers. Our GPU example launches four workgroups of sixteen invocations, or 64 invocations. Some never write an output, but they still participate in loading shared tiles and reaching barriers. Returning early can break the algorithm.
A GPU program describes many related computations and how they exchange data. This chapter implements a complete small matrix product in WebGPU, using WGSL for the device program and JavaScript for allocation, dispatch and readback. A CPU reference checks the result. The example was actually run through an Apple Metal adapter; that observation is not a speed benchmark.
Give each invocation an output and each group a tile
For A with shape M×K and B with shape K×N, row-major matrix multiplication is:
A naive output computation reloads its A row and B column independently. A tile lets neighboring invocations reuse values. Our group has four rows and four columns of invocations. Each invocation accumulates one output, while the group cooperatively loads a 4×4 tile from each input into workgroup memory.
A complete pair of tiles needs 32 scalar loads, followed by 64 multiply-and-add contributions across sixteen outputs. Computing those contributions through independent direct loads would use 128 scalar loads. This is an algorithmic access count for a full tile, not a fourfold runtime guarantee: caches, compiler decisions, transfers and scheduling also affect time.
Convert group coordinates into matrix coordinates
With local coordinates l and workgroup coordinates g:
dispatchWorkgroups(Gx,Gy) specifies groups, not individual invocations. Each group contains sixteen invocations because the shader declares workgroup_size(4,4). The dispatch reference defines that distinction.
For each inner-dimension tile, the group loads valid input positions and writes zero into padding positions. The first barrier makes the tile available before it is consumed. The second prevents an invocation from overwriting that tile for the next iteration while others still read it. Every invocation traverses the same tile loop, including invocations whose final output is outside the matrix.
WGSL requires these synchronization calls to occur in uniform control flow. The output-bound check therefore guards only the final store, not an early return before barriers. See the fixed WGSL specification.
Upload, compute and read back are separate stages
JavaScript numbers are packed into float32 input buffers and uploaded with writeBuffer. A uniform buffer carries M, N and K. The shader writes a storage buffer; the command encoder then copies it into a separate buffer with MAP_READ usage. Awaiting mapAsync makes its mapped contents accessible to JavaScript. The code copies those values before unmapping, then destroys its buffers and device. Buffer mapping
Submitting commands is not the same as observing their completion. Timing only queue.submit would mostly measure submission, excluding much of the workload. Our code does not report a performance ratio.
A complete browser module with explicit bounds
Save the module as gpu-matmul.mjs and import it from a browser page served over HTTPS or a browser-trusted local origin. WebGPU and an available adapter are required. Unsupported environments raise an error; the CPU function is a separately named reference, not a silently substituted GPU result.
Inputs are dense rectangular JavaScript arrays with 1–32 rows and columns, compatible inner dimensions, and integer elements in [−8,8]. Sparse arrays, NaNs and fractional values are rejected. These bounds make every product and partial sum exactly representable in float32:
This exact comparison domain is deliberate. General floating-point GEMM requires a numerical error policy; the example does not claim exact equality for arbitrary float inputs.
const TILE = 4;
const SHADER = `
@group(0) @binding(0) var<storage, read> a: array<f32>;
@group(0) @binding(1) var<storage, read> b: array<f32>;
@group(0) @binding(2) var<storage, read_write> c: array<f32>;
@group(0) @binding(3) var<uniform> dims: vec4<u32>;
var<workgroup> ta: array<array<f32, 4>, 4>;
var<workgroup> tb: array<array<f32, 4>, 4>;
@compute @workgroup_size(4, 4)
fn main(@builtin(workgroup_id) group: vec3<u32>,
@builtin(local_invocation_id) local: vec3<u32>) {
let row = group.y * 4u + local.y;
let col = group.x * 4u + local.x;
var total = 0.0;
for (var start = 0u; start < dims.z; start += 4u) {
ta[local.y][local.x] = 0.0;
tb[local.y][local.x] = 0.0;
if (row < dims.x && start + local.x < dims.z) {
ta[local.y][local.x] = a[row * dims.z + start + local.x];
}
if (start + local.y < dims.z && col < dims.y) {
tb[local.y][local.x] = b[(start + local.y) * dims.y + col];
}
workgroupBarrier();
for (var k = 0u; k < 4u; k += 1u) {
total += ta[local.y][k] * tb[k][local.x];
}
workgroupBarrier();
}
if (row < dims.x && col < dims.y) { c[row * dims.y + col] = total; }
}`;
function inputs(a, b) {
for (const matrix of [a,b]) {
if (!Array.isArray(matrix) || matrix.length < 1 || matrix.length > 32 ||
!Array.isArray(matrix[0]) || matrix[0].length < 1 || matrix[0].length > 32) {
throw new Error('Use nonempty matrices with at most 32 rows and columns.');
}
const width = matrix[0].length;
for (let i=0; i<matrix.length; i++) {
const row=matrix[i];
if (!Array.isArray(row) || row.length !== width) throw new Error('Use dense rectangular matrices.');
for(let j=0;j<width;j++) {
if (!Number.isInteger(row[j]) || Math.abs(row[j]) > 8) {
throw new Error('Use dense matrices of integers in [-8,8].');
}
}
}
}
if (a[0].length !== b.length) throw new Error('Inner dimensions must match.');
return {m:a.length, k:b.length, n:b[0].length};
}
export function multiplyCPU(a,b) {
const {m,k,n} = inputs(a,b);
return Array.from({length:m}, (_,i) => Array.from({length:n}, (_,j) => {
let total=0;
for(let h=0;h<k;h++) total+=a[i][h]*b[h][j];
return total;
}));
}
export async function multiplyGPU(a,b) {
const {m,k,n} = inputs(a,b);
const av=new Float32Array(a.flat()), bv=new Float32Array(b.flat());
if (!globalThis.navigator?.gpu) throw new Error('WebGPU is unavailable.');
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error('No WebGPU adapter is available.');
const device = await adapter.requestDevice();
const buffers=[];
let scope=true;
device.pushErrorScope('validation');
try {
const make = (size,usage) => {
const buffer=device.createBuffer({size,usage});buffers.push(buffer);return buffer;
};
const ab=make(m*k*4,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST);
const bb=make(k*n*4,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST);
const cb=make(m*n*4,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC);
const db=make(16,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST);
const read=make(m*n*4,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);
device.queue.writeBuffer(ab,0,av);
device.queue.writeBuffer(bb,0,bv);
device.queue.writeBuffer(db,0,new Uint32Array([m,n,k,0]));
const module=device.createShaderModule({code:SHADER});
const pipeline=await device.createComputePipelineAsync({layout:'auto',compute:{module,entryPoint:'main'}});
const group=device.createBindGroup({layout:pipeline.getBindGroupLayout(0),entries:
[ab,bb,cb,db].map((buffer,binding)=>({binding,resource:{buffer}}))});
const encoder=device.createCommandEncoder();
const pass=encoder.beginComputePass();pass.setPipeline(pipeline);pass.setBindGroup(0,group);
pass.dispatchWorkgroups(Math.ceil(n/TILE),Math.ceil(m/TILE));pass.end();
encoder.copyBufferToBuffer(cb,0,read,0,m*n*4);device.queue.submit([encoder.finish()]);
await read.mapAsync(GPUMapMode.READ);
const values=new Float32Array(read.getMappedRange()).slice();read.unmap();
const error=await device.popErrorScope();scope=false;
if(error) throw new Error(error.message);
return {matrix:Array.from({length:m},(_,i)=>Array.from(values.slice(i*n,(i+1)*n))),
workgroups:[Math.ceil(n/TILE),Math.ceil(m/TILE)],invocationsPerGroup:TILE*TILE};
} finally {
if(scope) await device.popErrorScope().catch(()=>{});
for(const buffer of buffers) buffer.destroy();
device.destroy();
}
}
For example, from a module script on the same origin:
import { multiplyCPU, multiplyGPU } from './gpu-matmul.mjs';
const a = [[1,2,3],[4,5,6]];
const b = [[1,0],[0,1],[1,1]];
const expected = multiplyCPU(a,b); // [[4,5],[10,11]]
const measured = await multiplyGPU(a,b);
console.log(measured.matrix, expected);
Both matrices are copied into typed arrays before the first await. Changing the caller’s array while adapter creation is pending therefore does not change this computation. The pipeline includes validation error handling and cleanup even when an asynchronous operation fails.
Six actual device checks covered 1×1 products, full tiles, partial outer tiles, a non-multiple inner dimension and bounds of 32 in the row or inner dimension. All 125 output entries matched the CPU reference exactly. A separate asynchronous input-mutation check retained the original input value. The recorded environment was Chrome 152.0.7977.76, adapter vendor apple, architecture metal-3, with software fallback reported false on 2026-09-06.
The 7×9 by 9×5 case dispatches 2×2 groups and has three inner tile iterations. Its 29 padded output invocations still cross both barriers in each iteration. Zero-filled inner padding does not contribute to the result.
Tiling is an organization technique, not a performance verdict
Useful arithmetic scales approximately as 2MNK floating-point operations when a multiply and add count separately. This implementation also computes padding positions. It stores both inputs and the output on the device, keeps a readback buffer, and uses 128 bytes of explicit workgroup tile arrays per group. Those arrays are not a description of total device memory or runtime overhead.
The four-by-four tile is chosen for inspection. Production kernels may choose different tiles, register blocking, subgroups or specialized matrix hardware. WGSL workgroups are programming abstractions; their mapping to physical execution units is implementation-dependent.
For these tiny matrices, creating a device, compiling a pipeline and moving results can dominate arithmetic. Reusing pipelines and buffers changes the workload and should be measured explicitly. Unified-memory hardware and discrete devices also have different physical costs behind the same API operations.
The experiment does not validate CUDA, ROCm, every browser or all GPU vendors. It checks this WebGPU implementation and stated input domain. An unavailable adapter is a capability result, not a reason to relabel CPU output as GPU output.
Trace the padded invocations
- For a 7×9 by 9×5 product, how many workgroups, invocations and useful outputs are there?
Answer: 2×2 workgroups, sixteen invocations each, and 7×5=35 useful outputs. There are 64 invocations; 29 do not perform a final output store.
- Why should an out-of-range output invocation not return before the tile loop?
Answer: It still participates in workgroup tile loading and synchronization. Returning early would make barrier participation nonuniform and can prevent the group’s valid outputs from receiving required data. Guard loads and the final store instead.
- Why does the code copy mapped results before calling
unmap()?
Answer: The mapping’s accessible storage belongs to the mapped buffer. The separate copied Float32Array retains values after that mapping is released; the code can then clean up GPU resources.
- Does four times fewer logical input loads for a full tile prove four times faster end-to-end execution?
Answer: No. The count excludes cache behavior, instruction scheduling, padded computation, device setup and transfers. Compare complete equivalent workloads after checking correctness.
Connect shader rules to matrix reasoning
The WGSL specification defines workgroup memory and synchronization requirements. WebGPU API references define dispatch counts, upload and readback behavior. The tile algorithm is original code; no vendor kernel or example implementation was copied.
Continue with matrix multiplication, parallel computing and profiling. Keep arithmetic correctness, API synchronization and performance measurement as separate checks.
Make a prediction, then check
Why must padded invocations still reach the tile barriers?
Learning objectives
- Map matrix outputs to workgroups and handle partial tiles without violating barriers.
- Run upload, tiled compute and readback with explicit buffer lifetime.
- Separate an exact small-integer test domain from general floating-point and performance claims.
Prerequisites & connections
Explore related knowledge →References
- WebGPU Shading Language — Candidate Recommendation Draft, 31 August 2026
W3C · 2026 - GPUComputePassEncoder/dispatchWorkgroups — MDN Web Docs
MDN contributors - GPUBuffer/mapAsync — MDN Web Docs
MDN contributors - GPUQueue/writeBuffer — MDN Web Docs
MDN contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.
- Three portable tests and the recorded real Apple Metal WebGPU check cover bounded integer multiplication, 125 outputs and asynchronous input snapshots. Strict bilingual rendering: three formulas and four answers.
- Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- WebGPU Shading Language — Candidate Recommendation Draft, 31 August 2026 · Read the 2026-08-31 draft and synchronization section: workgroup execution/memory scope and uniform-control requirement, lines 14206–14210; reviewed both tile barriers and guarded final stores.
- GPUComputePassEncoder/dispatchWorkgroups — MDN Web Docs · Read dispatch semantics and X/Y group counts, lines 186–213; 4×4 invocations are declared separately in the shader.
- GPUBuffer/mapAsync — MDN Web Docs · Read mapped readiness Promise, usage and alignment rules, lines 186–187 and 233–241.
- GPUQueue/writeBuffer — MDN Web Docs · Read host upload semantics and COPY_DST/alignment requirements, lines 186–188 and 238–245.
Related topics