Use input-output aliases for in-place Triton kernels
mainWhen a Triton kernel performs an in-place operation (where an input argument is also the output), use the input_output_aliases parameter in jt.triton_call.
input_output_aliases is a dictionary mapping the index of the input argument to the index of the output argument. For example, {1: 0} indicates that the argument at index 1 is also the first output argument.
To improve efficiency and avoid XLA making copies of non-donated in-out arguments (since JAX arrays are immutable by default), use jax.jit with donate_argnames.
Example: In-place addition
@triton.jit
def add_inplace_y_kernel(x_ptr, y_inout_ptr, length, block_size: tl.constexpr):
# ... kernel logic ...
tl.store(y_inout_ptr + offsets, output, mask=mask)
@partial(jax.jit, donate_argnames="y")
def add_inplace_y(x: jnp.ndarray, y: jnp.ndarray) -> jnp.ndarray:
block_size = 8
return jt.triton_call(
x,
y,
x.size,
kernel=add_inplace_y_kernel,
input_output_aliases={1: 0}, # arg index 1 (y) is the first output
out_shape=x,
grid=(x.size // block_size,),
block_size=block_size
)@partial(jax.jit, donate_argnames="y")
def add_inplace_y(x: jnp.ndarray, y: jnp.ndarray) -> jnp.ndarray:
block_size = 8
return jt.triton_call(
x,
y,
x.size,
kernel=add_inplace_y_kernel,
input_output_aliases={1: 0}, # input arg idx 1 (y) is the first output arg
out_shape=x,
grid=(x.size // block_size,),
block_size=block_size)