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

Examples

Matmul with bias and GELU

A descriptor matmul with a fused epilogue: gelu(a @ b + bias). The bias add, the GELU, and the cast run on the accumulator registers before the store.

What it computes

matmul_bias_gelu(a, b, bias) returns gelu(a @ b + bias) in the input dtype, where bias has one value per output column. a, b, and the output must be row-major. For a NumPy a, the wrapper allocates a NumPy output; for any other input, it allocates an enceladus.Tensor, unless you pass c.

The kernel

The following code shows the kernel and its host wrapper:

examples/07_matmul_fused.pyGitHub
@enceladus.jit
def matmul_bias_gelu_kernel(a_ptr, b_ptr, bias_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)
    cols = pid_n * BN + tl.arange(0, BN)
    bias = tl.load(bias_ptr + cols, mask=cols < N, other=0.0).to(tl.float32)
    y = acc + bias[None, :]
    y = 0.5 * y * (1.0 + tl.erf(y * 0.7071067811865476))
    c.store([pid_m * BM, pid_n * BN], y.to(c.dtype))


def matmul_bias_gelu(a, b, bias, c=None, bm: int = 64, bn: int = 64, bk: int = 32,
                     dot_backend: str = "auto"):  # fmt: skip
    """Returns `gelu(a @ b + bias)` in the input dtype.

    With `dot_backend="mpp"`, the epilogue runs on the elements of the `matmul2d`
    cooperative tensor.
    """
    (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_bias_gelu_kernel[grid](a, b, bias, c, m, n, k, k, n, n, BM=bm, BN=bn, BK=bk,
                                  dot_backend=dot_backend)  # fmt: skip
    return c

How it works

The K loop is the same as in the descriptor kernel of the matrix multiplication example: three tensor descriptors, a 2D grid over the output blocks, and acc = tl.dot(a_tile, b_tile, acc) with a float32 accumulator. After the loop, the kernel runs the epilogue on the accumulator:

  1. Load the BN bias values for the block's columns with a pointer tile, masking columns past N.
  2. Add the bias to every row with bias[None, :] broadcasting.
  3. Apply the exact GELU with tl.erf.
  4. Cast to the output dtype and store through the output descriptor, which skips out-of-bounds elements.

These steps work on the accumulator's registers in place, so the fused kernel costs about the same as a plain matmul. With dot_backend="mpp", the epilogue runs on the elements of the Metal 4 matmul2d cooperative tensor. For more information, see Performance.

Run the example

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

shell
uv run python examples/07_matmul_fused.py

The demo multiplies a 200 by 96 matrix by a 96 by 130 matrix in float32, adds a 130-element bias, and compares the result with a NumPy reference computed in float64. The output is similar to the following:

max abs error: 1.335144e-05

Full source

examples/07_matmul_fused.pyGitHub
"""Matmul with a fused epilogue: `gelu(a @ b + bias)`.

The bias add, the GELU, and the cast run on the accumulator registers before the store,
so the fused kernel costs about the same as a plain matmul.

Run the demo with `uv run python examples/07_matmul_fused.py`.
"""

import math

import numpy as np

import enceladus
import enceladus.language as tl


@enceladus.jit
def matmul_bias_gelu_kernel(a_ptr, b_ptr, bias_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)
    cols = pid_n * BN + tl.arange(0, BN)
    bias = tl.load(bias_ptr + cols, mask=cols < N, other=0.0).to(tl.float32)
    y = acc + bias[None, :]
    y = 0.5 * y * (1.0 + tl.erf(y * 0.7071067811865476))
    c.store([pid_m * BM, pid_n * BN], y.to(c.dtype))


def matmul_bias_gelu(a, b, bias, c=None, bm: int = 64, bn: int = 64, bk: int = 32,
                     dot_backend: str = "auto"):  # fmt: skip
    """Returns `gelu(a @ b + bias)` in the input dtype.

    With `dot_backend="mpp"`, the epilogue runs on the elements of the `matmul2d`
    cooperative tensor.
    """
    (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_bias_gelu_kernel[grid](a, b, bias, c, m, n, k, k, n, n, BM=bm, BN=bn, BK=bk,
                                  dot_backend=dot_backend)  # fmt: skip
    return c


_erf = np.vectorize(math.erf, otypes=[np.float64])


def reference(a, b, bias, **_):
    y = a.astype(np.float64) @ b.astype(np.float64) + bias.astype(np.float64)
    return (0.5 * y * (1 + _erf(y / math.sqrt(2)))).astype(a.dtype)


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    a = rng.standard_normal((200, 96)).astype(np.float32)
    b = rng.standard_normal((96, 130)).astype(np.float32)
    bias = rng.standard_normal(130).astype(np.float32)
    print("max abs error:", np.abs(matmul_bias_gelu(a, b, bias) - reference(a, b, bias)).max())