Skip to content

compute.kernels.compact

Summary

compute.kernels.compact gathers the elements selected by a matching 0/1 flag vector. The selected values occupy a stable prefix, and the kernel returns its valid length in a separate scalar GPU ndarray. Use that count to consume the prefix without assuming the output array shrank.

Syntax

compact(values: GPUndarray, flags: GPUndarray, opts?: CompactOptions): CompactResult
const packed = kernels.compact(values, flags);

Parameters

Name Type Required Description
values GPUndarray Yes Rank-one f32 or u32 values.
flags GPUndarray Yes Same-length u32 vector. Supply zero to skip a value and one to keep it.
opts CompactOptions No Optional separate destination arrays and dispatch settings.

Returns

CompactResult - The values array keeps the input shape and dtype. Only its first count elements are part of the compact result. count is a u32 scalar ndarray with shape []. When the input is empty, the count is zero.

Type Details

type CompactOptions = KernelDispatchOptions & NdarrayGPUOptions & {
    out?: GPUndarray;
    outCount?: GPUndarray;
};
type CompactResult = { values: GPUndarray; count: GPUndarray };

The supplied outputs must be C-contiguous, match their corresponding shape and dtype, and occupy disjoint ranges. An omitted output is allocated.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const { ndarray: nd, kernels } = wgpu.compute;
const values = nd.fromArray("f32", [4], [3, 8, 2, 9], { residency: "gpu" });
const flags = nd.fromArray("u32", [4], [0, 1, 0, 1], { residency: "gpu" });
const packed = kernels.compact(values, flags);
const [data, length] = await Promise.all([nd.toCPU(packed.values), nd.toCPU(packed.count)]);
console.log(data.data().subarray(0, Number(length.get()))); // [8, 9]
for (const array of [data, length, packed.values, packed.count, flags, values]) array.destroy();

See Also