← Back to Examples

Gridwise Reduce Primitive Example

This example calls Gridwise's reduce primitive. You can look at your developer console and see the input and output of this primitive, and whether the output matches what is expected (in which case the developer console will indicate "Validation passed").

It computes a sum-reduction on an input array of 224 i32s, producing a single output value. The entire JS source file is in github. While the entire file contains substantial WebGPU and input-output setup boilerplate, the important parts follow.

First, we declare the reduce primitive. We configure its datatype (i32), the binary operation for reduce (sum-reduction on i32s), and the type (reduce).

const datatype = "i32";
const binop = new BinOpAdd({ datatype });
const reducePrimitive = new DLDFScan({
  device,
  binop,
  type: "reduce",
  datatype,
});
const primitive = reducePrimitive;

We have declared buffers (using WebGPU's device.createBuffer) called memsrcBuffer and memdestBuffer. Note that for reduce, the output buffer is only 4 bytes (a single value). We then call the primitive's execute procedure (note that execute is an async call):

await primitive.execute({
  inputBuffer: memsrcBuffer,
  outputBuffer: memdestBuffer,
});

We then read back the result from the GPU and validate it.

Your developer console should show a result that allows you to inspect the input and output, and prints "Validation passed" if the output matches the (CPU-computed) reference. It should look something like:

input Int32Array(16777216) [array of values...]
output Int32Array(1) [reduced_value]
Validation passed