Efficient Sparse Attention needs Adaptive Token Release (2024)

Abstract: In recent years, Large Language Models (LLMs) have demonstrated remarkable capabilities across a wide array of text-centric tasks. However, their ‘large’ scale introduces significant computational and storage challenges, particularly in managing the key-value states of the transformer, which limits their wider applicability. Therefore, we propose to adaptively release resources from caches and rebuild the necessary key-value states. Particularly, we accomplish this by a lightweight controller module to approximate an ideal top-K sparse attention. This module retains the tokens with the highest top-K attention weights and simultaneously rebuilds the discarded but necessary tokens, which may become essential for future decoding. Comprehensive experiments in natural language generation and modeling reveal that our method is not only competitive with full attention in terms of performance but also achieves a significant throughput improvement of up to 221.8%. The code for replication is available on the https://github.com/WHUIR/ADORE.

heading: 1 Introduction
text: After breaking through the cognitive barriers, large language models (LLMs) are now widely used in many text-rich areas, such as voice assistants (Vu et al., 2024), search engines (Mao et al., 2024), and recommendation systems (Tang et al., 2023; Zhao et al., 2023). These successes are a testament to the philosophy of scaling up parameters to boost performance, i.e., the scaling law (Kaplan et al., 2020). However, in situations demanding rapid or extensive text modeling, the vast size of the model significantly escalates the computational and storage requirements for the key-value (KV) states of self-attention, which, in turn, limits its throughput (Liu et al., 2023a; Strati et al., 2024). For example, when using a model with 7 billion
*Corresponding author.
parameters, caching the KV states for 1,000 tokens results in a memory requirement that exceeds twice the size of the model parameters, consequently increasing time costs in attention cost and memory swapping.
Recent efforts address this issue from two perspectives: 1) hardware optimization, analogous to ‘increasing income’; 2) refining algorithms, similar to ‘reducing expenditure’. The former approach typically optimizes performance by scheduling tasks across multiple GPUs (Borzunov et al., 2022) or by implementing hierarchical unloading using the CPU and disk (Aminabadi et al., 2022; Sheng et al., 2023). These techniques, though efficient, require additional hardware and, if not carefully scheduled, can lead to increased communication latency. This, in turn, may potentially degrade the overall user experience (Rasley et al., 2020; Yang et al., 2023). The latter strategy enhances efficiency by limiting the caching size of key-value states, such as sparsely attending to its immediate neighbors (Zaheer et al., 2020; Beltagy et al., 2020) or compressing prompts (Li et al., 2023e; Pan et al., 2024). Though efficient, it can often lead to a drop in performance. Besides, some methods instantiate the sparse attention by masking attention after the attention weights have been calculated (Rao et al.,
14081
2021; Li et al., 2023d). Thus, they fail to enhance inference speed and reduce memory usage.
Among existing methods, the dynamic top-K attention (Goyal et al., 2020; Li et al., 2023a; Liang et al., 2023), which maintains sparse attention by selecting the highest attention contributions, demonstrates performance comparable to, or even better than, full attention models. Such an intuitive solution has only been well explored in encoders where the model can access the entire context simultaneously. However, in decoder-based LLMs, the required context shifts dynamically, necessitating multiple calculations of top-K attention throughout the decoding process. This unique characteristic further complicates the challenges: 1) Premature and erroneous releasing of unnecessary KV states may result in inaccuracies of top-K attention calculation. However, accurately determining the top-K attention requires considering all KV states of past tokens, thereby conflicting with the goal of reducing costs. 2) Tokens released earlier might be required for top-K attention in future decoding due to long-term dependencies in the text, as illustrated in Figure 1. Consequently, missing these necessary tokens can result in inaccurate calculations of sparse attention for subsequent tokens.
To this end, we introduce ADORE, ADaptive tOken RElease, which maintains a constant cache size by accurately releasing useless past key-value (KV) states and efficiently reconstructing vital past KV states that were previously released. ADORE introduces a lightweight controller module that adaptively releases tokens with the lowest predicted attention contribution for the current token from the KV cache. This ensures a fixed KV cache overhead, even when processing numerous tokens. Additionally, ADORE rebuilds the KV state for tokens that are likely to contribute higher attention scores but have been previously released. This rebuild mechanism counters the issue when a released token is essential for future decoding. Moreover, ADORE can seamlessly integrate into LLM inference, showing impressive results with only minor fine-tuning and training needed for the lightweight controller module. Extensive experiments on multiple benchmark datasets reveal that ADORE achieves up to a 221.8% improvement in throughput compared to full attention models while maintaining nearly identical text quality.

heading: 2 Methodology
text: This section first establishes the framework for efficient sparse attention, followed by initially exploring the adaptive token release in Section 2.2. Subsequently, we rebuild the KV states of important tokens, approximating the ideal dynamic sparse attention in Section 2.3. Finally, we propose an optimized matrix slicing algorithm to accelerate the implementation of our method in Section 2.4. An overview of our method is illustrated in Figure 2.

heading: 2.1 Efficient Sparse Transformer
text: Let Tn = {t1, . . . , ts, ts+1, . . . , tn} be a set of word tokens, where {t1, . . . , ts} represent user input tokens, and {ts+1, . . . , tn} are tokens generated by a transformer-based model, such as GPTNeo (Black et al., 2021) and Llama (Touvron et al., 2023). When generating the next token tn+1, the current token tn serves as the query input. The tn’s key-value states are based on the following scaled dot-product attention as
an,l = softmax
( qn,l × (Knl )⊤√
d
) × V nl , (1)
where an,l ∈ Rd denotes the hidden state at the lth layer of the transformer. It undergoes a non-linear transformation process to become the key and value states associated with the token t, qn,l denotes the query vector derived from tn at the lth layer. The terms Knl ∈ R(n)×d and V nl ∈ R(n)×d represent the key and value states from the current token set Tn at the same layer. These states are retained in the GPU memory to minimize redundant computations. The generation of the token tn+1 is accomplished through a multi-classification approach, utilizing the hidden state an,L ∈ Rd from the last layer.
For an efficient sparse transformer, we selectively cache the most relevant KV states, aiming to reduce computational demands while maintaining or even enhancing the model’s performance in generating subsequent tokens as
a′n,l = softmax
( qn,l × ( Knm+1,l )⊤ √ d ) × V nm+1,l.
Here, a′n,l approximates the an,l using the Knm+1,l ∈ R(m+1)×d, V n(m+1),l ∈ R(m+1)×d, which correspond to selecting m rows from Kn−1l and V n−1l and concatenating them with kn,l and vn,l respectively, with the condition that m <<
n − 1. kn,l, vn,l denote the key and value vector derived from tn at the lth layer. It implies only a significantly smaller Knm+1,l and V n m+1,l are retained in GPU for rapid inference and save memory. From a performance standpoint, achieving the ideal sparsity involves computing the full attention weight wn = qn,l × (Knl )⊤ ∈ Rn and then selecting the top-m query-key product weights. Then, these weights serve as indices for slicing V nl . While this method is optimal in performance, it does not confer any computational or memory savings as the process of computing full attention weights for all query-key pairs and then selecting the top weights is computationally intensive.

heading: 2.2 Adaptive Token Release
text: The adaptive token release is to create efficient scheduling of the key-value states within the GPU memory. The main idea is to use a lightweight controller module as an alternative to computing full weight for slicing the full key-value states. To be both efficient and effective, we have implemented several design strategies:
• Refine the model with top-K attention. Compared to the full attention, Top-K could mitigate the impact of excluding partial KV states once the pertinent top-K KV states are included within the m cached KV states, which is consistent with the target defined in Equ (2). Therefore, we initially fine-tune the LLMs with top-K attention, which utilizes only the highest top-K attention weights
via masking the weights out of the top-K. Remarkably, this approach yields performance that is on par with full attention models (Liu et al., 2022). To be efficient, the cache size m is slightly larger than K. As m decreases, the complexity of the scheduling process increases correspondingly.
• Adopt a uniform scheduling policy for the retention or exclusion of KV states across various layers. Constructing a layer-specific scheduling strategy would necessitate additional time to model each layer’s input. Moreover, the initial layer is more pivotal for integrating value states; as we delve deeper into the layers, the hidden states become increasingly homogeneous (Wu et al., 2023). Additionally, it is observed that different layers often focus on a similar set of top-K attentions. The effectiveness of the uniform scheduling policy is elaborated in Appendix C.
• Update the cached KV states by appending the latest KV state and selectively release an older one. An intuitive idea is to store the KV states in the motherboard’s memory as backup. However, due to bandwidth limitations between the GPU and motherboard, moving KV states in and out proves to be extremely slow, at times even slower than recalculating the KV states (Aminabadi et al., 2022). Consequently, when updating the cached KV states, we simply append the most recently computed KV states while removing a nonsignificant older one, thereby maintaining a constant size for the cache.
Adhering to above strategies, we develop a controller module that utilizes the lightweight and efficient GRU (Dey and Salem, 2017) for scheduling the cached KV states. Specifically, during the generation of token tn+1, we establish the probability of whether caching the KV state of token ti as:
zi = GRU(xi,zi−1) (2) σi = Sigmoid(MLP(pi + zi))
where xi ∈ Rd represents the token embedding from the LLMs. The GRU is a single-layer GRU (an unidirectional model with its effectiveness analyzed in Appendix D) that recurrently transforms this token embedding into a context-aware representation zi ∈ Rd′ . The term pi ∈ Rd′ denotes the position embedding for the ith token, which signifies the importance of token position in the scheduling model. During the update of the KV states, we discard those with the lowest σi values and append the most recent KV states to the cached states. To fine-tune its parameters, we construct a dataset by collecting word embeddings of each sequence as input. Then we construct corresponding labels by assigning a value of 1 to the indices of the top-K tokens that most frequently occur within the top-K/2 attention scores across all layers, and a value of 0 to all others.

heading: 2.3 KV States Rebuild
text: Adaptive token releasing facilitates the selective preservation of the most pertinent tokens, yet previously discarded tokens may become essential for future decoding due to the long-term dependencies in text. To counter this issue, we propose the rebuilding of KV states as a complement.
This method entails retrieving the top-R tokens with the highest σi values from the set of released tokens. Let XR ∈ RR×d represent the token embedding of selected released tokens. We concatenate XR with xn, i.e., the embedding of current token tn, forming the input XR+1 ∈ R(R+1)×d. After (l − 1)-layers processing, we can obtain the query states QnR+1,l ∈ R(R+1)×d, Knm+R+1,l ∈ R(m+R+1)×d and V nm+R+1,l ∈ R(m+R+1)×d, where Knm+R+1,l/V nm+R+1,l is formulated by concating cached key/value state and rebuild key/value states for the input tokens. With its argument, the attention is calculated as
A ′ R+1,l = softmax   QnR+1,l × ( Knm+R+1,l )⊤ √ d   × V nm+R+1,l,
where A′R+1,l is the hidden state. To get the corresponding value for the current generating tokens, we get the a′n,l by selecting the last row of A ′ R+1,l. Through the parallel rebuilding of the released KV states, we maximize the utilization of GPU without incurring excessive time overhead.

heading: 2.4 Matrix Slicing as Multiplication
text: The scheduling of KV states relies on certain matrix-slicing operators. Traditional slicing operators like gather and mask-select can lead to significant time overheads (Kim et al., 2022), particularly when batch operations involve varying slicing indices. To circumvent it, we leverage the GPU’s rapid matrix multiplication capabilities. For instance, to remove the jth row from Knm,l, we prepare a slicing matrix, Sj = I(1:j−1,j+1:m),:, where I ∈ Rm×m is the identity matrix and I(1:j−1,j+1:m),: selects all rows of I except the jth row. The resulting Knm−1,l = Sj ×Knm,l, with Sj being pre-prepared to save time.

heading: 3 Experiment

heading: 3.1 Experimental Settings
text: Dataset. To evaluate the effectiveness of various sparse attention mechanisms, we conduct extensive experiments across three distinct tasks: natural language generation, stream generation, and natural language modeling. For the first task, we evaluate on UltraChat (Ding et al., 2023), EverythingLM1, and Math (Li et al., 2023c). For the second task, we experiment on StreamEval (Xiao et al., 2024) and StreamChat (built upon UltraChat). For the last task, we evaluate models on CNN Dailymail (See et al., 2017) and SAMSum (Gliwa et al., 2019).
Specifically, UltraChat is a multi-turn dialogue dataset containing approximately 696,600 training samples and covering diverse topics such as questions about the world and creative writing. EverythingLM is an instructional dataset consisting of 1,000 conversations and encompassing a wide array of topics and interactions. Math dataset is composed of 50,000 problem-solution pairs obtained using GPT-4 across 25 math topics. StreamChat concatenates every 100 samples from UltraChat and feeds them into the model in a streaming fashion to assess the quality of the generated answers. StreamEval is a question-answer dataset, building upon LongEval (Li et al., 2023b). Specifi-
1https://huggingface.co/datasets/ totally-not-an-llm/EverythingLM-data
cally, it comprises about 2,000 samples, each with 1,000 lines of textual information and 100 retrieval questions. CNN Dailymail is a news summarization dataset containing over 300,000 news articles. SAMSum is a summarization dataset containing about 16,000 messenger-like conversations with summaries. The details of the datasets are reported in Appendix A.
Baseline. We compare our method with the following methods: 1) Full Attention encompasses all past KV states across every layer, characterized by a time complexity of O(T 2) and linear growth in cache size. 2) Window Attention (Hassani et al., 2023) focuses on the nearest tokens for self-attention at each layer, thus ensuring a constant size for the key-value cache. 3) Strided Attention (Child et al., 2019) attends to both the nearest and distant tokens by periodically focusing on one with a fixed interval, thus striking a balance between effectiveness and efficiency. 4) KV Compression (Ren et al., 2023) incrementally compress the intermediate activation of a specified span of tokens into compact ones. 5) StreamingLLM (Xiao et al., 2024) extends Window Attention by adding the first four tokens to the cache, aiming to maintain a normal distribution of attention scores and stable inference settings. 6) H2O (Zhang et al., 2024) dynamically evicts unimportant tokens from the cache, which contribute the least to the cumulative attention. 7) H2O(Rebuilt) selectively rebuilds the KV states of evicted token based on H2O.
Experimental Protocols. We employ Llama2 7B (Touvron et al., 2023) as our backbone for evaluation. It has 32 transformer layers and 4,000 context length. For our experiments, we employ the top-96 attentions and set the KV cache size m to 192 with top-8 rebuilt tokens. We randomly selected 1,000 samples from the benchmark dataset for training purposes. The samples were utilized to develop the sparse top-K backbone model using QLoRA (Dettmers et al., 2023), along with the con-
troller module. The extra data were employed for testing models. The training and inference times for the controller module are detailed in Appendix B and Appendix D, respectively. To evaluate the quality of the generated text, we use metrics including BLEU, ROUGE, BERT-F (Zhang et al., 2019) and Accuracy. To measure the inference speed of different methods, we use Throughput (Sheng et al., 2023), which is defined as the number of tokens generated per second.

heading: 3.2 Natural Language Generation
text: This subsection evaluates models’ performance in natural language generation. We summarize the quality of generating text on UltraChat, EverythingLM and Math benchmarks in Table 1 and the throughput against different sequence lengths in Figure 3. From the results reported, we have the following observations: 1) The proposed ADORE achieves the best performance, and consistently outperforms all the baselines on all datasets. In Table 1, our method shows an improvement over full attention in the UltraChat dataset, with increases of 1.2% in BLEU scores and 0.1% in BERT-F scores. On the other hand, Window Attention, Strided Attention, KV Compression, StreamingLLM, H2O, and H2O(Rebuilt) show reductions of 8.9%, 7.6%, 14.5%, 11.7%, 9.2% and 8.0% in BLEU scores, respectively. A similar trend is also observed in the learning curve illustrated in Appendix C. 2) Our proposal performs the best in achieving a high efficiency while maintaining a competitive performance against full attention. Specifically, it is evident that our method demonstrates a consistent throughput against various generated text lengths; whereas full attention suffers from a significant drop in throughput as the generated text length increases. Notably, our method outperforms full attention by 151.4% and 221.8% when generating text lengths of 768 and 960, respectively. 3) Existing SOTA
methods, i.e., StreamingLLM and H2O, sacrifice inference quality in exchange for improving throughput. Though StreamingLLM and H2O have slightly higher throughput, their performance on natural language generation suffers a lot.

heading: 3.3 Stream Generation
text: To show the real-world applicability of our proposal, we emulate the performance of the models on infinite streaming dialogue, i.e., StreamChat, and question-answering tasks, i.e., StreamEval. For StreamChat, we chunk the streaming chat with the size of 4096 to evaluate the quality of generation against different sequence lengths. The experimental results are reported in Table 2. For StreamEval, we report the generating accuracy of models’ responses after multi-times query in Figure 4.
From the Table 2 and Figure 4, we have following observations: 1) In the table, our method demonstrates a consistent performance across different sequence lengths, which justifies its efficacy in streaming dialogue, especially in length extrapolation and capturing high-importance tokens. While full attention exhibits the best performance on the first subset (length in range (0, 4096]), its performance rapidly declines as the streaming sequence length surpasses the pre-training window size, and eventually becomes almost 0. 2) In the
figure, our method consistently maintains high accuracy, even when the number of queries exceeds 20, which expresses the superiority of our proposed method. On the other hand, full attention and strided attention display competitive performance at limited query times. However, they suffer a significant drop in performance due to Out-ofMemory (OOM) issues, which arise as the accumulation of excessive KV states increases with the number of queries. This observation justifies the necessity of sparse attention. However, Window Attention and StreamingLLM demonstrate lower accuracy compared to our approach, primarily due to their fixed heuristic policies. KV Compression exhibits suboptimal accuracy due to the information loss in token compression. Benefiting from dynamic eviction strategy, H2O and H2O (Rebuilt) consistently demonstrate competitive performance compared to our method.

heading: 3.4 Natural Language Modeling
text: We evaluate the performance of various methods in natural language modeling on the CNN Dailymail and SAMSum datasets. We report perplexity (ppl.) as the metric to compare the performance of different methods across different sequence length subsets. Similar to Section 3.3, the length in each subset is in the range of ((i− 1)× 1024, i× 1024] for (i = 1, 2, . . . ).
Figure 5 illustrates the logarithm of perplexity for different methods across various modeling intervals. It is evident that our method, StreamingLLM, H2O, and H2O(Rebuilt) consistently maintain the lowest perplexity. They are effective in preserving the original attention distribution with sparse attention. Therefore, they demonstrate superior performance on extrapolating length. As the sequence length increases, KV Compression compresses more tokens, leading to a gradual increase in perplexity. Although full attention exhibits the
best performance in the shortest input length subset ([0, 4096]), its performance quickly becomes worse when the input length surpasses the size of the pretraining window.

heading: 3.5 Ablation Study

heading: 3.5.1 Influence of Attention Sparisity
text: We explore ADORE’s performance against different K in adaptive token release. In particular, we configure K in the range of {48, 96, 128, 192} for fine-tuning the model and top-m as {48 × 2, 96 × 2, 128 × 2, 192 × 2} for a fixed cache size. The inference performance and the corresponding training loss are presented in Table 3 and Figure 6, respectively.
Figure 6 shows that when K values are set to 96, 128, and 192, the differences in training loss are minimal. This indicates that retaining tokens with the highest top-K attention weights is sufficient, and further increasing K does not yield substantial improvements in model performance. From Table 3, it can be observed that there is no significant improvement in the quality of the generated text when m increases from 96× 2 to 192× 2, which, however, is accompanied by a notable decrease in throughput. Therefore, it is essential to select an appropriate set of K and m, which balances throughput and the quality of generated text.

heading: 3.5.2 Influence of KV States Rebuild
text: We evaluate the impact of different R in KV states rebuild. Specifically, we select R in the range of {0, 8, 16, 32} and summarize the inference performance in Table 4. The results demonstrate that as the R in rebuilt tokens increases, the model’s performance first improves. However, the improvement comes at the cost of a reduction in throughput. When the number of rebuilt tokens is further increased from 16 to 32, we can observe an improvement of 1.5% in BLEU, 1.0% in ROUGH, and 0.4% in BERT-F. However, this minor improvement is accompanied by a 34.4% decrease in throughput. This indicates that selecting the appropriate number of rebuilding tokens is crucial for maintaining a trade-off between performance and quality during the inference process.

heading: 3.5.3 Effectiveness of Controller Module
text: Since we use the controller module for advancedly predicting top-K attention weights, next we investigate how it affects overall performance. In particular, we adjust the module with the following variants: 1) w/o GRU: directly using the MLP for predicting the keeping/dropping probability of tokens; 2) ADORE d′=64: set hidden size of the controller to 64; 3) ADORE d′=128: set hidden size
of the controller to 128; We first report accuracy and F1 scores on the dataset that fine-tunes the controller module, as detailed in Section 2.2. Then, we report BLEU, ROUGE, and BERT-F scores on the Ultrachat benchmark, which further illustrate how the performance of the controller module influences the performance of LLMs.
We summarize the results in Table 5. Our observations are as follows: 1) The GRU is crucial for the controller module to serve as an effective alternative to full attention; 2) An improved controller module results in enhanced performance during the inference process, as it offers a more accurate approximation of sparse attention.

heading: 4 Related Work

heading: 4.1 Sparse Attention
text: Several works have attempted to integrate sparse attention into transformer-based models. This integration reduces the quadratic computational complexity in the sequence length, making it possible to process longer sequences. Some studies adopt fixed-pattern sparse strategies (Zaheer et al., 2020; Beltagy et al., 2020), while others focus on sparsification based on the distribution and features of self-attention (Goyal et al., 2020; Liu et al., 2023b; Huang et al., 2024). However, these methods either optimize bi-directional attention encoding, as in BERT, or fail to yield a practical improvement in the inference speed of language models (Ren et al., 2023; Tan et al., 2024). This is because the reduction in the number of tokens does not yield significant benefits on CUDA (Bolya et al., 2022). To address this issue, in the LLM inference process, we propose applying dynamic sparse attention to the storage of the KV cache, thereby fundamentally enhancing the throughput of the LLM.

heading: 4.2 Efficient Inference for LLMs
text: The efficiency improvement of LLM inference is becoming increasingly attention-grabbing (Huang and Chang, 2023). Recent research has primarily focused on two aspects: systems and algo-
rithms, aiming to enhance LLM inference efficiency. In recent years, numerous systems dedicated to LLM inference have emerged, such as FasterTransformer, Hugging Face Accelerate (Gugger et al., 2022), FlexGen (Sheng et al., 2023), and vLLM (Kwon et al., 2023). These systems often emphasize optimization from hardware accelerators and CUDA kernels. On the other hand, algorithms like Early-Exit (Sun et al., 2021; Rotem et al., 2023) Flashattention-2 (Dao, 2023) and Continuous Batch (Yu et al., 2022) attempt to optimize LLM inference performance by reducing computational costs. In this paper, our proposed method is orthogonal to all mainstream LLM inference systems and most algorithmic optimizations, and our method can be used in parallel with these methods.

heading: 4.3 Length Extrapolation for LLM Inference
text: Length extrapolation aims to enable language models to maintain satisfactory performance when applied to super-long sequences as well. Current research primarily focuses on finding improved representations for positional encoding. Rotary Position Embeddings (RoPE) (Su et al., 2024) attempt to transform absolute positions into relative position encodings for length expansion. Furthermore, ALiBi (Press et al., 2021) introduces relative positional information by imposing a penalty bias proportional to the distance in relative proximity on the attention matrix. However, current pproaches still struggle to model extremely long texts effectively. Simultaneously, when dealing with long texts, a major limiting factor lies in GPU memory overflow. In this paper, our approach extends the inference length of LLM by setting a fixed attention window size by adaptively releasing tokens, which is designed to maximize the length of inference without compromising performance significantly.

heading: 5 Conclusion
text: We propose an efficient sparse attention for the inference process of LLMs. This is achieved by adaptively releasing the KV state of the tokens with the lowest attention contribution in the cache while simultaneously rebuilding the state of tokens with the highest contribution during the step-by-step decoding of each token. Experimental results show that our approach significantly enhances the throughput of model inference without substantially compromising the quality of the generated text.

heading: 6 Limitations
text: In this paper, the primary limitation lies in the finetuning process required to align with our designed inference optimization method. Specifically, during fine-tuning, we still face an O(n2) time complexity for self-attention, resulting in no speed improvement when learning dynamic sparse attention. Furthermore, our method is not immediately applicable during inference; it requires additional computational overhead for fine-tuning and training the controller to attain enhanced performance during inference.
Acknowledgments We are grateful for the funding support from the National Natural Science Foundation of China under Grant Numbers 62302345 and U23A20305, the Natural Science Foundation of Hubei Province under Grant Numbers 2023AFB192 and 2023BAB160, the Xiaomi Young Scholar Program, and the Wuhan University Talent Startup Fund.

heading: A Dataset Statistics
text: In Table 6, we present the statistical information of the datasets used in our experiments, including dataset partitioning and sequence length statistics.
B Implementation Details
In this section, we illustrate the details of our implementation, primarily including training data collection for the controller module, fine-tuning with QLoRA, details of the controller module, inference settings, and hardware settings.
Training data collection for the controller module As detailed in Section 2.2, during the finetuning process of the full attention (baseline) on the training set, we collect the word embeddings and the most frequently top-K indices of each sample as input data and labels for training the controller. Given that full attention models the entire sequence, it consistently yields the lowest loss during fine-tuning, thereby ensuring that the attention distribution modeled is reliable and informative for capturing the top-K tokens.
Fine-tuning with QLoRA (i) Hyper-parameters: For all methods, we utilize the Adam optimizer with a learning rate of 3e-5, decayed by a rate of 0.98 every 40 steps. Regarding the parameters for Q-LORA, we uniformly set the rank parameter r = 16 and the learning rate scaling factor lora_alpha = 32. (ii) Alignment fine-tuning with ADORE: By collecting the top-K indices, we create attention masks for full attention, which block the attention from the current token to the lowcontribution tokens. This implementation achieves dynamic sparse attention during fine-tuning, resulting in a model aligned with our inference optimization approach. The fine-tuning time on the UltraChat, EverythingLM, and Math datasets is approximately 3 hours on four GeForce RTX 3090 GPUs, respectively.
Details of the controller module (a) Controller network structure: (i) Input layer: A GRU layer with an input size of 4096 and a hidden size of 128; (ii) Position layer: A fully connected layer with an input size of 1, projected to 128; (iii) Interaction layer: A fully connected layer with a hidden size of 128 and a Tanh activation function; (iv) Output layer: Each output, mapped to [0,1] for cross-entropy loss over the sequence length, is obtained through a fully connected layer followed by a sigmoid function. (b) Training Details: We employ the Adam optimizer with a learning rate of 0.005, accompanied by a decay rate of 0.98 every 2000 steps. We split the collected dataset into a training set and a validation set with an 8:2 ratio, and save the model parameters achieving the highest F1 score on the validation set.
Hardware settings We utilize four GeForce RTX 3090 GPUs, with a total runtime exceeding 20 hours.

heading: C Analysis of Dynamic Sparse Attention
text: In this section, we first demonstrate the effectiveness of applying a uniform scheduling policy across different layers. Then we showcase the superior performance of dynamic sparse attention in comparison to other methods and delve into the underlying reasons behind its effectiveness.
According to the settings in Section 2.2, we select the top-K/2 tokens sets for each layer and consider the top-K tokens that appear most frequently in these sets as the uniform token sets. In Figure 7(a), we observe that the uniform token set covers the majority of the top-K/2 token sets at each layer. Additionally, in Figure 7(b), we illustrate the cumulative softmax attention scores from the uniform token set for the current token across
different layers, demonstrating that the uniform token set can effectively replace the contributions of the top-K/2 token sets at each layer.
Figure 9 illustrates the comparison of loss with QLoRA fine-tuning for various methods on UltraChat, EverythingLM, and Math. It is evident that the loss by focusing on the tokens with the top-K highest attention (dynamic sparse attention) maintains consistency with the full attention approach and results in a notable reduction in loss compared to other methods.
The superior performance of dynamic sparse attention can be attributed to the observation that only a small portion of tokens significantly contributes to the attention mechanism during the modeling process for the current token. The Softmax scores in the self-attention curve on the cnn-daily dataset are presented in Figure 8. It can be observed that the blue curve in Figure 8 forms a long-tail distribution, i.e. a few tokens contribute to the significant attention and others can be disregarded.

heading: D Analysis of the unidirectional GRU
text: In this section, we explore the impact of the GRU unit for adaptive token release and selection on run-
time. Table 7 reports the time needed to generate 100, 200, and 500 tokens, as well as the time allocated to the GRU unit for adaptive token release and selection. It can be seen that the GRU unit’s average runtime is merely 2.9% of the total runtime. This suggests that the runtime overhead attributed to the GRU unit for adaptive token release and selection is negligible.
In addition, we compare the performance of unidirectional and bidirectional GRU in terms of top-K prediction Accuracy, F1-score, and Runtime (seconds) for 500 tokens to illustrate why we choose unidirectional GRU as the primary architecture for the controller module.
Table 8 demonstrates the Accuracy, F1-score, and Runtime. We can observe that bidirectional GRU does not significantly improve performance compared to unidirectional GRU. Instead, bidirec-
tional GRU is more computationally expensive in terms of runtime because it requires forward and backward computations at each time step.

heading: Future Work
text: Adaptive token releasing facilitates the selective preservation of the most pertinent tokens, yet previously discarded tokens may become essential for future decoding due to the long-term dependencies in text. To counter this issue, we propose the rebuilding of KV states as a complement. This method entails retrieving the top-R tokens with the highest σi values from the set of released tokens. Let XR ∈ RR×d represent the token embedding of selected released tokens. We concatenate XR with xn, i. e. , the embedding of current token tn, forming the input XR+1 ∈ R(R+1)×d. After (l − 1)-layers processing, we can obtain the query states QnR+1,l ∈ R(R+1)×d, Knm+R+1,l ∈ R(m+R+1)×d and V nm+R+1,l ∈ R(m+R+1)×d, where Knm+R+1,l/V nm+R+1,l is formulated by concating cached key/value state and rebuild key/value states for the input tokens. With its argument, the attention is calculated as
A ′ R+1,l = softmax   QnR+1,l × ( Knm+R+1,l )⊤ √ d   × V nm+R+1,l,
where A′R+1,l is the hidden state. To get the corresponding value for the current generating tokens, we get the a′n,l by selecting the last row of A ′ R+1,l. Through the parallel rebuilding of the released KV states, we maximize the utilization of GPU without incurring excessive time overhead