Skip to content

compute.kernels.add

Summary

compute.kernels.add combines two GPU ndarrays elementwise at their broadcast shape. Add a length-n vector to a [m, n] matrix to apply the same bias to each row. The arrays must share a dtype, and a compatible input can serve as out to update it in place.

Syntax

add(a: GPUndarray, b: GPUndarray, opts?: ElementwiseOptions): GPUndarray
const result = kernels.add(a, b);

Parameters

Name Type Required Description
a, b GPUndarray Yes Inputs with the same dtype, either f32, u32 or c64. Dimensions align from the right and must match or have length one on either side. Strided views are accepted.
opts ElementwiseOptions No Kernel output and dispatch settings.

Returns

GPUndarray - Sum in the broadcast shape and input dtype. Unsigned addition wraps modulo 2 ** 32. Complex addition operates on both components. The output can alias an input if it matches the required shape and is C-contiguous.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const { ndarray: nd, kernels } = wgpu.compute;
const a = nd.fromArray("f32", [2, 1], [1, 10], { residency: "gpu" });
const b = nd.fromArray("f32", [2], [2, 3], { residency: "gpu" });
const result = kernels.add(a, b);
const cpu = await nd.toCPU(result);
console.log(cpu.data()); // [3, 4, 12, 13]
cpu.destroy();
result.destroy();
b.destroy();
a.destroy();

See Also