Interoperability#

Warp interoperates with other Python-based frameworks through standard interface protocols. Warp accepts external arrays in kernel launches as long as they implement the __array__, __array_interface__, or __cuda_array_interface__ protocols. This works with NumPy, CuPy, PyTorch, JAX, and Paddle.

Guides in this section#

  • PyTorch: Share arrays and streams, integrate autograd, and call Warp kernels from custom operators.

  • JAX: Convert arrays, call Warp kernels through FFI, and use Warp with JAX transformations and distributed computation.

  • Array function overrides: Let array subclasses and wrappers intercept supported Warp host APIs, such as wp.launch and wp.copy, through __warp_function__.

  • cuTile Python: Call Warp functions from kernels written in cuTile Python through an experimental foreign-function bridge.

Quick Reference#

Framework

Conversion

Zero-copy

Gradient-aware

NumPy

wp.from_numpy / array.numpy()

CPU only

No

PyTorch

wp.from_torch / wp.to_torch

Yes

Yes

JAX

wp.from_jax / wp.to_jax

Yes

Via jax_kernel

Paddle

wp.from_paddle / wp.to_paddle

Yes

Yes

CuPy / Numba

__cuda_array_interface__ protocol

Yes

No

DLPack

wp.from_dlpack / framework.from_dlpack

Yes

No

For full framework coverage, see:

Paddle is documented inline below. NumPy, CuPy, Numba, and DLPack interop is protocol-level and covered in the sections that follow.

Pass Arrays Directly#

External objects that implement __array_interface__ (CPU) or __cuda_array_interface__ (GPU) can be passed to concrete regular-array parameters of wp.launch without calling a conversion function. This is the fastest on-ramp for most use cases.

Warp arrays and their subclasses use their native Warp descriptor when launched. Warp checks their native family, dtype, and ndim instead of reinterpreting an inherited or overridden array interface. Their gradient pointer and retain_grad flag follow the parent’s behavior. Code that previously reached the external-interface fallback for a Warp subclass must account for these changes:

  • Native gradient pointers and flags are preserved. Tape gradients for overwritten outputs or in-place writes can therefore change to match the parent array’s behavior, and retain_grad=True is honored.

  • Native storage is used even when a subclass overrides its array interface. The kernel no longer receives storage, a dtype, or a shape supplied by that alternate interface. Struct and bfloat16 arrays use their native dtype support without requiring an array-interface representation.

  • Family, dtype, and dimensionality mismatches are rejected through normal Warp array validation. Use array.view() for a supported dtype reinterpretation, or array.reshape() and array.flatten() to change shape explicitly. Use a typed Warp array and a conversion such as warp.utils.array_cast() when element values need to be converted rather than reinterpreted. Explicit conversion expresses the intended element layout; it does not reproduce accidental strided reads from a rank mismatch. For example, float32 data of shape (4, 3) can use a.view(wp.vec3) for a wp.array[wp.vec3] parameter. A vec3 array can use a.view(wp.float32).flatten() for a one-dimensional scalar parameter, while a two-dimensional scalar array can use a.flatten().

  • Device-access validation follows warp.config.launch_array_access_mode. The default RELAXED mode performs no pre-launch access checks; CHECKED diagnoses known-invalid access and warns when access cannot be verified, while STRICT requires arrays to be allocated on the launch device. See Checked Launch Validation. Wrong-device storage that the interface path previously rejected can now reach a kernel unchecked in RELAXED mode, just as for a parent array. Move arrays to the launch device or select an appropriate validation mode.

  • The subclass’s __ctype__() method is now called by concrete launches. Overrides must describe the object’s own storage and preserve the native descriptor contract. Fully initialize the parent and allow its descriptor cache and bookkeeping writes; a shell that only forwards public attributes through an array interface is insufficient.

  • Classification uses actual inheritance. A weakref.proxy or a wrapper whose __class__ property advertises a Warp class is not a Warp array at native-family boundaries. Pass the referenced Warp array for struct fields, indexed/strided copies, and explicit adjoint arguments. Its separate external array interface can still be used for concrete regular-array launch parameters.

  • Recorded commands from wp.launch(..., record_cmd=True) retain arguments. Manually constructing wp.Launch does not retain the incidental owner reference previously supplied by the interface fallback; use recorded commands or keep the arrays alive explicitly.

A separate, non-Warp object that owns or references an array and exposes an array interface continues to use the external-interface path for concrete regular-array parameters. Keep its storage owner alive according to that protocol’s requirements. CPU array.numpy() and np.asarray still use the array interface for interface-compatible dtypes. CUDA array.numpy() copies native Warp storage instead.

import numpy as np
import warp as wp

@wp.kernel
def saxpy(x: wp.array[float], y: wp.array[float], a: float):
    i = wp.tid()
    y[i] = a * x[i] + y[i]

x = np.arange(n, dtype=np.float32)
y = np.ones(n, dtype=np.float32)

wp.launch(saxpy, dim=n, inputs=[x, y, 1.0], device="cpu")

On CUDA, the same pattern works with CuPy, PyTorch, or any framework that exposes __cuda_array_interface__:

import cupy as cp

with cp.cuda.Device(0):
    x = cp.arange(n, dtype=cp.float32)
    y = cp.ones(n, dtype=cp.float32)

wp.launch(saxpy, dim=n, inputs=[x, y, 1.0], device="cuda:0")

When passing CUDA arrays, ensure the device on which the arrays reside matches the device on which the kernel is launched.

Object Handle Arrays#

External integer arrays do not carry Warp object-reference metadata. When sharing Mesh, Volume, Bvh, or HashGrid IDs, create a Warp array with dtype=wp.handle or an explicit array.view(wp.handle) before passing it to a kernel annotated with wp.array[wp.handle].

For example, construct a handle array from NumPy data with an explicit dtype:

# Keep the Mesh objects alive while these IDs are used.
numpy_ids = np.array([mesh.id for mesh in meshes], dtype=np.uint64)
mesh_ids = wp.array(numpy_ids, dtype=wp.handle, device="cpu")

For an existing Warp array of 64-bit integer IDs, mesh_ids = integer_ids.view(wp.handle) returns a zero-copy view; the original array keeps its dtype.

Warp’s NumPy imports accept dtype=wp.handle directly. PyTorch, JAX, Paddle, and DLPack imports require an integer dtype followed by a handle view. The table uses source for the external array and handles for a Warp array with dtype=wp.handle. Use np.uint64 storage for the NumPy row and signed 64-bit integer storage for the other rows. Call jax.config.update("jax_enable_x64", True) before creating JAX arrays to preserve all 64 bits of each ID. The integer views reinterpret the bits without a numeric cast.

Interface

Import into Warp

Export from Warp

NumPy

wp.from_numpy(source, dtype=wp.handle) or wp.array(source, dtype=wp.handle, device="cpu")

handles.numpy()

PyTorch

wp.from_torch(source, dtype=wp.int64).view(wp.handle)

wp.to_torch(handles.view(wp.int64))

JAX

wp.from_jax(source, dtype=wp.int64).view(wp.handle)

wp.to_jax(handles.view(wp.int64))

Paddle

wp.from_paddle(source, dtype=wp.int64).view(wp.handle)

wp.to_paddle(handles.view(wp.int64))

DLPack

wp.from_dlpack(source, dtype=wp.int64).view(wp.handle)

wp.to_dlpack(handles.view(wp.int64))

The DLPack export returns a single-use capsule for the receiving framework’s consumer. Consult each converter’s dtype, device, and ownership rules. Direct handle support in the converters is tracked in GH-2292.

External integer storage does not identify referenced objects or keep them alive, and sharing an ID does not make it valid in another process. See Object Handles for kernel and struct declarations and API Capture: Saving and Loading Graphs for the mesh-only resource serialization currently supported by API Capture.

NumPy#

Warp arrays may be converted to a NumPy array through the array.numpy() method. When the Warp array lives on the cpu device, this returns a zero-copy view onto the underlying Warp allocation. When the array lives on a cuda device, this method synchronously copies the data to a temporary CPU allocation and returns a NumPy view of that allocation.

Warp CPU arrays also implement the __array_interface__ protocol, so NumPy can create zero-copy views of them directly:

w = wp.array([1.0, 2.0, 3.0], dtype=float, device="cpu")
a = np.asarray(w)
print(a)
[1. 2. 3.]

Warp does not support implicit NumPy conversion of arrays on CUDA devices, such as passing them to np.asarray(). Call array.numpy() explicitly to obtain a NumPy array.

Scalar data types#

Use wp.dtype_to_numpy() to convert Warp scalar types to NumPy dtype specifications. Explicit conversion ensures the intended NumPy dtype is selected across both older and newer NumPy versions:

import numpy as np
import warp as wp

indices = np.zeros(100, dtype=wp.dtype_to_numpy(wp.int32))
values = np.full(100, 1.25, dtype=wp.dtype_to_numpy(wp.float32))
assert indices.dtype == np.dtype(np.int32)
assert values.dtype == np.dtype(np.float32)

The converted dtype can also be used with np.dtype(), astype(), and structured dtype fields. Warp scalar values require an explicit dtype when constructing NumPy arrays.

Note

Warp’s Boolean, signed and unsigned integer, and float16/float32/float64 types expose their equivalent NumPy dtype through the __numpy_dtype__ attribute. NumPy 2.4 and later recognize this attribute, avoiding object-dtype allocations and their performance overhead when a Warp scalar type is passed directly as a dtype specification. Older NumPy versions still select the object dtype in that case. Continue using wp.dtype_to_numpy() for consistent behavior across NumPy versions. This protocol does not change dtype inference from Warp scalar values.

wp.bfloat16 does not expose __numpy_dtype__ because NumPy has no native bfloat16 dtype.

The existing wp.dtype_to_numpy(wp.bfloat16) mapping returns np.uint16 for raw storage. When initializing or filling arrays with this dtype, use values that are already encoded as bfloat16 bit patterns. To convert floating-point values to bfloat16, use wp.array([1.5], dtype=wp.bfloat16) or ml_dtypes.bfloat16 as the NumPy dtype.

To create Warp arrays from NumPy arrays, use warp.from_numpy() or pass the NumPy array as the data argument of the warp.array constructor directly.

CuPy / Numba#

Warp GPU arrays support the __cuda_array_interface__ protocol for sharing data with other Python GPU frameworks. This allows frameworks like CuPy and Numba to use Warp GPU arrays directly.

Likewise, Warp arrays can be created from any object that exposes the __cuda_array_interface__. Such objects can also be passed to Warp kernels directly without creating a Warp array object.

Paddle#

Warp provides helper functions to convert arrays to/from Paddle:

w = wp.array([1.0, 2.0, 3.0], dtype=float, device="cpu")

# convert to Paddle tensor
t = wp.to_paddle(w)

# convert from Paddle tensor
w = wp.from_paddle(t)

These helper functions convert Warp arrays to/from Paddle tensors without copying the underlying data. Gradient arrays and tensors are converted to/from Paddle autograd tensors, allowing the use of Warp arrays in Paddle autograd computations.

To convert a Paddle CUDA stream to a Warp CUDA stream and vice versa, Warp provides:

Example: Optimization using warp.to_paddle()#

Less code is needed when we declare the optimization variables directly in Warp and use warp.to_paddle() to convert them to Paddle tensors. The following example minimizes a loss function over an array of 2D points written in Warp, with a single wp.to_paddle call supplying Adam with the optimization variables:

import warp as wp
import numpy as np
import paddle

@wp.kernel()
def loss(xs: wp.array2d[float], l: wp.array[float]):
    tid = wp.tid()
    wp.atomic_add(l, 0, xs[tid, 0] ** 2.0 + xs[tid, 1] ** 2.0)

# initialize the optimization variables in Warp
xs = wp.array(np.random.randn(100, 2), dtype=wp.float32, requires_grad=True)
l = wp.zeros(1, dtype=wp.float32, requires_grad=True)
# just a single wp.to_paddle call is needed, Adam optimizes using the Warp array gradients
opt = paddle.optimizer.Adam(learning_rate=0.1, parameters=[wp.to_paddle(xs)])

tape = wp.Tape()
with tape:
    wp.launch(loss, dim=len(xs), inputs=[xs], outputs=[l], device=xs.device)

for i in range(500):
    tape.zero()
    tape.backward(loss=l)
    opt.step()

    l.zero_()
    wp.launch(loss, dim=len(xs), inputs=[xs], outputs=[l], device=xs.device)
    print(f"{i}\tloss: {l.numpy()[0]}")

Note

Paddle follows the same performance-tuning pattern as PyTorch. See the “Performance Tuning” section of PyTorch Interoperability for return_ctype, direct tensor passing, and reuse-don’t-reconvert guidance.

DLPack#

Warp supports the DLPack protocol from the Python Array API standard v2022.12. See the Python Specification for DLPack.

Use wp.from_dlpack to import an array from a library that supports DLPack, such as PyTorch or JAX:

warp_array = wp.from_dlpack(external_array)

If the exporting library allows external writes to the exported buffer, in-place changes are visible through both views once the accesses are ordered. Otherwise, treat the imported array as read-only and use wp.clone() if you need a writable copy.

On CUDA, Warp passes its current stream on the source array’s device to the array’s __dlpack__() method. The exporting library makes later work on that Warp stream wait for its earlier work on the array.

Use wp.ScopedStream to select the Warp stream for the import and the work that uses the array. For work on a different Warp stream, add a wait for the stream used during import.

Warp represents vector and matrix components as trailing scalar dimensions in DLPack. To import a vector or matrix dtype, the trailing dimensions must match the component shape and be contiguous in row-major order. The outer dimensions can be strided.

The following example uses a Warp array as the DLPack source. It imports every other row of a CUDA array as a wp.vec3 value and scales the points in place.

@wp.kernel
def scale_points(points: wp.array[wp.vec3]):
    i = wp.tid()
    points[i] = 2.0 * points[i]

device = wp.get_device("cuda:0")
warp_stream = wp.Stream(device)
with wp.ScopedStream(warp_stream):
    source = wp.full((8, 3), 1.0, device=device)[::2]
    points = wp.from_dlpack(source, dtype=wp.vec3)
    wp.launch(scale_points, dim=points.shape[0], inputs=[points], device=device)
    print(f"Shape: {points.shape}, strides: {points.strides}")
    print(source.numpy())
Shape: (4,), strides: (24,)
[[2. 2. 2.]
 [2. 2. 2.]
 [2. 2. 2.]
 [2. 2. 2.]]

The (4,) Warp array keeps the 24-byte row stride of the (4, 3) source array. The kernel writes to the exported buffer, so reading the source array on the same stream returns the updated values.

To export a Warp array, pass it directly to the other library’s from_dlpack() function:

jax_array = jax.dlpack.from_dlpack(warp_array)
torch_tensor = torch.utils.dlpack.from_dlpack(warp_array)
paddle_tensor = paddle.utils.dlpack.from_dlpack(warp_array)

For an array on a CUDA device, the importing library can pass the CUDA stream it will use for the array to Warp’s __dlpack__() method. Use wp.ScopedStream around the other library’s from_dlpack() call to select the Warp stream with the earlier work on the array. When the streams differ, Warp records a CUDA event on its current stream for the array’s device. Warp queues a wait for that event on the importing library’s CUDA stream. Order later Warp reads after writes queued by the importing library. Order later Warp writes after both reads and writes queued by that library.

For libraries that use the older capsule API, call the exporting library’s to_dlpack() function and pass the capsule to the importer:

warp_array1 = wp.from_dlpack(torch.utils.dlpack.to_dlpack(torch_tensor))
warp_array2 = wp.from_dlpack(paddle.utils.dlpack.to_dlpack(paddle_tensor))

torch_tensor = torch.utils.dlpack.from_dlpack(wp.to_dlpack(warp_array))
paddle_tensor = paddle.utils.dlpack.from_dlpack(wp.to_dlpack(warp_array))

Each capsule can be consumed once. The import keeps the exported allocation alive after the source object goes out of scope. Exchanging a capsule on CUDA leaves stream ordering to the caller. Queue dependent accesses on the same CUDA stream or order them with a stream wait.

DLPack exchanges array values. To share gradient buffers, convert them separately or use a framework-specific converter such as warp.to_torch() or warp.to_paddle().