Vector addExamples pages
Examples
Vector add
The smallest complete kernel: out = x + y. It shows the program ID, block offsets, and masks that every other example builds on.
What it computes
add(x, y) returns the elementwise sum of two contiguous arrays with the same shape and dtype. It accepts NumPy arrays, enceladus.Tensor objects, PyTorch tensors on the mps device, and MLX arrays. enceladus.new_empty(x) allocates the output with the same framework and device as x, so the result is the same kind of array that you pass in.
The kernel
The following code shows the kernel and its host wrapper:
@enceladus.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
pid = tl.program_id(0)
offs = pid * BLOCK + tl.arange(0, BLOCK)
mask = offs < n
x = tl.load(x_ptr + offs, mask=mask)
y = tl.load(y_ptr + offs, mask=mask)
tl.store(out_ptr + offs, x + y, mask=mask)
def add(x, y, block: int = 1024):
"""Returns `x + y` for two contiguous arrays of the same shape and dtype."""
out = enceladus.new_empty(x)
n = int(np.prod(x.shape))
add_kernel[(enceladus.cdiv(n, block),)](x, y, out, n, BLOCK=block)
return outHow it works
- The grid is one-dimensional, with
cdiv(n, block)programs. Each program handlesBLOCKconsecutive elements, 1,024 by default. tl.program_id(0)returns the program's index, andpid * BLOCK + tl.arange(0, BLOCK)is the tile of element offsets that the program covers.mask = offs < nkeeps the last program in bounds. In the demo,nis 100,003, so the grid has 98 programs and the last one covers only 675 valid elements.- The wrapper flattens the array:
nis the product of the shape, so any shape works as long as the array is contiguous. BLOCK: tl.constexprmakes the block size a compile-time constant. Enceladus compiles one version of the kernel for each value you pass.
For more information about programs and tiles, see Programming model.
Run the example
From the root of a clone of the repository, run the following command:
uv run python examples/01_vector_add.pyThe demo adds two vectors of 100,003 random float32 values and compares the result with NumPy. If PyTorch is installed and the mps device is available, it repeats the add with PyTorch tensors and compares the result with tx + ty. The output is similar to the following:
max abs error: 0.0
max abs error, torch: 0.0Full source
"""Vector add: `out = x + y`.
`add` accepts NumPy arrays, `enceladus.Tensor` objects, PyTorch tensors on the `mps`
device, and MLX arrays, and returns an array of the same kind.
Run the demo with `uv run python examples/01_vector_add.py`.
"""
import numpy as np
import enceladus
import enceladus.language as tl
@enceladus.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
pid = tl.program_id(0)
offs = pid * BLOCK + tl.arange(0, BLOCK)
mask = offs < n
x = tl.load(x_ptr + offs, mask=mask)
y = tl.load(y_ptr + offs, mask=mask)
tl.store(out_ptr + offs, x + y, mask=mask)
def add(x, y, block: int = 1024):
"""Returns `x + y` for two contiguous arrays of the same shape and dtype."""
out = enceladus.new_empty(x)
n = int(np.prod(x.shape))
add_kernel[(enceladus.cdiv(n, block),)](x, y, out, n, BLOCK=block)
return out
def reference(x: np.ndarray, y: np.ndarray) -> np.ndarray:
return x + y
if __name__ == "__main__":
rng = np.random.default_rng(0)
x = rng.standard_normal(100_003).astype(np.float32)
y = rng.standard_normal(100_003).astype(np.float32)
out = add(x, y)
print("max abs error:", np.abs(out - reference(x, y)).max())
try:
import torch
except ImportError:
torch = None
if torch is not None and torch.backends.mps.is_available():
tx, ty = torch.from_numpy(x).to("mps"), torch.from_numpy(y).to("mps")
print("max abs error, torch:", (add(tx, ty) - (tx + ty)).abs().max().item())