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

Examples

Fused GELU

A scale, a bias add, and a GELU in one kernel: gelu(x * scale + bias). Fusing the three operations reads and writes the data once instead of three times.

What it computes

fused_gelu(x, bias, scale) takes a contiguous 2D NumPy array x, a bias with one value per column, and a scalar scale. It returns gelu(x * scale + bias) in the input dtype, using the exact GELU, 0.5 * y * (1 + erf(y / sqrt(2))).

The kernel

The following code shows the kernel and its host wrapper:

examples/05_fused_gelu.pyGitHub
import enceladus.language as tl


@enceladus.jit
def fused_gelu_kernel(x_ptr, bias_ptr, out_ptr, n, n_cols, scale, 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).to(tl.float32)
    b = tl.load(bias_ptr + offs % n_cols, mask=mask).to(tl.float32)
    y = x * scale + b
    tl.store(out_ptr + offs, 0.5 * y * (1.0 + tl.erf(y * 0.7071067811865476)), mask=mask)


def fused_gelu(x, bias, scale: float, block: int = 1024):
    """Returns `gelu(x * scale + bias)` for a contiguous 2D `x` and a bias per column."""
    out = enceladus.new_empty(x)

How it works

  • The kernel treats x as a flat array, like the vector add: the grid has cdiv(n, block) programs of BLOCK elements, and mask = offs < n guards the last one.
  • The bias is indexed with offs % n_cols, which maps each flat offset to its column. That's why x must be contiguous.
  • The math runs in float32. 0.7071067811865476 is 1 / sqrt(2), and tl.erf is the Gauss error function.
  • scale is an ordinary scalar argument, not a constexpr, so changing it doesn't recompile the kernel.

For the math builtins, see Math in the language reference.

Run the example

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

shell
uv run python examples/05_fused_gelu.py

The demo applies the kernel to a 64 by 300 float32 array with scale=0.5, and compares the result with a NumPy reference computed in float64. The output is similar to the following:

max abs error: 4.7683716e-07

The file's docstring runs the demo in the CPU interpreter, with ENCELADUS_INTERPRET=1. Both ways work, and they give errors of the same size. For more information, see Debugging.

Full source

examples/05_fused_gelu.pyGitHub
"""Fused elementwise op: `gelu(x * scale + bias)`, with a bias per column.

`fused_gelu` 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 `ENCELADUS_INTERPRET=1 uv run python examples/05_fused_gelu.py`.
"""

import math

import numpy as np

import enceladus
import enceladus.language as tl


@enceladus.jit
def fused_gelu_kernel(x_ptr, bias_ptr, out_ptr, n, n_cols, scale, 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).to(tl.float32)
    b = tl.load(bias_ptr + offs % n_cols, mask=mask).to(tl.float32)
    y = x * scale + b
    tl.store(out_ptr + offs, 0.5 * y * (1.0 + tl.erf(y * 0.7071067811865476)), mask=mask)


def fused_gelu(x, bias, scale: float, block: int = 1024):
    """Returns `gelu(x * scale + bias)` for a contiguous 2D `x` and a bias per column."""
    out = enceladus.new_empty(x)
    n = int(np.prod(x.shape))
    fused_gelu_kernel[(enceladus.cdiv(n, block),)](x, bias, out, n, x.shape[-1], scale, BLOCK=block)
    return out


def reference(x: np.ndarray, bias: np.ndarray, scale: float, **_) -> np.ndarray:
    y = x.astype(np.float64) * np.float32(scale) + bias.astype(np.float64)
    erf = np.vectorize(math.erf, otypes=[np.float64])
    return (0.5 * y * (1.0 + erf(y / math.sqrt(2.0)))).astype(x.dtype)


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    x = rng.standard_normal((64, 300)).astype(np.float32)
    bias = rng.standard_normal(300).astype(np.float32)
    print("max abs error:", np.abs(fused_gelu(x, bias, 0.5) - reference(x, bias, 0.5)).max())