compute.ndarray.sum¶
Summary¶
compute.ndarray.sum adds values over selected axes. Use compute.ndarray.prod to multiply them. Both accept strided arrays and return results in the input residency.
Syntax¶
sum<T extends CPUndarray | GPUndarray>(a: T, options?: NdarrayReduceOptions): T
prod<T extends CPUndarray | GPUndarray>(a: T, options?: NdarrayReduceOptions): T
const totals = nd.sum(a, { axes: 1 });
Parameters¶
| Name | Type | Required | Description |
|---|---|---|---|
a |
CPUndarray | GPUndarray |
Yes | Live real or complex array. |
options |
NdarrayReduceOptions |
No | Reduction axes, output dtype, NaN and integer overflow policy, and GPU output options. |
Returns¶
T - Packed result. The default dtype widens signed integers to i32 and unsigned integers to u32 and keeps the input float or complex dtype. Destroy newly allocated results when finished.
Type Details¶
type NdarrayNaNMode = "propagate" | "omit";
type NdarrayReduceOptions = NdarrayOperationOptions & {
axes?: number | readonly number[];
keepDims?: boolean;
dtype?: DType;
nan?: NdarrayNaNMode;
overflow?: NdarrayOverflowMode;
};
axes accepts a single axis or a list of distinct axes. Negative axes count from the end. It defaults to all axes, and [] reduces none. keepDims: true leaves each reduced axis at length one. The default removes those axes, so a whole-array reduction returns a scalar with shape [].
nan defaults to "propagate". With "omit", a complex value is skipped if either component is NaN. Infinities remain in the reduction. Empty and all-omitted slices give zero for sum and one for product.
The dtype override can select a real type for integer input, a float type for float input or a complex type for complex input. Integer sums accumulate exactly before output conversion. For integer output, overflow defaults to "saturate" for sum. Set it to "wrap" to wrap at the destination width. Integer products accumulate modulo 2 ** 32 and reject saturation.
GPU arithmetic rejects f64 and c128 input and output, with f64 output allowed for a sum of integer input. GPU out and encoder rules follow compute.ndarray.contiguous.
Example¶
const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const nd = wgpu.compute.ndarray;
const a = nd.fromArray("i16", [2, 2], [1, 2, 3, 4]);
const totals = nd.sum(a, { axes: -1 });
console.log(totals.data()); // Int32Array [3, 7]
totals.destroy();
a.destroy();
Notes¶
Reductions support up to 2 ** 32 - 1 input elements. Implementation note. Kept and reduced axes are coalesced separately before the CPU rank limit of 64 or GPU rank limit of eight is applied. Large GPU reductions may split their work into batches. If an individual result or working range still exceeds the device's buffer or binding limits, the call throws.