Row softmaxExamples pages
Examples
Row softmax
A softmax over each row of a 2D array, with one program per row. It shows reductions with tl.max and tl.sum, and how a mask's fill value keeps them correct.
What it computes
softmax(x) returns exp(x - max(x)) / sum(exp(x - max(x))) for each row of a 2D array, in the input dtype. It accepts NumPy arrays, enceladus.Tensor objects, PyTorch tensors on the mps device, and MLX arrays. The rows can be strided, including views with a nonzero offset, but the elements within a row must be contiguous.
The kernel
The following code shows the kernel and its host wrapper:
@enceladus.jit
def softmax_kernel(out_ptr, in_ptr, stride_in, stride_out, n_cols, BLOCK: tl.constexpr):
row = tl.program_id(0)
cols = tl.arange(0, BLOCK)
mask = cols < n_cols
x = tl.load(in_ptr + row * stride_in + cols, mask=mask, other=-float("inf"))
x = x.to(tl.float32)
x = x - tl.max(x, axis=0)
num = tl.exp(x)
tl.store(out_ptr + row * stride_out + cols, num / tl.sum(num, axis=0), mask=mask)
def softmax(x):
"""Returns the softmax of each row of a 2D array, in the input dtype.
The rows can be strided, but the elements within a row must be contiguous.
"""
m, n = x.shape
out = enceladus.new_empty(x)
softmax_kernel[(m,)](
out, x, enceladus.element_strides(x)[0], enceladus.element_strides(out)[0], n,
BLOCK=enceladus.next_power_of_2(n),
) # fmt: skip
return outHow it works
- The grid is
(m,): one program for each of themrows.tl.program_id(0)is the row index. - One tile holds a whole row. Tile dimensions must be powers of two, so
BLOCKisenceladus.next_power_of_2(n). For the demo's 1,000 columns, that's 1,024. - Masked lanes load
-infthroughother=-float("inf"). That value leaves the row maximum unchanged, and its exponential adds 0 to the sum. - The kernel converts the row to
float32, subtracts the row maximum for numerical stability, and then divides the exponentials by their sum.tl.storeconverts the result to the output's dtype. enceladus.element_stridesreturns the strides in elements for any supported array kind, so the wrapper passes the row stride of the input and the output separately.
For the reduction builtins, see Reductions in the language reference.
Run the example
From the root of a clone of the repository, run the following command:
uv run python examples/02_softmax.pyThe demo applies the softmax to a 64 by 1,000 float32 array and compares the result with a NumPy reference computed in float64. The output is similar to the following:
max abs error: 7.450581e-09Full source
"""Row softmax, one row per program.
`softmax` accepts NumPy arrays, `enceladus.Tensor` objects, PyTorch tensors on the
`mps` device, and MLX arrays, including row views with nonzero offsets.
Run the demo with `uv run python examples/02_softmax.py`.
"""
import numpy as np
import enceladus
import enceladus.language as tl
@enceladus.jit
def softmax_kernel(out_ptr, in_ptr, stride_in, stride_out, n_cols, BLOCK: tl.constexpr):
row = tl.program_id(0)
cols = tl.arange(0, BLOCK)
mask = cols < n_cols
x = tl.load(in_ptr + row * stride_in + cols, mask=mask, other=-float("inf"))
x = x.to(tl.float32)
x = x - tl.max(x, axis=0)
num = tl.exp(x)
tl.store(out_ptr + row * stride_out + cols, num / tl.sum(num, axis=0), mask=mask)
def softmax(x):
"""Returns the softmax of each row of a 2D array, in the input dtype.
The rows can be strided, but the elements within a row must be contiguous.
"""
m, n = x.shape
out = enceladus.new_empty(x)
softmax_kernel[(m,)](
out, x, enceladus.element_strides(x)[0], enceladus.element_strides(out)[0], n,
BLOCK=enceladus.next_power_of_2(n),
) # fmt: skip
return out
def reference(x: np.ndarray) -> np.ndarray:
z = x.astype(np.float64)
z = np.exp(z - z.max(axis=1, keepdims=True))
return (z / z.sum(axis=1, keepdims=True)).astype(x.dtype)
if __name__ == "__main__":
x = np.random.default_rng(0).standard_normal((64, 1000)).astype(np.float32)
print("max abs error:", np.abs(softmax(x) - reference(x)).max())