← Back to Examples

Gridwise Sort Primitive Example

This example calls Gridwise's sort 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 sorts an array of 224 random i32 values in ascending order using the OneSweep radix sort algorithm. 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 sort primitive. We configure its datatype (i32), the input length, and set copyOutputToTemp to true so the sorted result is written to a separate destination buffer rather than overwriting the input.

const datatype = "i32";
const sortKeysPrimitive = new OneSweepSort({
  device,
  datatype,
  inputLength: inputLength,
  copyOutputToTemp: true,
});
const primitive = sortKeysPrimitive;

We have declared buffers (using WebGPU's device.createBuffer) called memsrcBuffer and memdestBuffer. Sort operates on keysInOut (the input, which may be modified in place during sorting) and keysTemp (the destination buffer that holds the final sorted output when copyOutputToTemp is true). We then call the primitive's execute procedure (note that execute is an async call):

await primitive.execute({
  keysInOut: memsrcBuffer,
  keysTemp: 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 is correctly sorted. It should look something like:

input array Int32Array(16777216) [random values...]
output Int32Array(16777216) [sorted values in ascending order...]
Validation passed