compute.kernels¶
Summary¶
compute.kernels runs common numerical operations on GPU ndarrays. The operation selects an implementation from the input dtype, which must be supported by that operation. Use compute.ndarray.toGPU for CPU input and compute.ndarray.cast to align operand dtypes.
Syntax¶
Available APIs¶
- Elementwise add, sub, mul, scl and axpy.
- Vector dot, matrix matmul, and luFactor with luSolve.
- Whole-array sum, min, max, argmin and argmax.
- scanExclusive, histogram, compact, sort and sortPairs.
- scaleExtract, scaleHistogram and scaleRemap for custom scalar display pipelines.
Type Details¶
type KernelDispatchOptions = {
encoder?: GPUCommandEncoder;
label?: string;
validateLimits?: boolean;
};
type KernelOutputOptions = KernelDispatchOptions & NdarrayGPUOptions & {
out?: GPUndarray;
};
type ElementwiseOptions = KernelOutputOptions;
type KernelScalar = number | ComplexScalar;
Inputs and supplied outputs must be live GPU arrays on the kernel device. An out must have the required dtype and shape and be C-contiguous. A returned array owns its storage unless it is a supplied output or an explicitly overwritten input. Destroy owned results after use. Fresh allocations use storage usage, copySrc: true, copyDst: true and a label based on the operation by default. Use usage to add flags. Allocation flags cannot be given for a supplied output.
A call submits its work unless you supply encoder. It then records in order on that encoder and leaves submission to you. Keep arrays live through submission, and submit before reading results. validateLimits defaults to false and enables an additional dispatch-count check when encoding. Buffer, binding and workgroup limits still apply.
Example¶
const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const { ndarray: nd, kernels } = wgpu.compute;
const x = nd.fromArray("f32", [3], [2, 4, 6], { residency: "gpu" });
const total = kernels.sum(x);
const cpu = await nd.toCPU(total);
console.log(cpu.get()); // 12
cpu.destroy();
total.destroy();
x.destroy();
Notes¶
For standalone use, import ComputeKernels, construct it with new ComputeKernels(device, device.queue), and call destroy() when finished.
Most kernels accept strided inputs and can stage temporary storage when a binding is unaligned or shares a GPU buffer with a read-only operand. Check each operation for shape rules and supported aliasing. Use the ndarray namespace for axis reductions and general layout transformations.
For add, sub, mul and axpy, the strided and broadcasting path supports up to eight dimensions after adjacent dimensions with compatible strides are combined. If the layout exceeds this limit, reshape the inputs to fewer dimensions or use a packed layout where possible.