Enceladus v0.1.0 · alpha
Matrix multiplicationExamples pages
All examplesVector addRow softmaxLayerNormMatrix multiplicationFused GELURMSNormMatmul with bias and GELUFlash attentionHistogramCumulative sum

Examples

Matrix multiplication

c = a @ b with a float32 accumulator, written two ways: with pointer tiles and masks, and with tensor descriptors. The descriptor version also has an autotuned wrapper.

What it computes

The file defines three wrappers that return a @ b in the input dtype:

  • matmul uses pointer tiles with masks. The operands can have any strides.
  • matmul_desc uses tensor descriptors, so tl.dot loads its fragments straight from device memory. This is the fast path. a, b, and c must be row-major.
  • matmul_tuned runs the descriptor kernel with the fastest configuration for the shape and dtype.

All three accept NumPy arrays, enceladus.Tensor objects, PyTorch tensors on the mps device, and MLX arrays, and return an array of the same kind.

Pointer tiles

The following code shows the pointer-tile kernel and its wrapper:

examples/04_matmul.pyGitHub
@enceladus.jit
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K,
                  stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn,
                  BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):  # fmt: skip
    pid_n, pid_m = tl.program_id(0), tl.program_id(1)
    rm = pid_m * BM + tl.arange(0, BM)
    rn = pid_n * BN + tl.arange(0, BN)
    rk = tl.arange(0, BK)
    a_ptrs = a_ptr + rm[:, None] * stride_am + rk[None, :] * stride_ak
    b_ptrs = b_ptr + rk[:, None] * stride_bk + rn[None, :] * stride_bn
    acc = tl.zeros((BM, BN), dtype=tl.float32)
    for k in range(0, K, BK):
        a = tl.load(a_ptrs, mask=(rm[:, None] < M) & (rk[None, :] + k < K), other=0.0)
        b = tl.load(b_ptrs, mask=(rk[:, None] + k < K) & (rn[None, :] < N), other=0.0)
        acc = tl.dot(a, b, acc)
        a_ptrs += BK * stride_ak
        b_ptrs += BK * stride_bk
    c_ptrs = c_ptr + rm[:, None] * stride_cm + rn[None, :] * stride_cn
    tl.store(c_ptrs, acc.to(c_ptr.dtype.element_ty), mask=(rm[:, None] < M) & (rn[None, :] < N))


def matmul(a, b, bm: int = 32, bn: int = 32, bk: int = 32):
    """Returns `a @ b` in the input dtype. The operands can have any strides."""
    (m, k), (_, n) = a.shape, b.shape
    c = enceladus.new_empty(a, (m, n))
    s = [*enceladus.element_strides(a), *enceladus.element_strides(b),
         *enceladus.element_strides(c)]  # fmt: skip
    grid = lambda meta: (enceladus.cdiv(n, meta["BN"]), enceladus.cdiv(m, meta["BM"]))  # noqa: E731
    matmul_kernel[grid](a, b, c, m, n, k, *s, BM=bm, BN=bn, BK=bk)
    return c
  • The grid is two-dimensional. Axis 0 walks the BN-wide column blocks of c, and axis 1 walks the BM-tall row blocks. The grid is a function of meta, so it reads the block sizes from the launch.
  • a_ptrs and b_ptrs are 2D tiles of pointers, built from row and column offsets with [:, None] and [None, :] broadcasting and the strides that enceladus.element_strides returns.
  • Each iteration of the K loop masks both the M or N edge and the K tail, loads zeros outside the matrices, and accumulates with acc = tl.dot(a, b, acc). It then advances both pointer tiles by BK along K.
  • The store casts the accumulator to c_ptr.dtype.element_ty and masks the edges of c.

Pointer-tile operands go through threadgroup memory before tl.dot uses them. That works for any tile, but runs slower than the descriptor version.

Tensor descriptors

The following code shows the descriptor kernel and its wrapper:

examples/04_matmul.pyGitHub
@enceladus.jit
def matmul_desc_kernel(a_ptr, b_ptr, c_ptr, M, N, K, stride_am, stride_bk, stride_cm,
                       BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):  # fmt: skip
    pid_n, pid_m = tl.program_id(0), tl.program_id(1)
    a = tl.make_tensor_descriptor(a_ptr, [M, K], [stride_am, 1], [BM, BK])
    b = tl.make_tensor_descriptor(b_ptr, [K, N], [stride_bk, 1], [BK, BN])
    c = tl.make_tensor_descriptor(c_ptr, [M, N], [stride_cm, 1], [BM, BN])
    acc = tl.zeros((BM, BN), dtype=tl.float32)
    for k in range(0, K, BK):
        acc = tl.dot(a.load([pid_m * BM, k]), b.load([k, pid_n * BN]), acc)
    c.store([pid_m * BM, pid_n * BN], acc.to(c.dtype))


def matmul_desc(a, b, c=None, bm: int = 64, bn: int = 64, bk: int = 32, num_warps: int = 4,
                dot_backend: str = "auto"):  # fmt: skip
    """Returns `a @ b` in the input dtype. `a`, `b`, and `c` must be row-major.

    `dot_backend="mpp"` runs the loop as one Metal 4 `matmul2d` op.
    """
    (m, k), (_, n) = a.shape, b.shape
    if c is None:
        c = enceladus.new_empty(a, (m, n))
    grid = (enceladus.cdiv(n, bn), enceladus.cdiv(m, bm))
    matmul_desc_kernel[grid](a, b, c, m, n, k, k, n, n, BM=bm, BN=bn, BK=bk,
                             num_warps=num_warps, dot_backend=dot_backend)  # fmt: skip
    return c
  • tl.make_tensor_descriptor describes each matrix by its base pointer, shape, strides, and block shape. The innermost stride must be 1, so the wrapper passes only the row strides: k, n, and n.
  • Descriptors check their own bounds. a.load fills out-of-bounds elements with zeros, and c.store skips them, so the kernel has no masks.
  • The defaults are 64 by 64 output blocks, a K step of 32, and 4 SIMD groups. With dot_backend="mpp", the K loop runs as one Metal 4 matmul2d operation.

For more information about the two ways to address memory, see Memory and synchronization. For the tl.dot backends, see Performance.

Autotuning

The following code wraps the descriptor kernel in enceladus.autotune:

examples/04_matmul.pyGitHub
def _configs_for_dtype(configs, named):
    """Keeps the configs that `matmul_configs` lists for the dtype of `a`."""
    allowed = matmul_configs(named["a_ptr"].dtype)
    return [c for c in configs if c in allowed]


# The float16 list is a superset of the float32 one. Pruning by dtype keeps the float32
# spill-cliff shapes out of float32 tuning. The key includes the argument dtypes, so each
# dtype is tuned separately.
matmul_desc_tuned = enceladus.autotune(
    configs=matmul_configs("float16"),
    key=["M", "N", "K"],
    prune_configs_by={"early_config_prune": _configs_for_dtype},
)(matmul_desc_kernel)


def matmul_tuned(a, b, c=None):
    """Returns `a @ b` using the fastest configuration for this shape and dtype."""
    (m, k), (_, n) = a.shape, b.shape
    if c is None:
        c = enceladus.new_empty(a, (m, n))
    grid = lambda meta: (enceladus.cdiv(n, meta["BN"]), enceladus.cdiv(m, meta["BM"]))  # noqa: E731
    matmul_desc_tuned[grid](a, b, c, m, n, k, k, n, n)
    return c
  • The candidate list is matmul_configs("float16"), which is a superset of the float32 list.
  • _configs_for_dtype, passed as early_config_prune, keeps only the configurations that matmul_configs lists for the dtype of a. This keeps the float32 shapes that spill registers out of float32 tuning.
  • The tuning key is M, N, and K. The autotuner also keys on the argument dtypes, so it tunes each dtype separately.
  • The grid is a function of meta, because the block sizes come from the chosen configuration.

The demo doesn't call matmul_tuned. For more information about autotuning, see Performance.

Run the example

From the root of a clone of the repository, run the following command:

shell
uv run python examples/04_matmul.py

The demo multiplies a 100 by 70 matrix by a 70 by 90 matrix, in float32, with matmul and with matmul_desc. None of the dimensions is a multiple of the block sizes, so both kernels exercise their edge handling. It compares each result with NumPy, and the output is similar to the following:

max abs error, pointer tiles: 0.0
max abs error, descriptors: 0.0

Full source

examples/04_matmul.pyGitHub
"""Matmul, `c = a @ b`, accumulating in float32, in two variants.

- `matmul_desc` uses tensor descriptors. `tl.dot` loads its fragments straight from
  device memory, and out-of-bounds tiles are handled for you. This is the fast path.
- `matmul` uses pointer tiles with masks. The operands go through threadgroup memory,
  which works for any tile but runs slower.

All three wrappers accept NumPy arrays, `enceladus.Tensor` objects, PyTorch tensors on
the `mps` device, and MLX arrays, and return an array of the same kind.

Run the demo with `uv run python examples/04_matmul.py`.
"""

import numpy as np

import enceladus
import enceladus.language as tl
from enceladus.configs import matmul_configs


@enceladus.jit
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K,
                  stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn,
                  BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):  # fmt: skip
    pid_n, pid_m = tl.program_id(0), tl.program_id(1)
    rm = pid_m * BM + tl.arange(0, BM)
    rn = pid_n * BN + tl.arange(0, BN)
    rk = tl.arange(0, BK)
    a_ptrs = a_ptr + rm[:, None] * stride_am + rk[None, :] * stride_ak
    b_ptrs = b_ptr + rk[:, None] * stride_bk + rn[None, :] * stride_bn
    acc = tl.zeros((BM, BN), dtype=tl.float32)
    for k in range(0, K, BK):
        a = tl.load(a_ptrs, mask=(rm[:, None] < M) & (rk[None, :] + k < K), other=0.0)
        b = tl.load(b_ptrs, mask=(rk[:, None] + k < K) & (rn[None, :] < N), other=0.0)
        acc = tl.dot(a, b, acc)
        a_ptrs += BK * stride_ak
        b_ptrs += BK * stride_bk
    c_ptrs = c_ptr + rm[:, None] * stride_cm + rn[None, :] * stride_cn
    tl.store(c_ptrs, acc.to(c_ptr.dtype.element_ty), mask=(rm[:, None] < M) & (rn[None, :] < N))


def matmul(a, b, bm: int = 32, bn: int = 32, bk: int = 32):
    """Returns `a @ b` in the input dtype. The operands can have any strides."""
    (m, k), (_, n) = a.shape, b.shape
    c = enceladus.new_empty(a, (m, n))
    s = [*enceladus.element_strides(a), *enceladus.element_strides(b),
         *enceladus.element_strides(c)]  # fmt: skip
    grid = lambda meta: (enceladus.cdiv(n, meta["BN"]), enceladus.cdiv(m, meta["BM"]))  # noqa: E731
    matmul_kernel[grid](a, b, c, m, n, k, *s, BM=bm, BN=bn, BK=bk)
    return c


@enceladus.jit
def matmul_desc_kernel(a_ptr, b_ptr, c_ptr, M, N, K, stride_am, stride_bk, stride_cm,
                       BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):  # fmt: skip
    pid_n, pid_m = tl.program_id(0), tl.program_id(1)
    a = tl.make_tensor_descriptor(a_ptr, [M, K], [stride_am, 1], [BM, BK])
    b = tl.make_tensor_descriptor(b_ptr, [K, N], [stride_bk, 1], [BK, BN])
    c = tl.make_tensor_descriptor(c_ptr, [M, N], [stride_cm, 1], [BM, BN])
    acc = tl.zeros((BM, BN), dtype=tl.float32)
    for k in range(0, K, BK):
        acc = tl.dot(a.load([pid_m * BM, k]), b.load([k, pid_n * BN]), acc)
    c.store([pid_m * BM, pid_n * BN], acc.to(c.dtype))


def matmul_desc(a, b, c=None, bm: int = 64, bn: int = 64, bk: int = 32, num_warps: int = 4,
                dot_backend: str = "auto"):  # fmt: skip
    """Returns `a @ b` in the input dtype. `a`, `b`, and `c` must be row-major.

    `dot_backend="mpp"` runs the loop as one Metal 4 `matmul2d` op.
    """
    (m, k), (_, n) = a.shape, b.shape
    if c is None:
        c = enceladus.new_empty(a, (m, n))
    grid = (enceladus.cdiv(n, bn), enceladus.cdiv(m, bm))
    matmul_desc_kernel[grid](a, b, c, m, n, k, k, n, n, BM=bm, BN=bn, BK=bk,
                             num_warps=num_warps, dot_backend=dot_backend)  # fmt: skip
    return c


def _configs_for_dtype(configs, named):
    """Keeps the configs that `matmul_configs` lists for the dtype of `a`."""
    allowed = matmul_configs(named["a_ptr"].dtype)
    return [c for c in configs if c in allowed]


# The float16 list is a superset of the float32 one. Pruning by dtype keeps the float32
# spill-cliff shapes out of float32 tuning. The key includes the argument dtypes, so each
# dtype is tuned separately.
matmul_desc_tuned = enceladus.autotune(
    configs=matmul_configs("float16"),
    key=["M", "N", "K"],
    prune_configs_by={"early_config_prune": _configs_for_dtype},
)(matmul_desc_kernel)


def matmul_tuned(a, b, c=None):
    """Returns `a @ b` using the fastest configuration for this shape and dtype."""
    (m, k), (_, n) = a.shape, b.shape
    if c is None:
        c = enceladus.new_empty(a, (m, n))
    grid = lambda meta: (enceladus.cdiv(n, meta["BN"]), enceladus.cdiv(m, meta["BM"]))  # noqa: E731
    matmul_desc_tuned[grid](a, b, c, m, n, k, k, n, n)
    return c


def reference(a: np.ndarray, b: np.ndarray, **_) -> np.ndarray:
    return (a.astype(np.float32) @ b.astype(np.float32)).astype(a.dtype)


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    a = rng.standard_normal((100, 70)).astype(np.float32)
    b = rng.standard_normal((70, 90)).astype(np.float32)
    print("max abs error, pointer tiles:", np.abs(matmul(a, b) - reference(a, b)).max())
    print("max abs error, descriptors:", np.abs(matmul_desc(a, b) - reference(a, b)).max())