PyTorch 2.13 brings FlexAttention to Apple Silicon: a 12x sparse-attention speedup

FlexAttention reached Apple Silicon in PyTorch 2.13, with up to ~12x faster sparse attention than SDPA on the Mac's Metal (MPS) backend.

Read time
11 min
Word count
1.5K
Sections
10
FAQs
8
Share
Glowing silicon processor with radiating data pathways on a dark studio surface
Sparse attention kernels now run on Apple Silicon in PyTorch 2.13.
On this page · 10 sections
  1. What shipped for Apple Silicon in PyTorch 2.13
  2. The benchmark, and what it does not say
  3. Why sparse attention is the workload that benefits
  4. How to use FlexAttention on a Mac
  5. FlexAttention on PyTorch MPS versus MLX
  6. What else in 2.13 is worth your attention
  7. India-specific considerations
  8. FAQ
  9. How eCorpIT can help
  10. References

Summary. PyTorch 2.13 shipped on July 8, 2026, and for anyone training or running models on a Mac the headline is one line in the release notes: FlexAttention now runs on Apple Silicon through the Metal (MPS) backend, with up to a ~12x speedup over scaled dot-product attention (SDPA) on sparse masks. The release notes give the exact case: a 1x8x32768x64 attention shape with a 256-element sliding window (0.8% density) runs in about 35 ms with FlexAttention versus about 431 ms with SDPA, a ~12.3x gain. A smaller 8192-length, 64-window case lands at ~4.15x. The 2.13 release carries 3,328 commits from 526 contributors since 2.12. It matters because an entry M4 Mac mini starts at $599 in the US and ₹1,18,900 for the 512GB model in India (Apple), so a lot of local machine-learning work now happens on Metal rather than on rented NVIDIA GPUs. The catch: the MPS path is marked API Unstable, and for plain LLM inference MLX is often still faster.

This guide covers what actually shipped, what the benchmark does and does not say, how to write a sparse mask in about two lines of Python, and when FlexAttention on PyTorch MPS is the right tool versus MLX.

What shipped for Apple Silicon in PyTorch 2.13

Two changes drive Mac performance in this release. First, FlexAttention gained hand-written Metal kernels for both the sparse prefill and decode paths, including grouped-query attention (GQA) and captured buffers. Second, a broad set of MPS operations moved off Apple's MPSGraph framework onto hand-written Metal compute kernels, including copy and cast, uniform and normal random generation, comparisons, reductions such as sum and mean, cumsum and cumprod, sort, embedding backward, and scatter and gather. The native path removes MPSGraph's per-operation compilation cost and cuts kernel launch latency, according to the PyTorch 2.13 release notes.

FlexAttention is PyTorch's unified way to express a custom attention pattern as a plain Python function that the compiler fuses into a fast kernel. As the release notes put it, "instead of writing a custom CUDA kernel for every attention variant you need, FlexAttention will write a 2-line Python function, and the compiler builds a fast kernel for you automatically." That idea shipped for CUDA in 2024 as FlexAttention; 2.13 brings the same programming model to the Mac.

Here is the fuller list of what landed, and who each piece helps.

PyTorch 2.13 feature What it does Who it helps
FlexAttention on MPS Fused sparse-attention kernels on Apple Silicon, up to ~12x over SDPA Mac ML developers running long-context or windowed attention
Native Metal MPS kernels Moves common ops off MPSGraph to cut launch latency Anyone training or doing inference on a Mac GPU
nn.LinearCrossEntropyLoss Fuses the final projection and loss, up to ~4x lower peak memory Teams training large-vocabulary language models
torch.load for safetensors Loads .safetensors natively, no extra library Anyone distributing or loading model weights
FSDP2 reduce-scatter overlap Gives reduce-scatter its own group so it overlaps all-gather Multi-GPU distributed training
Python 3.15 wheels Linux-only wheels, including free-threaded 3.15t Early adopters of the new CPython
torchcomms backend New communications backend with better fault tolerance Large-cluster training operators

The benchmark, and what it does not say

The 12x figure is specific, and reading it precisely keeps expectations honest. It measures a sliding-window mask that is 99.2% empty, so FlexAttention skips almost all of the key-value blocks that SDPA still walks through. That is exactly the workload where block sparsity pays off.

Shape and mask (from the 2.13 notes) Density FlexAttention SDPA Speedup
1x8x32768x64, 256 sliding window 0.8% ~35 ms ~431 ms ~12.3x
8192 length, 64 window low faster slower ~4.15x
Dense patterns ~100% not favored favored SDPA wins

The release notes are direct that "dense patterns continue to favor SDPA, as expected." So the win is not universal. If your attention is full or near-full, SDPA remains the better call, and FlexAttention gives you no free speedup. The gain scales with how sparse the mask is and how long the sequence runs, which is why the 32768-token case beats the 8192-token case by a wide margin.

One more caveat sits in the release notes: the MPS FlexAttention work is labelled API Unstable. That is the right maturity signal for a first landing. Pin your PyTorch version, keep a test that compares FlexAttention output against SDPA on a small case, and expect the surface to shift in later releases.

Why sparse attention is the workload that benefits

Sliding-window attention is a good, real example of the pattern FlexAttention accelerates. Mistral 7B, released in 2023, uses a 4096-token sliding window on top of a 32,768-token maximum context, so each token attends to at most 4096 neighbours rather than the whole sequence (Mistral 7B paper). Stacked across 32 layers, that local window still reaches a theoretical span near 131K tokens, while the key-value cache can be capped at the window size, which halves cache memory at a sequence length of 8192 per Mistral's own writeup.

The point for a Mac developer: any model or research idea that uses local, windowed, block, or otherwise structured-sparse attention is now a candidate for a real speedup on Apple Silicon, without hand-writing a Metal kernel. Document masking, causal-plus-window schemes, and prefix-LM patterns all fit the same mould. For retrieval-heavy systems, the attention pattern often interacts with how you store context; if you are weighing where embeddings live, our note on pgvector versus a dedicated vector database covers that trade-off.

How to use FlexAttention on a Mac

The API mirrors the CUDA version. You describe the sparsity as a mask_mod function, pre-compute a BlockMask with create_block_mask, then call flex_attention. A sliding-window causal mask is about two lines of logic.


            import torch
from torch.nn.attention.flex_attention import flex_attention, create_block_mask

device = "mps"  # Apple Silicon GPU via Metal
WINDOW = 256

def sliding_window(b, h, q_idx, kv_idx):
    causal = q_idx >= kv_idx
    within = q_idx - kv_idx <= WINDOW
    return causal & within

# B, H, Q_LEN, KV_LEN
block_mask = create_block_mask(sliding_window, 1, 8, 32768, 32768, device=device)

q = torch.randn(1, 8, 32768, 64, device=device, dtype=torch.float16)
k = torch.randn_like(q)
v = torch.randn_like(q)

out = flex_attention(q, k, v, block_mask=block_mask)
          

Two practical notes. Keep a correctness check: run the same inputs through torch.nn.functional.scaled_dot_product_attention with an equivalent mask and compare, because an API-unstable kernel deserves a guard. And profile your real shape before committing; the speedup depends on your density and sequence length, not on the headline number. The FlexAttention documentation has the full score_mod and BlockMask reference.

FlexAttention on PyTorch MPS versus MLX

FlexAttention closes a real gap, but it does not make PyTorch the fastest path for every on-device job. For transformer LLM inference on Apple Silicon, MLX, Apple's own array framework, generally leads. On an M4 Pro, one comparison found MLX running object-detection inference 1.1x to 2.6x faster than PyTorch MPS, and the ExecuTorch MLX delegate reported 3x to 6x higher throughput on generative workloads than existing ExecuTorch delegates on macOS (PyTorch ExecuTorch MLX delegate). PyTorch MPS, meanwhile, holds up well for training and keeps the whole CUDA-era ecosystem.

Dimension FlexAttention on PyTorch MPS MLX
Custom attention patterns Strong: any mask as a Python function Manual; fewer ready-made sparse kernels
LLM inference throughput Improving, still behind on many models Generally faster on Apple Silicon
Training on Mac Competitive, mature autograd Improving, some ops still catching up
Ecosystem and portability Full PyTorch stack, CUDA parity Apple-only, smaller library set
Maturity on Mac MPS backend still beta, FlexAttention API Unstable Native Metal, purpose-built for Apple

The reasonable read: prototype and train in PyTorch, use FlexAttention when your attention is sparse, and reach for MLX when you are shipping latency-sensitive inference into a macOS or iOS product. If self-hosting cost is the real question behind "should this run locally," our breakdown of self-hosting GPU cost versus an API frames the maths.

What else in 2.13 is worth your attention

Beyond the Mac story, three changes affect day-to-day work. nn.LinearCrossEntropyLoss fuses the final linear projection and cross-entropy into one module and processes the vocabulary in chunks, cutting peak memory up to ~4x for large-vocabulary training as a drop-in replacement. torch.load now reads .safetensors files directly, so the format's memory-mapped, code-execution-free loading no longer needs a separate library. And PyTorch wheels now cover Python 3.15, including the free-threaded 3.15t build, though only on Linux for now and only via download.pytorch.org rather than PyPI.

A few deprecations deserve a note before you upgrade: named tensors were hard-removed, all_gather_into_tensor and reduce_scatter_tensor were renamed to the _single scheme, the Bazel build was dropped, and CUDA 13.0 is the default. Run your test suite against 2.13 in a branch before you move a training pipeline.

India-specific considerations

For teams in India, the economics push toward local Apple Silicon for a lot of experimentation. Apple lists the M4 Mac mini from $599 in the US and ₹1,18,900 for the 512GB, 16GB model in India, a one-time cost against per-hour cloud GPU rental. A single Mac with generous unified memory can hold a mid-sized model for prototyping without a cloud bill, and FlexAttention now removes one of the reasons you had to move sparse-attention work off the Mac. Where data residency and privacy matter, keeping model work on a local device also sits comfortably with the Digital Personal Data Protection Act, 2023 (DPDP), since experimentation data need not leave the machine. Production training at scale still belongs on multi-GPU clusters, where the 2.13 FSDP2 and torchcomms changes apply.

FAQ

How eCorpIT can help

eCorpIT is a Gurugram-based technology organisation, founded in 2021 and assessed at CMMI Level 5, with senior-led teams building AI and on-device machine-learning features across iOS, macOS, and cloud. We help teams decide what should run locally on Apple Silicon versus in the cloud, port and profile PyTorch workloads on the MPS backend, and design private, DPDP-aware inference. If you are planning on-device AI or weighing PyTorch against MLX for a product, talk to us.

References

  1. PyTorch Foundation, "PyTorch 2.13 Release Blog," July 8, 2026 - https://pytorch.org/pytorch-2-13-release-blog/
  1. PyTorch, "PyTorch 2.13.0 Release" (GitHub release notes) - https://github.com/pytorch/pytorch/releases/tag/v2.13.0
  1. PyTorch, "FlexAttention: The Flexibility of PyTorch with the Performance of FlashAttention" - https://pytorch.org/flexattention/
  1. PyTorch, "torch.nn.attention.flex_attention" documentation - https://docs.pytorch.org/docs/main/nn.attention.flex_attention.html
  1. Apple, "Accelerated PyTorch training on Mac" (Metal) - https://developer.apple.com/metal/pytorch/
  1. PyTorch, "Running PyTorch Models on Apple Silicon GPUs with the ExecuTorch MLX Delegate" - https://pytorch.org/running-pytorch-models-on-apple-silicon-gpus-with-the-executorch-mlx-delegate/
  1. Towards Data Science, "PyTorch and MLX for Apple Silicon" - https://towardsdatascience.com/pytorch-and-mlx-for-apple-silicon-4f35b9f60e39/
  1. Jiang et al., "Mistral 7B" (arXiv:2310.06825) - https://arxiv.org/pdf/2310.06825
  1. Mistral AI, "Announcing Mistral 7B" - https://mistral.ai/news/announcing-mistral-7b/
  1. Apple (India), "Buy Mac mini, M4 chip, 16GB memory, 512GB storage" - https://www.apple.com/in/shop/buy-mac/mac-mini/m4-chip-10-core-cpu-10-core-gpu-16gb-memory-512gb-storage
  1. Hugging Face, "Mistral" model documentation - https://huggingface.co/docs/transformers/en/model_doc/mistral
  1. MetalCloud, "MLX vs PyTorch: When to Use Apple's ML Framework" - https://metalcloud.space/mlx-vs-pytorch-comparison/

_Last updated: July 18, 2026._

Frequently asked

Quick answers.

01 What is FlexAttention in PyTorch?
FlexAttention is PyTorch's API for writing a custom attention pattern as a short Python function that the compiler fuses into a fast kernel. You define a mask or score modification, and PyTorch builds the kernel, so you avoid hand-writing a separate CUDA or Metal kernel for each attention variant you need.
02 How much faster is FlexAttention on Apple Silicon?
The PyTorch 2.13 release notes report up to a ~12x speedup over SDPA on sparse masks. A 1x8x32768x64 shape with a 256-element sliding window at 0.8% density runs in about 35 ms versus about 431 ms for SDPA. A shorter 8192-length, 64-window case reaches about 4.15x.
03 Does FlexAttention always beat SDPA on a Mac?
No. The gain applies to sparse attention patterns. The 2.13 release notes state that dense patterns continue to favor SDPA, as expected. If your attention is full or nearly full, keep using scaled dot-product attention. The FlexAttention advantage grows with mask sparsity and sequence length, not in every case.
04 Is the MPS FlexAttention path production-ready?
Treat it with care. The release notes label the MPS FlexAttention work API Unstable, which is normal for a first landing. Pin your PyTorch version, keep a correctness test comparing FlexAttention output against SDPA, and expect the interface to change in later releases before you depend on it in production.
05 Should I use PyTorch MPS or MLX on Apple Silicon?
Use PyTorch with FlexAttention for training and for sparse attention patterns, since it keeps the full ecosystem. Reach for MLX when shipping latency-sensitive LLM inference into a macOS or iOS product, where reported figures show MLX generally faster, including 1.1x to 2.6x on some inference workloads.
06 What is a sliding-window attention mask?
It is a pattern where each token attends only to a fixed number of nearby tokens rather than the whole sequence. Mistral 7B uses a 4096-token window over a 32,768-token context. This structured sparsity is exactly the shape FlexAttention accelerates, since most key-value blocks can be skipped safely.
07 Did PyTorch 2.13 change anything besides attention?
Yes. It added nn.LinearCrossEntropyLoss to cut peak memory up to ~4x for large-vocabulary training, native torch.load for safetensors files, Python 3.15 wheels on Linux, and FSDP2 reduce-scatter overlap. It also removed named tensors and renamed some distributed collectives, so test before upgrading a pipeline.
08 How do I install PyTorch 2.13 for Mac?
Install the standard PyTorch 2.13 wheel for macOS from the official Getting Started instructions and select the "mps" device in code. Python 3.15 wheels are Linux-only in this release, so on a Mac use a supported earlier Python version. Verify the MPS backend is available before running FlexAttention.

About the author

Manu Shukla

Founder & Director

Founder of eCorpIT. Hands-on engineer leading senior-only delivery for AI apps, custom software, and cloud systems for global clients.

Subscribe

One engineering note a week. No fluff, no spam.

Senior-architect playbooks on AI agents, mobile apps, cloud, security, data, and marketing — delivered every Wednesday.

Past the reading

Read enough. Let's build something.

A senior architect responds in 24 working hours with scope, indicative cost, and a timeline. NDA before any technical conversation.