HSR-Enhanced Sparse Attention Acceleration
Bo Chen, Yingyu Liang, Zhizhou Sha, Zhenmei Shi, Zhao Song
Introduction
Large Language Models (LLMs) have showcased remarkable capabilities across various applications, including context-aware question answering, content generation, summarization, and dialogue systems, among others . Long-context tasks of LLMs have gained more and more attention. Several LLMs extend their context length to K tokens, such as Yarn , GPT-4 , Claude 3.5 , Llama 3.1 , Phi-3.5 , Mistral Nemo , etc. A bottleneck for long-context tasks is the computational cost of the attention mechanism in LLMs. The key to LLM success is the transformer architecture , wildly used in various practical scenarios , whose critical component is the attention mechanism. Let be the data length, be the length of query tokens, and be the feature dimensionAs is always fixed in practice, there is no need to scale up in analysis. Thus, in this work, we always assume is a small constant.. The conventional attention uses Softmax activation and is defined as follows:
In practical LLM applications, there are two scenarios for attention computation depending on the context length and query length . The first case, , represents the iterative text generation based on the pre-computed Key Value Cache (KV), which stores the intermediate attention key and value matrices. The second case, , represents the full self-attention computation before text generation or the cross-attention computation. However, in both cases, when the context window becomes larger, the running time will increase correspondingly, i.e., it will be linear and quadratic in for and , respectively. Thus, reducing the running time of attention computations with long context input becomes essential to minimize response latency and increase throughput for LLM API calls.
In this work, we introduce novel methods to reduce the running time complexity for both cases, i.e., and . Our approach is inspired by the inherent sparsity found within attention mechanisms. Numerous prior studies have highlighted the significant sparsity in the attention matrix . This manifestation of sparsity in Softmax attention is that a large number of attention scores, i.e., , concentrate on a small number of entries, which is known as “massive activation”. Due to this nature, Softmax attention can be accelerated by only calculating the entries that contain large attention scores, introducing negligible approximation errors .
To expedite the computation, the critical task is to identify the large/non-zero entries for Softmax/ReLU attention, respectively. To do so, we utilize the half-space reporting (HSR) data structure, which is introduced in to address the half-space range reporting problem. This is a fundamental problem in computational geometry and can be formally defined as follows:
To the best of our knowledge, this is the first work incorporating the HSR data structure with attention computation, to reduce the running time complexity with the help of the sparsity within the attention mechanisms.
Theoretically, we provide rigorous proofs for reducing the computational time (1) for ReLU attention generation from to (Algorithm 2 and Theorem 4.1); (2) for full ReLU attention computation from to (Algorithm 3 and Theorem 5.1), without incurring any approximation error in both cases.
We achieve the same running time speed up for the conventional Softmax attention, and we give rigorous theoretical proofs to ensure that the resulting approximation error remains negligible (Theorem 4.2, 5.2 and Theorem 4.3).
We conduct empirical experiments on prominent LLMs to verify the approximation error associated with Softmax attention utilizing “massive activated” entries only. The results show that the error using a few top entries is already insignificant, consistent with our theoretical analysis.
Roadmap. Section 2 presents related work. In Section 3, we introduce essential concepts and key definitions used this paper. In Section 4, we present our main results, i.e., guarantees on run time reduction and approximation error. In Section 5, we introduce the extension of our method on full attention computation. In Section 6, we provide a brief summary of the techniques used in our proof. In Section 7, we provide our empirical results of evaluating three mainstream LLMs with Softmax attention with top- indices on different . In Section 8, we discuss the potential of extending our method to other activation functions. In Section 9, we concludes our algorithm and contributions.
Related Work
Attention acceleration for long context input. Long context window is essential for transformer based LLMs in many downstream tasks. However, due to the quadratic time complexity associated with self-attention mechanisms, transformers are usually hard to inference efficiently. Numerous methods have been proposed to enhance the inference efficiency. One approach involves using alternative architectures as proxies for attention to support faster inference, such as Mamba , PolySketchFormer , Hopfield Models and Linearizing Transformers . However, the broad applicability of these methods across different applications and modalities remains to be fully validated. Another line of research focuses on approximating attention matrix computation . Nevertheless, these methods often rely on assumptions that may not be practical. For instance, some approaches use polynomial methods to approximate the exponential function, which requires all entries to be bounded by a small constant. However, our HSR-enhanced attention framework is designed based on practical observation and validated by empirical support. These advancements in attention mechanisms and transformer efficiency not only improve general model performance but also play a crucial role in enhancing in-context learning capabilities, where models leverage information from the immediate context to perform tasks without fine-tuning. We refer the readers to some other related works .
ReLU attention. ReLU attention is an innovative mechanism that employs the ReLU activation function in place of the traditional Softmax function for attention computation. Previous studies have highlighted the promise potential of ReLU attention in various domains. From empirical side, has demonstrated that incorporating ReLU as the activation function in vision transformers enhances performance on downstream tasks. has shown that transformers equipped with ReLU attention outperform those with Softmax attention, particularly when dealing with large key-value memory in machine translation tasks. From theoretical side, the scale-invariant property of ReLU attention facilitates the scalability of transformer networks. Furthermore, have shown that the inherent properties of ReLU attention contribute positively to the learning process of transformer models. Another key advantage of ReLU attention is that the ReLU function effectively sets all negative values to zero, allowing us to bypass these non-contributory elements during attention computation, thereby reducing the running time of attention computation. Importantly, omitting these zero and negative entries does not introduce any error into the final output of the ReLU attention mechanism.
Half-space reporting (HSR) data structure. The Half-Space Reporting (HSR) data structure, initially proposed by , was developed to address the half-space range reporting problem. The expedited range query capability inherent to HSR has been demonstrated to significantly enhance computational efficiency across a variety of tasks, as evidenced by numerous previous works in the literature. Studies such as and have applied HSR to facilitate solving general linear programming (LP) problems. Another line of research has highlighted HSR’s potential in expediting the training process of contemporary neural networks . There is also a collection of research that concentrates on leveraging HSR for the advancement of solutions to geometric and graphical challenges .
Preliminary
In Section 3.1, we introduce notations used in the paper. In Section 3.2, we introduce a modified version of Softmax attention that operates on a specific subset of indices. It defines the top- nearest neighbors Softmax attention, which focuses on the most relevant entries in the attention matrix. In Section 3.3, we describe the massive activation property for attention mechanisms. In Section 3.4, we present a data structure for efficiently solving the half-space range reporting problem.
2 Softmax Attention with Index Set
Recall that we have already provided the definition of ReLU attention in Definition 1.2. Here, we present the key concepts of Softmax attention. For Softmax attention, since we only calculate the “massive activated” entries to get our approximated results, we introduce the formal definition:
as the submatrix of and , i.e., whose row index is in or , respectively.
In this work, we consider calculating the Softmax attention on the “massive activation” index set, where we define the “massive activation” index set as the top- indices. We introduce our definition for top- indices of Softmax attention as follows:
3 Massive Activation
Now, we introduce our observations on the properties of the attention scores (the inner products of query vectors and key vectors). This further facilitates the error analysis of the top- indices Softmax attention. To begin with, we provide the definition of the massive activation property as follows:
The top- entries are massive, i.e., .
The remaining terms are upper bounded, i.e, , .
An intuitive understanding of Definition 3.3 is that, the summation of “massive activated” entries dominates the summation of all entries, and the entries we ignored only contributes little to the final summation. Therefore, it is reasonable for us to omit those non “massive activated” entries.
There are many distributions satisfying the property in Definition 3.3, such as (1) drawing from any subexponential distribution, e.g., multivariate Laplace distributions, (2) drawing from any mixture of Gaussian distribution with Gaussian clusters.
4 Half-Space Reporting (HSR) Data Structure
We restate the result from for solving the half-space range reporting problem. The interface of their algortihm can be summarized as in Algorithm 1. Intuitively, the data-structure recursively partitions the set and organizes the points in a tree data-structure. Then for a given query , all points of with are reported quickly. Note that the query here defines the half-space in Definition 1.3. We summarize the time complexity of HSR data structure as follows:
Part 1. , .
Part 2. , .
Main Results on Attention Generation
In this section, we present our key findings regarding attention generation, , for both ReLU and Softmax attention mechanisms. Across both scenarios, we have reduced the time complexity from a naive to . Specifically, for the ReLU attention model, we have managed to accelerate the processing time without introducing any approximation errors. In the case of Softmax attention, our technique results in only an insignificant approximation error.
We begin with introducing our result on ReLU attention generation as follows:
Theorem 4.1 shows that our Algorithm 2 accelerates the running time of ReLU attention generation from naive to , which is a significant speed up when the KV Cache is large. The at least success probability originates from the sparsity analysis of ReLU attention (Lemma 6.1), where with probability at least , we have the number of non-zero entries of each row of the attention matrix is at most .
Then, we move on to presenting our result on Softmax attention generation. Our results consist two parts: the improved running time of Softmax attention generation, and the error analysis of Softmax attention with index set. Firstly, we introduce our result about the imporved running time of Softmax attention generation as follows:
Theorem 4.2 demonstrates that if we choose the threshold satisfying , we can achieve a significant running time improve of the Softmax attention generation.
It is evident that this method introduces an approximation error due to the exclusion of certain entries. Nevertheless, under mild assumptions about the distribution of the attention scores, we demonstrate that this approximation error is indeed negligible. The proof’s intuitive explanation lies in the fact that the majority of attention scores are focused on the small subset of entries that we retain. We organize our result as follows:
Theorem 4.3 presents the error of Softmax attention with index set is relatively small. Consequently, omitting the remaining less significant entries is a justifiable compromise.
With mild assumptions on , we can have more precious results from Theorem 4.3. For example, if the entries in conform to subgaussian distribution with constant variance, we have with high probability.
Extension on Full Attention Computation
In this section, we extend our results to full attention computation scenario, where the number of queries and keys is proportional, i.e., . Essentially, the full attention computation is beneficial in practical applications, particularly within the context of cross-attention computations. For ReLU attention, we leverage Part 1 result of Corollary 3.5 to accelerate the identification of non-zero entries (activated entries). We introduce our result on ReLU attention as follows:
In Theorem 5.1, we improve the running time of full ReLU attention computation from to , which is a notable uplift of the running time when is extremely large.
Then, we present our result on Softmax attention. Intuitively, we use the Part 1 result of Corollary 3.5 to identify those “massive activated” entries (top- indices) within the attention matrix of Softmax attention, and calculate the Softmax attention with top- indices. We organize our result as follows:
Theorem 5.2 demonstrates our running time on Softmax full attention computation, which improves from naive running time .
Technical Overview
In Section 6.1, we introduce our analysis about the sparsity in the ReLU attention mechanism. In Section 6.2, we present our results of two general attention frameworks. In Section 6.3, we provide our error analysis of Softmax attention with index set. We have shown that with mild assumption on the distribution of attention scores, the error of Softmax attention with index set is negligible.
Intuitively, the ReLU activation will deactivate some key and query pairs. We introduce the results of employing the concentration inequality to quantitatively analyze the number of non-zero entries.
2 General Attention Frameworks
First, we introduce our general framework for attention generation computation. Here, we use the Part 1 result of the HSR data structure. As for this framework is designed for the attention generation task, the key matrix is fixed in each inference. Therefore, in the Init procedure, we initialize the HSR data structure with the key matrix . Then, in each inference, we use the same HSR data structure to answer the query from each row of the query matrix . We provide the result of this general attention generation framework as follows.
Part 1. The Init procedure runs in time.
Part 2. For each query, the Inference procedure runs in time.
The general framework for full attention computation is quite different from the previous one. Namely, we choose the Part 2 result of the HSR data structure. Since in each inference, both the query matrix and the key matrix differ from any other inference, we first initialize the HSR data structure with the key matrix . Then for each row of the query matrix , we query the HSR data structure to find the activated entries.
3 Error Analysis of Softmax Attention with Top-r𝑟r Indices
Calculating the Softmax attention on the “massive actavted” index set will introduce approximation error. In the following Lemma, we analyze the quantity of this approximation error. Here, we use to denote the summation of all entries activated by function, and we use to denote the summation of those entries which are excluded from “massive activated” index set. We provide the general error bound of Softmax attention with index set as follows.
Note that Lemma 6.4 only provides a general error analysis of Softmax attention with index set. Under mild assumption on the distribution of attention scores, we show that this error is actually very small. For more details, please refer to Theorem 4.3.
Experiments
In this section, we present our empirical results of evaluating three mainstream LLMs with Softmax attention with top- indices on different , showing that the results of the experiments are consistent with our theoretical analysis.
Datasets. To estimate the approximation error of the Softmax attention with “massive activation” entries, we conduct experiments on the PaulGrahamEssays datasets from LLMTest-NeedleInAHaystack . Specifically, for each article in the dataset, we first input tokens to the LLMs, then generate tokens.
Models. To demonstrate the generalization of our approximation error bound, we conducted experiments on three mainstream large models: LLaMA 3.1 8B Instructhttps://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct , Mistral Nemo 12B Instructhttps://huggingface.co/mistralai/Mistral-Nemo-Base-2407 , and Phi 3.5 Mini 3.8B Instructhttps://huggingface.co/microsoft/Phi-3.5-mini-instruct .
Results. The experiments are conducted on the setting discussed in previous paragraphs. We evaluated the performance of three mainstream LLMs using Softmax attention with top- indices. In particular, we chose from the set . As depicted in Figure 2, a significant increase in the perplexity (drop in performance) of LLMs is observed only when falls below . This suggests that the “massive activated” tokens are predominantly found within the top- entries. In comparison to the total of entries, the “massive activated” entries constitute a relatively minor fraction. The observed results align with our theoretical analysis, confirming that the approximation error of the Softmax attention mechanism with top- indices is insignificant for larger values of .
Discussion and Future Work
The sparsity within neural networks arises primarily from the incorporation of non-linear activation functions. These non-linear functions determine the mechanism or circuit of the neural networks, e.g., the induction head in transformers . Gaining insight into these non-linear layers not only enhances our understanding of how neural networks work but also paves the way for optimizing training and inference. We hope our analysis may inspire efficient neural network architecture design. This work represents the initial point of this envisioned blueprint. We concentrate on analyzing the combinations of LLMs and fundamental non-linear activation functions—ReLU and Softmax, which are most relevant to contemporary applications. By analyzing these functions, we aim to demonstrate to the research community that a thorough examination of a model’s non-linear characteristics can significantly enhance the running time complexity of neural networks.
Conclusion
This work investigates the exploitation of the intrinsic sparsity present in both ReLU and Softmax attention mechanisms to decrease the computational complexity of full attention computation and attention generation scenarios. Specifically, we employ the Half-Space Reporting (HSR) data structure to accelerate the process of identifying non-zero or “massive activated” entries within ReLU and Softmax attentions, respectively. Importantly, our approach does not import any errors to ReLU attention, and it results in only a negligible approximation error for Softmax attention.
Acknowledgement
Research is partially supported by the National Science Foundation (NSF) Grants 2023239-DMS, CCF-2046710, and Air Force Grant FA9550-18-1-0166.
References
Appendix A Preliminary
In this section, we display more fundamental concepts. In Section A.1, we introduce several important probability properties and bounds. In Section A.2, we detail the time complexity and performance of half-space reporting (HSR) data structures.
We state several fundamental properties and bounds for some common distributions.
For , let denote the -th entry of .
Suppose for , .
Then the inner product of and , conforms Gaussian distribution . Namely, we have .
For any , and are independent.
Then, for any , and are independent.
We provide tail bounds for chi-square and Gaussian distributed random variables:
Let be a chi-squared distributed random variable with degrees of freedom. Each one has zero means and variance.
Suppose we have a random variable .
where the first step, the second step follows from basic algebra, the third step follows from that the inequality holds for any , and the fourth step follows from Markov’s inequality.
Then we consider the numerator and we use to simplify the calculation, we have
where the first step follows from the definition of the moment generating function, the second and the third steps follow from basic algebra, and the fourth step follows from the property of the probability density function.
where the first step follows from Eq. (A.1) and Eq.(A.1), the second step follows from the calculation of infimum. ∎
The Bernstein’s inequality for bounding sums of independent random variables is:
A.2 Half-Space Reporting (HSR) Data Structures
The time complexity of the HSR data structure is:
Let be a fixed constant. Let be a parameter between and . There is a dynamic data structure for half-space reporting that uses space and pre-processing time, time per query where is the output size and is any fixed constant, and amortized update time.
Part 1. , .
Part 2. , .
Appendix B Full ReLU Attention Computation
In this section, we focus on optimizing the standard ReLU attention calculation. By leveraging a HSR data structure and assuming sparsity, the time complexity can be reduced to .
Assume each entry of is from Gaussian , and each entry of is from Gaussian .
Let denote the failure probability.
Let .
Let hsr data structure be defined as Part 1 in Corollary A.7.
There exists an algorithm (Algorithm 3), with at least probability, computes full attention of in time.
The running time for Inference procedure can be written as
The first term corresponds to the initialization of the hsr data structure. Since we use Part 1 result from Corollary A.7, the running time for initialization is .
The second term comes from the HSR query operation (Line 11). Since we use Part 1 result from Corollary A.7, we have
where the first step follows from (Part 1 of Corollary A.7), the second step follows from with high probability at most (Lemma D.3).
The third term corresponds to calculating (Line 13). By Lemma D.3, we have the third term is .
The fourth term corresponds to calculating . Since for -th row of , there are non-zero entries. Therefore, it takes time for calculating . Therefore, it takes time to calculate . By Lemma D.3, with high probability, is at most . Therefore, we have the third term as .
To sum up, the overall running time is . ∎
We can now derive a more specific result for the full ReLU attention computation:
Let ReLU attention be defined as Definition 1.2.
Assume each entry of is from Gaussian , and each entry of is from Gaussian .
Let denote the failure probability.
Let .
There exists an algorithm (Algorithm 3), with probability at least , takes time to compute the full ReLU attention of .
By Lemma B.1, we have that the FullAttentionComputation data structure (Algorithm 3) can run Inference to calculate the ReLU attention, in time.
Then, we have the ReLU attention calculation run in time. ∎
Appendix C ReLU Attention Generation
In this section, we present a theoretical analysis of the time complexity of ReLU attention generation using a HSR data structure.
Assume each entry of is from Gaussian , and each entry of is from Gaussian .
Let denote the failure probability.
Let .
Let hsr data structure be defined as Part 2 in Corollary A.7.
Then, there exists an algorithm (Algorithm 2), with at least probability, has the following performance:
Part 1. The Init procedure runs in time.
Part 2. For each query, the Inference procedure runs in time.
The Init procedure only runs the initialization of the HSR data structure. Since we use Part 2 result from Corollary A.7, the running time of Init procedure is .
The running time for Inference procedure can be written as
The first term corresponds to the HSR query operation (Line 16). Since we use the Part 2 result from Corollary A.7, we have
where the first step follows from in Part 2 of Corollary A.7, the second step follows from with high probability, is at most (Lemma D.3), the third step follows from .
The second term corresponds to calculating (Line 18). There are iterations, and in each iteration, it calculates entries of . Then, the second term is . By Lemma D.3, with high probability, is at most . Therefore, we have the second term as .
Similar to the proof of Lemma B.1 this term is .
To sum up, we have the overall running time for Inference procedure is . ∎
We now derive a comprehensive sparsity analysis for the ReLU attention mechanism:
Let ReLU attention be defined as Definition 1.2.
Assume each entry of is from Gaussian , and each entry of is from Gaussian .
Let denote the failure probability.
Let .
There exists an algorithm (Algorithm 2), with at least probability, takes time to generate the answer.
We make use of the AttentionGeneration data structure (Algorithm 2) in Lemma C.1.
For calculating the attention between and , it takes time.
There are queries in total. The running time for queries is .
Since we have , the overall running time for the generation is . ∎
Appendix D Sparsity Analysis
To begin our analysis, we first examine the application of Bernstein’s inequality to the matrix :
Let the ReLU attention be defined as Definition 1.2.
Assume each entry of is from Gaussian
Let .
Then, we can show that, with probability at least , the number of non-zero entries is at most . Namely, we have
Let be the indicator function of . Then, we have .
Since is an indicator function, then we have
By assumption, we have .
Let .
By the property of Gaussian distribution (Fact A.1), we have and .
For any , by Fact A.2, we have and are independent, which implies and are independent.
By the tail bound of Gaussian distribution (Fact A.4), we have
Since we have , by Eq. (3), we have
Let . By the Bernstein inequality (Lemma A.5), we have
Then, we reach our conclusion: with probability at least , the number of non-zero entries in each row of the attention matrix is bounded by .
We turn our attention to bounding :
Assume each entry of is from .
Then, we can show that, for with probability , is at most . Namely, we have
By the assumption, we have .
Since , by Chi-square tail bound (Lemma A.3), we have
Since we have , Eq. (5) implies
We can now present our formal sparsity analysis, which builds upon the previous lemmas:
Let the ReLU attention be defined as Definition 1.2.
Assume each entry of is from Gaussian , and each entry of is from Gaussian .
Let denote the failure probability.
Let .
Then, we can show that, with probability at least , for all , the number of non-zero entries of the -th row is at most .
This proof follows from applying union bound on Lemma D.1 and Lemma D.2.
We choose . Then, Eq. (6) implies
Let . By Eq.(7), we have .
Let . Then, Eq. (8) implies
Taking union bound over Eq. (7) and Eq. (9), we have
where the first step follows from the union bound, the second step follows from basic algebra, the third step follows from Eq. (10).
Taking the union bound over rows in , then we can show that with probability , for all rows of , that row’s is at most .
Appendix E Running Time of Softmax Attention
In this section, we provide our results on reducing the running time of Softmax attention. We begin with introducing our result on Softmax attention generation.
The Softmax attention generation scenario can be proved by substituting the ReLU attention (Definition 1.2) with Softmax attention with index set (Definition 3.2) in Algorithm 2 and Theorem 4.1. ∎
Then, we move on to our result on Softmax full attention computation.
The Softmax full attention computation scenario can be proved by substituting the ReLU attention (Definition 1.2) with Softmax attention with index set (Definition 3.2) in Algorithm 3 and Theorem 5.1. ∎
Appendix F Error Analysis of Softmax Attention
In this section, we provide an error analysis of the Softmax attention mechanism, deriving error bounds for the general case and a specific case with the massive activation property.
The following lemmas establish error bounds for Softmax attention when using index sets, formalizing the approximation error in attention computation.
Let and be defined as Definition 3.2.
where the first step is by Definition 3.2, the second step is by triangle inequality, the third step is by for any vector and conformable matrix , and the fourth step is by definition of and , i.e., (note that each entry of is positive), the fifth step is by , the sixth step in by simple calculation and the last step is by . ∎
Building on this, we now present a more specific error analysis incorporating the massive activation property:
Let , .
Let the Softmax attention with index set be defined as Definition 3.2.
Let denote the indices of top- entries of .
Let , where .
Assume the query and key cache have massive activation property.
Let be defined in Definition 3.2. By Lemma F.1, we have
where the first step is by Definition of , the second step is by Definition 3.3 and Jensen inequality, and the last step is by simple calculation.
where the first step is by Definition of , the second step is by Definition 3.3, and the last step is by simple calculation.
Finally, we finish the proof by the fact . ∎