Faster Neighborhood Attention: Reducing the O(n^2) Cost of Self Attention at the Threadblock Level

Ali Hassani, Wen-Mei Hwu, Humphrey Shi

TL;DR

This paper introduces two high-performance CUDA kernel classes—GEMM-based and Fused—that drastically accelerate Neighborhood Attention (NA). By moving beyond naive implementations to hardware-aware kernels that utilize Tensor Cores and on-chip memory fusion, the authors achieve up to a 1759% speedup in 1-D problems and significantly reduce the memory footprint of local attention mechanisms.

What Problem Does This Paper Address?

While Transformers have revolutionized deep learning, their core mechanism—Self-Attention—suffers from a quadratic cost $O(n^2)$ in both time and memory. For high-resolution images or long video sequences, this becomes an insurmountable bottleneck.

Neighborhood Attention (NA) was proposed to solve this by restricting each token's attention to a local window (its "neighbors"), reducing complexity to linear $O(n)$. However, implementing this efficiently on GPUs is notoriously difficult. Standard deep learning libraries aren't built for the "sliding window" patterns of NA, especially in 2-D (images) and 3-D (video). Previous "naive" implementations were often memory-bandwidth bound and couldn't leverage specialized hardware like NVIDIA's Tensor Cores, meaning the theoretical $O(n)$ efficiency rarely translated into real-world speed.

Methods

The authors present two novel implementation strategies using NVIDIA’s CUTLASS framework:

  1. GEMM-based NA: The authors show that NA can be reformulated as a batched General Matrix-Matrix Multiplication (GEMM). By using space-aware tiling and fusing the "gather/scatter" operations (which collect neighboring tokens), they allow the operation to run on Tensor Cores.
  2. Fused Neighborhood Attention (FNA): Inspired by FlashAttention, this method keeps the attention weights in on-chip memory (shared memory or registers) rather than writing them to global memory. This circumvents the memory bandwidth bottleneck entirely.
Illustration of the spectrum of possible attention patterns provided by neighborhood attention.

The implementation supports 1-D, 2-D, and 3-D spaces, and handles advanced features like dilation (sparse global context) and causal masking (preventing tokens from looking "ahead" in time).

Datasets

The authors evaluated their kernels using:

  • ImageNet-1K: Used for model-level throughput benchmarks on hierarchical vision transformers like NAT and DiNAT.
  • FFHQ (Flickr-Faces-HQ): Used to benchmark StyleNAT, a generative adversarial network (GAN) based on neighborhood attention.
  • Synthetic Benchmarks: A large set of problem sizes varying in batch size, spatial size, and head dimensions were used to measure raw kernel speedups on an NVIDIA A100 GPU.

Key Insights and Ideas

  • The "Unfused" Bottleneck: The authors discovered that in 16-bit precision (FP16/BF16), unfused kernels are crippled by memory alignment issues. Specifically, the minimum transaction size for asynchronous loads (LDGSTS) on modern GPUs is 32 bits, which breaks the pipelining of 16-bit attention weights.
  • Arithmetic Intensity: The paper applies the Roofline model to NA. They show that while self-attention becomes compute-bound as sequence length grows, neighborhood attention's arithmetic intensity is tied to its window size. This means choosing the right window size is critical for balancing speed and performance.
  • Generalizing to Tensors: For 2-D and 3-D data, the kernels transition from simple GEMMs to General Tensor-Tensor contractions (GETTs). This requires sophisticated software predication to handle the multi-dimensional spatial layouts.

Key Results

The performance gains over the previous "naive" baseline are massive, particularly for the Fused NA (FNA) kernels:

  • 1-D Speedup: FNA achieved an average 1759% improvement in FP16 forward pass runtime.
  • 2-D/3-D Speedup: FNA improved 2-D problems by 958% and 3-D problems by 1135% (forward pass).
  • Model Throughput: Integrating these kernels into existing models like NAT and DiNAT resulted in up to a 104% increase in inference throughput and a 39% reduction in training time.
Figure 1: Overview of average improvement in speed on A100 from our proposed imple- mentation. Baseline is the set of naive CUDA kernels introduced in Neighborhood Attention Transformer [9]. GEMM-based NA improves 1-D problems by an average of 548% (forward pass) and 502% (forward + backward), and 2-D problems by an average of 193% (forward pass) and 92% (forward + backward). GEMM-based NA does not implement 3-D problems yet. Fused NA boosts performance further and improves 1-D problems by an average of 1759% (forward pass) and 844% (forward + backward), and 2-D problems by an average of 958% (forward pass) and 385% (forward + backward), and 3-D problems by an average of 1135% (forward pass) and 447% (forward + backward).

Crucially, the Fused NA kernels maintain a constant memory footprint regardless of the sequence length, mirroring the benefits FlashAttention brought to standard self-attention.

Limitations and Future Work

  • Register Pressure: The complex logic required for 2-D and 3-D masking and indexing increases "register pressure," which can lead to "register spilling" and slightly lower performance in cases where the window size is very large (approaching global self-attention).
  • Positional Biases: The current fused backward kernel does not yet support positional biases, a common feature in some vision models.
  • Hardware Specificity: While highly optimized for NVIDIA Ampere (A100) and later, the authors note that further work is needed to leverage specific features of newer architectures like Hopper (TMA - Tensor Memory Accelerator) and Blackwell.
  • Future Directions: The authors aim to explore Context Parallelism (CP) and auto-tuning methods to automatically find the best tiling configurations for any given hardware/problem size.

Summary updated

Abstract

Neighborhood attention reduces the cost of self attention by restricting each token's attention span to its nearest neighbors. This restriction, parameterized by a window size and dilation factor, draws a spectrum of possible attention patterns between linear projection and self attention. Neighborhood attention, and more generally sliding window attention patterns, have long been bounded by infrastructure, particularly in higher-rank spaces (2-D and 3-D), calling for the development of custom kernels, which have been limited in either functionality, or performance, if not both. In this work, we aim to massively improve upon existing infrastructure by providing two new methods for implementing neighborhood attention. We first show that neighborhood attention can be represented as a batched GEMM problem, similar to standard attention, and implement it for 1-D and 2-D neighborhood attention. These kernels on average provide 895% and 272% improvement in full precision runtime compared to existing naive CUDA kernels for 1-D and 2-D neighborhood attention respectively. We find that aside from being heavily bound by memory bandwidth, certain inherent inefficiencies exist in all unfused implementations of neighborhood attention, which in most cases undo their theoretical efficiency gain. Motivated by the progress made into fused dot-product attention kernels, we developed fused neighborhood attention; an adaptation of fused dot-product attention kernels that allow fine-grained control over attention across different spatial axes. Known for reducing the quadratic time complexity of self attention to a linear complexity, neighborhood attention can now enjoy a reduced and constant memory footprint, and record-breaking half precision runtime. We observe that our fused implementation successfully circumvents some of the unavoidable inefficiencies in unfused implementations...
BibTeX
@inproceedings{hassani2024faster,
  author = {Ali Hassani and Wen-Mei Hwu and Humphrey Shi},
  title = {{Faster Neighborhood Attention: Reducing the O(n^2) Cost of Self Attention at the Threadblock Level}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2024},
  url = {https://openreview.net/forum?id=8Ofbg2KYMu},
}
Figure