PyramidKV: Dynamic KV Cache Compression based on Pyramidal Information Funneling

Zefan Cai, Yichi Zhang, Bofei Gao, Yuliang Liu, Yucheng Li, Tianyu Liu, Keming Lu, Wayne Xiong, Yue Dong, Junjie Hu, Wen Xiao

Introduction

Large language models (LLMs) are integral to various natural language processing applications, including dialogue systems , document summarization , and code completion . These models have recently been scaled up to handle long contexts , with GPT-4 processing up to 128K tokens and Gemini-pro-1.5 handling 1M tokens. However, scaling LLMs to extremely long contexts naturally leads to a significant delay due to the quadratic computation of attention over long contexts. A common solution to mitigate such inference delays involves caching the key and value states (KV) of previous tokens , with the trade-off of requiring extensive GPU memory storage. For instance, maintaining a KV cache for 100K tokens in LLaMA-2 7B requires over 50GB of memory, while a 2K context requires less than 1GB of memory .

To tackle these memory constraints, recent studies have explored the optimization of KV caching, including approaches such as low-rank decomposition of the KV cache or pruning non-essential KV cache . Notably, it has been shown that maintaining merely 20% of the KV cache can preserve a substantial level of performance . Moreover, extreme compression of the KV cache for tasks of longer contexts (e.g., retrieval augmented generation or RAG for short) can drastically improve efficiency and further reduce resource use. However, questions about the universal applicability of these strategies across all layers of an LLM remain open. (1) Are these KV cache strategies applicable to all layers? (2) Is it computationally efficient to use the same KV cache size across layers as previous studies have done? These considerations suggest a need for an in-depth, more nuanced understanding of KV cache optimization in LLMs.

To examine these questions, we aim to systematically investigate the design principles of the KV cache compression across different layers, specifically tailored to the behaviors of the attention mechanism. We first investigate how information flow is aggregated via attention mechanisms across different layers in multi-document question answering (QA), a classic task involving long contexts. Our analysis identifies a notable transition of attention distribution from a broad coverage of global contexts to a narrow focus of local tokens over layers in LLMs. This pattern suggests an aggregated information flow where information is initially gathered broadly and subsequently narrowed down to key tokens, epitomizing the massive attention phenomenon. Our findings provide unique insights beyond the previously documented “massive activation” that very few activations exhibit significantly larger values than others when calculating multi-head attention in LLMs and “attention sink” that keeping the KV of initial tokens will largely recover the performance of window attention.

Building on these insights on how information flows are aggregated through a pyramid pattern, we design a novel and effective KV cache pruning approach that mirrors the geometric shape, named PyramidKV. As shown in Figure 1, unlike the fixed-and-same length KV cache pruning common in prior works , PyramidKV allocates more KV cache to the lower layers where information is more dispersed and each KV holds less information while reducing the KV cache in higher layers where information becomes concentrated in fewer key tokens. To the best of our knowledge, PyramidKV is the first KV cache compression method with varied cache retention across layers, tailoring cache amounts to the informational needs of each layer and paving the way for future research.

We conducted comprehensive experiments on LongBench using 17 datasets across various tasks and domains with two backbone models (LLaMa-3-8B and Mistral-7B ). Results indicate that PyramidKV maintains performance using just 12.0% KV cache and excels in extreme conditions with only 0.7% KV cache retained. Moreover, PyramidKV outperforms baseline models (H2O , SnapKV , StreamingLLM ) across all tested cache sizes (64, 96, 128, 256, 512), with its advantages most pronounced at smaller cache sizes. Additionally, in the Needle In A Haystack experiment, PyramidKV notably sustains the long-context comprehension of LLMs better than competing methods, contributing to its superior performance in LongBench.

Related Work

Prior research has shown that attention matrices in LLMs are typically sparse , focusing disproportionately on a few tokens. For instance, Xiao et al. identified an “attention sink” phenomenon, where maintaining the Key and Value (KV) states of the first few tokens can substantially restore the performance of windowed attention, despite these tokens not being semantically crucial. Similarly, Sun et al. identified a “massive activations” pattern, where a minority of activations show significantly larger values than others within LLMs. Interestingly, these values remain relatively constant across different inputs and act as critical bias terms in the model.

Further explorations in this field reveal distinct patterns across various attention heads and layers. Li et al. observed that certain attention heads consistently target specific prompt attention features during decoding. Additionally, Wang et al. discovered that in In-Context Learning scenarios, label words in demonstration examples serve as semantic anchors. In the lower layers of an LLM, shallow semantic information coalesces around these label words, which subsequently guide the LLMs’ final output predictions by serving as reference points. Recently, Wu et al. revealed that a special type of attention head, the so-called retrieval head, is largely responsible for retrieving information. Inspired by these findings that the attention mechanism exhibits varying behaviors across different layers, we discovered that “Massive Activation” does not consistently manifest across all layers in long context sequences; instead, it predominantly occurs in the upper layers. Additionally, we identified a novel trend of information aggregation specific to long-context inputs, which will be further explained in §3.

There has been a growing interest in addressing LLMs’ memory constraints on processing long context inputs. FastGen introduces an adaptive KV cache management strategy that optimizes memory use by tailoring retention tactics to the specific nature of attention heads. This method involves evicting long-range contexts from heads that prioritize local interactions, discarding non-special tokens from heads focused on special tokens, and maintaining a standard KV cache for heads that engage broadly across tokens. SnapKV improves efficiency by compressing KV caches via selecting/clustering significant KV positions based on their attention scores. Heavy Hitter Oracle (H2O) implements a dynamic eviction policy that effectively balances the retention of recent and historically significant tokens, optimizing memory usage while preserving essential information. StreamingLLM enables LLMs trained on finite attention windows to handle infinite sequence lengths without fine-tuning, thus expanding the models’ applicability to broader contexts. LM-Infinite allows LLMs pre-trained with 2K or 4K-long segments to generalize to up to 200M length inputs while retaining perplexity without parameter updates.

While these approaches have significantly advanced the efficient management of memory for LLMs, they generally apply a fixed KV cache size across all layers. In contrast, our investigations into the attention mechanisms across different layers of LLMs reveal that the attention patterns vary from layer to layer, making a one-size-fits-all approach to KV cache management suboptimal. In response to this inefficiency, we propose a novel KV cache compression method, called PyramidKV that allocates different KV cache budgets across different layers, tailored to the unique demands and operational logic of each layer’s attention mechanism. This layer-specific strategy takes a significant step toward balancing both memory efficiency and model performance, addressing a key limitation in existing methodologies.

Pyramidal Information Funneling

To systematically understand the attention mechanism over layers in LLMs for long-context inputs, we conduct a fine-grained study focusing on the multi-document question answering (QA) task. The model is presented with multiple interrelated documents and prompted to generate an answer for the given query. The main target is to investigate how the model aggregates dispersed information within these retrieved documents for accurate responses.

In particular, we focus on our analysis of the LLaMa and visualize the distribution and behavior of attention scores over layers. To assess the distinct behaviors of each multi-head self-attention layer, we compute the average attention from all heads within each layer. Figure 2 shows the attention patterns of one QA example over six different layers (i.e., 0, 6, 12, 18, 24, and 30).

We identify an approximately uniform distribution of attention scores from the lower layers (e.g., the 0th layer). This suggests that the model operates in a broad-spectrum mode at the lower layers, aggregating information globally from all available content without prioritizing its attention on specific input segments. Notably, a distinct transition to a more localized attention pattern within each document emerges, as the model progresses to encode information at the middle layers (6th to 18th layers). In this phase, attention is predominantly directed towards tokens within the same document, suggesting a more refined aggregation of information within individual contexts.

This trend continues and intensifies in the upper layers (from the 24th to the 30th layer), where we observed the emergence of ‘massive attention’ phenomena. In these layers, the attention mechanism concentrates overwhelmingly on a few key tokens. This pattern of attention allocation, where extremely high attention scores are registered, signifies that the model has aggregated the essential information into these focal tokens. Such behavior underscores a sophisticated mechanism by which LLMs manage and streamline complex and voluminous information, culminating in the efficient extraction of the most pertinent data points necessary for generating accurate answers.

PyramidKV

In an autoregressive transformer-based LLM, the generation of the ii-th token requires that the attention module computes the query, key, and value vectors for all previous i−1i-1 tokens. To speed up the inference process and avoid duplicate computations, the key and value matrices are typically stored in the GPU memory. While the KV cache enhances inference speed and reduces redundant computations, it can consume significant memory when dealing with long input contexts. To optimize memory usage, a strategy called KV cache compression is proposed , which involves retaining only a minimal amount of KV cache while preserving as much information as possible.

2 Proposed Method

In this section, we introduce our method, PyramidKV, based on the pyramidal information funneling observed across different layers in §3. PyramidKV consists of two steps: (1) Dynamically allocating different KV cache sizes/budgets across different layers (§4.2.1); and (2) Selecting important KV vectors in each attention head for caching (§4.2.2).

Previous work on KV cache compression often allocates a fixed KV cache size across LLM layers. However, as our analysis in §3 demonstrates, attention patterns are not identical across different layers. Particularly dense attention is observed in the lower layers, and sparse attention in higher layers. Therefore, using a fixed KV cache size across different layers may lead to suboptimal performance. These approaches may retain many unimportant tokens in the higher layers of sparser attentions while potentially overlooking many crucial tokens in the lower layers of denser attentions.

Thus, we propose to increase compression efficiency by dynamically allocating the cache budgets across layers to reflect the aggregated information flow based on attention patterns. Specifically, PyramidKV allocates more KV cache to the lower layers where information is more dispersed and each KV state contains less information, while reducing the KV cache in higher layers where information becomes concentrated in a few key tokens.

Following the common practice in KV cache compression , we first retain the KV cache for the last α\alpha tokens of the input across all layers, as these tokens have been shown to contain the most immediate task-related information, where α\alpha is a hyperparameter, controlling the number of last few tokens being included in the KV cache. For simplicity, we call these tokens “instruction tokens”, which is also referred to as “local window” in previous literature .

Subsequently, given the remaining total cache budget ktotal=∑l∈[0,m−1]klk^{\text{total}}=\sum_{l\in[0,m-1]}k^{l} that can be used over all transformer layers (noted as mm), we first determine the cache sizes for the top and bottom layers, and use an arithmetic sequence to compute the cache sizes for the intermediate layers to form the pyramidal shape. The key intuition is to follow the attention pattern in aggregated information flow, reflecting a monotonically decreasing pattern of important tokens for attention from lower layers to upper layers. We allocate k0=(2⋅ktotal)/mk^{0}=(2\cdot k^{\text{total}})/m for the first bottom layer, and km−1=ktotal/(β⋅m)k^{m-1}=k^{\text{total}}/(\beta\cdot m) for the top layer, where β\beta is a hyperparameter to adjust the pyramid’s shape. Once the cache sizes of the bottom and top layers are determined, the cache sizes for all intermediate layers are set according to an arithmetic sequence, defined as

2.2 KV Cache Selection

Once the KV cache budget is determined for each layer, our method needs to select specific KV states for caching within each layer in LLMs. As described in the previous section, the KV cache of the last α\alpha tokens, referred to as instruction tokens, are retained across all layers. Following SnapKV , the selection of the remaining tokens is then guided by the attention scores derived from these instruction tokens—tokens receiving higher attention scores are deemed more relevant to the generation process and are thus their KV states are prioritized for retention in the GPU cache.

In a typical LLM, the attention mechanism in each head hh is calculated using the formula:

where dkd_{k} denotes the dimension of the key vectors. Following , we utilize a pooling layer at Ah{\bm{A}}^{h} to avoid the risk of being misled by some massive activation scores.

To quantify the importance of each token during the generation process, we measure the level of attention each token receives from the instruction tokens, and use this measurement to select important tokens for KV caching. Specifically, we compute the score of selecting ii-th token for retention in the KV cache as sihs^{h}_{i} in each attention head hh by:

where [n−α,n][n-\alpha,n] is the range of the instruction tokens. In each layer ll and for each head hh, the top klk^{l} tokens with the highest scores are selected, and their respective KV caches are retained. All other KV caches are discarded and will not be utilized in any subsequent computations throughout the generation process.

Experiment

We conduct comprehensive experiments to evaluate the effectiveness of PyramidKV on performance preserving and memory reduction. First, we introduce the backbone LLMs (§5.1), the evaluation datasets ( §5.2), and the baselines in comparison (§5.3). Next, we report the performance in a memory-oriented scenario and a performance-oriented scenario experiments in §5.5. We also test if the model can preserve the performance on long-context inputs on the Needle-in-the-haystack experiment ( §5.6). Finally, we discuss the trade-off between memory, time, and performance in §5.7.

We compare PyramidKV against baselines using state-of-the-art open-sourced LLMs, namely LLaMa-3-8B-Instruct and Mistral-7B-Instruct . Testing examples are evaluated in a generative format, with answers generated by greedy decoding across all tasks to ensure a fair comparison.

2 Datasets

We use LongBench to assess the performance of PyramidKV on tasks involving long-context inputs. LongBench is a meticulously designed benchmark suite that tests the capabilities of language models in handling extended documents and complex information sequences. This benchmark was created for multi-task evaluation of long context inputs. It includes 17 datasets covering tasks such as single-document QA , multi-document QA , summarization , few-shot learning , synthetic, and code generation . The datasets feature an average input length ranging from 1,235 to 18,409 tokens (detailed average lengths can be found in Table 1), necessitating substantial memory for KV cache management. For all these tasks, we adhered to the standard metrics recommended by LongBench (i.e., F1 for QA, Rouge-L for summarization, Acc. for synthetic and Edit Sim. for code generation.) We refer readers to more details at Appendix B.

3 Baselines

We compare PyramidKV with three baselines, all of which keep the same KV cache size across different layers, with different strategies for KV cache selection.

is an efficient framework that enables LLMs trained with a finite length attention window to generalize to infinite sequence length without any fine-tuning. They propose StreamingLLM based on the attention sink phenomenon that keeping the KV of the first few tokens will largely recover the performance of window attention. StreamingLLM is a competitive method to solve long-context tasks. In our experiments, to be consistent with other methods, we simply keep the KV cache of the last α\alpha tokens and the first k−αk-\alpha tokens, as suggested in the paper.

is a KV cache compression policy that dynamically retains a balance of recent and Heavy Hitter (H2) tokens. H2O keeps a fixed cache size of the Key and Value matrix across Transformer layers. The selection process for the KV cache is driven by attention scores, specifically utilizing the average attention scores from all queries across all tokens to guide the selection.

automatically compresses KV caches by selecting clustered important tokens for each attention head. This method discerns the attention patterns of the Key and Value matrices using a localized observation window positioned at the end of the prompts. However, unlike H2O, SnapKV employs a more nuanced clustering algorithm that includes a pooling layer. Additionally, SnapKV captures attention signals using patterns from a localized window (Instruction Tokens), rather than aggregating attention across all queries, allowing for more targeted and efficient compression.

caches all keys and values for each input token in each layer. All methods are compared to the FullKV simultaneously.

4 Experiment Setup

We maintain a fixed constant KV cache size for each layer for the baseline methods. In contrast, PyramidKV employs varying KV cache sizes across different layers. To ensure a fair comparison, we adjusted the average KV cache size in PyramidKV to match that of the baseline models, to keep the total memory consumption of all methods the same. In our experiment, we set β=20\beta=20 and α=8\alpha=8. We use the same prompt for each dataset in all the experiments.

5 PyramidKV Excels in Memory-constrained Settings

The evaluation results from LongBench are shown in Table 1 and Figure 4. In Figure 4, we report the average score across datasets for 64, 96, 128, 256 and 512 case sizes. In Table 1, we report the results for two different KV cache sizes with 128 and 2048. These two sizes represent two distinct operational scenarios—the memory-efficient scenario and the performance-preserving scenario, respectively for a trade-off between memory and model performance. In Appendix E, we report the results of KV cache sizes with 64, 96, 128, 256, 512, 1024 and 2048.

Overall, PyramidKV preserves the performance with only 12% of the KV cache and it consistently surpasses other method across a range of KV cache sizes and different backbone models, with its performance advantages becoming particularly pronounced in memory-constrained environments where only about 0.7% of the KV cache from the prompt is retained. Upon examining specific tasks, PyramidKV demonstrates a notably superior performance on the TREC task, a few-shot question answering challenge. This suggests that the model effectively aggregates information from the few-shot examples, highlighting the potential for further investigation into in-context learning tasks.

6 PyramidKV Preserves the Long-Context Understanding Ability

We conduct the "Fact Retrieval Across Context Lengths" (Needle In A Haystack) experiment to evaluate the in-context retrieval capabilities of LLMs when utilizing various KV cache compression methods. For this purpose, we employ LlaMa-3-8B-Instruct and Mistral-7B-Instruct as our base, with context lengths extending up to 8k and 32k tokens. We compared several KV cache compression techniques (PyramidKV, SnapKV , and H2O ) at cache sizes of 64 and full cache. The results are displayed in Figure 5 and Figure 6 (Additional results with varying KV cache sizes with Mistral-7B-Instruct-32k-v0.2 and LlaMa-3-8B-8k are available in Appendix F). The results demonstrate that with only 64 KV cache retained, PyramidKV effectively maintains the model’s ability to understand short contexts (up to a context length of 6.8k), and experiences only a modest degradation in performance on longer contexts. In contrast, other KV cache compression methods significantly impair the performance of LLMs.

7 PyramidKV Significantly Reduces Memory with Limited Performance Drop

In this section, we study how sensitive the methods are with different sizes of KV cache. We report the KV cache memory reduction in Table 2. We evaluate the memory consumption of LLaMa-3-8B-Instruct. Specifically, we evaluate the memory consumption of all methods with a fixed batch size of 1, a sequence length of 8192, and model weights in fp16 format. We observe that PyramidKV substantially reduces the KV cache memory across different numbers of cache sizes.

Conclusion

In this study, we investigate the intrinsic attention patterns of Large Language Models (LLMs) when processing long context inputs. Our empirical analysis leads us to discover the existence of Pyramidal Information Funneling in the attention across layers: it distributes information broadly in lower layers, increasingly concentrates it within specific contexts, and ultimately focuses on critical tokens in higher layers with massive activation or attention sink. Motivated by this discovery, we design a novel KV cache compression approach PyramidKV that utilizes this information flow pattern. It varies KV cache sizes across layers, uniquely designed to complement the attention behavior observed across different layers. By leveraging the Pyramidal Information Funneling into KV cache compression design, our method excels in memory-constrained settings, preserves long-context understanding ability, and significantly reduces memory usage with minimal performance trade-offs compared to the baselines.

Future Work

Our investigation on PyramidKV highlights considerable opportunities for optimizing KV cache compression by adjusting the number of KV caches retained according to the distinct attention patterns of each layer (or even for each head). For instance, the retention of KV cache for each layer could be dynamically modified based on real-time analysis of the attention matrices, ensuring that the compression strategy is consistently aligned with the changing attention dynamics within LLMs. Furthermore, our experiments indicate that PyramidKV significantly surpasses other methods in few-shot learning tasks, suggesting promising applications of KV cache in in-context learning. This approach could potentially enable the use of more shots within constrained memory limits.

References

Appendix A Limitations

Our experiments were limited to two base models: LLAMA-3-8B-Instruct and Mistral-7B-Instruct. While these models demonstrated consistent trends, the robustness of our findings could be enhanced by testing a broader array of model families, should resources permit. Additionally, our research was conducted exclusively in English, with no investigations into how these findings might be transferred to other languages. Expanding the linguistic scope of our experiments could provide a more comprehensive understanding of the applicability of our results globally.

Appendix B Details of Evaluation

We use LongBench to assess the performance of PyramidKV on tasks involving long-context inputs. LongBench is a meticulously designed benchmark suite that tests the capabilities of language models in handling extended documents and complex information sequences. This benchmark was created for multi-task evaluation of long context inputs. We present the details of metrics, language and data for LongBench at Table 3.

We run all the experiments on NVIDIA V100 and A100.

Appendix C Ablation Study

One topic we want to analyze for our ablation study is the selection of β\beta, which can determine the staircase. The smaller β\beta is, the gentler the staircase is; the larger β\beta is, the steeper the staircase is. We want to investigate the effect of β\beta step size on the final result. Results on 128 KV cache size and LlaMa-3-8B-Instruct are shown in Table 4. The results at Table 4 show that using a relatively small value of β\beta yields better outcomes, and PyramidKV is generally robust to the selection of β\beta.

Appendix D License

Appendix E PyramidKV Excels in all KV Cache Size Limitation

The evaluation results from LongBench are shown in Table 5. We report the results using LlaMa-3-8B-Instruct and Mistral-7B-Instruct for different KV cache sizes.

Overall, consistently surpasses other method across a range of KV cache sizes and different backbone models, with its performance advantages becoming particularly pronounced in memory-constrained environments. Upon examining specific tasks, PyramidKV demonstrates a notably superior performance on the TREC task, a few-shot question answering challenge. This suggests that the model effectively aggregates information from the few-shot examples, highlighting the potential for further investigation into in-context learning tasks.

Appendix F PyramidKV Preserves the Long-Context Understanding Ability

We perform Fact Retrieval Across Context Lengths (“Needle In A HayStack”) to test the in-context retrieval ability of LLMs after leveraging different KV cache methods. Figure 7, Figure 8, Figure 9 show the results of Mistral-7B-Instruct with different cache size (64, 96 and 128, respectively).

Figure 10, Figure 11, Figure 12 show the results of LlaMa-3-8B with different cache size (64, 96 and 128, respectively).