Enceladus v0.1.0 · alpha
Softmax and reductionsBenchmarks pages
OverviewMethodologyElementwiseSoftmax and reductionsNormalizationScans and atomicsMatmulFlash attentionDispatch overhead

Benchmarks

Softmax and reductions

Row softmax bandwidth on a 4096 × 4096 matrix against MLX and PyTorch, and a row-sum reduction across threadgroup sizes.

What it measures

bench_softmax defines its own two kernels and runs them on a 4096 × 4096 matrix, one row per program with BLOCK=4096:

  • Row softmax in float32 and float16, computed in float32, with 4, 8, and 16 SIMD groups (num_warps). It compares against mx.softmax(x, axis=-1) and torch.softmax(x, dim=-1) on MPS. GB/s counts one read and one write of the matrix.
  • Row sum in float32 with 4, 8, 16, and 32 SIMD groups, that is, 128 to 1,024 threads per threadgroup. GB/s counts one read of the matrix. This checks whether reductions stay fast as the threadgroup grows.

Enceladus times are the minimum of 20 GPU-timed runs. MLX and PyTorch times are the minimum of 20 wall-clock runs after 10 warmup runs, so they include about 0.1 ms of launch and synchronization overhead.

Results

The following table lists softmax bandwidth by dtype and SIMD-group count. MLX and PyTorch are measured once per dtype, so their columns repeat:

dtypenum_warpsMin (ms)Enceladus GB/sMLX GB/sPyTorch GB/s
float3240.556241.3193.7161.1
float3280.555241.9193.7161.1
float32160.564238.1193.7161.1
float1640.270248.7171.3145.3
float1680.262256.3171.3145.3
float16160.269249.6171.3145.3

The following table lists row-sum bandwidth by threadgroup size:

Threads per threadgroupGB/s
128265.9
256267.0
512267.9
1024266.9

The spread between the fastest and slowest row-sum configuration is 0.7%.

Reading the results

  • Softmax runs at copy bandwidth. Enceladus reaches 238.1-256.3 GB/s, at or above the vector add's bandwidth, so the max, exponent, and sum cost little on top of the memory traffic. The SIMD-group count changes the result by about 3% at most.
  • The lead over MLX is mostly overhead. Enceladus reports 25% more bandwidth than MLX in float32 and 50% more in float16. Converted back to time, MLX takes 0.13-0.14 ms longer in both dtypes, only a little more than the wall-clock overhead of about 0.1 ms. So the data can't show that the Enceladus kernel itself is much faster; it shows that it isn't slower.
  • PyTorch trails both. Its 161.1 and 145.3 GB/s correspond to about 0.83 and 0.46 ms, more than the overhead alone explains.
  • Reductions scale with threadgroup size. Row sums stay within 0.7% from 128 to 1,024 threads, so the reduction doesn't slow down as the threadgroup grows.

Raw output

The following output is the bench_softmax section of the results file:

bench_softmax outputFull report
Device: Apple M4 Pro; softmax 4096 x 4096
dtype      num_warps       ms    GB/s     MLX   torch
float32            4    0.556   241.3   193.7   161.1
float32            8    0.555   241.9   193.7   161.1
float32           16    0.564   238.1   193.7   161.1
float16            4    0.270   248.7   171.3   145.3
float16            8    0.262   256.3   171.3   145.3
float16           16    0.269   249.6   171.3   145.3

Row sum 4096 x 4096 fp32, by threads per threadgroup:
    128 threads:  265.9 GB/s
    256 threads:  267.0 GB/s
    512 threads:  267.9 GB/s
   1024 threads:  266.9 GB/s
  spread between 128 and 1024 threads: 0.7%

Source

benchmarks/bench_softmax.pyGitHub
"""Row softmax bandwidth at 4096 x 4096 against MLX and PyTorch MPS, plus a reduction sweep.

GB/s counts one read and one write of the matrix. Enceladus uses GPU timestamps; MLX and
PyTorch use wall clock around a synchronized call, so they include about 0.1 ms of
launch and sync overhead.

Run with `uv run python benchmarks/bench_softmax.py`.
"""

from __future__ import annotations

import time

import enceladus
import enceladus.language as tl
from enceladus.testing import do_bench

M = N = 4096


@enceladus.jit
def softmax_kernel(out_ptr, in_ptr, stride, 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 + cols, mask=mask, other=-float("inf")).to(tl.float32)
    x = x - tl.max(x, axis=0)
    num = tl.exp(x)
    y = num / tl.sum(num, axis=0)
    tl.store(out_ptr + row * stride + cols, y.to(out_ptr.dtype.element_ty), mask=mask)


@enceladus.jit
def rowsum_kernel(out_ptr, in_ptr, stride, BLOCK: tl.constexpr):
    row = tl.program_id(0)
    x = tl.load(in_ptr + row * stride + tl.arange(0, BLOCK))
    tl.store(out_ptr + row, tl.sum(x, axis=0))


def gbps(nbytes: int, ms: float) -> float:
    return nbytes / (ms * 1e-3) / 1e9


def wall_min(fn, sync, reps: int = 20) -> float:
    for _ in range(10):
        fn()
    sync()
    out = []
    for _ in range(reps):
        t0 = time.perf_counter()
        fn()
        sync()
        out.append((time.perf_counter() - t0) * 1e3)
    return min(out)


def mlx_ms(dtype: str) -> float | None:
    try:
        import mlx.core as mx
    except ImportError:
        return None
    x = mx.random.normal((M, N)).astype(getattr(mx, dtype))
    mx.eval(x)
    return wall_min(lambda: mx.eval(mx.softmax(x, axis=-1)), lambda: None)


def torch_ms(dtype: str) -> float | None:
    try:
        import torch
    except ImportError:
        return None
    if not torch.backends.mps.is_available():
        return None
    x = torch.randn(M, N, device="mps", dtype=getattr(torch, dtype))
    return wall_min(lambda: torch.softmax(x, dim=-1), torch.mps.synchronize)


def main() -> None:
    print(f"Device: {enceladus.get_device().caps.name}; softmax {M} x {N}")
    print(f"{'dtype':<10}{'num_warps':>10}{'ms':>9}{'GB/s':>8}{'MLX':>8}{'torch':>8}")
    for dtype in ("float32", "float16"):
        x = enceladus.randn(M, N, dtype=dtype)
        out = enceladus.empty_like(x)
        nbytes = 2 * M * N * x.itemsize
        ref = [mlx_ms(dtype), torch_ms(dtype)]
        refs = "".join(f"{gbps(nbytes, r):8.1f}" if r else f"{'n/a':>8}" for r in ref)
        for nw in (4, 8, 16):
            def run(x=x, out=out, nw=nw):
                softmax_kernel[(M,)](out, x, N, N, BLOCK=N, num_warps=nw)

            ms = do_bench(run, rep=20, return_mode="min")
            print(f"{dtype:<10}{nw:>10}{ms:9.3f}{gbps(nbytes, ms):8.1f}{refs}")

    # Reduction microbenchmark: row sums across threadgroup sizes.
    x = enceladus.randn(M, N)
    out = enceladus.empty(M)
    print("\nRow sum 4096 x 4096 fp32, by threads per threadgroup:")
    results = {}
    for nw in (4, 8, 16, 32):
        def run(nw=nw):
            rowsum_kernel[(M,)](out, x, N, BLOCK=N, num_warps=nw)

        results[nw * 32] = gbps(M * N * 4, do_bench(run, rep=20, return_mode="min"))
        print(f"  {nw * 32:>5} threads: {results[nw * 32]:6.1f} GB/s")
    spread = (max(results.values()) - min(results.values())) / max(results.values())
    print(f"  spread between 128 and 1024 threads: {spread:.1%}")


if __name__ == "__main__":
    main()