Flash attentionBenchmarks pages
Benchmarks
Flash attention
Flash attention forward throughput in float16, causal and non-causal, against MLX's fused attention kernel.
What it measures
bench_attention runs the autotuned flash attention kernel from examples/08_flash_attention.py and compares it with mx.fast.scaled_dot_product_attention. The benchmark uses the following setup:
- Shapes: batch 1 and 16 heads, with sequence lengths of 2,048 and 4,096 and head dimensions of 64 and 128. Each shape runs with and without a causal mask.
- Data:
float16queries, keys, and values. MLX gets copies of the same data. - Configuration: the autotuner picks the block sizes and SIMD-group count on first use. The table lists the configuration as
BLOCK_M×BLOCK_NandwSIMD groups. - Timing: Enceladus and MLX alternate in one process for 3 rounds of 10 runs. Each cell shows the best round's minimum and, in parentheses, the median of the round medians. MLX's wall-clock time adds about 0.1 ms, under 2% at these sizes.
- FLOPs: the two matmuls, 4 × batch × heads × sequence length² × head dimension, halved for a causal mask.
Results
The following table lists TFLOPS as the minimum (median). The ratio is the Enceladus minimum time divided by the MLX minimum time, so a ratio below 1.00 means Enceladus is faster:
| Sequence length | Head dim | Causal | Config | Enceladus | MLX | Ratio |
|---|---|---|---|---|---|---|
| 2048 | 64 | No | 64×16 w4 | 5.23 (5.11) | 5.23 (5.08) | 1.00× |
| 2048 | 64 | Yes | 64×32 w8 | 4.96 (4.94) | 4.75 (4.62) | 0.96× |
| 2048 | 128 | No | 64×32 w8 | 5.07 (4.89) | 5.20 (5.05) | 1.03× |
| 2048 | 128 | Yes | 64×32 w8 | 4.83 (4.77) | 4.87 (4.71) | 1.01× |
| 4096 | 64 | No | 64×32 w4 | 5.26 (5.16) | 5.37 (5.26) | 1.02× |
| 4096 | 64 | Yes | 64×32 w8 | 5.06 (4.88) | 5.16 (5.01) | 1.02× |
| 4096 | 128 | No | 64×32 w8 | 5.04 (4.88) | 5.29 (5.14) | 1.05× |
| 4096 | 128 | Yes | 64×32 w8 | 4.93 (4.73) | 5.08 (5.01) | 1.03× |
Reading the results
- Enceladus is within 5% of MLX everywhere. The eight shapes range from 4% faster to 5% slower, with a ratio from 0.96× to 1.05×.
- Enceladus leads or ties at the smallest shapes. At sequence length 2,048 with head dimension 64, the two tie at 5.23 TFLOPS without a mask. With a causal mask, Enceladus is 4% faster by minimum time, and its median, 4.94, is 7% above MLX's 4.62.
- MLX leads as the problem grows. At sequence length 4,096, MLX is 2-5% faster, with the largest gap at head dimension 128 without a mask: 5.04 against 5.29 TFLOPS. The wall-clock overhead is under 2% here, so this gap isn't a measurement effect.
- Head dimension 128 runs slower than 64 for both implementations, for example 5.04 against 5.26 TFLOPS for Enceladus and 5.29 against 5.37 for MLX at sequence length 4,096 without a mask.
- One configuration covers most shapes. The autotuner picked 64×32 with 8 SIMD groups for six of the eight shapes.
For tuning attention kernels, including attention_configs and dot_warps, see Performance.
Raw output
The following output is the bench_attention section of the results file:
Device: Apple M4 Pro; float16; TFLOPS as min (median)
shape causal config Enceladus MLX ratio
(1, 16, 2048, 64) False 64x16 w4 5.23 (5.11) 5.23 (5.08) 1.00x
(1, 16, 2048, 64) True 64x32 w8 4.96 (4.94) 4.75 (4.62) 0.96x
(1, 16, 2048, 128) False 64x32 w8 5.07 (4.89) 5.20 (5.05) 1.03x
(1, 16, 2048, 128) True 64x32 w8 4.83 (4.77) 4.87 (4.71) 1.01x
(1, 16, 4096, 64) False 64x32 w4 5.26 (5.16) 5.37 (5.26) 1.02x
(1, 16, 4096, 64) True 64x32 w8 5.06 (4.88) 5.16 (5.01) 1.02x
(1, 16, 4096, 128) False 64x32 w8 5.04 (4.88) 5.29 (5.14) 1.05x
(1, 16, 4096, 128) True 64x32 w8 4.93 (4.73) 5.08 (5.01) 1.03xSource
"""Flash attention forward TFLOPS against MLX `mx.fast.scaled_dot_product_attention`.
Enceladus uses GPU timestamps. MLX uses the wall clock around a synchronized call, which
adds about 0.1 ms, under 2% at these sizes. The two run interleaved in one process, round
after round, so clock and thermal drift affect both alike. Each round reports the minimum
and the median of 10 runs; the table shows the best round and the median of the round
medians.
FLOPs count the two matmuls, `4 * batch * heads * seq_len^2 * head_dim`, halved for a
causal mask.
Run with `uv run python benchmarks/bench_attention.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
from enceladus.testing import do_bench
ROOT = Path(__file__).resolve().parents[1]
# (batch, heads, seq_len, head_dim)
SHAPES = [(1, 16, 2048, 64), (1, 16, 2048, 128), (1, 16, 4096, 64), (1, 16, 4096, 128)]
ROUNDS, REPS = 3, 10
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 tflops(shape, causal: bool, ms: float) -> float:
z, h, n, d = shape
flops = 4 * z * h * n * n * d / (2 if causal else 1)
return flops / (ms * 1e-3) / 1e12
def wall(fn, reps: int = REPS) -> list[float]:
for _ in range(3):
fn()
out = []
for _ in range(reps):
t0 = time.perf_counter()
fn()
out.append((time.perf_counter() - t0) * 1e3)
return out
def main() -> None:
import mlx.core as mx
ex = load("08_flash_attention")
shapes = SHAPES[:2] if "--quick" in sys.argv else SHAPES
print(f"Device: {enceladus.get_device().caps.name}; float16; TFLOPS as min (median)")
print(f"{'shape':<20}{'causal':<8}{'config':<14}{'Enceladus':>16}{'MLX':>16}{'ratio':>8}")
for shape in shapes:
z, h, n, d = shape
q, k, v = (enceladus.randn(*shape, dtype="float16", seed=i) for i in range(3))
o = enceladus.empty(shape, "float16")
mq, mk, mv = (mx.array(np.array(t.numpy())) for t in (q, k, v))
mx.eval(mq, mk, mv)
scale = 1.0 / d**0.5
for causal in (False, True):
ex.attention_tuned(q, k, v, causal, o=o) # tunes on first use
best = ex.attention_tuned_kernel.config_for(q, k, v, o, scale, n, n * d, d,
HEAD_DIM=d, CAUSAL=causal) # fmt: skip
mask = "causal" if causal else None
def run_ours():
ex.attention_tuned(q, k, v, causal, o=o)
def run_mlx():
mx.eval(mx.fast.scaled_dot_product_attention(mq, mk, mv, scale=scale,
mask=mask)) # fmt: skip
ours, theirs = [], []
for _ in range(ROUNDS):
ours.append(do_bench(run_ours, rep=REPS, return_mode="all"))
theirs.append(wall(run_mlx))
o_min = min(min(r) for r in ours)
o_med = statistics.median(statistics.median(r) for r in ours)
m_min = min(min(r) for r in theirs)
m_med = statistics.median(statistics.median(r) for r in theirs)
cfg = f"{best.kwargs['BLOCK_M']}x{best.kwargs['BLOCK_N']} w{best.num_warps}"
ot = f"{tflops(shape, causal, o_min):.2f} ({tflops(shape, causal, o_med):.2f})"
mt = f"{tflops(shape, causal, m_min):.2f} ({tflops(shape, causal, m_med):.2f})"
print(f"{str(shape):<20}{str(causal):<8}{cfg:<14}{ot:>16}{mt:>16}"
f"{o_min / m_min:>7.2f}x") # fmt: skip
if __name__ == "__main__":
main()