MatmulBenchmarks pages
Benchmarks
Matmul
Matrix multiply throughput for both tl.dot backends and the autotuned kernel, across four shapes and three dtypes, against MLX and PyTorch, plus an exact int8 matmul.
What it measures
bench_matmul multiplies an M × K matrix by a K × N matrix from device memory with the descriptor matmul in examples/04_matmul.py. It runs the following shapes (M × N × K) in float32, float16, and bfloat16:
- 4096 × 4096 × 4096, a large square matmul.
- 2000 × 2000 × 2000, whose size isn't a multiple of the tile size.
- 513 × 513 × 513, a small matmul with a one-element ragged edge.
- 1024 × 4096 × 1024, a rectangular output.
For each shape and dtype, the script times the following Enceladus variants:
- simdgroup: a fixed 64 × 64 × 32 tile over 4 SIMD groups, on the
simdgroup_matrixbackend. - mpp: a fixed 64 × 64 tile over 4 SIMD groups, on the Metal 4
matmul2dbackend. - Tuned:
matmul_tuned, which autotunes overmatmul_configson first use. The table names the configuration it picked. - Fused bias and GELU:
examples/07_matmul_fused.pyon both backends, at 4096³ infloat32andfloat16only.
MLX (mx.eval(a @ b)) and PyTorch MPS (a @ b followed by torch.mps.synchronize()) run in the same 3 interleaved rounds as the Enceladus variants. In each round, every Enceladus variant runs 10 times with GPU timestamps, and then MLX and PyTorch each run 3 warmup calls and 10 wall-clock runs. Every cell reports TFLOPS at the minimum and the median of the 30 samples. Because all of them share the rounds, a change in the GPU clock during the run affects each one alike.
The script also times an exact int8 matmul with int32 accumulation at each shape, with three fixed tiles, and reports TOPS. MLX's matmul takes only floating-point types, and PyTorch MPS int8 matmul returns int8, so neither has a comparable int8 number.
Results
The following table lists TFLOPS for each shape and dtype. Every cell shows the minimum, with the median in parentheses:
| Shape | dtype | simdgroup | mpp | Tuned | Tuned config | MLX | PyTorch |
|---|---|---|---|---|---|---|---|
| 4096³ | float32 | 5.27 (5.14) | 5.40 (4.69) | 5.23 (5.14) | 64×64 sg w4 | 5.21 (5.14) | 5.42 (5.27) |
| 4096³ | float16 | 5.73 (5.60) | 6.04 (5.93) | 6.03 (5.91) | 64×64 mpp w4 | 5.88 (5.75) | 5.86 (5.79) |
| 4096³ | bfloat16 | 5.74 (5.63) | 6.06 (5.92) | 6.06 (5.94) | 64×64 mpp w4 | 5.86 (5.79) | 5.84 (5.78) |
| 2000³ | float32 | 4.50 (4.16) | 5.14 (4.91) | 5.10 (4.78) | 64×32 mpp w4 | 4.75 (4.45) | 4.95 (4.72) |
| 2000³ | float16 | 4.94 (4.71) | 5.76 (5.73) | 5.86 (5.63) | 64×32 mpp w4 | 5.40 (5.25) | 5.33 (5.04) |
| 2000³ | bfloat16 | 4.95 (4.68) | 5.76 (5.74) | 5.86 (5.80) | 64×32 mpp w4 | 5.42 (5.31) | 5.25 (5.10) |
| 513³ | float32 | 1.74 (1.73) | 2.93 (2.87) | 3.74 (3.64) | 32×32 mpp w4 | 1.42 (1.26) | 1.49 (1.19) |
| 513³ | float16 | 1.82 (1.80) | 3.31 (3.26) | 4.31 (4.26) | 32×32 mpp w4 | 1.53 (1.46) | 1.62 (1.50) |
| 513³ | bfloat16 | 1.94 (1.92) | 3.29 (3.22) | 4.31 (4.25) | 32×32 mpp w4 | 1.52 (1.46) | 1.60 (1.51) |
| 1024×4096×1024 | float32 | 5.34 (5.32) | 5.24 (5.19) | 5.34 (5.31) | 64×64 sg w4 | 4.89 (4.72) | 4.95 (4.82) |
| 1024×4096×1024 | float16 | 5.78 (5.77) | 6.05 (6.02) | 6.03 (6.02) | 64×64 mpp w4 | 5.47 (5.27) | 5.35 (5.24) |
| 1024×4096×1024 | bfloat16 | 5.79 (5.77) | 6.04 (6.02) | 6.04 (6.02) | 64×64 mpp w4 | 5.41 (5.26) | 5.39 (5.24) |
In the tuned configuration, sg is the simdgroup backend and wN is the number of SIMD groups. The following table lists the fused bias-plus-GELU matmul at 4096³, in TFLOPS as the minimum (median):
| dtype | simdgroup + bias + GELU | mpp + bias + GELU |
|---|---|---|
float32 | 5.26 (5.14) | 5.48 (4.78) |
float16 | 5.73 (5.63) | 6.00 (5.90) |
The following table lists the exact int8 matmul, in TOPS as the minimum (median). Each tile is BM × BN × BK over w SIMD groups:
| Shape | 64×64×32 w4 | 64×64×64 w4 | 128×64×32 w8 |
|---|---|---|---|
| 4096³ | 4.57 (4.50) | 4.75 (4.70) | 4.72 (4.64) |
| 2000³ | 4.29 (4.14) | 4.51 (4.28) | 4.51 (4.29) |
| 513³ | 2.58 (2.55) | 2.49 (2.44) | 2.15 (2.10) |
| 1024×4096×1024 | 4.42 (4.40) | 4.83 (4.81) | 4.72 (4.71) |
Reading the results
- At 4096³, Enceladus matches or leads MLX in the same rounds.
mppleads MLX by 3% infloat16(6.04 against 5.88) and inbfloat16(6.06 against 5.86). Infloat32,simdgroupand MLX are even, at 5.27 and 5.21, and PyTorch is fastest at 5.42. At this size, the wall-clock overhead in the MLX and PyTorch times is under 1%. float32mppvaries between rounds. At 4096³, its minimum is 5.40 but its median is 4.69, and the fusedmppvariant measures 5.48 (4.78).float32matmul2dthroughput swings by 20% or more from one round to the next, whilesimdgroupand MLX hold steady in the same rounds. Apple's ownmatmul2dreference kernel, run without Enceladus, swings the same way. Grouped (swizzled) program orders don't help: the hardware's 2D dispatch order already gives cache reuse, and a plain row-major 1D order dropsfloat32matmul2dto 2.2 TFLOPS.float16andbfloat16mppare stable, with medians within about 2% of their minimums.mppwins on ragged shapes. At 2000³,mppis 14-17% faster thansimdgroup, and the best Enceladus kernel beats MLX by 8-9% in every dtype, for example 5.86 against 5.40 infloat16. That's more than the wall-clock overhead of about 3% at this size.- 513³ favors small tiles. The tuned 32 × 32
mppkernel reaches 3.74-4.31 TFLOPS, more than twice the fixed 64 × 64simdgroupkernel. A 32 × 32 tile splits the output into 289 programs instead of 81, and wastes less work on the ragged edge. MLX and PyTorch measure 1.42-1.62 TFLOPS here, which is 0.17-0.19 ms per matmul, so the roughly 0.1 ms of wall-clock overhead is about half of their times. Part of the 2.5-2.8× gap is measurement, not kernel speed. - The lead at 1024 × 4096 × 1024 is about the size of the overhead. Enceladus leads MLX by 9-12%, for example 6.05 against 5.47 TFLOPS in
float16. That's a difference of about 0.15 ms on a 1.4-1.8 ms matmul, so most of the lead can come from the wall-clock overhead. - Fused epilogues cost at most 1% in
float16. Bias plus GELU runs at 6.00 TFLOPS onmpp, against 6.04 for the plainmppmatmul, and at 5.73 onsimdgroup, the same as the plainsimdgroupmatmul. - The tuned kernel matches the best fixed variant. In this run, the tuned kernel is at least as fast as the fixed
simdgroupkernel for every shape and dtype, within noise. At 4096³ infloat32, it pickedsimdgroup64 × 64, the fixed configuration itself, and infloat16andbfloat16it pickedmpp64 × 64. In four separate tuning runs with an empty cache on a cool GPU, the tuner pickedmpp64 × 64 at 4096³ forfloat32,float16, andbfloat16every time. Those picks beat the fixedsimdgroupconfiguration by 3-6% and matched the fixedmppconfiguration within 1%. - Exact
int8runs belowfloat16. The fastestint8tile reaches 4.75 TOPS at 4096³ and 4.83 TOPS at 1024 × 4096 × 1024, against 6.04 and 6.05 TFLOPS forfloat16mpp. The 64 × 64 × 64 tile is fastest, or tied for fastest, at every shape except 513³.
For how to choose a backend and autotune a matmul, see Performance. For the tl.dot arguments, see the language reference.
Raw output
The following output is the bench_matmul section of the results file:
Device: Apple M4 Pro
TFLOPS at the minimum and median time over 3 interleaved rounds of 10 runs.
MLX and torch run in the same rounds and use the wall clock.
shape dtype config TFLOPS median
4096x4096x4096 float32 simdgroup 64x64x32 w4 5.27 5.14
float32 mpp 64x64 w4 5.40 4.69
float32 tuned 64x64 sg w4 5.23 5.14
float32 simdgroup + bias + GELU 5.26 5.14
float32 mpp + bias + GELU 5.48 4.78
float32 MLX a @ b 5.21 5.14
float32 torch a @ b 5.42 5.27
4096x4096x4096 float16 simdgroup 64x64x32 w4 5.73 5.60
float16 mpp 64x64 w4 6.04 5.93
float16 tuned 64x64 mpp w4 6.03 5.91
float16 simdgroup + bias + GELU 5.73 5.63
float16 mpp + bias + GELU 6.00 5.90
float16 MLX a @ b 5.88 5.75
float16 torch a @ b 5.86 5.79
4096x4096x4096 bfloat16 simdgroup 64x64x32 w4 5.74 5.63
bfloat16 mpp 64x64 w4 6.06 5.92
bfloat16 tuned 64x64 mpp w4 6.06 5.94
bfloat16 MLX a @ b 5.86 5.79
bfloat16 torch a @ b 5.84 5.78
int8 exact 64x64x32 w4 4.57 4.50
int8 exact 64x64x64 w4 4.75 4.70
int8 exact 128x64x32 w8 4.72 4.64
2000x2000x2000 float32 simdgroup 64x64x32 w4 4.50 4.16
float32 mpp 64x64 w4 5.14 4.91
float32 tuned 64x32 mpp w4 5.10 4.78
float32 MLX a @ b 4.75 4.45
float32 torch a @ b 4.95 4.72
2000x2000x2000 float16 simdgroup 64x64x32 w4 4.94 4.71
float16 mpp 64x64 w4 5.76 5.73
float16 tuned 64x32 mpp w4 5.86 5.63
float16 MLX a @ b 5.40 5.25
float16 torch a @ b 5.33 5.04
2000x2000x2000 bfloat16 simdgroup 64x64x32 w4 4.95 4.68
bfloat16 mpp 64x64 w4 5.76 5.74
bfloat16 tuned 64x32 mpp w4 5.86 5.80
bfloat16 MLX a @ b 5.42 5.31
bfloat16 torch a @ b 5.25 5.10
int8 exact 64x64x32 w4 4.29 4.14
int8 exact 64x64x64 w4 4.51 4.28
int8 exact 128x64x32 w8 4.51 4.29
513x513x513 float32 simdgroup 64x64x32 w4 1.74 1.73
float32 mpp 64x64 w4 2.93 2.87
float32 tuned 32x32 mpp w4 3.74 3.64
float32 MLX a @ b 1.42 1.26
float32 torch a @ b 1.49 1.19
513x513x513 float16 simdgroup 64x64x32 w4 1.82 1.80
float16 mpp 64x64 w4 3.31 3.26
float16 tuned 32x32 mpp w4 4.31 4.26
float16 MLX a @ b 1.53 1.46
float16 torch a @ b 1.62 1.50
513x513x513 bfloat16 simdgroup 64x64x32 w4 1.94 1.92
bfloat16 mpp 64x64 w4 3.29 3.22
bfloat16 tuned 32x32 mpp w4 4.31 4.25
bfloat16 MLX a @ b 1.52 1.46
bfloat16 torch a @ b 1.60 1.51
int8 exact 64x64x32 w4 2.58 2.55
int8 exact 64x64x64 w4 2.49 2.44
int8 exact 128x64x32 w8 2.15 2.10
1024x4096x1024 float32 simdgroup 64x64x32 w4 5.34 5.32
float32 mpp 64x64 w4 5.24 5.19
float32 tuned 64x64 sg w4 5.34 5.31
float32 MLX a @ b 4.89 4.72
float32 torch a @ b 4.95 4.82
1024x4096x1024 float16 simdgroup 64x64x32 w4 5.78 5.77
float16 mpp 64x64 w4 6.05 6.02
float16 tuned 64x64 mpp w4 6.03 6.02
float16 MLX a @ b 5.47 5.27
float16 torch a @ b 5.35 5.24
1024x4096x1024 bfloat16 simdgroup 64x64x32 w4 5.79 5.77
bfloat16 mpp 64x64 w4 6.04 6.02
bfloat16 tuned 64x64 mpp w4 6.04 6.02
bfloat16 MLX a @ b 5.41 5.26
bfloat16 torch a @ b 5.39 5.24
int8 exact 64x64x32 w4 4.42 4.40
int8 exact 64x64x64 w4 4.83 4.81
int8 exact 128x64x32 w8 4.72 4.71Source
"""Matmul TFLOPS for both `tl.dot` backends, against MLX and PyTorch MPS.
It also reports exact `int8` matmul (`int32` accumulation) in TOPS. MLX's matmul takes
only floating-point types, and PyTorch MPS `int8` matmul returns `int8`, so neither has a
comparable `int8` number.
Enceladus uses GPU timestamps. MLX and PyTorch use the wall clock around a synchronized
call (overhead is under 1% at 4096^3). All of them run in the same interleaved rounds, so
GPU clock changes, such as thermal throttling on a laptop, affect each one alike. Operands
come from memory, never constants.
Run with `uv run python benchmarks/bench_matmul.py [--quick]`.
"""
from __future__ import annotations
import importlib.util
import statistics
import sys
import time
from pathlib import Path
import numpy as np
import enceladus
import enceladus.language as tl
from enceladus.testing import do_bench
ROOT = Path(__file__).resolve().parents[1]
SHAPES = [(4096, 4096, 4096), (2000, 2000, 2000), (513, 513, 513), (1024, 4096, 1024)]
def load(stem: str):
spec = importlib.util.spec_from_file_location(stem, ROOT / "examples" / f"{stem}.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def wall_samples(fn, sync, reps: int = 10) -> list[float]:
"""Returns the wall-clock time of `reps` synchronized calls of `fn`, after 3 warmups."""
for _ in range(3):
fn()
sync()
out = []
for _ in range(reps):
t0 = time.perf_counter()
fn()
sync()
out.append((time.perf_counter() - t0) * 1e3)
return out
def mlx_matmul(m, n, k, dtype):
"""Returns a timed MLX `a @ b` and its sync, or None without MLX."""
try:
import mlx.core as mx
except ImportError:
return None
a = mx.random.normal((m, k)).astype(getattr(mx, dtype))
b = mx.random.normal((k, n)).astype(getattr(mx, dtype))
mx.eval(a, b)
return lambda: mx.eval(a @ b), lambda: None
def torch_matmul(m, n, k, dtype):
"""Returns a timed PyTorch MPS `a @ b` and its sync, or None without PyTorch."""
try:
import torch
except ImportError:
return None
a = torch.randn(m, k, device="mps", dtype=getattr(torch, dtype))
b = torch.randn(k, n, device="mps", dtype=getattr(torch, dtype))
return lambda: a @ b, torch.mps.synchronize
def interleaved(variants: dict, refs: dict | None = None, rounds: int = 3,
rep: int = 10) -> dict[str, list[float]]: # fmt: skip
"""Times each variant `rounds` times in turn and returns all samples per variant.
`variants` launch Enceladus kernels, timed with GPU timestamps. `refs` maps a name to
a `(fn, sync)` pair timed with the wall clock. Alternating all of them spreads GPU
clock changes, such as thermal throttling, and other GPU users across them.
"""
refs = refs or {}
samples: dict[str, list[float]] = {name: [] for name in [*variants, *refs]}
for _ in range(rounds):
for name, fn in variants.items():
samples[name] += do_bench(fn, rep=rep, return_mode="all")
for name, (fn, sync) in refs.items():
samples[name] += wall_samples(fn, sync, rep)
return samples
def row(label: str, dtype: str, cfg: str, flops: float, ms: list[float]) -> None:
best, med = min(ms), statistics.median(ms)
print(f"{label:<18}{dtype:<10}{cfg:<24}{flops / best / 1e9:8.2f}{flops / med / 1e9:8.2f}")
@enceladus.jit
def int8_matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K, 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], [K, 1], [BM, BK])
b = tl.make_tensor_descriptor(b_ptr, [K, N], [N, 1], [BK, BN])
c = tl.make_tensor_descriptor(c_ptr, [M, N], [N, 1], [BM, BN])
acc = tl.zeros((BM, BN), dtype=tl.int32)
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)
def int8_variants(m: int, n: int, k: int) -> dict:
"""Returns exact int8 matmul launches, after checking one against NumPy."""
rng = np.random.default_rng(0)
a_np = rng.integers(-128, 128, (m, k), dtype=np.int8)
b_np = rng.integers(-128, 128, (k, n), dtype=np.int8)
a, b = enceladus.from_numpy(a_np), enceladus.from_numpy(b_np)
c = enceladus.empty((m, n), "int32")
out = {}
for bm, bn, bk, nw in ((64, 64, 32, 4), (64, 64, 64, 4), (128, 64, 32, 8)):
grid = (enceladus.cdiv(n, bn), enceladus.cdiv(m, bm))
out[f"exact {bm}x{bn}x{bk} w{nw}"] = (
lambda grid=grid, bm=bm, bn=bn, bk=bk, nw=nw: int8_matmul_kernel[grid](
a, b, c, m, n, k, BM=bm, BN=bn, BK=bk, num_warps=nw))
if m * n * k <= 1 << 33:
next(iter(out.values()))()
want = (a_np.astype(np.int64) @ b_np.astype(np.int64)).astype(np.int32)
if not np.array_equal(c.numpy(), want):
raise AssertionError(f"int8 matmul {m}x{n}x{k} differs from NumPy")
return out
def main() -> None:
ex = load("04_matmul")
fused = load("07_matmul_fused")
shapes = SHAPES[:1] if "--quick" in sys.argv else SHAPES
print(f"Device: {enceladus.get_device().caps.name}")
print("TFLOPS at the minimum and median time over 3 interleaved rounds of 10 runs.")
print("MLX and torch run in the same rounds and use the wall clock.")
print(f"{'shape':<18}{'dtype':<10}{'config':<24}{'TFLOPS':>8}{'median':>8}")
for m, n, k in shapes:
flops = 2 * m * n * k
for dtype in ("float32", "float16", "bfloat16"):
a, b = enceladus.randn(m, k, dtype=dtype), enceladus.randn(k, n, dtype=dtype)
c = enceladus.empty((m, n), dtype)
refs = {name: r for name, r in (("MLX a @ b", mlx_matmul(m, n, k, dtype)),
("torch a @ b", torch_matmul(m, n, k, dtype)))
if r is not None} # fmt: skip
ex.matmul_tuned(a, b, c) # tunes on first use
best = ex.matmul_desc_tuned.config_for(a, b, c, m, n, k, k, n, n)
variants = {
"simdgroup 64x64x32 w4": lambda: ex.matmul_desc(a, b, c, 64, 64, 32, 4,
"simdgroup"),
"mpp 64x64 w4": lambda: ex.matmul_desc(a, b, c, 64, 64, 32, 4, "mpp"),
f"tuned {best.kwargs['BM']}x{best.kwargs['BN']} "
f"{'mpp' if best.dot_backend == 'mpp' else 'sg'} w{best.num_warps}":
lambda: ex.matmul_tuned(a, b, c),
} # fmt: skip
if (m, n, k) == SHAPES[0] and dtype != "bfloat16":
bias = enceladus.randn(n, dtype=dtype)
for backend in ("simdgroup", "mpp"):
variants[f"{backend} + bias + GELU"] = (
lambda backend=backend: fused.matmul_bias_gelu(a, b, bias, c,
dot_backend=backend))
res = interleaved(variants, refs)
label = f"{m}x{n}x{k}"
for i, (cfg, ms) in enumerate(res.items()):
row(label if i == 0 else "", dtype, cfg, flops, ms)
res = interleaved(int8_variants(m, n, k))
for cfg, ms in res.items():
row("", "int8", cfg, flops, ms)
if __name__ == "__main__":
main()