.. _cutile-interop:
cuTile Python Interoperability
==============================
.. versionadded:: 1.20.0
.. admonition:: Experimental
The cuTile interop API is experimental and may change without a formal deprecation cycle.
It builds on cuTile preview interfaces that may change between CUDA Toolkit and cuTile Python releases.
Introduction
------------
:func:`warp.experimental.cutile.export_func` makes a ``@wp.func`` callable from kernels written in
`cuTile Python `_.
Inside a :obj:`@ct.kernel `, calling the exported function on tiles
runs the Warp function once per tile element and returns the results as a tile.
The Warp function can use Warp's :doc:`built-in functions `,
such as mesh and BVH queries, volume sampling, and noise.
`Supported Types and Limitations`_ lists the exceptions.
For cuTile users, the bridge adds per-element operations that cuTile has no equivalent for,
such as signed distances, ray casts, and closest points against a triangle mesh.
A typical use is computing network inputs or training labels inside the tile kernel that consumes them,
for example signed distances to a mesh.
For Warp users, Warp's own :doc:`tile programming model `
already combines block-cooperative tile operations with the rest of Warp's built-in functions in one kernel,
and its tile matrix multiplies run on Tensor Cores.
Warp tiles also support automatic differentiation, CPU execution, and Turing GPUs,
and they need no compiler beyond Warp itself.
Kernels that use this bridge are forward-only, need a compute capability 8.0 or newer GPU,
and need the CUDA Toolkit 13.5 ``tileiras`` compiler (see `Requirements`_).
Prefer Warp tiles for new Warp code,
and use this bridge when the tile code is written in cuTile Python,
for example to call Warp from an existing cuTile kernel.
See the :doc:`API reference ` for the full signatures.
Requirements
------------
* A GPU and driver supported by cuTile Python: compute capability 8.0 or newer and an R580 or newer driver
(see the cuTile :ref:`prerequisites `).
* A CUDA 13 build of Warp, such as the default PyPI wheel.
* cuTile Python 1.8.1 or newer and the ``tileiras`` compiler from CUDA Toolkit 13.5.
The ``cutile`` extra installs cuTile Python and ``tileiras`` along with Warp:
.. code-block:: console
pip install "warp-lang[cutile]"
To install the same packages without the extra:
.. code-block:: console
pip install warp-lang "cuda-tile-preview>=1.8.1" "nvidia-cuda-tileiras==13.5.*" "nvidia-cuda-nvcc==13.5.*" "nvidia-nvvm==13.5.*" "nvidia-cuda-crt==13.5.*" "nvidia-nvjitlink>=13.5,<14"
``cuda-tile-preview`` provides the preview interface that the bridge uses and installs the matching ``cuda-tile``.
The ``nvidia-*`` packages provide ``tileiras`` and the CUDA 13.5 components it runs,
such as ``ptxas``, libNVVM, and nvJitLink.
If PyTorch or JAX share the environment:
* Install the ``nvidia-*`` packages above rather than ``cuda-tile[tileiras]``.
That extra installs ``tileiras`` through the ``cuda-toolkit`` metapackage.
PyTorch's CUDA 13 wheels pin that metapackage to an earlier release,
so the install either fails to resolve or gets a ``tileiras`` older than 13.5.
* Install JAX into the same environment as cuTile Python.
cuTile Python looks for the pip ``tileiras`` only in the first ``nvidia/cu13`` directory on the Python path,
so a layered environment such as ``uv run --with "jax[cuda13]"`` can hide it.
A CUDA Toolkit 13.5 installation can supply ``tileiras`` instead
when no ``nvidia-cuda-tileiras`` package is installed
and the toolkit's ``bin`` directory comes before other CUDA toolkits on ``PATH``.
Warp and cuTile Python both use a pip-installed ``tileiras`` of any release before one on ``PATH``.
Quick Start
-----------
The following example computes the signed distance from points to a triangle mesh inside a cuTile kernel,
using a BVH closest-point query that cuTile has no operation for:
.. code:: python
import cuda.tile as ct
import numpy as np
import warp as wp
import warp.experimental.cutile as wpct
TILE_SIZE = 128
@wp.func
def mesh_sdf(mesh_id: wp.handle, p: wp.vec3) -> float:
query = wp.mesh_query_point_sign_normal(mesh_id, p, 1.0e6)
closest = wp.mesh_eval_position(mesh_id, query.face, query.u, query.v)
return query.sign * wp.length(p - closest)
wp_mesh_sdf = wpct.export_func(mesh_sdf)
@ct.kernel
def mesh_sdf_cutile_kernel(mesh_id: ct.Constant[int], points, sdf):
bid = ct.bid(0)
point_tile = ct.load(points, (bid, 0), shape=(TILE_SIZE, 4))
distances = wp_mesh_sdf(mesh_id, ct.reshape(point_tile, (TILE_SIZE * 4,)))
ct.store(sdf, (bid,), distances)
# a closed triangle mesh: the unit tetrahedron
mesh = wp.Mesh(
points=wp.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=wp.vec3),
indices=wp.array([0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3], dtype=int),
)
num_points = 1024
rng = np.random.default_rng(42)
points = wp.array(rng.uniform(-0.5, 1.5, (num_points, 4)), dtype=wp.float32) # x, y, z, unused
sdf = wp.empty(num_points, dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream, (num_points // TILE_SIZE, 1, 1), mesh_sdf_cutile_kernel, (mesh.id, points, sdf)
)
print(sdf.numpy()[:4])
Each call to ``wp_mesh_sdf`` runs ``mesh_sdf`` once for each of the ``TILE_SIZE`` points in the tile
and returns a tile of ``TILE_SIZE`` distances.
The mesh id is a single value shared by every point.
It is a :data:`ct.Constant[int] ` kernel parameter
because the id is 64-bit and cuTile's runtime scalar parameters are 32-bit.
A ``wp.vec3`` operand takes four elements of the tile per point, so the points are stored padded to four components.
:func:`ct.launch() ` accepts Warp arrays directly,
and launching on Warp's stream orders the kernel with other Warp work.
`Calling Convention`_ gives the rules for every parameter type.
For a larger program, :github:`example_cutile_neural_sdf.py `
trains a neural signed-distance field of the Stanford bunny.
Each training step launches one cuTile kernel that computes ground-truth distances with the same mesh query,
evaluates the MLP with cuTile matrix multiplies, and reduces the loss.
Calling Convention
------------------
Call :func:`~warp.experimental.cutile.export_func` on each ``@wp.func`` that a cuTile kernel calls,
and call the object it returns inside the kernel with one argument per Warp parameter.
A call takes tiles of ``TILE_SIZE`` elements, runs the Warp function once per element,
and returns the ``TILE_SIZE`` results as one tile.
By default the invocations are independent, like the threads of a :func:`wp.launch() `;
`Block-Cooperative Functions`_ describes functions that use Warp's block-cooperative tile operations.
The examples on the rest of this page continue the Quick Start.
They reuse its imports, ``TILE_SIZE``, ``rng``, ``mesh``, ``num_points``, and ``points``,
and each one runs when appended to it.
This one displaces each point by procedural noise:
.. code:: python
@wp.func
def noise_displacement(p: wp.vec3, frequency: float, amplitude: float) -> float:
return amplitude * wp.noise(wp.rand_init(42), p * frequency)
wp_noise_displacement = wpct.export_func(noise_displacement)
@ct.kernel
def displacement_cutile_kernel(points, amplitudes, displacement):
bid = ct.bid(0)
point_tile = ct.load(points, (bid, 0), shape=(TILE_SIZE, 4))
amplitude_tile = ct.load(amplitudes, (bid,), shape=(TILE_SIZE,))
result = wp_noise_displacement(
ct.reshape(point_tile, (TILE_SIZE * 4,)), frequency=4.0, amplitude=amplitude_tile
)
ct.store(displacement, (bid,), result)
amplitudes = wp.array(rng.uniform(0.0, 0.1, num_points), dtype=wp.float32)
displacement = wp.empty(num_points, dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream,
(num_points // TILE_SIZE, 1, 1),
displacement_cutile_kernel,
(points, amplitudes, displacement),
)
Tile Length
^^^^^^^^^^^
``TILE_SIZE`` is the number of elements in the tiles passed to a call,
and so the number of times the Warp function runs.
Any power of two from 32 to 1024 works, and calls in the same kernel can use different lengths;
`When to Set num_worker_warps`_ covers the cases that fix or bound it.
The tile length is independent of the kernel's ``num_worker_warps``:
cuTile distributes the invocations over however many worker threads the kernel has.
This kernel calls the same function on 128 points and then on 32:
.. code:: python
@ct.kernel
def mixed_lengths_cutile_kernel(points, displacement_128, displacement_32):
point_tile = ct.load(points, (0, 0), shape=(128, 4))
ct.store(displacement_128, (0,), wp_noise_displacement(ct.reshape(point_tile, (128 * 4,)), 4.0, 0.1))
point_tile = ct.load(points, (0, 0), shape=(32, 4))
ct.store(displacement_32, (0,), wp_noise_displacement(ct.reshape(point_tile, (32 * 4,)), 4.0, 0.1))
displacement_128 = wp.empty(128, dtype=wp.float32)
displacement_32 = wp.empty(32, dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream, (1, 1, 1), mixed_lengths_cutile_kernel, (points, displacement_128, displacement_32)
)
Operands
^^^^^^^^
Each argument is either *per-invocation* or *shared*, and the call tells the two apart by what you pass.
A per-invocation argument is a rank-1 tile with one value per invocation: shape ``(TILE_SIZE,)`` for a scalar,
or ``(TILE_SIZE * width,)`` for a vector, matrix, quaternion, or transform,
where ``width`` is the component count rounded up to a power of two (``wp.vec3`` becomes 4).
Every per-invocation argument in one call must describe the same number of invocations,
so their tiles share ``TILE_SIZE``; a mismatch is reported when the kernel is traced.
A shared argument is one value that every invocation reads.
For a scalar, pass a plain Python number, a ``ct.Constant`` kernel parameter such as ``mesh_id`` in the Quick Start,
or a runtime kernel parameter.
For a vector, matrix, or struct, pass one ``(width,)`` tile.
Arrays are always shared; structs and opaque ids usually are.
In ``displacement_cutile_kernel``, the point and amplitude tiles are per-invocation,
and ``frequency=4.0`` is shared.
Get the ``width`` factor right for vector, matrix, quaternion, and transform operands.
A ``wp.vec3`` operand for 128 invocations must be a ``(512,)`` tile (128 × 4).
A ``(128,)`` tile passed by mistake is read as 32 invocations of 4 components each (128 = 32 × 4).
Unless a scalar operand fixes the tile length at 128, the call then runs 32 times without an error.
A length that is not a supported tile length times ``width`` raises an error when the kernel is traced.
Arguments are passed positionally or by Warp parameter name.
When cuTile traces the kernel, it reports call-site mistakes
such as a wrong rank, tile length, or element type, or a value of the wrong kind.
The ``StaticAssertionError`` names the function and the parameter.
Operands by Parameter Type
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. list-table::
:header-rows: 1
:widths: 35 65
* - Warp parameter type
- What to pass
* - Scalar (``int8`` ... ``uint64``, ``float32``, ``float64``)
- A ``(TILE_SIZE,)`` tile, or a plain number to share one value
* - Vector / matrix / quaternion / transform
- A flat ``(TILE_SIZE * width,)`` tile, or a ``(width,)`` tile to share one value
* - ``@wp.struct`` struct
- An ``int32`` tile of the struct's padded bytes from :func:`~warp.experimental.cutile.encode_struct`:
``(words,)`` to share one struct (the usual case), or ``(TILE_SIZE * words,)`` per invocation,
where ``words`` is the length of the array ``encode_struct`` returns
* - ``wp.array``
- The ``(address, size, ...)`` tuple of plain values from :func:`~warp.experimental.cutile.array_pointer_args`;
always shared
* - Opaque ids (``wp.handle`` mesh, BVH, hash-grid, and volume ids)
- The id as a plain value, shared
The Quick Start passes an id, and ``displacement_cutile_kernel`` passes a vector and scalars.
This example shares one struct with every point:
.. code:: python
@wp.struct
class SphereFalloff:
center: wp.vec3
radius: float
@wp.func
def falloff_weight(falloff: SphereFalloff, p: wp.vec3) -> float:
return wp.max(1.0 - wp.length(p - falloff.center) / falloff.radius, 0.0)
wp_falloff_weight = wpct.export_func(falloff_weight)
falloff = SphereFalloff()
falloff.center = wp.vec3(0.5, 0.5, 0.5)
falloff.radius = 0.25
falloff_words = wp.array(wpct.encode_struct(falloff), dtype=wp.int32)
NUM_FALLOFF_WORDS = falloff_words.shape[0]
@ct.kernel
def falloff_weight_cutile_kernel(falloff_words, points, weights):
bid = ct.bid(0)
falloff_tile = ct.load(falloff_words, (0,), shape=(NUM_FALLOFF_WORDS,)) # one struct for every point
point_tile = ct.load(points, (bid, 0), shape=(TILE_SIZE, 4))
ct.store(weights, (bid,), wp_falloff_weight(falloff_tile, ct.reshape(point_tile, (TILE_SIZE * 4,))))
weights = wp.empty(num_points, dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream,
(num_points // TILE_SIZE, 1, 1),
falloff_weight_cutile_kernel,
(falloff_words, points, weights),
)
All tiles are rank-1, so multi-dimensional data is flattened with ``ct.reshape`` at the call site,
and host data for vectors and matrices is stored padded to ``width``.
When loading 64-bit ids or pointers from an array yourself, load them as ``int64`` tiles.
Tile IR has no unsigned dtypes, and the bits pass through unchanged.
Ids and array addresses passed as plain values must be ``ct.Constant[int]`` kernel parameters:
cuTile's runtime scalar parameters are 32-bit.
A constant specializes the kernel,
so cuTile compiles and caches a separate kernel variant for every distinct id or address.
Reuse meshes and arrays across launches where you can.
Small shared scalars such as a count or a weight may be ordinary runtime parameters.
A ``wp.array`` parameter is not copied into a tile.
The kernel passes the array's address and sizes to the Warp function as one tuple,
and the function reads, writes, and runs atomics on the array's memory in place.
Multidimensional arrays follow the same pattern
with one more size value per dimension (a ``wp.array2d`` parameter takes ``(ptr, rows, cols)``).
On the host, :func:`warp.experimental.cutile.array_pointer_args` supplies the address and size values:
.. code:: python
@wp.func
def gather_scale(data: wp.array[float], i: int, scale: float) -> float:
return data[i] * scale
wp_gather_scale = wpct.export_func(gather_scale)
@ct.kernel
def gather_scale_cutile_kernel(data_ptr: ct.Constant[int], data_len: ct.Constant[int], indices, gathered):
bid = ct.bid(0)
index_tile = ct.load(indices, (bid,), shape=(TILE_SIZE,))
ct.store(gathered, (bid,), wp_gather_scale((data_ptr, data_len), index_tile, 2.5)) # data[i] * 2.5
data = wp.array(np.arange(100), dtype=wp.float32)
indices = wp.array(rng.integers(0, 100, num_points), dtype=wp.int32)
gathered = wp.empty(num_points, dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream,
(num_points // TILE_SIZE, 1, 1),
gather_scale_cutile_kernel,
(*wpct.array_pointer_args(data), indices, gathered),
)
Return Value
^^^^^^^^^^^^
A call returns one tile: ``(TILE_SIZE,)`` for a scalar and ``(TILE_SIZE * width,)`` for a vector or matrix.
A struct comes back as an ``int32`` tile of shape ``(TILE_SIZE * words,)``,
where ``words`` is the length of the array :func:`encode_struct ` returns.
Each invocation's leading ``sizeof(struct)`` bytes hold the struct, and the rest are zero.
This function returns the closest point on the mesh as a ``wp.vec3``,
so the kernel reshapes the flat ``(TILE_SIZE * 4,)`` result before a 2-D store:
.. code:: python
@wp.func
def mesh_closest_point(mesh_id: wp.handle, p: wp.vec3) -> wp.vec3:
query = wp.mesh_query_point_no_sign(mesh_id, p, 1.0e6)
return wp.mesh_eval_position(mesh_id, query.face, query.u, query.v)
wp_mesh_closest_point = wpct.export_func(mesh_closest_point)
@ct.kernel
def closest_point_cutile_kernel(mesh_id: ct.Constant[int], points, closest_points):
bid = ct.bid(0)
point_tile = ct.load(points, (bid, 0), shape=(TILE_SIZE, 4))
closest_tile = wp_mesh_closest_point(mesh_id, ct.reshape(point_tile, (TILE_SIZE * 4,))) # (TILE_SIZE * 4,)
ct.store(closest_points, (bid, 0), ct.reshape(closest_tile, (TILE_SIZE, 4)))
closest_points = wp.empty((num_points, 4), dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream,
(num_points // TILE_SIZE, 1, 1),
closest_point_cutile_kernel,
(mesh.id, points, closest_points),
)
When to Set ``num_worker_warps``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A function exported with the default ``scope="thread"`` is built for every power-of-two tile length
from 32 to 1024, so each call site picks its length through the tiles it passes.
``num_worker_warps`` can usually stay at its default of 4.
It is the same quantity as the calling kernel's ``@ct.kernel(num_worker_warps=...)``.
Three cases need it set:
.. list-table::
:header-rows: 1
:widths: 40 60
* - Case
- What ``num_worker_warps`` does
* - A call passes only shared values, so no tile carries a length
- Sets how many invocations that call runs; it returns a ``(num_worker_warps * 32,)`` tile
* - ``scope="block"`` (see `Block-Cooperative Functions`_)
- Pins the block size baked into the cooperative code; must equal the calling kernel's ``num_worker_warps``
* - Iterator geometry queries in kernels with more than 8 worker warps (see `Iterator Queries`_)
- Sizes the traversal stacks; must be at least the calling kernel's ``num_worker_warps``
At block scope the exported function is built for the single tile length ``num_worker_warps * 32``.
A kernel whose ``num_worker_warps`` differs from the value passed to ``export_func``
fails to compile with a ``CompilerExecutionError`` from ``tileiras``.
The block-scope and iterator-query cases have examples in their own sections.
A call with only shared arguments runs ``num_worker_warps * 32`` invocations:
.. code:: python
@wp.func
def add_scalars(a: float, b: float) -> float:
return a + b
wp_add_scalars = wpct.export_func(add_scalars, num_worker_warps=2)
@ct.kernel
def shared_arguments_cutile_kernel(sums):
ct.store(sums, (0,), wp_add_scalars(1.0, 2.0)) # no tile operand: 2 * 32 invocations
sums = wp.empty(2 * 32, dtype=wp.float32)
ct.launch(wp.get_stream().cuda_stream, (1, 1, 1), shared_arguments_cutile_kernel, (sums,))
Block-Cooperative Functions
---------------------------
By default (``scope="thread"``), each call performs one independent invocation of the Warp function per tile element.
cuTile may run several invocations on one thread in turn or leave threads idle,
so no two invocations are guaranteed to execute together, and the function must not synchronize across threads.
Passing ``scope="block"`` instead runs a single cooperative invocation per thread block (CTA)
in which all worker threads participate.
Each participating thread receives its slice of the operands, as at thread scope.
Because the threads can cooperate, the function can use Warp's block-cooperative built-in tile functions
(``wp.tile_load``, ``wp.tile_sum``, ...).
``tileiras`` allocates the shared memory those functions need,
and ``export_func`` rejects a function that needs it at ``scope="thread"`` with an error pointing to ``scope="block"``.
A cuTile tile cannot be passed to the Warp function as a Warp tile.
The function builds its own tiles, usually by loading them cooperatively from a ``wp.array``:
.. code:: python
@wp.func
def array_block_sum(data: wp.array[float], start: int) -> float:
values = wp.tile_load(data, shape=TILE_SIZE, offset=start) # cooperative load
total = wp.tile_sum(values) # block-wide reduction
return total[0]
wp_array_block_sum = wpct.export_func(array_block_sum, num_worker_warps=TILE_SIZE // 32, scope="block")
@ct.kernel(num_worker_warps=TILE_SIZE // 32)
def array_block_sum_cutile_kernel(data_ptr: ct.Constant[int], data_len: ct.Constant[int], block_sums):
ct.store(block_sums, (0,), wp_array_block_sum((data_ptr, data_len), 0))
data = wp.array(np.arange(TILE_SIZE), dtype=wp.float32)
block_sums = wp.empty(TILE_SIZE, dtype=wp.float32)
ct.launch(
wp.get_stream().cuda_stream,
(1, 1, 1),
array_block_sum_cutile_kernel,
(*wpct.array_pointer_args(data), block_sums),
)
The call still returns a ``(TILE_SIZE,)`` tile, holding one copy of the return value per participating thread.
In this example every element holds the block-wide sum.
Inside a block-scope function, ``wp.tile(x)`` gathers each participating thread's ``x`` into one Warp tile.
That is how per-invocation operands enter a block-wide computation.
Geometry Queries
----------------
Exported functions can use Warp's mesh, BVH, hash-grid, and volume queries, as ``mesh_sdf`` in the Quick Start does.
Iterator queries and block-cooperative tiled queries have extra requirements.
Iterator Queries
^^^^^^^^^^^^^^^^
Iterator queries (``wp.mesh_query_aabb``, ``wp.mesh_query_sphere``, ``wp.bvh_query_*``)
keep per-thread traversal stacks in shared memory, sized for a block of 8 worker warps by default.
A kernel with more worker warps needs the function exported with at least its ``num_worker_warps``:
.. code:: python
@wp.func
def mesh_aabb_count(mesh_id: wp.handle, p: wp.vec3) -> int:
half_extent = wp.vec3(0.05, 0.05, 0.05)
query = wp.mesh_query_aabb(mesh_id, p - half_extent, p + half_extent)
count = int(0)
face = int(0)
while wp.mesh_query_aabb_next(query, face):
count += 1
return count
wp_mesh_aabb_count = wpct.export_func(mesh_aabb_count) # kernels of up to 8 warps
wp_mesh_aabb_count_16_warps = wpct.export_func(mesh_aabb_count, num_worker_warps=16) # 16-warp kernels
@ct.kernel(num_worker_warps=16)
def mesh_aabb_count_cutile_kernel(mesh_id: ct.Constant[int], points, counts):
bid = ct.bid(0)
point_tile = ct.load(points, (bid, 0), shape=(TILE_SIZE, 4))
ct.store(counts, (bid,), wp_mesh_aabb_count_16_warps(mesh_id, ct.reshape(point_tile, (TILE_SIZE * 4,))))
counts = wp.empty(num_points, dtype=wp.int32)
ct.launch(
wp.get_stream().cuda_stream,
(num_points // TILE_SIZE, 1, 1),
mesh_aabb_count_cutile_kernel,
(mesh.id, points, counts),
)
``num_worker_warps`` is a lower bound on the kernel's compiled block, which can be larger;
a block that exceeds the capacity the function was exported for traps.
This is a known limitation of thread-scope iterator queries.
A trap is a sticky device fault:
the launch fails with a CUDA error (typically ``an illegal instruction was encountered``),
the CUDA context is unusable afterwards, and the process has to be restarted.
Export the function with a larger ``num_worker_warps`` to fix it.
The cost is 128 bytes per thread per query family (mesh or BVH), so a 32-warp block needs 128 KiB per family;
``export_func`` rejects a function whose scratch would exceed the GPU's per-block shared memory.
Mesh and BVH queries use separate stacks, so nesting one inside the other is safe.
At ``scope="block"`` the stacks are sized to the pinned block exactly.
Block-Cooperative Tiled Queries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Block-cooperative tiled queries (``wp.tile_mesh_query_*``, ``wp.tile_bvh_query_*``)
traverse with the whole block and keep block-sized result buffers in static shared memory,
so they are accepted only at ``scope="block"``;
that memory is in addition to what cuTile plans for the kernel.
Supported Types and Limitations
-------------------------------
Supported parameter types are scalars, vectors, matrices, quaternions, transforms, structs,
and contiguous ``wp.array`` values (not indexed arrays).
``float16``, ``bfloat16``, and ``bool`` are not supported, as scalars or inside vectors and matrices.
The function must return exactly one scalar, vector, matrix, quaternion, transform, or struct.
The function body may call any Warp built-in function, with two exceptions:
the block-cooperative built-in tile functions need ``scope="block"`` (see `Block-Cooperative Functions`_),
and the MathDx-accelerated built-in tile functions (``wp.tile_matmul``, ``wp.tile_fft``, ``wp.tile_cholesky``, ...)
compile to Warp's portable implementations rather than the MathDx device libraries.
Not currently supported:
* Warp tile parameters: a cuTile tile cannot be passed to a Warp function as a Warp tile
(see `Block-Cooperative Functions`_).
* Stateful query objects across calls (e.g. ``wp.mesh_query_aabb`` iterators):
the whole query loop must live inside a single ``@wp.func`` call.
* Functions with more than one overload, including generic (``Any``-typed)
parameters: ``export_func`` needs a single concrete signature.
* Default parameter values: ``export_func`` rejects a function with defaults;
every parameter is passed at the call site.
* Automatic differentiation: the exported function is forward-only, and cuTile has no autodiff to drive adjoints.
Explicit ``wp.grad()`` calls inside the function do work, since they are part of its forward computation.
* API capture (APIC) save/load: ``ct.launch()`` is not a Warp API call,
so a cuTile kernel that calls Warp functions is not recorded into a ``.wrp`` capture
and a saved/loaded replay omits it silently.
* Wide shared operands: sharing a value costs nothing for operands of up to 64 ``int32`` words
(``mat44``, 6x6 matrices, structs of up to 16 ``vec4`` fields).
Wider shared operands can run several times slower at small tile lengths;
keep shared structs small, or pass large data as an array.
A function called only for its side effects still needs a return value, so give it a dummy scalar return.
For example, a function that only calls ``wp.atomic_add()`` on a ``wp.array`` can return ``0.0``.
The call runs even if the kernel drops its returned tile:
``tileiras`` never removes a call to an exported function, because it assumes the call may read or write memory.
Compilation and Caching
-----------------------
``export_func`` compiles the function when it is called and caches the result on disk in the Warp kernel cache.
Exporting the same function again reuses the cached result, even in a new process.
One thread-scope build covers every tile length.
Each target architecture, each scope, and each ``num_worker_warps`` value that changes the build
(block scope, or iterator queries above 8 warps) is a separate build.
The function is compiled with the options set on its Warp module by :func:`warp.set_module_options`:
``mode``, ``optimization_level``, ``fast_math``, ``lineinfo``,
and the CUDA preamble, include directories, and build dependencies in ``extra_build_options``.
It also honors the global ``warp.config.verify_fp``.
It therefore computes what the same ``@wp.func`` computes under :func:`warp.launch`,
including through ``wp.func_native`` dependencies that rely on the preamble.
Geometry queries and built-in tile functions are recognized only in Warp code and in ``wp.func_native`` snippet text.
A call inside a header that a snippet includes is not seen, and the shared memory it needs is not reserved,
so keep such calls in the Warp function or in the snippet itself.
The exported function targets the architecture of ``device``,
which defaults to the current Warp device (:func:`warp.get_device`).
Two options do not carry over fully.
``export_func`` forwards ``fuse_fp=False`` but warns that it is not guaranteed,
because ``tileiras`` decides floating-point contraction when it link-time-optimizes the calling kernel.
Exported functions do not honor deterministic mode (``deterministic``).
For inspection, the generated CUDA C++ for each function is kept beside its compiled code
in the ``cutile/`` directory of the kernel cache.
The cache is keyed on content, so changing the function, its Warp version, its module build options,
or the toolchain triggers recompilation.
If you edit Warp's native headers or replace the ``tileiras`` toolchain while a process is running,
restart it before exporting functions again.
Moving a function's source file to another path causes a rebuild.
:func:`wp.clear_kernel_cache() ` removes the cached artifacts
along with Warp's other kernel-cache contents;
a function exported before then reports its missing ``.tilelib`` when a new kernel traces it,
and must be exported again.
CUDA Graph Capture
------------------
A ``ct.launch()`` on Warp's stream is recorded
by :func:`warp.capture_begin` / :func:`warp.capture_end` (or :class:`warp.ScopedCapture`)
like any other stream-ordered work, and the graph replays with :func:`warp.capture_launch`.
The kernel may be compiled during capture; no warm-up launch is needed.
Keep the ``@ct.kernel`` object alive for as long as the graph is replayed.
The graph refers to the kernel's device code but does not keep the kernel object alive;
once that object is garbage collected,
replaying the graph crashes the process with a segmentation fault rather than a Python exception.
A helper that defines the kernel locally must therefore return the kernel along with the graph
(the exported function object itself does not need to outlive the graph):
.. code:: python
@wp.func
def scale_add(x: float, y: float) -> float:
return 2.0 * x + y
wp_scale_add = wpct.export_func(scale_add)
def capture_scale_add(xs, ys, results):
@ct.kernel
def scale_add_cutile_kernel(xs, ys, results):
x = ct.load(xs, (0,), shape=(TILE_SIZE,))
y = ct.load(ys, (0,), shape=(TILE_SIZE,))
ct.store(results, (0,), wp_scale_add(x, y))
with wp.ScopedCapture() as capture:
ct.launch(wp.get_stream().cuda_stream, (1, 1, 1), scale_add_cutile_kernel, (xs, ys, results))
return capture.graph, scale_add_cutile_kernel # the kernel must outlive the graph
xs = wp.array(np.arange(TILE_SIZE), dtype=wp.float32)
ys = wp.ones(TILE_SIZE, dtype=wp.float32)
results = wp.empty(TILE_SIZE, dtype=wp.float32)
graph, scale_add_cutile_kernel = capture_scale_add(xs, ys, results)
wp.capture_launch(graph)
Troubleshooting
---------------
These errors come from cuTile Python, ``tileiras``, or the CUDA driver,
and their messages do not point to the cause when a kernel calls an exported function.
.. list-table::
:header-rows: 1
:widths: 30 40 30
* - Error
- Cause
- Fix
* - ``an illegal instruction was encountered`` or another sticky CUDA error
after a kernel that calls an exported function
- The function uses iterator geometry queries,
and the kernel's compiled block is larger than its ``num_worker_warps`` supports.
The compiler can add warps beyond the kernel's ``num_worker_warps``.
- Export the function with a larger ``num_worker_warps`` and restart the process (see `Iterator Queries`_).
* - ``CompilerExecutionError`` from ``tileiras``:
``expected tensor_view rank and tile rank to match`` or similar
- A tile operation near the call uses a vector or matrix result as a 2-D tile.
Results are flat ``(TILE_SIZE * width,)`` tiles.
- Reshape the result before a 2-D store, as ``closest_point_cutile_kernel`` does in `Return Value`_.
* - ``CompilerExecutionError`` from ``tileiras`` with only ``failed to compile Tile IR program``,
for a kernel that calls a ``scope="block"`` function
- The kernel's ``num_worker_warps`` differs from the value passed to ``export_func``.
``tileiras`` rejects the mismatch without printing a reason.
- Make the two values equal (see `When to Set num_worker_warps`_).
* - ``foreign_call requires tileiras 13.5 or later. Current version is ...``
with ``tileiras`` 13.5 installed
- cuTile Python checks its own ``tileiras``, which can differ from the one Warp uses.
The check fails when an older ``ptxas`` on ``PATH`` breaks it (``Unsupported .version`` in the underlying error),
or when a layered environment hides the pip ``tileiras`` from cuTile Python (see `Requirements`_).
- Put the 13.5 toolkit's ``bin`` directory ahead of other CUDA toolkits on ``PATH``,
or install JAX into the same environment as cuTile Python.