Skip to content
lastowlPublic

About

Fused variable-length attention (flash-attention style) for Apple Silicon / PyTorch MPS

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

mtlattn

Fused flash-attention (forward + backward) for Apple Silicon — Metal compute kernels for PyTorch MPS tensors, with online softmax, fp32 accumulation, no padding and no materialized [L, L] score matrix.

Since torch 2.14, PyTorch's own MPS SDPA has a fast matmul2d prefill kernel, and it beats mtlattn on plain dense attention. mtlattn covers what native SDPA still doesn't do well, and hands plain attention to native SDPA wherever that is faster, so calling it is never a slowdown:

vs native MPS SDPA (torch 2.14.1, M5 Pro)
Training (fused backward; native MPS SDPA has none) 1.1–5.4× faster, far less memory (native needs +11 GiB at 8K tokens)
Sliding-window attention (window=) 5–10× faster (native needs a dense mask; FlexAttention on MPS is ~40× slower still)
head_dim 80 / 88 / 160 (SD1.5, Hunyuan DiT) 1.3–2.9× faster (outside native's prefill kernel)
2–8-query decode (speculative decoding) ~1.75× faster
plain dense / ragged attention, 1-query decode, fp32, masks native SDPA is faster → routed there automatically

Also: a variable-length (cu_seqlens) API that's a drop-in for flash_attn's varlen entry points (packed ragged batches, no padding), causal masking, GQA/MQA, an additive attention bias (prefix-LM / ALiBi / custom masks, forward + backward), and a scaled_dot_product_attention patch that sends a model's training calls to the fused backward.

Built for pixal3d-mac (image-to-3D on Mac), but standalone: sparse / 3D transformers, LLMs (Llama / Mistral / Qwen-class: causal + GQA + sliding-window), and fine-tuning on MPS.

Install

pip install mtlattn

Requires macOS on Apple Silicon and PyTorch ≥ 2.14 with MPS (on older torch, use mtlattn<0.5). The published wheels are built against torch 2.14 for Python 3.11–3.13 — a torch C++ extension is tied to the torch version it was built against, and a mismatched wheel fails at call time with errors like tensor does not have a device. One arm64 wheel covers every Apple Silicon Mac: the Metal 4 matmul2d (MPP) path runs on any GPU with macOS 26.2+ (the M5 Neural Accelerator where present, the regular matrix units on M3/M4), and the portable simdgroup path covers M1/M2 and pre-26.2. Both metallibs are bundled and the MPP framework is weak-linked, so it loads on macOS 13+.

On other torch versions, build from source:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \
  pip install --no-build-isolation .

Building from source needs Xcode with the Metal Toolchain (xcodebuild -downloadComponent MetalToolchain); the metal4.0 MPP path additionally needs Xcode 26 / macOS 26.2, else the build falls back to the portable simdgroup kernel.

Use

import mtlattn, torch

# q, k, v: [total_tokens, num_heads, head_dim] bf16/fp16/fp32 on MPS.
# cu_seqlens_*: int32 [num_seqs + 1], cumulative sequence lengths.
# GQA/MQA: k/v may have fewer heads than q (q heads must be a multiple of
# kv heads); each query head reads kv head (q_head // (H_q / H_kv)).
out = mtlattn.varlen_attention(q, k, v, cu_seqlens_q, cu_seqlens_kv,
                               max_seqlen_q, scale=None, causal=False)

# causal=True: query i attends key j iff j <= i + (kv_len - q_len), the
# flash_attn end-aligned convention (self-attention and cached-decode both
# work). Fully-masked KV tiles are skipped.

# window=W: sliding-window / local attention — query i attends only its last
# W keys (relative to the causal diagonal). Mistral-style SWA is causal=True
# with window=W. The kernel jumps straight to each block's window band, so
# cost is O(W) not O(seqlen).

# attn_bias=B: arbitrary ADDITIVE mask, [total_q, H or 1, max_kv] fp32, added to
# the logits before softmax (logit = scale*(q·k) + bias). dim1==1 broadcasts
# across heads. Use it for prefix-LM, ALiBi, custom/soft patterns — anything not
# expressible as causal/window. Indexed by global query row and seq-local key;
# composes with causal/window/GQA. Applied in forward AND backward (the bias is
# treated as constant — a grad-requiring bias raises). MPP-only (macOS 26.2+,
# fp16/bf16, head_dim 64/96/128/256).
out = mtlattn.varlen_attention(q, k, v, cu_seqlens_q, cu_seqlens_kv,
                               max_seqlen_q, attn_bias=B)

# flash_attn-compatible wrappers (differentiable — forward + backward):
out = mtlattn.flash_attn_varlen_qkvpacked_func(qkv, cu_seqlens, max_seqlen)
out = mtlattn.flash_attn_varlen_kvpacked_func(q, kv, cu_q, cu_k, max_q, max_k)

varlen_attention is differentiable: if q/k/v require grad it runs the fused backward kernel (composing with causal / GQA / sliding-window / additive bias). Plain attention (no window, no attn_bias) goes to native MPS SDPA wherever the kernel doesn't win; set MTLATTN_FORCE_KERNEL=1 to always use the kernel.

Drop-in for scaled_dot_product_attention

import mtlattn

mtlattn.replace_sdpa()   # patches F.scaled_dot_product_attention globally
# ... train / run any PyTorch/HF model on MPS ...
mtlattn.restore_sdpa()   # undo

replace_sdpa() intercepts only the calls mtlattn wins on the MPP path: training (any call where q/k/v require grad — forward + fused backward, at any sequence length) and inference with head_dim 80/88/160 at min_seqlen (default 1024) tokens or more. Everything else — masked calls, dropout, other head dims, the simdgroup-only machines (M1/M2, macOS < 26.2) — goes to native SDPA unchanged. mtlattn.sdpa(q, k, v, is_causal=...) is the same dense [B, H, N, D] adapter callable directly (no attn_mask/dropout).

head_dim: 64/80/88/96/128/160/256 run on the MPP path; any other head_dim ≤ 128 runs on the portable simdgroup kernel; 160/256 need the MPP path (macOS 26.2+). fp16 / bf16 / fp32.

Runnable tour of all of the above: examples/quickstart.py.

Using it in your project

ComfyUI. Install ComfyUI-mtlattn into custom_nodes/ and add its Apply mtlattn Attention node between the model loader and the sampler.

Training / fine-tuning on MPS — no code changes. mtlattn.replace_sdpa() before building the model routes every attention backward through the fused kernel.

Already using flash_attn. The varlen entry points are signature-compatible and differentiable, so it's an import swap:

# from flash_attn import flash_attn_varlen_qkvpacked_func
from mtlattn import flash_attn_varlen_qkvpacked_func

Custom transformer / new code. Call the kernel directly with the flags you need — ragged batches, causal, GQA, sliding window all compose:

out = mtlattn.varlen_attention(q, k, v, cu_q, cu_kv, max_seqlen_q,
                               causal=True, window=4096)

Performance

Two kernel paths, selected automatically at runtime:

  • MPP path (default on any GPU with macOS 26.2+, head_dim 64/80/88/96/128/160/256, fp16/bf16): fused varlen attention through Metal 4 Metal Performance Primitives matmul2d. On M5 matmul2d targets the per-core Neural Accelerator; on M3/M4 it runs on the regular GPU matrix units. Forward ~10.5 TF/s, backward ~5.8 TF/s on an M5 Pro.
  • simdgroup path (portable, M1+): the fallback on older GPUs/macOS and odd head dims, or with MTLATTN_NO_MPP=1.

Measured on an M5 Pro, torch 2.14.1, bf16, through the public API (each row includes the routing; "native" is F.scaled_dot_product_attention):

workload native mtlattn
training fwd+bwd, causal, H12 D128, 4K tokens 95.6 ms 29.6 ms (3.2×)
training fwd+bwd, causal, H24 D64, 4K tokens 150.8 ms 27.8 ms (5.4×)
training fwd+bwd, H12 D128, 8K tokens 351 ms, +11.3 GiB 226 ms
sliding window W=1024, causal, H32/8 GQA, 16K 246 ms 25.6 ms (9.6×)
sliding window W=4096, causal, H32/8 GQA, 32K 1002 ms 189 ms (5.3×)
head_dim 160, H8, 4K 27.0 ms 9.2 ms (2.9×)
head_dim 80, H16, 8K 51.2 ms 39.8 ms (1.3×)
4-query decode, KV 8K, H32/8 GQA 0.79 ms 0.45 ms (1.75×)
dense prefill H12 D128, 16K (routed native) 65 ms 65 ms

The kernel alone on that dense row is 160 ms — native SDPA on torch 2.14 is ~2.4× faster for plain prefill, which is why it's routed there. On the simdgroup path (M1/M2, macOS < 26.2) the kernel loses to native even for training, so only window / attn_bias calls use it there.

Reproduce the kernel numbers with the benchmark CLI (it always times the kernel, not the routing):

python -m mtlattn.bench --paths both --vs-sdpa --causal   # MPP, simdgroup, native SDPA
python -m mtlattn.bench --sizes 8192 --causal --window 256

Benchmarking caveat: Apple-Silicon GPU clocks are load-state-dependent — a cold call after idle can read ~¼ of the warmed number, and short bursts understate sustained large-N throughput. Warm up and take a median. Full measured ceilings, what bounds each kernel, the tuning constants, and the known dead-ends are in docs/PERFORMANCE.md.

Correctness

python tests/test_correctness.py — the kernels vs a per-sequence fp32 reference across fp16/bf16/fp32, ragged self/cross attention, packed forms, odd head dims, thousands of tiny windows, causal / GQA-MQA / sliding-window (and their combinations), additive bias forward + backward, decode, the sdpa() adapter, the native-SDPA routing, replace_sdpa() training interception, and an outlier-channel overflow regression (transformer activations spike to ~10²–10³; fp32 fragment accumulation is required — half fragments overflow to NaN).

Notes

  • Fragments accumulate in fp32 for all input dtypes. The softmax scale is folded into Q at staging so scores live near ±1 (better fragment precision than at raw logit magnitude).
  • The kernel encodes into PyTorch's MPSStream, so it sequences correctly with surrounding torch ops without a per-call CPU sync. The native-SDPA routing for ragged batches reads cu_seqlens on the host (one sync).

Credits

  • The torch↔Metal buffer bridge pattern follows Pedro Naugusto's mtlgemm.
  • The MPP path targets the M5 Neural Accelerator via Metal 4 matmul2d; the simdgroup fallback draws on the tiling approach of Philip Turner's metal-flash-attention.
  • The replace_sdpa() drop-in and the causal / GQA / sliding-window feature set were inspired by mpsops/mps-flash-attention, a related flash-attention-for-PyTorch-MPS project; mtlattn's own focus is variable-length (cu_seqlens) attention and the M5 accelerator path.

License

MIT.

About

Fused variable-length attention (flash-attention style) for Apple Silicon / PyTorch MPS

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages