Skip to content

compute.ndarray.empty

Summary

compute.ndarray.empty allocates storage with the requested layout. Use compute.ndarray.zeros when the initial contents must be zero. Both default to WebAssembly memory and can allocate on the compute device.

Syntax

empty(dtype: DType, layout: NdLayoutDescriptor, options: NdarrayCreateOptions & { residency: "gpu" }): GPUndarray
empty(dtype: DType, layout: NdLayoutDescriptor, options?: NdarrayCreateOptions & { residency?: "cpu" }): CPUndarray
zeros(dtype: DType, layout: NdLayoutDescriptor, options: NdarrayCreateOptions & { residency: "gpu" }): GPUndarray
zeros(dtype: DType, layout: NdLayoutDescriptor, options?: NdarrayCreateOptions & { residency?: "cpu" }): CPUndarray
empty(dtype: DType, layout: NdLayoutDescriptor, options?: NdarrayCreateOptions): CPUndarray | GPUndarray
zeros(dtype: DType, layout: NdLayoutDescriptor, options?: NdarrayCreateOptions): CPUndarray | GPUndarray
const a = wgpu.compute.ndarray.zeros("f32", { shape: [3, 4] }, { residency: "gpu" });

Parameters

Name Type Required Description
dtype DType Yes Element representation, including real and complex types.
layout NdLayoutDescriptor Yes Shape, optional byte strides, and optional byte offset. See the layout rules below.
options NdarrayCreateOptions No Residency and GPU buffer creation flags.

Returns

CPUndarray | GPUndarray - Owned array. Call destroy() when finished.

Type Details

type NdLayoutDescriptor = {
    shape: ReadonlyArray<number>;
    stridesBytes?: ReadonlyArray<number>;
    offsetBytes?: number;
};

type NdarrayGPUOptions = {
    label?: string;
    copySrc?: boolean;
    copyDst?: boolean;
    usage?: GPUBufferUsageFlags;
};

type NdarrayCreateOptions = NdarrayGPUOptions & { residency?: NdarrayResidency };

The shape contains non-negative integers that fit in u32. An empty shape denotes one scalar. Custom strides must match the rank, fit in signed 32-bit integers and be multiples of the element size. Strides default to C order. The offset defaults to zero and must be a non-negative multiple of the element size. Choose the offset so negative strides stay inside the backing range. The backing byte count must fit in u32 and in the available memory.

residency defaults to "cpu". Buffer options require "gpu". On the GPU, both copy flags default to true, label is optional, and usage adds flags to storage and the enabled copy flags.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const a = wgpu.compute.ndarray.zeros("f32", { shape: [2, 2] });
a.set(1, 0, 1);
console.log(a.data());
a.destroy();

See Also