Skip to content

compute.kernels.sum

Summary

compute.kernels.sum reduces all entries of a GPU ndarray to a scalar in the same dtype. Use it when the result will feed another GPU operation. Unsigned sums wrap at 32 bits, so use compute.ndarray.sum when you need a wider result or selected axes.

Syntax

sum(a: GPUndarray, opts?: KernelOutputOptions): GPUndarray
const total = kernels.sum(a);

Parameters

Name Type Required Description
a GPUndarray Yes f32, u32 or c64 array of any supported shape and layout.
opts KernelOutputOptions No Kernel output and dispatch settings.

Returns

GPUndarray - Scalar of shape [] and the input dtype. Empty input gives zero. Unsigned sums wrap modulo 2 ** 32. A NaN is propagated, including when either component of a complex element is NaN.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const { ndarray: nd, kernels } = wgpu.compute;
const a = nd.fromArray("u32", [2, 2], [1, 2, 3, 4], { residency: "gpu" });
const total = kernels.sum(a);
const cpu = await nd.toCPU(total);
console.log(cpu.get()); // 10
cpu.destroy();
total.destroy();
a.destroy();

See Also