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

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...

Paper

Similar papers

Peer review

Reviewer rBem5/10 · confidence 4/52024-06-16

Summary

This paper proposes two CUDA kernel optimization techniques: batched GEMM and fusion for neighborhood attention. On average, batched GEMM optimization provides 895% (548%) and 272% (193%) improvement in full precision (half precision) latency compared to existing naive CUDA kernels for 1-D and 2-D neighborhood attention, respectively. Fusion optimization improves naive kernels by an average of 1759% and 958% in 1-D and 2-D problems respectively. These optimizations translate into up to 104% improvement in inference and 39% improvement in training existing models based on neighborhood attention. The fused kernels can match or outperform the authors' self-attention baseline in approximately 100% of 1-D, 98.6% of 2-D, and 97.3% of 3-D problem sizes that they benchmarked.

Strengths

1. The paper clearly explains the overhead one can expect from switching from a standard self-attention kernel to neighborhood attention. 2. The paper clearly illustrates the CUDA kernel optimization techniques they use, which is challenging because the kernels are complex.

Weaknesses

1. The paper does not quantitively compare the neighborhood attention kernel with the state-of-the-art fused dot-product attention kernel. 2. The paper only evaluates one type of GPU, the NVIDIA A100, which questions the generality of the proposed kernel optimization technique.

Questions

1. The paper does not quantitively explain where the performance benefits come from. It would help the readers assess the kernel better if you could show the arithmetic intensity of the naive, GEMM, and fused kernels under different inputs and configurations. Meanwhile, could you show some measurements on the memory, cache, and occupancy that would help explain the performance improvement? 2. Could you show the best performance achieved by torch.compile in PyTorch 2? That would help motivate the necessity of developing CUDA kernels. 3. Could you show how the optimized kernels impact the algorithm, such as enabling larger models or longer contexts? 4. Could you explain whether the new tensor memory accelerator introduced in H100 can help with the neighborhood attention kernel?

Rating

5

Confidence

4

Soundness

3

Presentation

3

Contribution

2

Limitations

1. The paper only shows that optimized kernels can accelerate current algorithms, but not extend their ability to more applications.

Authorsrebuttal2024-08-04

Rebuttal, continued

We are also trying to gain access to H100s, so we can develop future versions of the kernels specifically targeting Hopper. We are hopeful that we will gain access in the coming months, and if time permits we will add those results as well. Finally, as stated, we fully intend to extend our methodology to not just newer CUDA architectures, but other platforms and hardware as well (ROCm and Metal to name a few.)

Reviewer 9m2o7/10 · confidence 4/52024-07-01

Summary

They implemented a fused neighborhood attention kernel (N Atten). N Atten is very useful in reducing the computational cost of various tasks because sequences usually attend to nearby (e.g., Mistral and StreamingLLM). However, previous implementations of N-Atten kernels are very inefficient because of a lack of (1) utilizing HW tensor acceleration (matmul units such as TensorCore), (2) utilizing fused softmax attention scheme (flash-attention). They provide two solutions for each problem. (1) Using GEMM by padding the attention matrix (masking the QK matmul), the implementation could be much more easily accelerated by modern HW. (2) using fused softmax attention (flash-attention) to compute the attention output.

Strengths

They provide clear procedures for building the N-Atten efficiently. The writing and presentation are very clear, especially in Figures 3 and 4. Their implementation is very general to handling 1D-2D-3D attention.

Weaknesses

Their scientific contribution is not novel enough. (1) GEMM-based acceleration is not a unique technique. In many sparse matrix multiplication applications, partially padding and using GEMM units is quite a natural solution (e.g., structural sparsity) (2) Fused softmax attention was a common acceleration technique now (after the release of flash-attention)

Questions

1. Can you provide the code? 2. This could be easily implemented in tiled acceleration languages like OpenAI Triton and Apache TVM Tensor Expression. How about implementing this method in those languages and checking the performance in heterogeneous architectures (e.g., AMD ROCm, Intel Gaudi)?

Rating

7

Confidence

4

Soundness

4

Presentation

4

Contribution

3

Limitations

The proposed method only supports the N-Atten. In recent LLM research (e.g., StreamingLLM), many works propose novel methodologies to perform linear or sub-quadratic attention mechanisms using sparse masks. The current state of implementation does not consider such global attention or regional attention.

Reviewer 9m2o2024-08-09

Thank you for detailed and kindly described responses. I read most of your response (including mine), and I want to raise my score, because I understand how detailed engineering considerations are there in behind. I think this paper is good enough to be accpeted because this paper will give many insight about fused N Attention applications. I hope this kind of detailed considerations are described in the further revision (in Appendix).

Authorsrebuttal2024-08-09

We sincerely thank you for your invaluable feedback; we will indeed adjust the writing and add more details according to suggestions from yourself and other reviewers. Indeed our goal is not only accelerating the speed of research and inference in these cases, but to also provide context and information for accelerated AI and hopefully benefit future researchers, so that they can realize their ideas unencumbered by the tools they have available.

Reviewer RCPh7/10 · confidence 3/52024-07-15

Summary

The paper introduce a method to improve the performance of neighborhood attention mechanisms. The authors present two new implementations: GEMM-based kernels and fused kernels. These implementations aim to reduce the latency and memory footprint of neighborhood attention in deep learning models, particularly in higher-dimensional spaces. The proposed methods show significant speedup in both full and half precision compared to existing naive CUDA kernels.

Strengths

1. The proposed GEMM-based and fused kernels significantly reduces latency, average improvements of 895% and 272% in full precision latency for 1-D and 2-D neighborhood attention 2. The implementations can also reduce the memory consumption of neighborhood attention. 3. The methods are designed to work efficiently across different spatial ranks (1-D, 2-D, and 3-D), which makes it more generally applicable.

Weaknesses

1. The performance improvements in half precision are limited due to the inefficiencies in gather/scatter operations。 2. The performance gains are more significant on newer architectures like Ampere and Hopper, limiting the generalizability of the results to other hardware setups.

Questions

1. What is the implications of the fp16 acceleration to more advanced low precision format such as fp8 or even fp6? 2. While the paper provides significant speedup of neighborhood attention, more discussions on the overall bottleneck of it would be interesting, whether the improvements on the speed can be further translated to better accuracy.

Rating

7

Confidence

3

Soundness

4

Presentation

3

Contribution

3

Limitations

No significant negative societal impacts.

Authorsrebuttal2024-08-10

Of course, we're attaching them below. However, we note these measurements are only of the backbone and not the entire detector/segmentor end to end. The reason for that is that the original paper used MMDet and MMSeg, which have since completely changed their API, and the version used in the original NAT/DiNAT papers was build with CUDA Toolkit 11.3, while our GEMM kernel and FNA kernel require 11.8 at a minimum. We tried multiple newer MMDet/MMSeg versions (really MMCV, their co-dependency) and unfortunately the only ones compatible with our newer kernels still do not support the old NAT/DiNAT configurations, and break during inference. Because of that, the only solution we could think of was benchmarking the backend models separately. In addition, benchmarking the backend alone indicates our performance improvement better than the end to end measurement, because the detection/segmentation heads are usually highly unoptimized and use CPU operations somewhat frequently (i.e. when producing masks or RoI maps), and that will bias these measurements. Overall, for FNA we observe up to 113% speedup over naive, 165% speedup over tiled naive, and 40% speedup over our own GEMM-based kernel. ## Detection Backbone benchmarked on an A100-PCIe with 800x1216 resolution inputs (per detection resolution in the code from original NAT/DiNAT papers). *Disclaimer: throughput measurements are from backbone only, and do not include detection head and post processing.* | Backbone | mAP | Mask mAP | Naive Throughput | Tiled Naive Throughput | GEMM Throughput | FNA Throughput | |---|---|---|---|---|---|---| | NAT-Mini | 50.3 | 43.6 | 71.9 FPS | 82.0 FPS | 82.0 FPS | **98.1** FPS | | NAT-Tiny | 51.4 | 44.5 | 49.8 FPS | 49.5 FPS | 50.2 FPS | **62.6** FPS | | NAT-Small | 52.0 | 44.9 | 36.4 FPS | 46.5 FPS | 48.7 FPS | **61.1** FPS | | NAT-Base | 52.3 | 45.1 | 28.4 FPS | 36.8 FPS | 44.7 FPS | **56.8** FPS | | DiNAT_s-Tiny | 51.0 | 44.1 | 73.5 FPS | 92.9 FPS | 107.2 FPS | **138.8** FPS | | DiNAT_s-Small | 52.3 | 45.2 | 45.5 FPS | 57.1 FPS | 61.2 FPS | **76.1** FPS | | DiNAT_s-Base | 52.6 | 45.3 | 35.3 FPS | 44.5 FPS | 51.5 FPS | **70.9** FPS | | DiNAT_s-Large | 54.8 | 47.2 | 23.6 FPS | 29.5 FPS | 33.7 FPS | **46.1** FPS | | DiNAT-Mini | 51.2 | 44.4 | 71.0 FPS | 83.2 FPS | 82.7 FPS | **100.2** FPS | | DiNAT-Tiny | 52.2 | 45.1 | 49.4 FPS | 51.2 FPS | 51.5 FPS | **61.6** FPS | | DiNAT-Small | 52.9 | 45.8 | 36.9 FPS | 46.9 FPS | 51.2 FPS | **63.0** FPS | | DiNAT-Base | 53.4 | 46.2 | 28.0 FPS | 35.9 FPS | 42.0 FPS | **57.5** FPS | | DiNAT-Large | 55.3 | 47.8 | 19.5 FPS | 25.2 FPS | 29.7 FPS | **41.6** FPS | ## Segmentation Backbone benchmarked on an A100-PCIe with 512x512 resolution inputs for Mini, Tiny, Small, and Base variants, and 640x640 for Large varient (per segmentation resolution in the code from original NAT/DiNAT papers). *Disclaimer: throughput measurements are from backbone only, and do not include segmentation head and post processing.* | Backbone | mIoU | mIoU (multiscale) | Naive Throughput | Tiled Naive Throughput | GEMM Throughput | FNA Throughput | |---|---|---|---|---|---|---| | NAT-Mini | 45.1 | 46.4 | 82.4 FPS | 84.2 FPS | 81.1 FPS | **102.7** FPS | | NAT-Tiny | 47.1 | 48.4 | 50.3 FPS | 50.6 FPS | 48.9 FPS | **61.6** FPS | | NAT-Small | 48.0 | 49.5 | 48.2 FPS | 47.5 FPS | 47.7 FPS | **57.6** FPS | | NAT-Base | 48.5 | 49.7 | 47.4 FPS | 47.6 FPS | 46.8 FPS | **57.9** FPS | | DiNAT_s-Tiny | 46.0 | 47.4 | 116.6 FPS | 114.8 FPS | 109.4 FPS | **139.7** FPS | | DiNAT_s-Small | 48.6 | 49.9 | 63.4 FPS | 56.7 FPS | 60.0 FPS | **72.4** FPS | | DiNAT_s-Base | 49.4 | 50.2 | 61.7 FPS | 59.7 FPS | 63.3 FPS | **73.0** FPS | | DiNAT_s-Large | 53.4 | 54.6 | 49.4 FPS | 59.2 FPS | 59.8 FPS | **72.1** FPS | | DiNAT-Mini | 45.8 | 47.2 | 80.1 FPS | 80.4 FPS | 81.5 FPS | **99.0** FPS | | DiNAT-Tiny | 47.8 | 48.8 | 49.8 FPS | 51.1 FPS | 49.6 FPS | **62.2** FPS | | DiNAT-Small | 48.9 | 49.9 | 48.6 FPS | 49.6 FPS | 49.2 FPS | **59.3** FPS | | DiNAT-Base | 49.6 | 50.4 | 47.2 FPS | 48.6 FPS | 47.3 FPS | **60.9** FPS | | DiNAT-Large | 54.0 | 54.9 | 41.1 FPS | 49.1 FPS | 49.1 FPS | **59.2** FPS |

Reviewer rBem2024-08-10

Thank you for the results and I will keep my rate.

Reviewer RCPh2024-08-13

I appreciate the response from the authors, especially the clarification on the applicable architecture. I would like to raise the score.

Program Chairsdecision2024-09-25

Decision

Accept (poster)

© 2026 NYSGPT2525 LLC