warp.array#
- class warp.array(*args, **kwargs)[source]#
A fixed-size multi-dimensional array containing values of the same type.
- dtype#
The data type of the array.
- Type:
DType
- strides#
Number of bytes in each dimension between successive elements of the array.
- deleter#
A function to be called when the array is deleted, taking two arguments: pointer and size. If
None, then no function is called.
- __init__(
- data=None,
- dtype=Any,
- shape=None,
- strides=None,
- ptr=None,
- capacity=None,
- device=None,
- pinned=False,
- copy=True,
- deleter=None,
- ndim=None,
- grad=None,
- requires_grad=False,
Constructs a new Warp array object
When the
dataargument is a valid list, tuple, or ndarray the array will be constructed from this object’s data. For objects that are not stored sequentially in memory (e.g.: a list), then the data will first be flattened before being transferred to the memory space given by device.The second construction path occurs when the
ptrargument is a non-zero uint64 value representing the start address in memory where existing array data resides, e.g.: from an external or C-library. The memory allocation should reside on the same device given by the device argument, and the user should set the length and dtype parameter appropriately.If neither
datanorptrare specified, theshapeargument is checked next. This construction path can be used to create new uninitialized arrays, but users are encouraged to callwp.empty(),wp.zeros(), orwp.full()instead to create new arrays.If none of the above arguments are specified, a simple type annotation is constructed. This is used when annotating kernel arguments or struct members (e.g.,``arr: wp.array(dtype=float)``). In this case, only
dtypeandndimare taken into account and no memory is allocated for the array.- Parameters:
data (list | tuple | ndarray[tuple[Any, ...], dtype[_ScalarT]] | None) – An object to construct the array from, can be a Tuple, List, or generally any type convertible to an np.array
dtype (Any) – One of the available data types, such as
warp.float32,warp.mat33, or a custom struct. If dtype isAnyand data is an ndarray, then it will be inferred from the array data typeshape (int | tuple[int, ...] | list[int] | None) – Dimensions of the array
strides (tuple[int, ...] | None) – Number of bytes in each dimension between successive elements of the array
ptr (int | None) – Address of an external memory address to alias (
datashould beNone)capacity (int | None) – Maximum size in bytes of the
ptrallocation (datashould beNone)copy (bool) – Whether the incoming
datawill be copied or aliased. Aliasing requires that the incomingdataalready lives on thedevicespecified and the data types match.deleter (Callable[[int, int], None] | None) – Function to be called when the array is deleted, taking two arguments: pointer and size
requires_grad (bool) – Whether or not gradients will be tracked for this array, see
warp.Tapefor detailsgrad (array | None) – The array in which to accumulate gradients in the backward pass. If
Noneandrequires_gradisTrue, then a gradient array will be allocated automatically.pinned (bool) – Whether to allocate pinned host memory, which allows asynchronous host–device transfers (only applicable with
device="cpu")ndim (int | None)
Methods
__init__([data, dtype, shape, strides, ptr, ...])Constructs a new Warp array object
assign(src)Wraps
srcin anwarp.arrayif it is not already one and copies the contents toself.Returns a contiguous array with this array's data.
cptr()Return a ctypes cast of the array address.
fill_(value)Set all array entries to value
flatten()Returns a zero-copy view of the array collapsed to 1-D.
Return an IPC handle of the array as a 64-byte
bytesobjectlist()Returns a flattened list of items in the array as a Python list.
Resets this array's read flag
Marks this array as having been read from in a kernel or recorded function on the tape.
mark_write(**kwargs)Detect if we are writing to an array that has already been read from
numpy()Converts the array to a
numpy.ndarray(aliasing memory through the array interface protocol) If the array is on the GPU, a synchronous device-to-host copy (on the CUDA default stream) will be automatically performed to ensure that any outstanding work is completed.reshape(shape)Returns a reshaped array.
to(device[, requires_grad])Returns a Warp array with this array's data moved to the specified device, no-op if already on device.
transpose([axes])Returns an zero-copy view of the array with axes transposed.
view(dtype)Returns a zero-copy view of this array's memory with a different data type.
zero_()Zeroes-out the array entries.
Attributes
- mark_read()[source]#
Marks this array as having been read from in a kernel or recorded function on the tape.
- fill_(value)[source]#
Set all array entries to value
- Parameters:
value – The value to set every array entry to. Must be convertible to the array’s
dtype.- Raises:
ValueError – If value cannot be converted to the array’s
dtype.
Examples
fill_()can take lists or other sequences when filling arrays of vectors or matrices.>>> arr = wp.zeros(2, dtype=wp.mat22) >>> arr.numpy() array([[[0., 0.], [0., 0.]], [[0., 0.], [0., 0.]]], dtype=float32) >>> arr.fill_([[1, 2], [3, 4]]) >>> arr.numpy() array([[[1., 2.], [3., 4.]], [[1., 2.], [3., 4.]]], dtype=float32)
- assign(src)[source]#
Wraps
srcin anwarp.arrayif it is not already one and copies the contents toself.
- numpy()[source]#
Converts the array to a
numpy.ndarray(aliasing memory through the array interface protocol) If the array is on the GPU, a synchronous device-to-host copy (on the CUDA default stream) will be automatically performed to ensure that any outstanding work is completed.
- cptr()[source]#
Return a ctypes cast of the array address.
Notes:
Only CPU arrays support this method.
The array must be contiguous.
Accesses to this object are not bounds checked.
For
float16types, a pointer to the internaluint16representation is returned.
- to(device, requires_grad=None)[source]#
Returns a Warp array with this array’s data moved to the specified device, no-op if already on device.
- flatten()[source]#
Returns a zero-copy view of the array collapsed to 1-D. Only supported for contiguous arrays.
- reshape(shape)[source]#
Returns a reshaped array. Only supported for contiguous arrays.
- Parameters:
shape – An int or tuple of ints specifying the shape of the returned array.
- view(dtype)[source]#
Returns a zero-copy view of this array’s memory with a different data type. The array’s contents are not modified in any way.
- Parameters:
dtype – The desired data type.
If
dtypehas the same byte size as the array’sdtype, the result is an array with the same shape and strides and the newdtype.This method can also be used to convert between vector, matrix, and scalar types, in which case the resulting shape and strides are adjusted as needed.
Example
Simple views (same dtype size):
# view an array of signed integers as unsigned integers ai = wp.ones(10, dtype=wp.int32) au = ai.view(wp.uint32) # view an array of vec4 as quat or mat22 av = wp.ones(10, dtype=wp.vec4) aq = av.view(wp.quat) am = av.view(wp.mat22) # view 4-byte vectors as a single unsigned integer rgba = wp.ones(10, dtype=wp.vec4ub) color = rgba.view(wp.uint32)
Vector/matrix to scalar views:
av = wp.ones(10, dtype=wp.vec4) am = wp.ones(10, dtype=wp.mat33) avf = av.view(float) # shape (10, 4) amf = am.view(float) # shape (10, 3, 3)
Scalar to vector/matrix views:
avf = wp.ones((10, 4), dtype=float) amf = wp.ones((10, 3, 3), dtype=float) av = avf.view(wp.vec4) # shape (10,) am = amf.view(wp.mat33) # shape (10,)
- contiguous()[source]#
Returns a contiguous array with this array’s data. No-op if array is already contiguous.
- transpose(axes=None)[source]#
Returns an zero-copy view of the array with axes transposed.
Note: The transpose operation will return an array with a non-contiguous access pattern.
- Parameters:
axes (optional) – Specifies the how the axes are permuted. If not specified, the axes order will be reversed.
- ipc_handle()[source]#
Return an IPC handle of the array as a 64-byte
bytesobjectfrom_ipc_handle()can be used with this handle in another process to obtain aarraythat shares the same underlying memory allocation.IPC is currently only supported on Linux. Additionally, IPC is only supported for arrays allocated using the default memory allocator.
Eventobjects created with theinterprocess=Trueargument may similarly be shared between processes to synchronize GPU work.Example
Temporarily using the default memory allocator to allocate an array and get its IPC handle:
with wp.ScopedMempool("cuda:0", False): test_array = wp.full(1024, value=42.0, dtype=wp.float32, device="cuda:0") ipc_handle = test_array.ipc_handle()
- Raises:
RuntimeError – The array is not associated with a CUDA device.
RuntimeError – The CUDA device does not appear to support IPC.
RuntimeError – The array was allocated using the mempool memory allocator.
- Return type: