A Training-Free Sub-quadratic Cost Transformer Model Serving Framework with Hierarchically Pruned Attention

## Abstract

Abstract In modern large language models (LLMs), increasing the context length is crucial for improving comprehension and coherence in long-context, multi-modal, and retrieval-augmented language generation.
While many recent transformer models attempt to extend their context length over a million tokens, they remain impractical due to the quadratic time and space complexities.
Although recent works on linear and sparse attention mechanisms can achieve this goal, their real-world applicability is often limited by the need to re-train from scratch and significantly worse performance. In response, we propose a novel approach, Hierarchically Pruned Attention (HiP), which reduces the time complexity of the attention mechanism to O ⁢ ( T ⁢ log ⁡ T ) 𝑂 𝑇 𝑇 O(T\log T) italic_O ( italic_T roman_log italic_T ) and the space complexity to O ⁢ ( T ) 𝑂 𝑇 O(T) italic_O ( italic_T ) , where T 𝑇 T italic_T is the sequence length.
We notice a pattern in the attention scores of pretrained LLMs where tokens close together tend to have similar scores, which we call “attention locality”. Based on this observation, we utilize a novel tree-search-like algorithm that estimates the top- k 𝑘 k italic_k key tokens for a given query on the fly, which is mathematically guaranteed to have better performance than random attention pruning. In addition to improving the time complexity of the attention mechanism, we further optimize GPU memory usage by implementing KV cache offloading, which stores only O ⁢ ( log ⁡ T ) 𝑂 𝑇 O(\log T) italic_O ( roman_log italic_T ) tokens on the GPU while maintaining similar decoding throughput. Experiments on benchmarks show that HiP, with its training-free nature, significantly reduces both prefill and decoding latencies, as well as memory usage, while maintaining high-quality generation with minimal degradation.
HiP enables pretrained LLMs to scale up to millions of tokens on commodity GPUs, potentially unlocking long-context LLM applications previously deemed infeasible.

## 1 Introduction

Large Transformer-based generative language models (LLM) trained on huge datasets have recently demonstrated remarkable abilities in various problem domains, such as natural language understanding (Touvron et al., ), code generation (Rozière et al., ), and multi-modal question answering (Liu et al., ).
This is made possible by the effectiveness of the attention mechanism, which learns $T^{2}$ pairwise relationships between all tokens in a sequence of $T$ tokens.
Despite their success, the quadratic complexity of the attention mechanism makes it increasingly challenging to meet growing resource demands when processing longer sequences.

Various approaches have been suggested to handle longer sequences efficiently to overcome this limitation.
FlashAttention (Dao et al., ; Dao, ) has reduced the space complexity to $O(T)$ by fusing the component computations to avoid storing $T^{2}$ attention scores at one time.
However, its time complexity remains $O(T^{2})$, making it less applicable to inference tasks with long contexts.
Many other methods (Lee et al., ; Beltagy et al., ; Zaheer et al., ; Tay et al., ; Kitaev et al., ; Tay et al., ; Liu et al., ) tackle the issue by sparsifying the attention matrix or approximate the attention mechanism using kernel methods to reduce its quadratic complexity.
However, these works are not widely employed in real-world LLM serving frameworks because they often lead to performance degradation due to drastic changes in the computation flow and are too complex to implement efficiently for actual speedups.
Moreover, they often require extensive fine-tuning or even pre-training from scratch, which can be prohibitively expensive and prevent the timely deployment of production-ready pre-trained models.

Figure: Figure 1: HiP Attention. HiP dynamically prunes block sparse attention depending on a given query token in sub-quadratic cost by utilizing the hierarchy and locality of natural language.
Refer to caption: x1.png

In this paper, we define and achieve three fundamental objectives for frameworks tailored to long-context transformer serving frameworks: (1) minimizing the algorithmic complexity of attention mechanisms, (2) enhancing GPU compute efficiency, particularly through TensorCore utilization, and (3) maximizing the effective use of limited GPU memory capacity.

First, to serve long sequences in a timely manner, we propose Hierarchically Pruned Attention (HiP), an efficient training-free attention mechanism reducing the quadratic time complexity to $O(T\log T)$ by approximating the top-$k$ key tokens in a sequence.
HiP exploits “attention locality”, where neighboring tokens often have similar attention scores, as shown in Figure 1 (Left).
Therefore, as shown in Figure 1 (Center), HiP divides the input sequence into $2k$ chunks, and the center token in each chunk is chosen to represent its neighbors, driven by the attention locality within the chunk.
HiP computes the attention scores of these representative tokens to approximate the importance of each chunk for a given query.
HiP iteratively refines its selection by starting with the top-$k$ most important chunks and progressively narrowing them down until each chunk contains a single token.
This hierarchical top-$k$ key estimation takes $O(T\log T)$ time, which is used for sparse attention computation that costs $O(T)$, making the overall complexity of our attention mechanism log-linear.
We provide mathematical proof demonstrating that our HiP outperforms random selection, supported by empirical evidence from attention score statistics in Section 4.

Second, we introduce hardware-aware optimizations to enhance GPU compute efficiency for our HiP through block-wise key sparsity, as illustrated in Figure 1 (Right).
Specifically, our top-k approximation is implemented in a tiled manner (Tillet et al., ) so that it can fully utilize matrix multiplier units (MMUs; e.g., TensorCores (Nvidia, )) and achieve the highest possible token-processing throughput.
Additionally, we integrate our attention mechanism into throughput-optimized LLM serving frameworks, such as vLLM (Kwon et al., ) and SGlang (Zheng et al., ), further enhancing deployment efficiency.

Lastly, to serve extremely long sequences within the limited GPU memory, we propose a KV cache management strategy that stores only $O(\log T)$ tokens in GPU memory (HBM) and offloads the remaining tokens to host memory (DRAM).
The $O(\log T)$ tokens stored in GPU memory are the ones accessed most frequently and are meant to provide quick access for the GPU’s MMUs.
In contrast, other less frequently accessed tokens reside in main memory and are transferred to GPU memory only upon token access misses.
With a high access hit ratio in HiP, our memory management scheme effectively meets the demand for limited HBM capacity while leveraging the larger DRAM capacity, preventing token access from becoming a bottleneck.

We validate HiP on various benchmarks by applying it to Llama3.1-8B (Meta, ).
In LongBench (Bai et al., ), HiP maintains 96% of its relative performance while achieving almost $2.7\times$ speedup in the prefill stage and $16.5\times$ speedup attention computation in the decode stage with 32k context length compared to Flash Attention.
Additionally, in passkey retrieval tasks such as RULER (Hsieh et al., ), HiP preserves its original effective context length, while all baselines fail to do so.
We also evaluate the effectiveness of the proposed KV cache offloading framework.
On a machine capable of serving up to a 16k context length with Flash Attention, our method extends the context length up to 64k by offloading the KV cache without significant throughput degradation.

In conclusion, by integrating the three proposed solutions, we present a single long-context serving framework that efficiently manages compute and memory resources while being transparent and easily usable.
This extension of serving context length, achieved within the constraints of limited space and compute budgets, delivers substantial benefits for long-context applications, such as question answering with long texts (Kryściński et al., ), multi-agent chatbots (Hu et al., ), enhanced retrieval-augmented reasoning, and long video data summarization.
Furthermore, since our approach is training-free, HiP can be seamlessly applied to pretrained LLMs without requiring additional training.
As a result, we expect our method to be highly practical for a wide range of long-context LLM applications.

Our contributions within the proposed framework can be summarized as follows:

- •
We propose a novel, training-free hierarchically pruned attention mechanism that uses hierarchical score-locality-aware top-$k$ approximation to accelerate LLM serving, reducing the quadratic cost of the attention mechanism to $O(T\log T)$ time and $O(T)$ space complexity (Section 3.1).
- •
We further optimize our HiP mechanism with a hardware-aware block-wise tiled optimization using OpenAI Triton, achieving up to speed up to $6.83\times$ speedup in end-to-end decoding for 128k context. (Section 3.2, Figure 7)
- •
We implement KV cache offloading to reduce GPU memory efficiency further, increasing serving context from 16k up to 64k tokens in an RTX 4090 with 8B model
(Section 3.3).

## 2 Related Works

Previous studies proposed several attention approximations with linear complexity using either kernel methods or sparse attention.
Low-rank approximations of softmax attention via kernel methods (Choromanski et al., ; Qin et al., ) achieve faster inference speeds but significantly alter the data flow, leading to performance degradation that is hard to mitigate.
In contrast, sparse attention methods, which use attention pruning to preserve trained attention scores, allow for simple replacement of pre-trained mechanisms.
However, they often require additional fine-tuning to adapt to static attention patterns (Beltagy et al., ; Zaheer et al., ; Xiao et al., ) or the training of an attention estimator (Lee et al., ; Liu et al., ).
These methods are generally less efficient than fused attention techniques (Dao et al., ; Dao, ) due to their fine-grained sparsity, which prevents optimal MMU utilization.
For more details, see Section E.1.

## 3 Methodology

Figure: Figure 2: Overview of our HiP attention mechanism. In HiP, the model dynamically decides which $k$ number of key tokens to attend to for each query by generating a sparse attention mask. The sparse attention mask is generated in a tree search-like manner. At each iteration, the top-$k$ blocks with the largest attention scores are selected, and the rest of the branches are discarded. The final mask becomes an accurate approximation of the top-$k$ blocks of the true attention map.
Refer to caption: x2.png

Given query, key, and value sequences $\bm{Q},\bm{K},\bm{V}\in\mathbb{R}^{T\times d}$, the conventional single-head attention output $\bm{O}$ is computed as
$\bm{S}=\bm{Q}\bm{K}^{\top}\in\mathbb{R}^{T\times T}$,
$\bm{P}=\mathrm{softmax}(\bm{S})\in\mathbb{R}^{T\times T}$,
$\bm{O}=\bm{P}\bm{V}\in\mathbb{R}^{T\times d}$,
where $d$ denotes embedding dimension, and softmax is applied row-wise. The causal masking and constant scaling are omitted for brevity.
The $\bm{S}$ and $\bm{P}$ matrices are respectively called the attention scores and probabilities.
We focus on the fact that, due to the nature of the softmax function, only the highest attention scores significantly impact the output.
Therefore, a promising approach to approximating $\bm{S}$ in a sparse format and reducing the complexity from $O(T^{2})$ is to retain only its top-$k$ elements, as detailed in the following equations:

$$ $\displaystyle\bm{M}=\mathrm{top_}k\mathrm{_mask}\left(\bm{Q}\bm{K}^{\top} \right)\in\{0,1\}^{T\times T},$ (1) $\displaystyle\widehat{\bm{S}}=\mathrm{mask}_{\bm{M}}(\bm{Q}\bm{K}^{\top})\in \mathbb{R}^{T\times T},\quad\widehat{\bm{P}}=\mathrm{softmax}(\widehat{\bm{S}} )\in\mathbb{R}^{T\times T},\quad\widehat{\bm{O}}=\widehat{\bm{P}}\bm{V}\in \mathbb{R}^{T\times d},$ (2) $\displaystyle\text{where }[\mathrm{mask}_{\bm{M}}(\bm{S})]_{i,j}:=\begin{cases }{S}_{i,j}&\text{if }{M}_{i,j}=1\\ -\infty&\text{if }{M}_{i,j}=0\end{cases},$ (3) $$

where $\mathrm{top_}k\mathrm{_mask}(\cdot)$ denotes a binary mask which selects the top-$k$ largest elements for each row of the given matrix.
Since $\widehat{\bm{S}}$ is a sparse matrix with only $kT$ valid elements, $\widehat{\bm{S}}$ and $\widehat{\bm{O}}$ in Equation 2 can be computed in $O(T)$ time using sparse matrix operations.

However, obtaining the binary mask $\bm{M}$ in sub-quadratic time is no easy task.
To address this challenging problem, we exploit what we call “attention locality”. Observation of attention scores reveal that the scores tend to exhibit local similarity, a phenomenon we refer to as attention locality.
We exploit this observation by performing a tree-based search for the top-$k$ tokens.
We divide the sequence into $2k$ chunks, and then select a representative token from each chunk.
Due to attention locality, a representative token have similar scores to other tokens in its chunk - thereby “representing” that chunk.
We select the top-$k$ most important chunks based on the attention scores of the representative tokens.
By repeating this process, we refine the tokens until we can no longer divide chunks.
Exact details of our method are shown in Section 3.1.
We only cover the single-head non-causal case here, but note that our method can easily be extended to causal multi-head attention.

### 3.1 Hierarchical Score-Locality-Aware Top- k 𝑘 k italic_k Estimation

As shown in Equation 1, our goal is to select the top-$k$ largest elements of each row of pre-trained attention score $S$ without computing the entire matrix.
To this end, we use a greedy binary tree search algorithm, as illustrated in the left side of Figure 2.
The complete algorithm for mask estimation is presented in Algorithm 1.

For a given query $\bm{q}\in\mathbb{R}^{d}$, at the first iteration, we divide the key sequence $\bm{K}\in\mathbb{R}^{T\times d}$ along the time dimension into $k$ equal-sized chunks $(f^{(1)}_{1}:l^{(1)}_{1}),(f^{(1)}_{2}:l^{(1)}_{2}),\dots,(f^{(1)}_{k}:l^{(1)}
_{k})$,
where $f^{(1)}_{j}=\left\lfloor\frac{j\cdot T}{k}\right\rceil$ and $l^{(1)}_{j}=\left\lfloor\frac{(j+1)\cdot T}{k}\right\rceil-1$ are the first and last indices of the $j$th chunk, each.(^1^11$\left\lfloor\cdot\right\rceil$ denotes rounding to the nearest integer.) The superscripts denote the iteration number.
At each iteration $i$, we further divide each of the $k$ chunks into two equal-sized branches:

$$ $\mathcal{B}^{(i)}_{2j-1}=(f^{(i)}_{j},m^{(i)}_{j}-1),~{}~{}\mathcal{B}^{(i)}_{ 2j}=(m^{(i)}_{j},l^{(i)}_{j}),\text{ where }m^{(i)}_{j}=\left\lfloor(f^{(i)}_{ j}+l^{(i)}_{j})/2\right\rceil,\text{ for }j=1~{}..~{}k.$ $$

A representative key index $r^{(i)}_{j}$ is the center key token index for each branch $\mathcal{B}^{(i)}_{j}$. We assume that this representative key represents the entire branch. Thus, among the $2k$ branches, the top $k$ branches whose representative key’s scores are the highest are chosen for the next iteration:

$$ $\displaystyle(f^{(i+1)}_{j},l^{(i+1)}_{j}):=\mathcal{B}^{(i)}_{t_{j}}\text{ for }j=1~{}..~{}k,\text{ where }\{t_{1},\dots,t_{k}\}:=\underset{j\in[1~{}..~{ }2k]}{\mathrm{argtop}_{k}}\left[\bm{q}^{\top}\bm{K}_{r^{(i)}_{j},:}\right].$ (4) $$

We repeat the above iteration $n_{it}:=\left\lceil\log_{2}T\right\rceil$ times, i.e., until the length of each branch all becomes 1. In the end, we obtain a set of indices $\mathcal{I}=\{f_{1}^{(n_{it})},\dots,f_{k}^{(n_{it})}\}$, which is our estimation of the top-$k$ indices of $\bm{K}$ which have the largest attention scores with the query $\bm{q}$. Thus, we obtain $\widehat{\bm{m}}$, an estimation of a row of the attention mask $\bm{M}$(^2^22$\mathds{1}_{\mathcal{A}}(x)$, where $\mathcal{A}$ is a set, denotes the indicator function: $\mathds{1}_{\mathcal{A}}(x)=1$ if $x\in\mathcal{A}$, and otherwise $\mathds{1}_{\mathcal{A}}(x)=0$.):

$$ $\displaystyle\widehat{\bm{m}}=\mathrm{estimate_attn_mask}_{k}(\bm{q},\bm{K}) :=\left[\mathds{1}_{\mathcal{I}}(1),\mathds{1}_{\mathcal{I}}(2),\dots,\mathds{ 1}_{\mathcal{I}}(d)\right].$ (5) $$

In conclusion, this algorithm takes $O(T\log T)$ time in total because the total number of iterations is $\log_{2}T$ where each iteration takes constant time $O(k)$, and we do this for each of the $T$ queries.

### 3.2 Block Approximation of Top- k 𝑘 k italic_k Estimation

Despite the log-linear complexity, obtaining competitive latency to the state-of-the-art implementations of dense attention on an accelerator (e.g., GPU) is difficult.
This is because the matrix multiplier unit (MMU) inside accelerators is optimized for dense attention, where they compute fixed-size blocks of matrix multiplication in a few clock cycles.
In contrast, the attention score computation in the top-$k$ estimation of HiP cannot be performed with traditional matrix multiplication because a different key matrix is used to compute the dot product for each query vector.
To utilize MMU, we use a technique called block approximation during top-$k$ estimation, illustrated in Figure 2 (Right).

In top-$k$ estimation, we replace $\bm{K}\in\mathbb{R}^{T\times d}$ with its tiled version $\bm{\mathsf{K}}\in\mathbb{R}^{T/b_{k}\times b_{k}\times d}$, and $\bm{Q}$ with its tiled version $\bm{\mathsf{Q}}\in\mathbb{R}^{T/b_{q}\times b_{q}\times d}$, where $b_{k}$ and $b_{q}$ are the size of a key block and a query block.
The top-$k$ estimation iterations are done similarly to before, except that the division and branching of the key sequence are done block-wise (using the first dimension of $\bm{\mathsf{K}}$). Importantly, instead of $k$, $k/b_{k}$ chunks are maintained at each iteration in order to select $k$ tokens, and the score calculation in Equation 4 is replaced with $\max_{\scriptstyle m\in[1:b_{q}],\scriptstyle n\in[1:b_{k}]}\left(\bm{q}_{m,:}
^{\top}\bm{\mathsf{K}}_{l_{j}^{(i)},n,:}\right),$
where $\bm{q}\in\mathbb{R}^{b_{q}\times d}$ is the given query block.
While this modification enables HiP to reduce the cost further, we internally sample the blocks with stride $b_{sq}$ in the query dimension and $b_{sk}$ in the key dimension instead of using the full $b_{q}\times b_{k}$ block.

As a result of this optimization, the estimated mask $\widehat{\bm{M}}$ becomes block-sparse.
Therefore, each $(b_{q}/b_{sq})\times d$-block of the query can be matrix-multiplied with the same $(k/b_{sk})\times d$ key matrix to obtain $(b_{q}/b_{sq})\times(k/b_{sk})$ elements of $\widehat{\bm{S}}$.
Thus, $b_{q}$ and $b_{sq}$ are critical for the most efficient utilization of the MMU:
we can achieve a considerable latency reduction if we set $b_{q}/b_{sq}$ to a multiple of 16 or 32, as shown in Section E.4.
While the choice of $b_{k}$ and $b_{sk}$ is irrelevant to the MMU utilization, it helps reduce the number of top-$k$ estimation iterations.

### 3.3 KV Cache Offloading

Figure: Figure 3: Flow of KV Cache Offloading with HiP.
Refer to caption: x3.png

Thanks to our top-$k$ estimation algorithm, HiP only accesses $(k/b_{sk})\log{T}$ key states per attention head.
Moreover, the algorithm’s memory access pattern exhibits strong temporal locality.
Using this fact, we can further enhance efficiency by exploiting the memory hierarchy: we offload less frequently accessed key-value (KV) states from the GPU to the main memory.
This involves caching frequently accessed KV states (hot tokens) by tracking state access patterns of top-$k$ estimation and sparse attention using the estimated HiP mask.

Figure: Figure 4: KV Token Index Translation
Refer to caption: x4.png

Our GPU cache that holds the hot tokens consists of two components: a token bank containing the actual KV states and a page table with the token-bank index mapping, as shown in Figure 4.
One straightforward implementation for the page table would be a vector map: a simple length-$T$ array of pointers.
While this approach is practical for typical sequence lengths (e.g., 128k - 1M), its space complexity is $O(T)$.
We employ a linear probing hash table to reduce the space complexity, achieving $O(\log T)$ space complexity.
However, empirical results show that GPU hash map lookups introduce additional latency compared to using a simpler vector-based page table.

Given the distinct memory access patterns in top-$k$ estimation and in sparse attention, we maintain two separate offloading contexts, each containing a page table and a set of GPU-resident hot tokens, as illustrated as two separate GPU loaded KV caches in Figure 3.
For the top-$k$ estimation stage, $k_{\text{cache}}:=c\cdot(k/b_{sk})\log T$ key states are held in VRAM, where $c$ is a hyperparameter determining the cache size. For sparse attention, $k$ key and value states are held.
In summary, we need to hold $(k_{\text{cache}}/2+k)$ tokens’ equivalent of KV states in the GPU.
The kernel first queries the GPU cache when accessing key or value tokens.
Upon a cache miss (which is unavoidable due to the dynamic nature of the attention access pattern), the system attempts to retrieve tokens from the main memory. By using our cache, we can significantly speed up memory access compared to directly accessing CPU memory from the GPU.

In conclusion, we reduce the GPU memory footprint for KV tokens from $O(T)$ to $O(\log T)$, but this comes with page table overhead that can range between $O(T)$ and $O(\log T)$ depending on the data structure used.
The overall space complexity is thus determined by the type of page table, allowing for a configurable trade-off between GPU memory efficiency and latency.
However, we suggest that users use vector maps in many practical long-context ranges (32-512k) to achieve competitive latency compared to Flash attention.
Please refer to Section 5.5 for detailed benchmarks.

## 4 Theoretical Analysis

In this section, we justify the design choices of our HiP’s approximate top-$k$ key selection algorithm by answering the following questions: (1) Is HiP’s key selection algorithm better than the random selection baseline at finding keys with the biggest scores? (2) How should the representative token in each branch be chosen?
We answer these questions by providing a probabilistic analysis of HiP’s key selection algorithm in a simplified setting ($k$ = 1), based on the assumption of attention locality.

##### Observation: keys closer together exhibit higher similarity in attention scores.

In each attention head of a layer in an LLM, a key sequence $\bm{K}\in\mathbb{R}^{T\times d}$ is used for computing the attention mechanism. Given a query vector $\bm{q}\in\mathbb{R}^{d}$, the scores for each key $\bm{s}=\bm{K}\bm{q}\in\mathbb{R}^{T}$ can be computed. We investigate how much locality these scores exhibit by studying the correlation between their distance $\Delta:=|i-j|$ and the score difference $\delta_{\Delta}:=s_{i}-s_{j}$ for every $i,j\in[1..T]$, with a sample natural language data.
As shown in Figure 5, our empirical observation shows that $\delta_{\Delta}$ generally follows a normal distribution, whose mean is almost zero and the standard deviation is an increasing function of distance $\Delta$. More details regarding this observation are provided in Section A.3.

Figure: Figure 5: Score Difference Distribution. We collect the attention score statistics from the 17${}^{\text{th}}$ layer and second attention head of Llama3.1-8B. The left figure shows the raw distribution when $\Delta=500$. The middle and right figures show the mean and standard deviation as a function of $\Delta$.
[Uncaptioned image]: x5.png

##### Analysis.

Based on this observation, we assume that we can approximate the difference in attention scores between two keys separated by $\Delta$ tokens as a scalar random variable $\delta_{\Delta}\sim\mathcal{N}\left(0,\sigma(\Delta)^{2}\right)$, where $\sigma(\Delta)$ is an increasing function of $\Delta$.
This can be interpreted as keys that are closer together are more likely to have a similar attention score, which fits well with our observation and attention locality assumption. With this assumption, the following Theorem 1 can be shown.

###### Theorem 1 (Informal) .

Consider the case of finding the location of the top-$1$ key token with the maximum attention score in a context of $T$ tokens. Suppose that our locality assumption holds true.
We divide the context into two branches with $T/2$ keys each. Then, the branch whose center token has the bigger attention score is more likely to contain the top-$1$ key token.

The above shows the effectiveness of one iteration of HiP’s key selection algorithm.
By recursive application of HiP’s key selection iterations, we can intuitively see that the probability of HiP’s key selection algorithm finding the location of the top-$1$ key would be higher than that of uniform random selection as well.
Therefore, under the attention locality assumption, on average, HiP’s key selection algorithm on average finds the best key tokens more often than random selection. This is also the basis for choosing the center key token as the representative in our algorithm. See Section A.1 for the proof sketch and Section A.2 for the formal statement and proof of the theorem.

###### Theorem 1 (Informal) .

## 5 Experiments

### 5.1 Experiment Settings

Large Language Models (LLMs) are one of the most prominent models that utilize the attention mechanism.
Thus, we first apply our proposed HiP to Llama3.1-8B (Touvron et al., ), a pretrained LLM that is reported to perform well on various long-context natural language understanding tasks up to 128k context tokens, to evaluate the effectiveness of our HiP mechanism.
We replace all, but the initial $l_{d}$ attention layers with HiP in the pretrained LLM, where $L$ is the total number of layers, and $l_{d}$ denotes the remaining dense attention layers.
We choose $l_{d}$ through an ablation study (Section E.5).
During LLM decoding, we cache the sparse attention mask from the previous step and refresh it every $r_{m}$ step to reduce the decoding latency.
The latency-performance tradeoff of $r_{m}$ is discussed in Section 5.4.
For a detailed description of HiP’s decoding process, see Algorithm 2 in the appendix.
Further details on the hyperparameters are in Appendix D.

Baselines. We use several sparse attention baselines: A, StreamingLLM (SLLM) (Xiao et al., ), AVD (Jiang et al., ; Li et al., ), BigBird (Zaheer et al., ), HyperAttention (Han et al., ), and H2O (Zhang et al., ), chosen for their training-free and sub-quadratic properties.
Both StreamingLLM and A use a combination of global sink tokens and sliding window (Beltagy et al., ), with StreamingLLM additionally using rolling RoPE indexing (Xiao et al., ).
AVD retains key vertical and diagonal lines in the prefill attention mask based on snapshot scores on top of A. As it is a prefill-oriented method, A is used for decoding.
BigBird uses random masking along with the A pattern.
HyperAttention is a token-clustering-style (Kitaev et al., ) attention mechanism.
Finally, H2O retains the top-$k$ high-scoring KV tokens for the next step’s KV cache.

Figure: Figure 6: Latency and Perplexity Evaluation with Various Context Lengths. We evaluate our proposed HiP and baselines in PG19 (Rae et al., ) with various context length on Llama3.1-8B (Meta, ). See Appendix D for experiment details.
Refer to caption: x8.png

### 5.2 Language Modeling Performance Evaluation

We evaluate HiP on the PG19 (Rae et al., ) datasets.
We measure latency in two stages: (1) the initial pass (prefill), where the forward pass covers the entire prompt, and (2) subsequent passes (decode), which process one token at a time with a KV cache.
In Figure 6, HiP attention is $9.00\times$ faster in prompt latency and $29.99\times$ faster in decoding latency on Llama3.1-8B, with only a +0.5348 increase in perplexity on PG19 (8.1151 $\rightarrow$ 8.6499).
Our method leverages block approximation to maximize MMU efficiency, outperforming quadratic baselines and achieving near-linear decoding latency.
Further details on experimental settings are in Appendix D.

Figure: Table 1: Passkey Results. We evaluate our proposed HiP and baselines using passkey retrieval which is a needle in a haystack style context utilization benchmark.

### 5.3 Long Context Performance

In this section, we investigate the performance of our HiP, comparing its latency and accuracy against baselines on various benchmarks.
Mainly, we build two kinds of benchmark sets: (1) long-context utilization to verify our method can retrieve the information in a given context using a needle in a haystack (NIAH) and (2) long-context natural language understanding to show that our method can preserve reasoning and text generation performance of original long-context LLM.
We apply the efficient attention method to mimic various deployment settings by replacing prefill, decode, or prefill-decode flash attention.
We can find our HiP performs robustly in every scenario compared to baselines, by applying efficient attention methods in different phases separately.

Figure: Table 2: RULER Results. We compare the effective context lengths of HiP and baselines with Llama3.1-8B. Accuracies surpassing 80% are marked with bold font.

Passkey and RULER. First, we analyze the result of long-context utilization performance using passkey retrieval in Sections 5.2, LABEL: and 5.3.
Our passkey retrieval test is a simple test to find a five-digit passkey in a repeated haystack sentence.
RULER (Hsieh et al., ) is a more complex benchmark containing NIAH tests, such as finding multiple passkeys and tracking variable changes inside complicated essay-style haystack sentences.
In Section 5.2, our method is the strongest in every deployment setting.
Dense prefill in general scores high in this benchmark because the model has no chance of overlooking the passkey tokens.
However, interestingly, AVD shows an almost perfect score with sparse prefill + dense decode. We think this is because the snapshot heuristic that captures important tokens during prefill is a perfect fit for this benchmark.
However, because of this aspect, it performs poorly on more complex tasks such as RULER and LongBench.
The combination of HiP and AVD slightly increases the performance from regular HiP, achieving 100% accuracy in passkey up to 64k context length.

Figure: Table 3: LongBench Results. We evaluate HiP and baselines. We measure the speedup of prefill and decode on 32k context length, the maximum context length of LongBench.

LongBench. We then use the LongBench benchmark (Bai et al., ) to evaluate the long context prompt and decoding performance of HiP in Section 5.3.
We believe that this benchmark is the most important because it shows both long context generation performance and knowledge retrieval performance, which are critical in many LLM applications, such as multi-turn assistants and in-context learning.
Compared to passkey, the dense decode setting scores higher because this benchmark is much more decoding-heavy.
This means that real-world natural language question answering and long context text generation rely more on decoding accuracy rather than prefill.
Therefore, we can see non-decode-friendly baselines such as StreamingLLM, AVD and A failing to recover long-generation performance in GovReport and MultiNews subtasks, which decode 512 tokens.
Interestingly, AVD completely fails on those two subsets while it works moderately well on some QA tasks.
We think this is because AVD fails to capture complex reasoning and long-term context due to its restrictive attention mask patterns.
In Section E.2, we illustrate this long context knowledge retrieval ability by using an example from LongBench. HiP outperforms every baseline, and with a small amount of fine-tuning with an unrelated dataset, it even recovers the original model’s performance (‘HiP heal’). See Appendix D for more details and discussion about healing.

**Table 4: Benchmark Performance on Long-Booksum Task. We evaluate the book summarization task. 2k tokens are generated for the summary of each book, whose lengths are between 32k-128k tokens. For the ‘Half’ and ‘Quarter window’ settings, the context window size of each sparse attention method is adjusted accordingly. The speedups are measured on the Normal setting.**
|  | Method | KVCache<br>footprint<br>(tokens) | Decoding<br>context<br>window<br>(tokens) | Llama3.1-8B-Instruct |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|  | Normal Window ($\times$1) | Half Window ($\times$.5) | Quarter Window ($\times$.25) | Decode<br>Speedup |  |  |  |  |  |  |  |  |  |
|  | rouge-1 | rouge-2 | rouge-L | rouge-1 | rouge-2 | rouge-L | rouge-1 | rouge-2 | rouge-L |  |  |  |  |
|  | FlashAttn | $\infty$ | $\infty$ | 41.63% | 10.16% | 23.58% | 41.63% | 10.16% | 23.58% | 41.63% | 10.16% | 23.58% | 1.00x |
| Un-<br>limited<br>VRAM | BigBird 4k | $\infty$ | 4K | 36.05% | 7.59% | 19.81% | 34.20% | 7.02% | 18.90% | 31.97% | 6.23% | 18.71% | 5.90x |
| \cdashline1-14[0.5pt/1pt]<br>Restricted<br>vram Size | FlashAttn trunc | 8K | 8K | 36.62% | 8.33% | 20.97% | 36.62% | 8.33% | 20.97% | 36.62% | 8.33% | 20.97% | 15.68x |
| BigBird 2k Trunc | 8K | 4K | 35.44% | 7.57% | 19.65% | 34.60% | 7.20% | 19.32% | 32.36% | 6.46% | 18.62% | 5.90x |  |
| AVD 8K + 8k + 8k | 8K | 8K | 37.18% | 8.28% | 21.62% | 36.07% | 7.72% | 20.60% | 35.72% | 7.67% | 20.81% | 7.51x |  |
| HiP 2k (Ours) | 7K | 3K | 38.84% | 9.11% | 21.92% | 38.47% | 8.57% | 21.50% | 37.34% | 8.52% | 21.53% | 7.75x |  |
| HiP 2k + V2k D1k | 7K | $\sim$4K | 39.98% | 9.61% | 22.61% | 39.44% | 9.09% | 22.05% | 38.00% | 8.70% | 22.04% | 7.05x |  |

BookSum.
We use the BookSum benchmark (Kryściński et al., ) to assess the long-context and long-response generation capabilities of HiP.
We report the average ROUGE F1-scores (Lin, ) for the generated summaries in Table 4.
To simulate a realistic long-context decoding scenario and demonstrate the effectiveness of KV cache offloading, we put a limit on the GPU KV memory size to 8K tokens. This represents a practical context length on a 24GB GPU with an 8B model without KV offloading.
Specifically, for FlashAttention and BigBird, we truncate the context to 8K tokens, and AVD uses an 8K token length sliding window.
With our method, with KV cache offloading, we can expand the effective context length only limited by the main memory’s capacity, which is much cheaper.
HiP outperforms all other baselines in this VRAM-limited setting while maintaining high decoding speed: over $7\times$ faster than regular FlashAttention.
Although FlashAttention with a truncated context is faster, it suffers from significant performance degradation and, most importantly, breaks the user’s expectation that the model can access the entire context.
We observe that HiP with a context window of only 512 still outperforms AVD with an 8k window.

Figure: Figure 7: End-to-end Decoding Latency. We show two phases of HiP decoding: mask refreshing step triggered in every $r_{m}$ decoding step and mask cached sparse attention.
Refer to caption: x12.png

### 5.4 Latency Breakdown and End-to-end Decoding Speedup

We evaluate the trade-off between attention latency and the model performance with HiP in Figure 6.
We observe that our HiP’s latency-optimized setting shows about 9.00$\times$ speedup of attention decoding latency but only increases the perplexity by 0.5348 in PG19 (Rae et al., ), compared to FlashAttention2.
In Figure 7, we show the latency breakdown of the HiP-applied transformer model.
Our proposed method contains two major components that contribute to the overall latency: (1) top-$k$ estimation iterations and (2) fused sparse attention.
We observe that the HiP top-$k$ estimation kernel is the only scaling part as the sequence grows; the sparse attention and linear layer shows constant time for each decoding step.
Since the top-$k$ estimation iteration results can be cached and reused $r_{m}$ times, the latency of the HiP method is dominated by fused sparse attention in most practical scenarios, as shown in Figure 7.
On the other hand, the $r_{m}$ hyperparameter trades off the generation quality for latency, especially for long decoding, as shown in Figure 7.
HiP achieves 6.83 times end-to-end decoding speedup with 128k context while maintaining 96.0% relative performance in LongBench.
We can speed up further to 14.30$\times$ when we allow a moderate amount of performance degradation (-3.6%p).

### 5.5 KV Cache Offloading Benchmark

In Figure 8, we evaluate the latency and memory usage of our KV offloading framework.
The UVM variants use the CUDA unified virtual memory API to offload the whole KV cache to the main memory.
Our HiP has two variants that depend on the type of cache implementation.
We use Llama3.1-8B with 16-bit weights, and the KV states are stored in 8-bit floats.
We use a single RTX 4090 24GB for the graph on the left, and to additionally test our method up to 512k tokens, we also test on a single A100 80GB GPU.
We set $l_{d}=0$, and choose the last token for the representative key to reduce the memory access in this test.
See Appendix D for details.

Figure: Figure 8: KV Cache Offloading Performance (left). We measure batched prefill and decoding throughput (tokens/s) with our novel KV cache offloading framework with an on-device offloading cache. Straight lines show the latency, and dashed lines show the GPU memory usage by KV caches.
Refer to caption: x13.png

As shown in Figure 8, with UVM, both ours and Flash Attention slow down decoding about 5 to 7 times compared to full GPU runtime.
However, we could serve until 64k context, while the same machine can serve only 16k at maximum.
Since memory access is significantly more costly with UVM, the trend of logarithmic scaling of decode throughput is clearer than when working with pure GPU memory.
So, at 64k context length, ours is more than 50 times faster than Flash Attention with UVM.
However, UVM slows down both methods too much compared to full GPU runtime.

We test two types of cache implementation: vector map and hash map.
A vector map uses a $T$-sized vector of pointers pointing to the allocated bank to store the mapping between a token index and a bank index.
Our GPU-loaded KV offloading cache (Vector Map) shines by achieving 93% decoding throughput compared to no KV offloading at all.
Without a significant slowdown, we could extend the serving context from 16k to 64k on an RTX 4090, which is 4.17$\times$ higher decoding throughput compared to HiP${}_{\text{UVM}}$ and 49.97$\times$ higher decoding throughput compared to Flash Attention${}_{\text{UVM}}$, as shown in Table 6.
However, with the vector map, the space complexity is $O(T)$.
To reduce the space complexity to $O(\log T)$, we use a linear probing hash map to store the index mapping.
This way, we can reduce the GPU memory consumption by 40.8% on 512k context length.
However, since the hash map lookup is not friendly to the GPU, it slows down token accesses more than naive UVM.

We present our KV offloading framework on a standard gaming PC equipped with a single RTX 4090.
Our experiments confirm that the PCIe 4.0x8 bandwidth is sufficient to manage offloading traffic through KV accesses using UVM.
Furthermore, when scaled up to a single A100 80GB, our framework demonstrates its ability to extend serving context length, even on server-grade hardware.
We anticipate that our HiP’s KV offloading framework will effectively increase serviceable context length across a wide range of deployments, from on-device setups to cloud-based environments.

## 6 Conclusion

In this study, we present HiP Attention, a novel framework for accelerating pretrained Transformer-based models without any training, with a focus on the acceleration of LLMs for long-context tasks.
Our proposed HiP rapidly estimates the top-$k$ context keys for computing sparse attention, drastically reducing the computation required for long context inference and fine-tuning from $O(T^{2})$ to $O(T\log T)$.
Our HiP attention is a drop-in replacement for the core of any Transformer-based model, such as language and multimodal models, and does not require modifying the existing weights.
This is a practical and meaningful improvement as it allows pre-trained models to be fine-tuned and executed much more efficiently in long sequences without sacrificing quality.
We are looking forward to contributing to open-source LLM serving frameworks by combining various efficient decoding strategies with HiP attention.

## Reproducibility Statement

We provide every experiment code and kernel code in the attached supplementary file.
We also provide detailed instructions on how to run experiments in readme markdown files, so please read those files.
And we put detailed experiment settings in Appendix D.
We will try our best to resolve further reproducibility problems.
Inside the HiP library, we have multiple versions of HiP kernels, all written with OpenAI Triton.
The upstream kernel path is hip / models / hip_attention / attention2_draft_prefetch.py.
Additionally, you can see the evolution of our HiP from the very first HiP implementation hip / models / hip_attention / attention1.py; please feel free to enjoy our codebases.
We left them all for research purposes when someone needs various settings, such as dynamic retention ratios, that are only supported by old versions.
Our main experiment entry file is hip / main / model_eval.py.
Please execute --help option to gather further information.
Our offloading experiment entry file is hip / models / hip_attention / offload_runner / offload_runner.py.
For Longbench and RULER, we modified the official code to run our method with vLLM.
Please refer to HiPAttentionArgs class to investigate full settings, including every subtle configuration.
A, AVD and BigBird are using the same HiP kernel since they are the same block sparse attention.
We just modify the block masks that passed to block sparse attention.
StreamingLLM is implemented in hip/models/sink_attention/sink_attention.py.
About HiP-related environment variables of vLLM and SGlang, please refer to HiPAttentionEnvs in vLLM and SGlang attention backend implementations.

## Acknowledge

This research was supported in part by the NAVER-Intel Co-Lab. The work was conducted by KAIST and reviewed by both NAVER and Intel.

## Appendix A Theoretical Analysis

### A.1 Proof Sketch

This section provides sketches of the proofs and derivations for the theorems and lemmas mentioned in the main section of the paper. The full formal proofs are presented in the next subsection.

Using the insight obtained from our observations, we model the random variable $\delta_{\Delta}$ as follows.

###### Axiom 1 .

The attention score difference between two tokens distance $\Delta$ apart is defined as a random variable $\delta_{\Delta}$ with the following distribution.

$$ $\delta_{\Delta}\sim\mathcal{N}(0,\sigma(\Delta)^{2}),\;\Delta>0.$ $$

Where the standard deviation $\sigma(\Delta)$ is an increasing function of $\Delta$, note that both $\delta_{\Delta}$ and $\sigma(\Delta)$ are defined only when $\Delta>0$, and cases when $\Delta=0$ will be dealt separately.
We also need to define the problem setting precisely in terms of math. Without losing generality, we model the tokens as a list of indices of length $2n$. For simplicity, we simplify the problem into the case of top-1 selection. The indices of tokens range from 1 to $2n$, where indices 1 to $n$ belong to the first section, and indices $n+1$ to $2n$ belong to the second section.
The number $k$ represents the location of the representative token inside each section, and hence, indices $k$ and $n+k$ are the representative tokens of the first and second sections, respectively.
We visualize each token position in Figure 9.

Figure: Figure 9: Visualization of Problem Setting.
Refer to caption: extracted/5927425/figures/hip_theory_problem_setting.png

For the ensuing theorems, we define the following random variables and events: t is the random variable regarding the index of the maximum token, and it is assumed to be a uniform random variable. ${\mathbb{A}}$ and ${\mathbb{B}}$ are the events where the maximum token is located in the first and second section, respectively. ${\mathbb{X}}$ is the event where the first representative token is selected, due to the attention score at index $k$ being larger than the score at index $n+k$. The event ${\mathbb{Y}}$ is the exact opposite of ${\mathbb{X}}$, where the second representative token is selected.

What is the probability of a token whose distance from the maximum token is $\alpha$, having a greater attention score than a token distance $\beta$ away from the maximum token? Using the random variable $\delta_{\Delta}$ from earlier, since the tokens cannot have larger scores than the maximum token, the scores can be calculated as $s_{max}-|\delta_{\alpha}|$ and $s_{max}-|\delta_{\beta}|$, where $s_{max}$ denotes the maximum attention score. Thus, this problem is equivalent to calculating the probability $\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)$, which can be calculated as follows.

###### Lemma 1 .

$$ $\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)=4\int_{0}^{\infty}\Phi\left( \frac{\sigma(\beta)}{\sigma(\alpha)}x\right)\cdot\frac{1}{\sqrt{2\pi}}e^{- \frac{x^{2}}{2}}\,dx-1.$ $$

A detailed derivation of the above lemma can be found in Section A.2. For convenience, in the proofs to follow, we will abbreviate $\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)$ as $\phi(\sigma(\alpha),\sigma(\beta))$. Please note that $\phi(\sigma(\alpha),\sigma(\beta))$ is a decreasing function of $\alpha$, and an increasing function of $\beta$. Intuitively, this means that the probability of the token with distance $\alpha$ being larger than one with distance $\beta$ gets larger as the first token gets closer and the second token gets further away from the maximum token. This intuition agrees with the assumption of locality.

Using Lemma 1, we can calculate the probabilities for the following four cases — the case of the first or second representative token is selected, either when the maximum token lies in the first or section. The detailed derivation processes are provided in Section A.2.

###### Claim 1 .

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(k-i),\sigma(n+k-i))+1+\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+k- i))\right),$ $$

###### Claim 2 .

$$ $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(n+k-i),\sigma(k-i))+0+\sum_{i=k+1}^{n}\psi(\sigma(n+k-i),\sigma(i- k))\right),$ $$

###### Claim 3 .

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{B}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(n+i-k),\sigma(k-i))+0+\sum_{i=k+1}^{n}\psi(\sigma(n+i-k),\sigma(i- k))\right),$ $$

###### Claim 4 .

$$ $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(k-i),\sigma(n+i-k))+1+\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+i- k))\right).$ $$

From these claims, we now appraise HiP’s ability to make the correct choice. In particular, if HiP is indeed better than random token selection, then it should select the first representative token with a higher probability if the maximum token is in the first section, and vice versa. The following theorems specify the conditions in which HiP performs better than random selection. Similarly, more detailed proof can be found in the appendix section.

###### Lemma 2 .

If $k\geq n/2$, then $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})>\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A
}}).$

###### Proof (sketch).

If $k\geq n/2$, then the following three inequalities hold.

$$ $\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+k-i))>\sum_{i=1}^{k-1}\psi(\sigma(n+ k-i),\sigma(k-i)),\quad 1>0,$ $$

$$ $\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+k-i))>\sum_{i=k+1}^{n}\psi(\sigma(n+ k-i),\sigma(i-k)).$ $$

Therefore, if $k\geq n/2$, $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})>\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A
}})$.
∎

###### Lemma 3 .

If $k\leq n/2+1$, then $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})>\mathbf{P}({\mathbb{X}}\cap{\mathbb{B
}}).$

###### Proof (sketch).

If $k\leq n/2+1$, then the three inequalities hold.

$$ $\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+i-k))>\sum_{i=1}^{k-1}\psi(\sigma(n+ i-k),\sigma(k-i)),\quad 1>0,$ $$

$$ $\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+i-k))>\sum_{i=k+1}^{n}\psi(\sigma(n+ i-k),\sigma(i-k)).$ $$

Therefore, if $k\leq n/2+1$, $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})>\mathbf{P}({\mathbb{X}}\cap{\mathbb{B
}})$.
∎

The final theorem follows directly from the above two lemmas.

###### Theorem 1 .

If $k=n/2$, then $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})>\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A
}})$ and $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})>\mathbf{P}({\mathbb{X}}\cap{\mathbb{B
}})$.

This theorem tell us that if $k=n/2$, then HiP consistently outperforms random token selection in terms of making the correct choice. Thus, just by setting the representative token as the middle token, the hierarchical structure of HiP consistently outperforms random token selection! We now have the answers for the questions mentioned at the beginning of section Section 4. Through mathematical analysis, we have shown that by using the middle token as the representative token, the hierarchical approach of HiP consistently guarantees better performance than random token selection. Therefore, throughout our paper, we always use the middle token as the representative token of a section.

###### Axiom 1 .

###### Lemma 1 .

###### Claim 1 .

###### Claim 2 .

###### Claim 3 .

###### Claim 4 .

###### Lemma 2 .

###### Proof (sketch).

###### Lemma 3 .

###### Proof (sketch).

###### Theorem 1 .

### A.2 Detailed Proofs

This section provides more detailed proofs and derivations for the theorems and lemmas mentioned in the main section of the paper.

###### Lemma 1 .

$$ $\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)=4\int_{0}^{\infty}\Phi\left( \frac{\sigma(\beta)}{\sigma(\alpha)}x\right)\cdot\frac{1}{\sqrt{2\pi}}e^{- \frac{x^{2}}{2}}\,dx-1.$ $$

###### Proof.

$$ $\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)=\mathbf{P}(-|\delta_{\beta}|< \delta_{\alpha}<|\delta_{\beta}|)=\int_{-\infty}^{\infty}\int_{-|y|}^{|y|} \mathbf{P}(\delta_{\alpha}=x,\delta_{\beta}=y)dxdy$ $$

Assuming that $\delta_{\alpha}$ and $\delta_{\beta}$ are independent, we can expand the equation as follows.

$$ $\mathbf{P}(\delta_{\alpha}=x,\delta_{\beta}=y)=\mathbf{P}(\delta_{\alpha}=x) \mathbf{P}(\delta_{\beta}=y)$ $$

$$ $\therefore\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)=\int_{-\infty}^{ \infty}\int_{-|y|}^{|y|}\mathbf{P}(\delta_{\alpha}=x)\mathbf{P}(\delta_{\beta} =y)dxdy$ $$

From Axiom 1, note that $\delta_{\alpha}\sim\mathcal{N}(0,\sigma(\alpha)^{2})$ and $\delta_{\beta}\sim\mathcal{N}(0,\sigma(\beta)^{2})$.

$$ $\int_{-\infty}^{\infty}\int_{-|y|}^{|y|}\mathbf{P}(\delta_{\alpha}=x)\mathbf{P }(\delta_{\beta}=y)dxdy$ $$

$$ $=\int_{-\infty}^{\infty}\int_{-|y|}^{|y|}\frac{1}{\sqrt{2\pi\sigma(\alpha)^{2} }}e^{-\frac{x^{2}}{2\sigma(\alpha)^{2}}}\frac{1}{\sqrt{2\pi\sigma(\beta)^{2}}} e^{-\frac{y^{2}}{2\sigma(\beta)^{2}}}dxdy$ $$

$$ $=\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi\sigma(\beta)^{2}}}e^{-\frac{y^{2}} {2\sigma(\beta)^{2}}}\int_{-|y|}^{|y|}\frac{1}{\sqrt{2\pi\sigma(\alpha)^{2}}}e ^{-\frac{x^{2}}{2\sigma(\alpha)^{2}}}dxdy$ $$

$$ $=\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi\sigma(\beta)^{2}}}e^{-\frac{y^{2}} {2\sigma(\beta)^{2}}}\int_{-|y|/\sigma(\alpha)}^{|y|/\sigma(\alpha)}\frac{1}{ \sqrt{2\pi}}e^{-\frac{x^{2}}{2}}dxdy$ $$

$$ $=\int_{-\infty}^{\infty}\left(2\Phi\left(\frac{|y|}{\sigma(\alpha)}\right)-1 \right)\frac{1}{\sqrt{2\pi\sigma(\beta)^{2}}}e^{-\frac{y^{2}}{2\sigma(\beta)^{ 2}}}dy$ $$

$$ $=2\int_{-\infty}^{\infty}\Phi\left(\frac{|y|}{\sigma(\alpha)}\right)\frac{1}{ \sqrt{2\pi\sigma(\beta)^{2}}}e^{-\frac{y^{2}}{2\sigma(\beta)^{2}}}dy-1$ $$

Note that the symbol $\Phi$ represents the cumulative distribution function (CDF) of the standard normal distribution.

$$ $2\int_{-\infty}^{\infty}\Phi\left(\frac{|y|}{\sigma(\alpha)}\right)\frac{1}{ \sqrt{2\pi\sigma(\beta)^{2}}}e^{-\frac{y^{2}}{2\sigma(\beta)^{2}}}dy-1$ $$

$$ $=4\int_{0}^{\infty}\Phi\left(\frac{y}{\sigma(\alpha)}\right)\frac{1}{\sqrt{2 \pi\sigma(\beta)^{2}}}e^{-\frac{y^{2}}{2\sigma(\beta)^{2}}}dy-1$ $$

$$ $=4\int_{0}^{\infty}\Phi\left(\frac{\sigma(\beta)}{\sigma(\alpha)}y\right)\frac {1}{\sqrt{2\pi}}e^{-\frac{y^{2}}{2}}dy-1$ $$

$$ $=4\int_{0}^{\infty}\Phi\left(\frac{\sigma(\beta)}{\sigma(\alpha)}x\right)\frac {1}{\sqrt{2\pi}}e^{-\frac{x^{2}}{2}}dx-1$ $$

∎

As mentioned in the main section, for convenience, we will denote $\mathbf{P}(|\delta_{\alpha}|<|\delta_{\beta}|)$ as $\psi(\sigma(\alpha),\sigma(\beta))$. Please remember that $\psi(\sigma(\alpha),\sigma(\beta))$ is a decreasing function of $\alpha$, the first argument, and an increasing function of $\beta$, the second argument. Note that in our derivation, we assumed that $\delta_{\alpha}$ and $\delta_{\beta}$ are independent. More discussion on this assumption will be provided in the ensuing subsections.

###### Claim 1 .

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(k-i),\sigma(n+k-i))+1+\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+k- i))\right)$ $$

###### Proof.

Recall that t is a uniform random variable denoting the index of the maximum token. Since the number of tokens is $2n$, event ${\mathbb{A}}$ is actually the union of events ${\textnormal{t}}=1\dots n$. Therefore,

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})=\sum_{i=1}^{n}\mathbf{P}({\mathbb{X}} \cap{\textnormal{t}}=i)=\sum_{i=1}^{n}\mathbf{P}({\textnormal{t}}=i)\mathbf{P} ({\mathbb{X}}|{\textnormal{t}}=i)=\frac{1}{2n}\sum_{i=1}^{n}\mathbf{P}({ \mathbb{X}}|{\textnormal{t}}=i)$ $$

Using 1, $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)$ can be calculated as follows.

$$ $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=\begin{cases}\psi(\sigma(k-i), \sigma(n+k-i))&\textbf{if $i<k$}\\ 1&\textbf{if $i=k$}\\ \psi(\sigma(i-k),\sigma(n+k-i))&\textbf{if $i>k$}\end{cases}$ $$

A detailed explanation for the above derivation is as follows. When the maximum token index is smaller than the first representative token (i.e. $i<k$), the distances between the maximum token and the two representative tokens are $k-i$ and $n+k-i$. Thus, using 1, $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=\psi(\sigma(k-i),\sigma(n+k-i))$. Similarly, $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=\psi(\sigma(i-k),\sigma(n+k-i))$ when the maximum token index is larger than the first representative token (i.e. $i>k$). When the maximum token is the first representative token (i.e. $i=k$), we cannot use 1 as $\sigma(\Delta)$ is defined only when $\Delta>0$. However, if the maximum token is the first representative token, then it will always be larger than the second representative token - hence, $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=1$.

Using the above derivation, we can rewrite the original summation as follows.

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})=\frac{1}{2n}\sum_{i=1}^{n}\mathbf{P}( {\mathbb{X}}|{\textnormal{t}}=i)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+k-i))+1+\sum_{i=k +1}^{n}\psi(\sigma(i-k),\sigma(n+k-i))\right)$ $$

∎

###### Claim 2 .

$$ $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(n+k-i),\sigma(k-i))+0+\sum_{i=k+1}^{n}\psi(\sigma(n+k-i),\sigma(i- k))\right)$ $$

###### Proof.

The derivation is almost the same as 1, except that the second representative token needs to have a larger attention score than the first one. Therefore, the arguments in the $\psi$ function are switched for cases $i<k$ and $i>k$. When $i=k$, the maximum token is the first representative token, so $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)$ is zero. Therefore,

$$ $\mathbf{P}({\mathbb{Y}}|{\textnormal{t}}=i)=\begin{cases}\psi(\sigma(n+k-i), \sigma(k-i))&\textbf{if $i<k$}\\ 0&\textbf{if $i=k$}\\ \psi(\sigma(n+k-i),\sigma(i-k))&\textbf{if $i>k$}\end{cases}$ $$

$$ $\therefore\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A}})=\frac{1}{2n}\sum_{i=1}^{n} \mathbf{P}({\mathbb{Y}}|{\textnormal{t}}=i)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(n+k-i),\sigma(k-i))+0+\sum_{i=k +1}^{n}\psi(\sigma(n+k-i),\sigma(i-k))\right)$ $$

∎

###### Claim 3 .

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{B}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(n+i-k),\sigma(k-i))+0+\sum_{i=k+1}^{n}\psi(\sigma(n+i-k),\sigma(i- k))\right)$ $$

###### Proof.

Recall that t is a uniform random variable denoting the index of the maximum token. Since the number of tokens is $2n$, event ${\mathbb{B}}$ is actually the union of events ${\textnormal{t}}=n+1\dots 2n$. Therefore,

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{B}})=\sum_{i=n+1}^{2n}\mathbf{P}({\mathbb{ X}}\cap{\textnormal{t}}=i)=\sum_{i=n+1}^{2n}\mathbf{P}({\textnormal{t}}=i) \mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=\frac{1}{2n}\sum_{i=n+1}^{2n} \mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)$ $$

Similarly to 1, using 1, $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)$ is derived as follows.

$$ $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=\begin{cases}\psi(\sigma(i-k), \sigma(n+k-i))&\textbf{if $i<n+k$}\\ 0&\textbf{if $i=n+k$}\\ \psi(\sigma(i-k),\sigma(i-n-k))&\textbf{if $i>n+k$}\end{cases}$ $$

$$ $\therefore\mathbf{P}({\mathbb{X}}\cap{\mathbb{B}})=\frac{1}{2n}\sum_{i=n+1}^{2 n}\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=n+1}^{n+k-1}\psi(\sigma(i-k),\sigma(n+k-i))+0+\sum_ {i=n+k+1}^{2n}\psi(\sigma(i-k),\sigma(i-n-k))\right)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(n+i-k),\sigma(k-i))+0+\sum_{i=k +1}^{n}\psi(\sigma(n+i-k),\sigma(i-k))\right)$ $$

∎

###### Claim 4 .

$$ $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(k-i),\sigma(n+i-k))+1+\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+i- k))\right)$ $$

###### Proof.

The derivation is similar to 3, except that the second representative token needs to have a larger attention score than the first one. Therefore, the parameters of the $\psi$ function are switched compared to 3. Also, when $i=n+k$, then the second representative token is the maximum token. Therefore, $\mathbf{P}({\mathbb{Y}}|{\textnormal{t}}=i)$ is derived as follows.

$$ $\mathbf{P}({\mathbb{X}}|{\textnormal{t}}=i)=\begin{cases}\psi(\sigma(n+k-i), \sigma(i-k))&\textbf{if $i<n+k$}\\ 1&\textbf{if $i=n+k$}\\ \psi(\sigma(i-n-k),\sigma(i-k))&\textbf{if $i>n+k$}\end{cases}$ $$

$$ $\therefore\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})=\frac{1}{2n}\sum_{i=n+1}^{2 n}\mathbf{P}({\mathbb{Y}}|{\textnormal{t}}=i)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=n+1}^{n+k-1}\psi(\sigma(n+k-i),\sigma(i-k))+1+\sum_ {i=n+k+1}^{2n}\psi(\sigma(i-n-k),\sigma(i-k))\right)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+i-k))+1+\sum_{i=k +1}^{n}\psi(\sigma(i-k),\sigma(n+i-k))\right)$ $$

∎

###### Lemma 2 .

If $k\geq n/2$, then $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})>\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A
}})$

###### Proof.

From 1 and 2,

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(k-i),\sigma(n+k-i))+1+\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+k- i))\right)$ $$

$$ $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(n+k-i),\sigma(k-i))+0+\sum_{i=k+1}^{n}\psi(\sigma(n+k-i),\sigma(i- k))\right)$ $$

The following inequalities trivially hold.

$$ $\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+k-i))>\sum_{i=1}^{k-1}\psi(\sigma(n+ k-i),\sigma(k-i))$ $$

$$ $1>0$ $$

For the remaining two terms, the direction of the inequality depends on the relationship between $\sigma(i-k)$ and $\sigma(n+k-i)$. In order for $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})>\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A
}})$, we need to have $\sigma(i-k)\leq\sigma(n+k-i)$, i.e. $i-k\leq n+k-i$ for all $i=k+1\cdots n$.

$$ $i-k\leq n+k-i\quad\forall i=k+1\cdots n$ $$

$$ $\therefore 2k\geq 2i-n,\quad\forall i=k+1\cdots n$ $$

$$ $\therefore k\geq i-\frac{n}{2}\quad\forall i=k+1\cdots n$ $$

$$ $\therefore k\geq\frac{n}{2}$ $$

Therefore, if $k\geq n/2$, then the inequality $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})>\mathbf{P}({\mathbb{Y}}\cap{\mathbb{A
}})$ holds.
∎

###### Lemma 3 .

If $k\leq n/2+1$, then $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})>\mathbf{P}({\mathbb{X}}\cap{\mathbb{B
}})$

###### Proof.

From 3 and 4,

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{B}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(n+i-k),\sigma(k-i))+0+\sum_{i=k+1}^{n}\psi(\sigma(n+i-k),\sigma(i- k))\right)$ $$

$$ $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})=\frac{1}{2n}\left(\sum_{i=1}^{k-1} \psi(\sigma(k-i),\sigma(n+i-k))+1+\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+i- k))\right)$ $$

The following inequalities trivially hold.

$$ $\sum_{i=k+1}^{n}\psi(\sigma(i-k),\sigma(n+i-k))>\sum_{i=k+1}^{n}\psi(\sigma(n+ i-k),\sigma(i-k))$ $$

$$ $1>0$ $$

For the remaining two terms, the direction of the inequality depends on the relationship between $\sigma(n+i-k)$ and $\sigma(k-i)$. In order for $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})>\mathbf{P}({\mathbb{X}}\cap{\mathbb{B
}})$, we need to have $\sigma(k-i)\leq\sigma(n+i-k)$, i.e. $k-i\leq n+i-k$ for all $i=1\cdots k-1$.

$$ $k-i\leq n+i-k\quad\forall i=1\cdots k-1$ $$

$$ $\therefore 2k\leq 2i+n,\quad\forall i=1\cdots k-1$ $$

$$ $\therefore k\leq i+\frac{n}{2}\quad\forall i=1\cdots k-1$ $$

$$ $\therefore k\leq\frac{n}{2}+1$ $$

Therefore, if $k\leq n/2+1$, then the inequality $\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B}})>\mathbf{P}({\mathbb{X}}\cap{\mathbb{B
}})$ holds.
∎

###### Theorem 2 .

If $\sigma^{\prime\prime}(k)\sigma(k)<\sigma^{\prime}(k)^{2}$, then $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})+\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B
}})$ is maximized when $k=n/2$.

###### Proof.

From 1 and 4,

$$ $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})+\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B }})$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+k-i))+1+\sum_{i=k +1}^{n}\psi(\sigma(i-k),\sigma(n+k-i))\right)$ $$

$$ $+\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+i-k))+1+\sum_{i=k +1}^{n}\psi(\sigma(i-k),\sigma(n+i-k))\right)$ $$

$$ $=\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+k-i))+1+\sum_{i=k +1}^{n}\psi(\sigma(i-k),\sigma(n+i-k))\right)$ $$

$$ $+\frac{1}{2n}\left(\sum_{i=1}^{k-1}\psi(\sigma(k-i),\sigma(n+i-k))+1+\sum_{i=k +1}^{n}\psi(\sigma(i-k),\sigma(n+k-i))\right)$ $$

For simplicity, we refer to the first term as $T1$, and the second term as $T2$. We now investigate which value of $k$ maximizes $T1$ and $T2$.

For $T2$, suppose the value of $k$ changes from $k$ to $k+1$.

$$ $T2_{k+1}-T2_{k}=\psi(\sigma(k),\sigma(n-k))-\psi(\sigma(n-k),\sigma(k))$ $$

It can be easily seen that $\psi(\sigma(k),\sigma(n-k))$ is a decreasing function of $k$, and $\psi(\sigma(n-k),\sigma(k))$ is an increasing function of $k$. Therefore, $T2_{k+1}-T2_{k}$ is a decreasing function of $k$, and its value goes from a positive value when $k=1$, and a negative value when $k=n-1$. Thus, $T2$ is maximized when $T2_{k+1}-T2_{k}=\psi(\sigma(k),\sigma(n-k))-\psi(\sigma(n-k),\sigma(k))=0$.
The value of $k$ where $\psi(\sigma(k),\sigma(n-k))-\psi(\sigma(n-k),\sigma(k))=0$ is computed as follows.

$$ $k=n-k,\quad\therefore k=\frac{n}{2}$ $$

Therefore, $T2$ is maximized when $k=\frac{n}{2}$.

For $T1$, suppose the value of $k$ changes from $k$ to $k+1$.

$$ $T1_{k+1}-T1_{k}=\psi(\sigma(k),\sigma(n+k))-\psi(\sigma(n-k),\sigma(2n-k))$ $$

Unlike $T2$, we cannot easily determine whether $\psi(\sigma(k),\sigma(n+k))$ or $\psi(\sigma(n-k),\sigma(2n-k))$ is an increasing or decreasing function of $k$. Therefore, we turn to the definition of $\psi(\sigma(\alpha),\sigma(\beta))$. From 1,

$$ $\psi(\sigma(\alpha),\sigma(\beta))=4\int_{0}^{\infty}\Phi\left(\frac{\sigma( \beta)}{\sigma(\alpha)}x\right)\cdot\frac{1}{\sqrt{2\pi}}e^{-\frac{x^{2}}{2}} \,dx-1$ $$

Thus, the positivity of $T1_{k+1}-T1_{k}$ depends on the characteristics of the function $\sigma(n+k)/\sigma(k)$. If $\sigma(n+k)/\sigma(k)$ is a decreasing function of $k$, then $\psi(\sigma(k),\sigma(n+k))$ becomes a decreasing function of $k$, and inversely, $\psi(\sigma(n-k),\sigma(2n-k))$ becomes an increasing function of $k$. In this case, similarly to $T2$, we can show that $T1$ is maximized when $k=n/2$. In order to find the condition where $\sigma(n+k)/\sigma(k)$ becomes a decreasing function of $k$, we take its derivative in terms of $k$.

$$ $\frac{d}{dk}\frac{\sigma(n+k)}{\sigma(k)}=\frac{\sigma^{\prime}(n+k)\sigma(k)- \sigma(n+k)\sigma^{\prime}(k)}{\sigma(k)^{2}}<0$ $$

$$ $\therefore\sigma^{\prime}(n+k)\sigma(k)<\sigma(n+k)\sigma^{\prime}(k),\quad \therefore\frac{\sigma^{\prime}(n+k)}{\sigma(n+k)}<\frac{\sigma^{\prime}(k)}{ \sigma(k)}$ $$

Thus, we see that if $\sigma^{\prime}(k)/\sigma(k)$ is a decreasing function of $k$, then $\sigma(n+k)/\sigma(k)$ also becomes a decreasing function of $k$. This condition is equivalent to the condition $\sigma^{\prime\prime}(k)\sigma(k)<\sigma^{\prime}(k)^{2}$. The derivation is as follows.

$$ $\frac{d}{dk}\frac{\sigma^{\prime}(k)}{\sigma(k)}<0,\quad\therefore\frac{\sigma ^{\prime\prime}(k)\sigma(k)-\sigma^{\prime}(k)^{2}}{\sigma(k)^{2}}<0$ $$

$$ $\therefore\sigma^{\prime\prime}(k)\sigma(k)<\sigma^{\prime}(k)^{2}$ $$

To summarize, if $\sigma^{\prime\prime}(k)\sigma(k)<\sigma^{\prime}(k)^{2}$, then $\psi(\sigma(k),\sigma(n+k))$ becomes a decreasing function of $k$, and $\psi(\sigma(n-k),\sigma(2n-k))$ becomes an increasing function of $k$. Therefore, $T1_{k+1}-T1_{k}$ becomes a decreasing function of $k$, and its value goes from positive to negative as $k$ goes from $1$ to $n-1$. The crossover point is where $k=n-k$, and $n+k=2n-k$. Coincidentally, this is when $k=n/2$. Therefore, if $\sigma^{\prime\prime}(k)\sigma(k)<\sigma^{\prime}(k)^{2}$ the value of $k$ which maximizes $T1$ is $k=n/2$.

To summarize, if $\sigma^{\prime\prime}(k)\sigma(k)<\sigma^{\prime}(k)^{2}$, then $k=n/2$ maximizes both $T1$ and $T2$. This concludes the proof.
∎

###### Lemma 1 .

###### Proof.

###### Claim 1 .

###### Proof.

###### Claim 2 .

###### Proof.

###### Claim 3 .

###### Proof.

###### Claim 4 .

###### Proof.

###### Lemma 2 .

###### Proof.

###### Lemma 3 .

###### Proof.

###### Theorem 2 .

###### Proof.

### A.3 Revisiting Assumptions in Theoretical Analysis

In Axiom 1 and 1, we make two important assumptions: that $\delta_{\Delta}$ follows a normal distribution $\mathcal{N}(0,\sigma(\Delta)^{2})$, and that $\delta_{\alpha}$ and $\delta_{\beta}$ are independent of each other. However, is this justifiable? In this section, we provide an analysis and explanation of each of these assumptions.

#### A.3.1 The Distribution of δ Δ subscript 𝛿 Δ \delta_{\Delta} italic_δ start_POSTSUBSCRIPT roman_Δ end_POSTSUBSCRIPT

First, we justify the assumption $\delta_{\Delta}\sim\mathcal{N}(0,\sigma(\Delta)^{2})$ by validating three parts - that $\delta_{\Delta}$ does follow a normal distribution, that $\sigma(\Delta)$ is an increasing function of $\Delta$, and that the mean can be approximated as zero.

Figure 10 shows some examples of the distribution of $\delta_{\Delta}$. As can be seen in the figure, $\delta_{\Delta}$ clearly follows a normal distribution. In order to prove statistical evidence that $\delta_{\Delta}$ indeed follows a normal distribution, we compute the KL divergence between $\delta_{\Delta}$ and the normal distribution fitted onto $\delta_{\Delta}$. We experiment on all layers for various $\Delta$ values and show some of the results in Figure 10 of Section A.3.3. As can be seen in Figure 10, the KL divergence values are extremely small and close to zero, which validates that $\delta_{\Delta}$ follows the normal distribution.

Figure: Figure 10: Distribution of $\delta_{\Delta}$. The above figures show the distributions of $\delta_{\Delta}$ for $\Delta$ values 200, 400, 600, and 800, respectively. The values were sampled from the $9^{\textbf{th}}$ attention head of the first layer in the Llama3.1 8B model. The Wikitext2 dataset was used as input.
[Uncaptioned image]: x14.png

Next, we show that $\sigma(\Delta)$ is an increasing function of $\Delta$. We observe an interesting phenomenon, where the overall demeanor with which $\sigma(\Delta)$ increases resembles a logarithmic function, as can be seen in Figure 11. Although there may be some amount of minor deviations, the standard deviation $\sigma(\Delta)$ of $\delta_{\Delta}$ has consistently shown to resemble a logarithmic function for almost all layers and attention heads. In order to prove this claim, in Section A.3.3, we show the results for fitting $\sigma(\Delta)$ as a logarithmic function for each attention head and layer. As can be seen in Figure 16, except for a few outliers (especially in the early layers), the results converge within NRMSE (Normalized Root Mean Squared Error) of 0.1, which suggests a very good fit. This shows that $\sigma(\Delta)$ resembles a logarithmic function and, therefore, can be seen as an increasing function.

Figure: Figure 11: Plots of $\sigma(\Delta$) and their Normalized Root Mean Squared Error. The above figures show example plots of $\sigma(\Delta)$, and the NRMSE values for fitting as a logarithmic function. For the above plot, various attention heads in the 16th layer of the Llama3.1 8B model were used. For the input, we used the Wikitext2 dataset.
Refer to caption: x18.png

The above observation actually opens up the room for discussion about the optimality of HiP. In 2, $\mathbf{P}({\mathbb{X}}\cap{\mathbb{A}})+\mathbf{P}({\mathbb{Y}}\cap{\mathbb{B
}})$ is the probability of HiP making the right choice, regardless of the location of the maximum token. Therefore, 2 proves that if $\sigma^{\prime\prime}(\Delta)\sigma(\Delta)<\sigma^{\prime}(\Delta)^{2}$, then not only does HiP perform better than random token selection, but it is also in fact optimal. If $\sigma(\Delta)$ resembles a logarithmic function like our observation, then $\sigma^{\prime\prime}(\Delta)<0$, and therefore the inequality $\sigma^{\prime\prime}(\Delta)\sigma(\Delta)<0<=\sigma^{\prime}(\Delta)^{2}$ holds. Thus, on top of HiP guaranteeing better performance than random token selection, there also is the possibility of HiP being, in fact, optimal.

However, we are very careful with making this claim because we do not yet have a logical explanation about why $\sigma(\Delta)$ displays a logarithmic increase. In the main paper, based on the assumption of locality, we only claim that $\sigma(\Delta)$ is an increasing function of $\Delta$. However, the assumption of locality does not cover the exact detailed behavior of $\sigma(\Delta)$. There is always the possibility that the logarithmic pattern we see in $\sigma(\Delta)$ may be the result of some model-specific traits, the overall training corpus, or some other reasons that we are not aware of. Therefore, although we find this observation interesting, we only leave it as a discussion topic in the appendix section. We plan to analyze the detailed characteristics of the $\sigma(\Delta)$ function in future work.

Finally, we discuss approximating the mean to zero. Unlike our assumption, the mean of which normal distribution $\delta_{\Delta}$ follows does not stay as zero. As can be seen in the following Figure 12, the mean of $\delta_{\Delta}$ consistently begins from zero when $\Delta=0$, but it moves away from zero as $\Delta$ increases. The manner in which the mean gets further away from zero is not consistent. In some cases, the mean decreases negatively away from zero, and in some cases, it is the opposite. The exact behavior differs between different layers, or attention heads or the input dataset, so it seems that we cannot deterministically express the mean in terms of math.

Figure: Figure 12: Plots of the mean of $\delta_{\Delta}$. The above figures show the plots of the mean of $\delta_{\Delta}$, as a function of $\Delta$. For the above plots, various attention heads in the 17th layer of the Llama3.1 8B model was used. For the input, we used the LongBench dataset.
Refer to caption: x26.png

However, this does not undermine the integrity of our mathematical analysis. Note that in our proof, we use the absolute attention score difference $|\delta_{\Delta}|$. The main logic of our proof is that since attention scores display locality, the representative token near the maximum token is likely to have a larger score than the other representative token and, hence, is more likely to be chosen by HiP’s algorithm. This does not change, even if the mean of $\delta_{\Delta}$ displays the aforementioned nonzero characteristic. Since $\delta_{\Delta}$ moves away from zero as $\Delta$ increases, $|\delta_{\Delta}|$ is an increasing function of $\Delta$. This makes it even more likely that the representative token near the maximum token will have a larger score than the other representative token compared to when the mean is zero. For this reason, $\psi(\sigma(\alpha),\sigma(\beta))$ is still a decreasing function of $\alpha$ and an increasing function of $\beta$, even if the mean exhibits nonzero characteristics. Thus, our mathematical analysis remains valid.

We approximate the mean as zero mainly for three reasons. First, even though the mean gradually moves away from zero, regardless, it is still close to zero and much smaller than the standard deviation of $\delta_{\Delta}$. Secondly, the behavior of the mean is not consistent, which makes it very difficult to express it in terms of math. Finally, the approximation does not compromise the integrity of the mathematical analysis while making the overall derivation much simpler and easier to understand. These are the reasons why we approximate the mean as zero in this paper.

Figure: Figure 13: Correlation Coefficient Between $\delta_{10}$ and $\delta_{100}$. The above figures show the scatter plots of the joint distribution of $\delta_{10}$ and $\delta_{100}$. The nonzero correlation coefficient suggests that there exists some amount of dependency between $\delta_{10}$ and $\delta_{100}$. The $16^{\textbf{th}}$ layer of the Llama3.1 8B model was used for sampling the values. We use Wikitext2 dataset for the input.
Refer to caption: x34.png

#### A.3.2 The Independence between δ α subscript 𝛿 𝛼 \delta_{\alpha} italic_δ start_POSTSUBSCRIPT italic_α end_POSTSUBSCRIPT and δ β subscript 𝛿 𝛽 \delta_{\beta} italic_δ start_POSTSUBSCRIPT italic_β end_POSTSUBSCRIPT

Now, we talk about the independence between $\delta_{\alpha}$ and $\delta_{\beta}$. In 1, for simplicity, we have assumed that $\delta_{\alpha}$ and $\delta_{\beta}$ is independent of each other. However, this is not necessarily true. As can be seen in Figure 13, the correlation coefficient between $\delta_{\alpha}$ and $\delta_{\beta}$ is nonzero. From empirical analysis, we observe that the correlation coefficient between $\delta_{\alpha}$ and $\delta_{\beta}$ is actually dependent on $|\alpha-\beta|$ - the distance between the two tokens. As can be seen in Figure 14, the correlation coefficient decreases from around 0.7 when the distance is short to around 0.4 when the distance is long.

Figure: Figure 14: Correlation Coefficient. The above figures plot the relationship of the correlation coefficient between $\delta_{\alpha}$ and $\delta_{\beta}$, and the index difference $|\alpha-\beta|$ for different attention heads. In order to obtain a more clearer plot, the value of $\alpha$ was fixed to 10. As can be seen in the figures, the correlation coefficient consistently decreases from 0.7 to around 0.4, as the distance between $\alpha$ and $\beta$ increases. The values were sampled from layer 16 of the Llama3.1 8B model, using the Wikitext2 dataset as input.
Refer to caption: x35.png

This suggests that $\delta_{\alpha}$ and $\delta_{\beta}$ have a strong positive correlation when $\alpha$ and $\beta$ are close to each other, and a weak positive correlation when they are far away. In other words, nearby tokens have a higher probability of having similar attention scores. This is exactly equivalent to the assumption of attention locality that we discussed in the main section of this paper, and this empirical data is the strongest evidence we have that supports this assumption. To summarize, due to attention locality, $\delta_{\Delta}$ is not independent, and nearby tokens are less independent than faraway tokens.

If so, then does the dependency between $\delta_{\alpha}$ and $\delta_{\beta}$ disprove our analysis? In order to analyze this issue, we compare $\mathbf{P}(\delta_{\alpha}=x,\delta_{\beta}=y)$ when $\delta_{\Delta}$ are independent and dependent. When they are independent, then $\mathbf{P}(\delta_{\alpha}=x,\delta_{\beta}=y)$ is expressed as follows.

$$ $\mathbf{P}(\delta_{\alpha}=x,\delta_{\beta}=y)=\mathbf{P}(\delta_{\alpha}=x) \mathbf{P}(\delta_{\beta}=y)=\frac{1}{2\pi\sigma(\alpha)\sigma(\beta)}\exp{- \left(\frac{x^{2}}{2\sigma(\alpha)^{2}}+\frac{y^{2}}{2\sigma(\beta)^{2}}\right )}.$ $$

When $\delta_{\alpha}$ and $\delta_{\beta}$ are dependent with the correlation coefficient being $\rho$, the probability can be expressed using the multivariate normal distribution as follows.

$$ $\displaystyle\mathbf{P}($ $\displaystyle\delta_{\alpha}=x,\delta_{\beta}=y)$ $\displaystyle=\frac{1}{2\pi\sigma(\alpha)\sigma(\beta)\sqrt{1-\rho^{2}}}\exp{ \left(-\frac{1}{2[1-\rho^{2}]}\left[\frac{x^{2}}{2\sigma(\alpha)^{2}}+\frac{y^ {2}}{2\sigma(\beta)^{2}}-2\rho\frac{xy}{\sigma(\alpha)\sigma(\beta)}\right] \right)}.$ $$

We argue that the critical difference between these two equations is the nonlinear term $1-\rho^{2}$. When the tokens are far apart, i.e., $\rho\simeq 0.4$, then the $1-\rho^{2}=0.85$, which is relatively close to 1. Therefore, we can largely approximate the dependent $\mathbf{P}(\delta_{\alpha}=x,\delta_{\beta}=y)$ equation with its independent version without much error. However, when the tokens are near to each other, i.e., $\rho\simeq 0.7$, then $1-\rho^{2}=0.51$, which is significantly different from 1. In this case, we can no longer justify the approximation of independence.

This means that if the representative tokens are too close to each other, then our mathematical analysis, which proves that HiP performs better than random token selection, might no longer hold. Interestingly, we have actually observed experimental results that support this notion. In the last few iterations of HiP, we have noticed that HiP’s binary search algorithm does not perform well, unlike previous iterations. The main reason behind this phenomenon is that in the last few iterations, the sections become too short and too close to each other. Since they are all close to each other, due to attention locality, there no longer exists a significant attention score difference between each section. Hence, HiP fails to successfully identify the sections with the largest attention scores, and deteriorates to almost random token selection level performance.

In order to resolve this issue, we tried to develop a simple patch that acts after the top-$k$ selection process. Recall that in order to foster the efficient usage of matrix multiplier units, HiP was developed with block granularity. Previously, after the hierarchical top-$k$ selection process, only the selected blocks are used for creating the sparse attention mask. Instead, we grabbed entire vicinity of tokens around the selected blocks, and used those for the sparse attention mask. The key idea was that due to attention locality, the tokens around the selected blocks would have the highest attention scores in the entire sequence. If HiP cannot choose among those tokens, the easiest workaround would be to use all of them. Therefore, by simply using the entire range around the selected blocks, we thought that we would be able to save the most important tokens from being discarded. During development, we used range sizes of 16 or 32.

The effects of this experimental revision definitely improved the overall performance. As can be seen in table Table 7, the relative performance compared to FlashAttention2 was enhanced by 5%. However, as this patch requires the algorithm to access much more key tokens than before, it is significantly detrimental to the overall latency. Due to this reason, we did not include this experimental patch in the final version of HiP. Yet, we believe that with further research, we may be able to find a method that can exploit the strengths of this approach while minimizing the additional latency. Thus, we reserve this topic as a future work.

**Table 7: $b_{k}$ Patch Results. In order to resolve the dependency issue of $\delta_{\Delta}$, we test an experimental patch where the $b_{k}$ values are modified for the last few iterations. Results show that the patch is beneficial for overall performance yet comes at the cost of latency. The Relative Performance is measured compared to FlashAttention2. The unit of the prefill latency is milliseconds (ms). Also, note that we use 128k context length for experiments.**
|  | NQA | Qasper | HQA | 2WM | GR | MN | Rel. Perf | Prefill<br>Latency<br>$T$=128k |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Flash Attention | 29.53 | 44.27 | 54.61 | 39.49 | 34.99 | 27.39 | 100.0% | 855.2 |
| HiP $k=512$ | 21.44 | 41.73 | 50.36 | 45.17 | 30.09 | 26.01 | 92.40% | 105.7 |
| Range Size 16 | 25.46 | 44.12 | 52.87 | 42.30 | 33.40 | 26.89 | 97.51% | 181.4 |
| Range Size 32 | 26.82 | 44.30 | 52.85 | 41.23 | 33.71 | 27.18 | 97.88% | 227.2 |

To summarize, when the representative tokens are far apart, the dependency between $\delta_{\Delta}$ is weak, so we can approximate them as independent. When the representative tokens are nearby, (i.e. last few iterations of HiP), the dependency of $\delta_{\Delta}$ can no longer be ignored, and thus HiP’s binary search like algorithm no longer suffices. We acknowledge this issue, and have tried to develop an experimental method that solves the problem. We find that while the method definitely helps performance, it comes at a large cost of latency. We plan on tackling this problem in future work.

#### A.3.3 Empirical Data Analysis

Figure: Figure 15: KL Divergence. The above figures express the KL Divergence between $\delta_{\Delta}$ and its fitted normal distributions of various layers in the Llama3.1 8B model. The $y$ axis represents attention heads, and the $x$ axis represents $\Delta$, ranging from 50 to 950. We use the Wikitext2 dataset as input for the model. As can be seen in the figures, almost all of the KL divergence values are extremely close to zero. Interestingly, the first layer seems to display larger KL divergence values, but even those values are less than 0.1. This justifies our mathematical modeling of $\delta_{\Delta}$ as a normal distribution.
Refer to caption: x36.png

Figure: Figure 16: NRMSE of Fitting $\sigma(\Delta)$ as a Logarithmic Function. The above figures show the NRMSE (Normalized Root Mean Squared Error) result of fitting the $\sigma(\Delta)$ function as a logarithmic function. For fitting the function, the general formula $y=a\log(x+b)+c$ was used. As can be seen in the above figures, except for a couple of outliers, especially in the earlier layers, the NRMSE results lie within 0.1, which signifies a good fit. In order to prove that $\sigma(\Delta)$ exhibits logarithmic increase regardless of input, we demonstrate on various datasets. The model used was Llama3.1 8B.
Refer to caption: x37.png

## Appendix B Detailed Methodology Descriptions

### B.1 Hierarchical Sparse Attention Mask Estimation Algorithm

Figure: Algorithm 1 Hierarchical Sparse Attention Mask Estimation

In Algorithm 1, we describe the complete algorithm used for mask estimation. The peak amount of memory used during the mask estimation process is in $O(T)$, since at each iteration, only the immediately previous iteration’s node indices are needed, and the rest can be discarded.

### B.2 HiP Decoding Algorithm

Figure: Algorithm 2 HiP Decoding Algorithm

In Algorithm 2, we show a rough sketch of the decoding process with HiP. In particular, note the function of the mask estimation period $r_{m}$ and the number of initial dense layers $l_{d}$, as well as the time and space complexities of each component.

### B.3 Additional Optimization Techniques

#### B.3.1 Top-r Approximation

In order to reduce the cost of the mask estimator even further, we take inspiration from SparQ Attention (Ribar et al., ), where global memory (HBM or GDDR) transfer is reduced by selectively fetching only the most relevant components of the key vectors.
Specifically, when computing the inequality condition in Equation 4, instead of fetching all $d$ components of the key vectors, we only fetch $r\ll d$ most prominent components estimated by the query vector $\bm{q}$.
Thus, we compute the following as an approximation:

$$ $\displaystyle\bm{q}^{\top}\bm{k}_{t}$ $\displaystyle\approx\sum_{l=1}^{r}\bm{q}_{p_{l}}\cdot\bm{k}_{p_{l}}$ (6) $$

where $\{p_{1},p_{2},\dots,p_{r}\}=\mathrm{argtop_}r(|\bm{q}|)$.
By using the top-$r$ approximation, the total number of global memory accesses in the mask estimation stage can be drastically reduced.
However, we disable this approximation by default.

#### B.3.2 Block Sparse Flash Attention

We utilize the Flash Attention (Dao et al., ) mechanism to reduce the latency of sparse attention and use a small size sliding window to reduce performance degradation on the side of the sparse attention kernel.
Following the receipt of StreamingLLM (Xiao et al., ), local sliding window and global sink attention are also added during block sparse flash attention operation.

### B.4 Training Downstream Tasks with HiP

In this section, we describe the HiP attention training strategy for downstream tasks.
We discovered that direct fine-tuning after applying HiP could not achieve the performance of the fine-tuned vanilla attention.
Empirically, HiP’s highly sparse attention matrices show excellent performance approximation during test time but not in train gradients.
Since our method heavily prunes the attention matrix, the gradient cannot flow through dense attention probabilities.
This incomplete and unstable gradient of the attention matrix leads to significant training performance degradation because HiP forces the model to have attention patterns similar to those of the pretrained model rather than adopting them for the downstream task.

However, we could achieve the same performance as vanilla by using the following two-step training strategy: (1) fine-tuning with vanilla first and (2) further fintuning after applying HiP (healing).
First, we train the pretrained model with vanilla attention to the downstream task as usual.
Then, we load the finetuned weight, apply HiP, and further finetuning with the downstream task dataset with just a few optimizer steps.
We call this a healing process because we only finetune a few steps from the finetuned weight.
For training details about each experiment, we describe hyperparameter and optimization setups in Appendix D.

## Appendix C Additional Experimental Results

### C.1 Large Multimodal Model with HiP

Figure: Table 8: LMMs-Eval on LLaVA-1.6-13B. We apply the efficient attention mechanism in only LLM backbone of LMM.

Since large multi-modal models (LMM) (Liu et al., ; ) leverage pre-trained LLMs as a backbone for their NLU ability, without changes, except for the tokenizer, we also evaluated our HiP on top of LLaVA-1.6-13B (Liu et al., ), a large multi-modal model, using LMMs-eval (Li* et al., ), which provides extensive benchmarks for large multimodal model suites.
As we show in Table 8, our method scores 95.9% relative scores, which is similar to the performance recovery ratio of HiP on NLU tasks.

### C.2 Massive Multitask Language Understanding (MMLU)

Figure: Figure 17: MMLU scores on Llama3.1-8B.

Next, we evaluate HiP on the MMLU benchmark (Hendrycks et al., ) to show that our method does not negatively affect the NLU ability of the pretrained model.
The results show that our HiP preserves the NLU performance of the original model.
All tested methods are able to recover original MMLU scores without significant loss here.
This is probably due to the nature of the MMLU task: the answer is only dependent on the most recent span of tokens rather than the entire prompt (which contains few-shot examples in the beginning).

### C.3 Comparison with Reformer and SEA

**Table 9: Comparison of WikiText2 perplexity against Reformer and SEA. For this comparison, we use the Llama2-7b model. The experimental setting for HiP is the same as the main experiment. For Reformer, we use 512 for the bucket size and replace the attention module in all layers except the first three for a fair comparison with HiP. For SEA, we use 512 for the attention predictor length and $k$ (the top $k$ sampling factor) as 64. We fine-tune both Reformer and SEA models using LoRA with rank = 128, the same as HiP heal, until convergence.**
| Method | Perplexity |
| --- | --- |
| Vanilla PyTorch | 5.5933 |
| Reformer ft (Kitaev et al., ) | 45.5130 (+39.92) |
| SEA ft (Lee et al., ) | 23.1964 (+17.60) |
| HiP (k=512) pp | 5.7938 (+0.20) |
| HiP (k=512) heal | 5.6872 (+0.09) |

We compare the performance of HiP against Reformer (Kitaev et al., ) and SEA (Lee et al., ) using the Llama2-7b model and show the results in Table 9. Even though HiP requires no fine-tuning, unlike Reformer and SEA, which need fine-tuning, our HiP attention is far superior in language modeling performance compared to these two baselines.

For a fair comparison, we fine-tune Reformer and SEA using LoRA (Low-rank adapters), which have the same rank as the healed version of HiP. Due to this, the Reformer and SEA’s performance converges to a much-degraded value compared to the values reported in their respective original papers. We conclude that both methods need much modification to the original weights in order to perform well, whereas since HiP performs well even without any modification to the weights whatsoever, a small amount of LoRA training can even close this small gap.

### C.4 Context Extention with Self-Extend

Since our method has a considerable advantage in long-context decoding, we need the pre-trained long-context model.
Unfortunately, however, not all pretrained transformer models support long contexts.
Therefore, many previous studies (Peng et al., ; Jin et al., ) try to extend maximum position embeddings of the trained model to extend the context size of LLM.
We adopt the SelfExtend (Jin et al., ) method into our method because it is also a training-free context extension method.
We picked Gemma2 (Team, ) to target LLM and extend the context model because the model is a hybrid of sliding windows and dense attention.
Therefore, it will have the advantage of a long context model with HiP by saving the KV cache of sliding window layers.
The Gemma2 repeats the attention layer by repeating the stack of different attention blocks: sliding window and dense attention.
To evaluate the effectiveness of the combination of HiP and SelfExtend, we apply them to attention layers.

**Table 10: Self-Extend Result with HiP. We apply Self-Extend with HiP $k$=256 on Gemma2-2B-it. We extend the maximum context length of Gemma2 from 8k up to 128k tokens. We measure the perplexity of Wiktiext2.**
| Method | Self<br>Extend | Sliding<br>Window | $T$=1k | $T$=2k | $T$=4k | $T$=8k | $T$=16k | $T$=32k | $T$=64k | $T$=128k |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| FA2 | ✗ | ✓ | 18.90 | 14.48 | 12.35 | 11.40 | 46.66 | 167.40 | 363.02 | - |
| FA2 | ✗ | ✗ | 18.90 | 14.48 | 12.35 | 30.17 | 198.84 | 638.65 | 1310.26 | - |
| HiP | ✓ (x4) | ✗ | 18.98 | 14.77 | 13.00 | 12.14 | 12.00 | 46.51 | 277.54 | - |
| HiP | ✓ (x8) | ✗ | 18.98 | 14.90 | 13.30 | 12.57 | 12.22 | 12.63 | 49.26 | - |
| HiP | ✓ (x4-8) | ✗ | 18.98 | 14.81 | 13.15 | 12.36 | 12.06 | 13.62 | 116.18 | - |
| HiP | ✓ (x8-16) | ✗ | 18.98 | 15.00 | 13.51 | 12.83 | 12.53 | 12.55 | 14.32 | - |
| HiP | ✓ (x8) | ✓ | 19.28 | 14.86 | 12.87 | 11.95 | 11.53 | 11.36 | 11.69 | - |
| HiP | ✓ (x16) | ✓ | 19.28 | 14.98 | 13.11 | 12.25 | 11.86 | 11.69 | 11.54 | 11.68 |

We can observe Gemma2 explode after its pretrained context length, which is 8192 (First row of the Table 10).
We can see the model fails after the sliding window context length, which is 4096 for the sliding window layer (Second row of the Table 10).
Therefore, we know that treating sliding windows especially is quite essential for performance.
In the third and fourth rows of the Table 10, we apply the same Self-Extend group size for every attention layer, including the layer that was originally a sliding window, before replacing it with HiP.
We could observe the settings are struggling to recover performance right after $\text{Self-Extend Group Size}\times\text{Sliding Window Size}$, so we apply twice the larger Self Extend group size for the HiP layers originally sliding window.
The modified group size application is in the fifth and sixth rows of the Table 10.
We could observe that we can extend the context window as expected, not bounded by sliding window size.
However, the above replacements are quite restarted setting because they are not even allowed to use sliding window attention, which is usually very efficient in practical LLM frameworks.
Therefore, we replace only dense attention to HiP, and we could observe a significant performance boost from all layer replacements while extending context length up to 128k, as shown in the last two rows of the Table 10.

### C.5 Ensemble Hierarchical Top- k 𝑘 k italic_k Approximation

For the first attempt to address the challenges in HiP described in Section E.9, we perform an ensemble of HiP masks by introducing slight randomness to the branching decisions within a given iteration.
Our empirical results on Wikitext2 indicate that the ensemble of HiP with no dense layers ($l_{d}=0$) achieves comparable perplexity to HiP with dense layers ($l_{d}=3$) across context lengths from 4k to 16k. This highlights how considering different branching strategies within a given iteration can improve inference performance and suggests the potential for replacing the dense layers in HiP with comparable performance.

Methodology.
First, we generate $n_{e}$ HiP attention mask samples by adding randomness $r_{e}$ to the branch direction when the middle iteration branches out to the next iteration.
As $r_{e}$ slightly adjusts the selected node in the iteration, each sample can take a slightly different path during tree branching, leading to a diverse construction of attention masks.

Second, we count the number of agreements of the indices per query and retain the indices that exceed or equal to the agreement threshold $\theta_{\text{vote}}$.
Therefore, $\theta_{\text{vote}}=1$ functions as a union operator and $\theta_{\text{vote}}=n_{e}$ as an intersection operator. By adjusting $\theta_{\text{vote}}$ from 1 to $n_{e}$, we can perform an operation that lies between union and intersection, prioritizing indices with a higher number of votes.
To prevent the union-like $\theta_{\text{vote}}$ increasing the number of active attention elements too much, we truncate the number of the final selected indices by original $k$ when $\tau\in\{0,1\}$ is $1$, prioritizing the indices having more votes.

Lastly, we perform the introduced ensemble method for the first $l_{e}$ layers, just like we do with $l_{d}$.

Experiments.
We first provide experimental evidence on how ensemble enables end-to-end sub-quadratic complexity and then give details on our hyperparameter tuning process. The experiments are conducted with the LLaMA2-7B model.

Figure: Figure 18: Perplexity Evaluation on Long Context. (Left) Perplexity result in Wikitext2 with different ensemble settings ($\theta_{\text{vote}},~{}\tau$) where $r_{e}=5.0,~{}l_{e}=all$. (Right) Perplexity comparison between full HiP ($l_{d}=0$) and ensemble ($\theta_{\text{vote}}=1,~{}\tau=0,~{}r_{e}=5.0,~{}l_{e}=all$) using same relative retention ratio in each sequence length.
Refer to caption: x38.png

Figure: Figure 19: Effect of Randomness in HiP sampling and Ensemble-Enabled Layers $l_{e}$. Perplexity in Wikitext2 with $T=4k$. (Left) We adjust randomness $r_{e}$ with fixed $l_{e}=all$. (Right) We adjust number of $l_{e}$ with fixed $\theta_{\text{vote}}=1,~{}r_{e}=5.0$. The dashed horizontal line shows the performance of HiP ($l_{d}=0,~{}l_{d}=3$).
Refer to caption: x40.png

Performance Comparison with Original HiP.
To show that ensemble enables end-to-end sub-quadratic complexity with comparable performance to our default HiP ($l_{d}=3$), we compare the full HiP ($l_{d}=0$), the default HiP ($l_{d}=3$), and the ensemble with $l_{d}=0$.
We fix $r_{e}=5.0$, $l_{e}=\text{all}$ that gave the best performance in $T=4096$, as shown in Figure 19.
The result indicates that ensemble with $\theta_{\text{vote}}=1$, $\tau=0$ outperforms both full HiP and default HiP, as shown in Figure 18 (Left), and therefore this suggests that ensemble could not only improve the performance but also replace the dense layers with comparable performance.

Moreover, we provide a comparison with full HiP ($l_{d}=0$) at the same level of sparsity as the ensemble to demonstrate that the improvement is not solely due to the increased number of selected indices resulting from our ensemble method.
As shown in Figure 18 (Right), our ensemble method is Pareto frontier compared to HiP, with performance measured against the retention ratio.

Latency of Ensemble.
Since we sample multiple HiP masks by $n_{e}$ and perform voting operations across $n_{e}\times k$ number of indices, the ensemble costs a few times more than the original HiP.
However, since the cost of dense attention grows quadratically, the ensemble will become more efficient compared to the dense attention as the context length increases. Therefore, we think that the use of the ensemble method could be particularly advantageous in extremely long contexts.

Figure: Figure 20: Relative Retention Ratio and Ensemble Factors. Relative retention ratio after mask ensemble. The ratio is computed by dividing the number of active indices after the ensemble by before. (Left) We adjust the sequence length $T$ with fixed $r_{e}=5.0,~{}l_{e}=all$. (Center) We adjust the randomness $r_{e}$ in $T=4k$ with fixed $l_{e}=all$. (Right) We adjust the number of ensemble enabled layer $l_{e}$ in $T=4k$ with fixed $\theta_{\text{vote}}=1,~{}r_{e}=5.0$. Ensemble disabled layers are computed as 1.0.
Refer to caption: x42.png

Figure: Figure 21: Attention Mask Ensemble Visualization. Visualization of attention mask in $T=16k$ for (Left) HiP ($l_{d}=0$). (Center) ensemble ($\theta_{\text{vote}}=1$, $\tau=0$). (Right) ensemble ($\theta_{\text{vote}}=1$, $\tau=1$). Red indicates indices added by our ensemble method, yellow indicates indices from HiP, and green indicates where attention will not be computed.
Refer to caption: x45.png

Ablation Study of Ensemble Hyperparameter: $\theta_{\text{vote}}$, $\tau$, $r_{e}$, $l_{e}$.
As shown in Figure 19 (Left), $\theta_{\text{vote}}=1$ with $\tau=0$, and $r_{e}>=5.0$ gives the highest score.
This indicates that performing the union operation with large randomness in sampling gives the highest performance.
Also, in Figure 19 (Right), with $\theta_{\text{vote}}=1$, we show that $l_{e}=\text{all}$ works the best, therefore if we want to replace the few layers of vanilla attention, then we would have to apply ensemble in every layer.

Correlation Between the Relative Retention Ratio and Ensemble Factors. In Figure 20, we show that the relative retention ratio shows no correlation with sequence length, while randomness shows a positive correlation.
Moreover, when measuring the relative retention ratio changes over $l_{e}$ with $\theta_{\text{vote}}=1$, since we treat the ensemble disabled layer as having a 1.0 relative retention ratio, more ensemble-enabled layers lead to a higher relative retention ratio.

Analysis with Visualization.
In Figure 21, we provide a visual analysis to show how the ensemble selects indices that HiP missed to fill up a complete attention pattern and how it enables dynamic sparsity.
We can see how the ensemble catches missed important indices such as diagonal, vertical, and stride attention patterns in (a), (b), and (c) of Figure 21.
Moreover, compared to HiP (left), the union operation (center) enables dynamic sparsity per head.
Especially in (c), we can see that the ensemble is effective for filling missed indices in a long sequence while providing dynamic sparsity for each row (red pixels are gradually frequent in the bottom). Lastly, in Figure 21 (center, right), we show how $\tau=1$ selects indices that receive more votes compared to those selected by $\tau=0$.

## Appendix D Detailed Experimental Settings

Computation Resources. We use two machines to run experiments and training. (1) 4090 Machine. We use this local development machine. Most of the micro-benchmark and kernel optimization is done with this machine. (2x RTX 4090 24GB, 128GB DDR5-3600, Ryzen 7950x), (2) A100 Machine. We use this AWS cloud node as the main computation horse. All training and most long context benchmarks are measured with this machine. We use different GPU architectures for kernel development because we could not get an H100 AWS node due to a lack of quota. Therefore, our kernel’s CUDA hyper-parameters, such as the number of warps per program and block sizes, are not optimal in the A100 machine. To overcome these mismatches between the development machine and the computation horse, we used triton.autotune as much as possible. However, for the above reasons, the optimization of the GPU kernel may not be optimal for every GPU architecture.

Experiment Settings.
By default, for the HiP experiment, we use $b_{q}=32,b_{k}=2,k=512,l_{d}=3~{}\texttt{if}~{}\text{7B}~{}\texttt{else}~{}4,r
_{m}=8$. For StreamingLLM, we use $\text{num_sink}=4$.

We show overall experiment settings, such as the number of GPUs and model IDs to which the experiment is introduced (e.g., the caption of the figure and table). To reference, we leave the huggingface model path in Table 11.
We used an instruction model from the same provider for instruction following ability-required tasks such as passkey, LongBench, and RULER.

**Table 11: Model IDs on Huggingface. We use large language models trained on long context inputs in order to demonstrate our method’s effectiveness at long context lengths.**
| Model | Huggingface ID | Maximum<br>context length |
| --- | --- | --- |
| LLaMA2-7b | togethercomputer/LLaMA-2-7B-32K | 32K |
| LLaMA2-13b | Yukang/Llama-2-13b-chat-longlora-32k-sft | 32K |
| Qwen1.5-7B | Qwen/Qwen1.5-7B-Chat | 32K |
| Qwen1.5-14B | Qwen/Qwen1.5-14B-Chat | 32K |
| Luxia-21.4B | saltlux/luxia-21.4b-alignment-v1.1 | 32K |
| Llama3.1-8B | meta-llama/Meta-Llama-3.1-8B | 128K |
| Llama3.1-8B-Instruct | meta-llama/Meta-Llama-3.1-8B-Instruct | 128K |

Experiment Details.
We measure every latency measures with a single NVIDIA RTX 4090, PCIe 4.0 x8, 128GB DDR5-5600, and Ryzen 7950x.
The batch size is 32 for decoding and 1 for prefilling.
The official implementation of HyperAttention is not available for decoding; therefore, we did not measure the decoding latency and decoding benchmark.

For FlashAttention, we use flash_attn==2.6.3 for every baseline that requires a FlashAttention backend, such as vLLM, SGlang, and HyperAttention.

We do not use HyperAttention in another experiment because it fails to recover the perplexity of PG19, the most basic metric of language modeling.
For HyperAttention (Han et al., ) we used lsh_num_projs=7, block_size=64, sample_size=1024, min_seq_len=32.
We select min_seq_len to match the size of the MMU’s block size ($32$) rather than $4096$, which is suggested by the authors’ code repository.
Since in sortLSH (Han et al., ) it processes shorter block size of min_seq_len with vanilla attention.
Therefore, we have to reduce its size to a smaller size than $4096$.

Since StreamingLLM does not use block-wise computation just like HiP’s block approximation, it cannot utilize TensorCore in GPU.
This downside degrades the throughput significantly compared to HW-aware algorithms such as ours and Flash Attention (Dao, ).
However, since the method requires a different RoPE index for every query-key dot product, we cannot easily adopt block sparsity on their method.
This will slow down attention computation more than twice because the RoPE re-computation costs twice as much as attention score computation.

In the Figure 6, the latency is measured with our latency measure machine (RTX 4090).
StreamingLLM shows OOM over 32k context due to the overhead of the COO sparse matrix.
HyperAttention shows invalid kernel parameters over 32k context due to heavily nested tensors in a long context.
It uses high-dimensional striding to perform reformer-style token clustering, but the backbone flash attention kernel does not support that high-dimensional striding with a larger tensor.

In the Figure 8, the latency is measured with our latency measure machine (RTX 4090).
The machine has about 4GB of VRAM available for the KV cache, excluding model weight and temporary buffers.
We limit the size of the CPU offloaded KV cache to 32GB.
The tested model is Llama3.1-8B.

Training Details (Healing HiP in Arxiv).
The HiP healing in Section 5.3 is done as follows.
For the Llama3.1-8B model, after applying HiP, we fine-tune the pretrained model on the Arxiv dataset for 500 steps with AdamW optimizer with learning rate 1e-5, and with batch size 32, LoRA rank 256, and HiP’s hyperparameters set to $b_{k}=2,b_{q}=64,b_{s}q=2,b_{s}k=1,k=512,l_{d}=3$. We use the Arxiv dataset in Redpajama (Computer, ). The inputs are truncated to a maximum of 8192 tokens to speed up the process.

The purpose of this fine-tuning, which we call healing, is to make the model adapt to the slight differences in the activations that appear when the original dense attention layers are replaced with sparse HiP attention. As shown in Section 5.3, the healed model performs slightly better than the plug-and-play (unhealed) model on LongBench. However, we emphasize that HiP is meant to be training-free, and healing is just an additional option for extra performance, as our method already works near-perfectly without training.

## Appendix E Additional Analysis

### E.1 More Discussion on Related Works

**Table 12: Comparison of time and space complexities of various efficient attention methods.**
|  | Complexity | Is Training-<br>free? | Is Dynamic<br>Attention? |  |
| --- | --- | --- | --- | --- |
|  | Time | Space |  |  |
| HiP (Ours) | Log-linear | Linear | ✓ | ✓ |
| SEA (Lee et al., ) | Linear | Linear | ✗ | ✓ |
| FlashAttention (Dao, ) | Quadratic | Linear | ✓ | ✓ |
| StreamingLLM (Xiao et al., ) | Linear | Linear | ✓ | ✗ |
| HyperAttention (sortLSH) (Han et al., ) | Near-linear | Near-linear | ✓ | ✓ |
| Reformer (LSH) (Kitaev et al., ) | Log-linear | Log-linear | ✗ | ✓ |
| Performer (Choromanski et al., ) | Linear | Linear | ✗ | ✓ |
| Cosformer (Qin et al., ) | Linear | Linear | ✗ | ✓ |
| Longformer (Beltagy et al., ) | Linear | Linear | ✗ | ✗ |

Figure: Figure 22: Visualization of sparse attention baselines’ attention masks.
Refer to caption: x46.png

In Table 12, we compare efficient attention methods that we do not include in our main benchmarks. For each method, we show the time and space complexities, whether it is training-free, and whether it uses dynamic attention.
Dynamic attention methods can attend to each other content dynamically rather than using static attention patterns such as a sliding window.
Besides HiP, HyperAttention is the only method that satisfies all four criteria, but HyperAttention suffers from substantial performance degradation (see Figure 6).
In Figure 22, we conceptually visualize the various sparse attention baselines’ attention patterns for extra clarity.

##### StreamingLLM (Xiao et al., 2024 ) .

StreamingLLM uses a sliding window attention with an attention sink, which processes the input sequence in linear complexity without resetting the KV cache; they call this process ‘streaming.’
StreamingLLM introduces the attention sink, which is similar to the global attention token in Longformer (Beltagy et al., ), and streams the KV cache using RoPE indexing.
However, due to the sliding window, the method cannot perform long-context knowledge retrieval.
Therefore, this method cannot utilize the full context, and they do not extend the context window of the model by any amount.
Since the method loses the key-value memory as time passes, it cannot take advantage of the Transformer’s strength: its powerful past knowledge retrieval ability.
Furthermore, since they use a different RoPE indexing for every query-key dot-product, they cannot utilize a MMU, which is a critical speedup factor in modern accelerators.

##### HyperAttention (Han et al., 2024 ) .

HyperAttention introduces sortLSH, improved version of LSH (Kitaev et al., ), to work as plug-and-play.
The method uses block sparsity to utilize MMU.
It is training-free, has sub-quadratic time complexity (near-linear), and has the ability to potentially access to every past key token, much like our method.
However, HyperAttention struggles to recover vanilla performance when replacing most of the layers in the trained model in a training-free manner (see Figure 6).

##### Sparse Linear Attention with Estimated Attention Mask (SEA) (Lee et al., 2023 ) .

Inspired by SEA’s framework, which introduces linear complexity attention estimation and sparse matrix interpolation, we aimed to improve its efficiency.
SEA estimates each query’s attention probabilities over the keys with a fixed-size vector, turns it into a sparse mask by selecting the top-k elements, and resizes it; this process is done with linear complexity.
However, the method is difficult to implement efficiently due to its extra modules, mainly the estimator and sparse matrix interpolation.
Furthermore, the method does not support block sparsity; thus, it cannot utilize the MMU.
We were motivated to improve this work drastically by introducing a fused and train-free attention mask estimator, HiP.

### E.2 Analysis of Summarizing Result between StreamingLLM and HiP

Figure: Figure 23: Summarizing Example of GovReport Dataset from LongBench. We sample random examples from GovReport summarization results with Qwen1.5-14B.
Refer to caption: x47.png

In Figure 23, we analyze one example generation result from GovReport in LongBench.
We pick four important keywords from the human ground truth summary: MYP, BBC, DOD, and 10 U.S.C 2306b.
We pick two keywords (MYP, DOD) that appear in every summary and two keywords (BBC, 10 U.S.C 2306b) that appear only in the ground truth and HiP result.
The result clearly shows that StreamingLLM is struggling to gather information beyond its single-layer window size, $k=1024$.
StreamingLLM should be accessible to a much longer distance than $k$ because information keeps exchanging across time dimensions in each layer, like Mistral.
In contrast to StreamingLLM, our proposed HiP attention shows successful knowledge retrieval in summary from long-range in-context documents, with the same plug-and-play manner.
Also, quantitatively, ROUGE-* scores show that the summary generated by HiP is much better in coherence with ground truth than StreamingLLM.

### E.3 Hierarchical Attention Mask Pruning Visualization

Figure: Figure 24: Visualization of Hierarchical Attention Mask Pruning. Yellow indicates a non-zero entry of the attention matrix, and green indicates an empty entry of the attention matrix. We use $k=512,b_{q}=32,b_{k}=2,T=4k$.
Refer to caption: x48.png

In Figure 24, we demonstrate real-world examples of hierarchical attention mask pruning.
We sample the Q, K, and V tensors from the first layer of LLaMA2-7B with a random text sample from Wikitext-2.
Note that each attention mask in the masking iteration is not the final attention mask.
The final attention mask generated by this process is from iteration 3.
In an earlier iteration, the sparsity of the mask is low because the group size of blocks is very large (8), so the $8*2$ key values are treated as single groups.
The attention score of that group is represented by the attention score between the query and the group’s first block ($b_{k}$).

### E.4 Ablation Study on Block Size

**Table 13: Ablation Study on Block Size: Perplexity on WikiText2. We use LLaMA-2-7B-32k model, $k=512,dl=3,T=12\text{k}$. Average shows the average perplexity of each row and column. Red means a bad perplexity score, and green means a good perplexity score.**
|  | $b_{q}$ |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| PPL. | 1 | 2 | 4 | 8 | 16 | 32 | Avg. |  |
| $b_{k}$ | 1 | 5.5210 | 5.5172 | 5.4996 | 5.4952 | 5.5064 | 5.5331 | 5.5121 |
| 2 | 5.6032 | 5.6060 | 5.5863 | 5.5599 | 5.5577 | 5.5901 | 5.5839 |  |
| 4 | 5.6316 | 5.6280 | 5.5971 | 5.5872 | 5.5838 | 5.5870 | 5.6024 |  |
| 8 | 5.5807 | 5.5928 | 5.5553 | 5.5238 | 5.5100 | 5.5212 | 5.5473 |  |
| Avg. | 5.5841 | 5.5860 | 5.5596 | 5.5415 | 5.5395 | 5.5578 | 5.5614 |  |

**Table 14: Ablation Study on Block Size: Attention latency on decoding phase with a single query. We use same setting with Table 13. Batch size is 96 and $r_{m}=1$ and sequence length is 12k. Average shows the average latency of each row and column. Red means bad latency, and green means good latency. The unit of latency is milliseconds. We use RTX-4090 to measure the latency of attention operation. Pytorch shows $20.7215$ ms and FlashAttention2 shows $20.2527$ ms.**
|  | $b_{q}$ |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Lat. | 1 | 2 | 4 | 8 | 16 | 32 | Avg. |  |
| $b_{k}$ | 1 | 1.6416 | 1.6397 | 1.6397 | 1.6398 | 1.6397 | 1.6401 | 1.6401 |
| 2 | 1.3543 | 1.3542 | 1.3530 | 1.3533 | 1.3535 | 1.3534 | 1.3536 |  |
| 4 | 1.2312 | 1.2311 | 1.2296 | 1.2305 | 1.2322 | 1.2306 | 1.2309 |  |
| 8 | 1.2836 | 1.2842 | 1.2830 | 1.2827 | 1.2830 | 1.2835 | 1.2833 |  |
| Avg. | 1.3777 | 1.3773 | 1.3763 | 1.3766 | 1.3771 | 1.3769 | 1.3770 |  |

**Table 15: Ablation Study on Block Size: Attention latency on decoding phase with multiple queries (Speculative Decoding). We use same setting with Table 14. We use 32 query tokens to mimic speculative decoding scenarios. PyTorch shows $31.0632$ ms and FlashAttention2 shows $20.3378$ ms.**
|  | $b_{q}$ |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Lat. | 1 | 2 | 4 | 8 | 16 | 32 | Avg. |  |
| $b_{k}$ | 1 | 152.4423 | 77.2624 | 39.2077 | 20.1341 | 10.4925 | 5.5461 | 50.8475 |
| 2 | 85.3140 | 43.8207 | 22.7708 | 12.1814 | 6.4987 | 3.5056 | 29.0152 |  |
| 4 | 54.2530 | 27.7025 | 14.3960 | 7.9660 | 4.5839 | 2.6156 | 18.5862 |  |
| 8 | 41.5079 | 21.3036 | 11.5369 | 7.4481 | 5.0634 | 3.0337 | 14.9823 |  |
| Avg. | 83.3793 | 42.5223 | 21.9779 | 11.9324 | 6.6596 | 3.6753 | 28.3578 |  |

We perform an ablation study on block sizes ($b_{q},b_{k}$) using our method.
Block size $b_{q}$ determines how many queries are grouped into the block during the masking iteration and sparse attention.
And block size $b_{k}$ determines how many keys are grouped.
Block size is a really important factor in utilizing MMU (e.g., NVIDIA TensorCore) in modern accelerators.
MMU enables matrix multiplication and tensor operations to be performed in single or fewer cycles rather than processing one by one using floating point multiplication and addition.
This kind of accelerator trend leads to mismatching of wall-clock latency and FLOPs in modern hardware.
Therefore, we check the performance and latency trade-off among grouping queries and keys by block size $b_{q},b_{k}$.

In Table 13, we show that perplexity gets better as $b_{q}$ increases while it gets worse as $b_{k}$ increases.
It is not intuitive that increasing $b_{q}$ shows better perplexity than before because they lose the resolution across the query dimension in attention mask estimation.
However, the result shows that more block size (more averaging) across the query (time) dimension shows better performance.
In contrast to this observation, $b_{k}$ works as expected, like that less resolution in key (past knowledge or memory) dimension leads to worse performance.

This phenomenon makes our method speed up without any performance loss, even achieving better performance.
In Table 14, we measure the micro latency benchmark of our attention operation during the decoding stage, which feeds a single query into the attention operator.
With a single query, we cannot utilize the MMU fully because, during sparse attention and attention score estimation in masking iteration, we cannot matrix multiply between the $Q$ group and $K$ group.
We have a single query vector; therefore, we need a vector-matrix multiplier instead of matrix-matrix multiplication, which is the main key feature of MMU.
However, in Table 15, we measure the micro latency benchmark of our attention operation during the decoding stage with a speculative decoding strategy, which feeds multiple queries into the attention operator.
We feed 32 query vectors within a query dimension in the input tensor; therefore, now we can utilize a matrix-matrix multiplier in an MMU.
With these multiple queries and MMU utilization, our method could achieve a 10.23 times speedup on 12k sequence length compared to PyTorch naive implementation (using bmm).

We use $b_{q}=32,b_{k}=2$ by default, according to the ablation study across the block sizes.
We choose $b_{q}=32$ because increasing $b_{q}$ leads to better latency and perplexity.
However, we stopped increasing $b_{q}$ by 32 because the current modern GPU, especially the NVIDIA Ampere series, usually does not support matrix-matrix multiplication larger than 32.
And maybe in the future, some variants will support larger matrix multiplication, just like Google TPU.
However, larger blocks need more register allocation for block masking and address calculation.
Therefore, considering implementation limitations, we think there is no benefit to increasing $b_{q}$ infinitely.
Also, from a performance perspective, we do not think this trend will keep over $b_{q}>32$.
We choose $b_{k}=2$ because latency speedup from $b_{k}=1$ to $b_{k}=2$ is huge respect to perplexity loss.

Additionally, we measure the latency with $r_{m}=1$, which means without mask caching.
Therefore, this speedup will be amplified with $r_{m}$ in a practical setting.

### E.5 Ablation Study on Dense Layer Choice

Figure: Figure 25: How Many Layers Should be Remained as Dense Layer $l_{d}$? We use $l_{d}=3$ as the default value. The Y-axis means how many first layers of the Transformer model are kept as dense attention layers rather than replaced with HiP. We use Llama2 7B 32k for PPL evaluation on Wikitext2
Refer to caption: x49.png

We do not replace the first few layers ($l_{d}$) of the Transformer because the first few layers tend to have dense attention probabilities rather than sparse attention probabilities.
This phenomenon is well described in previous results (Ribar et al., ).
The first few layers exchange information globally and uniformly across the tokens.

Therefore, in Figure 25, we perform an ablation study on how many first layers should remain as dense attention.
We observe that the first layers are kept as dense attention and then more perplexity.
In other words, if we replace the original transformer block with HiP attention, we could minimize the performance degradation.
However, for maximum practical speedup, we want to minimize the number of dense layers for the experiment.
Therefore, we run the ablations study on different numbers of dense layers, and we choose 3.
For 2 to 3, the performance (perplexity) improvement is maximized.
In conclusion, the practical effect of dense layers on latency is minimal because the number of dense layers (e.g., 3, 4) is small compared to the number of HiP layers (e.g., 29, 36).
We show that we could achieve practical end-to-end speedup compared to baselines in Figure 7.

### E.6 Ablation Study on Representative Token Location

In the theoretical analysis section, we have mathematically proved that selecting the middle token as the representative token of a section guarantees better performance than random selection. In this subsection, we perform a brief ablation study on the location of the representative token to see if this claim is true. In the following experiment, we measured the perplexity values of the Llama3.1 8B model for various representative token locations. We used the PG19 dataset as the input for the model.

**Table 16: Ablation Study of Representative Token Location. Perplexity is measured on the first 3.2M tokens in the PG19 dataset with a 128k context length. We use Llama3.1-8B for evaluation.**
| Position | First | 0.2 | 0.4 | Middle | 0.6 | 0.8 | Last |
| --- | --- | --- | --- | --- | --- | --- | --- |
| PG19 Perplexity | 8.851 | 8.752 | 8.691 | 8.685 | 8.818 | 8.934 | 8.812 |

Table 16 shows the experimental results. As can be seen in the table, the perplexity value is minimized when the middle token is selected as the representative token. This closely matches our expectations, and it asserts that our theoretical analysis of the representative token location is valid. Therefore, this ablation study justifies the selection of the middle token as the representative token.

### E.7 Discussion about KV Cache Eviction and Compression Strategy

We think the KV eviction and compression strategy is an orthogonal method to our proposed HiP method, and we can cooperate with KV cache strategies.
Users can use sparse linear attention methods like ours with a KV eviction strategy.
If the KV eviction strategy is careful enough, our method should retain the same performance as vanilla attention.

Also, the typical retention ratio ($512/32000=1.6\%$) of our method is much more extreme than state-of-art eviction strategies ($10$ to $20\%$ (Zhang et al., )).
Moreover, the KV eviction strategy loses information permanently, which should be a problem.
We think we can solve the memory pressure from the KV cache should be solved with the memory hierarchy of the computer system. NVMe storage should be large enough to store everything.
We think KV eviction has limitations because we cannot estimate which information will be important in the future.
Therefore, we should store every important piece of knowledge somewhere in our memory.
During the storage of the KV cache, we can utilize a partial KV cache eviction strategy.

We believe KV cache offloading is the future direction to tackle the memory limitation of the attention mechanism, as we proposed in the main section.

### E.8 Discussion about Speculative Decoding

We think that HiP can cooperate with many other speculative decoding strategies orthogonal (Leviathan et al., ; Miao et al., ; Fu et al., ; Cai et al., ) because they are working with the output of LLM, which is logits.
Also, the speculative decoding method tries to decode multiple queries simultaneously to verify the speculative generation candidates.
This characteristic of speculative decoding will take advantage of additional speedup with the large batches in HiP.

### E.9 Remaining Challenges in HiP and Potential Solutions

Although HiP successfully replaces the existing vanilla attention, there is room for improvement as follows:

- •
While HiP outperforms the baselines and performs similarly with Flash Attention in long context evaluation, HiP still underperforms Flash Attention with smaller $k$ (lower compute budget).
- •
As shown in Section E.5, HiP uses a few layers ($l_{d}$) of quadratic dense attention, which could lead to a higher cost as the context length increases.
- •
Since HiP enforces every row in the attention matrix to have the same sparsity, this is not optimal to handle dynamic sparsity of attention (Ribar et al., ; Lee et al., ).

As shown in Figure 2, because HiP discards the bottom chunks for unselected branches, it is impossible to select tokens from the actual top-$k$ set if they happen to be within those discarded chunks. We refer to this as ’branch early termination’ in HiP, and addressing this issue could help resolve above improvement points.
Therefore, we propose two possible research directions that tackle the branch early termination problem while also enabling dynamic sparsity: (1) an ensemble hierarchical top-$k$ approximation and (2) an improved tree traverse strategy.

First, for the ensemble hierarchical top-$k$ approximation, we generate multiple HiP masks by injecting randomness into branching decisions during a specific iteration and create a final ensemble mask by aggregating indices from these masks.
The ensemble method demonstrates that applying different branching in a given iteration can enhance inference accuracy and indicates the potential to replace the dense layers $l_{d}$ in HiP with comparable performance, as shown in Section C.5. Moreover, Figure 21 illustrates how the ensemble method enables dynamic sparsity across layers and heads, addressing the limitation of uniform sparsity in HiP.

Second, we could explore more diverse traversal methods, rather than strictly relying on binary branching and selecting the top-$k$ tokens at each iteration. In Section C.5, we examine the effectiveness of applying ensemble techniques to HiP masks with slight randomness. However, this approach incurs additional computational costs due to the oversampling of the mask, which can be quite expensive.
Therefore, to achieve a similar effect, we could diversify the tree branching beyond the binary structure, similar to an n-beam search. Another potential solution specifically tailored to HiP is to apply multi-branching in a certain iteration and oversample the chunks in subsequent iterations, maintaining multiple paths until the end. By doing so, the final iteration would include more than $k$ candidates, resolving the branch early termination issue and allowing us to decide how many tokens to select for dynamic sparsity across the layers.

### E.10 Unique GPU Resource Demand Pattern of HiP Compared to Flash Attention

Our novel HiP attention is quite different from any other attention implementations.
We do not heavily rely on ALUs (floating operations) like Flash Attention/
Also, we do not heavily rely on memory bandwidth like previous sparse attention methods like H2O (it has to store attention scores in global memory).
The HiP relies on thread resources because of the top-$k$ operator in between HiP iterations.
Moreover, we have highly complex algorithms compared to traditional GPU applications like graphics shaders.
Due to this highly complex algorithm, we heavily rely on thread resources, even if we are heavily optimized with MMU for attention score sampling.

Thanks to the reduced complexity of HiP, $O(T\log T)$, we are winning every configuration with long context prefill and decoding.
Since the decoding phase is highly memory-dependent for Flash Attention, we also always win in most practical context lengths.
However, we sometimes lose if Flash Attention is way too much faster because of the trillions of floating operation specifications of high-end server-grade GPUs.
Moreover, Flash Attention 2 and 3 utilize special floating point valuation resources in GPU, especially on H100; FA3 is way too much faster in another setting.
Therefore, we are starting to lose in short context ($T$=32k) to FA2 and FA3 because of the speedup of Flash Attention on H100.

This phenomenon is disappointing to us. Therefore, we try to investigate why HiP in H100 is so slower than others, even compared to consumer-grade GPUs such as RTX 4090.
We think the high demand for CUDA thread resources is due to our internal sorting algorithm.
Since we must remain top-$k$ blocks in every iteration, we must perform $O(k\log k)$ cost sorting operation $O(\log T)$ times.
Therefore, as $k$ grows, we are staving to allocate worker thread for score comparison.

**Table 17: Prefill Latency Speedup of HiP by Removing Sorting on RTX 4090 and H100 with different $k$ and $T$. The time unit is milliseconds.**
| Device | 4090 | H100 |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Context Length | 32k | 128k | 32k | 128k |  |  |  |  |  |  |  |  |
| Prefill Latency | w/o Sort | w/ Sort | Speedup | w/o Sort | w/ Sort | Speedup | w/o Sort | w/ Sort | Speedup | w/o Sort | w/ Sort | Speedup |
| Flash Attention | 56.0 | 855.2 | 24.05 | 430.79 |  |  |  |  |  |  |  |  |
| HiP k=512 | 16.48 | 19.33 | 1.173 | 85.62 | 103.13 | 1.204 | 16.55 | 19.80 | 1.196 | 86.65 | 108.38 | 1.251 |
| HiP k=1024 | 26.96 | 33.70 | 1.250 | 150.90 | 190.98 | 1.266 | 27.56 | 36.30 | 1.317 | 153.41 | 210.78 | 1.374 |
| HiP k=2048 | 44.12 | 62.27 | 1.411 | 263.60 | 386.97 | 1.468 | 43.74 | 69.54 | 1.590 | 260.22 | 434.30 | 1.669 |

**Table 18: Technical Specifications of 4090 and H100. We put a comparison of prefill latency compared to RTX 4090.**
|  | Rel. CUDA Core | Rel. TFLOPs | Rel. Mem. Bandwidth | Rel. Clock Speed | Rel. HiP Speedup | Rel. FA2 Speedup |
| --- | --- | --- | --- | --- | --- | --- |
| RTX 4090 | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 |
| H100 | 1.00 | 3.66 | 3.32 | 0.71 | 0.89 | 1.99 |

We want to show that the elimination of the sorting operation will speed up our top-$k$ estimation.
To do so, we replace sorting with an identity function.
So, in this version, we always select the first half blocks to pass the next HiP iteration.
As shown in Table 17, eliminating sorting speed up our HiP significantly. In 4090, we could observe 46.8% speedup, and in H100, we could observe 66.9%.
We can see the high relation between (CUDA cores + relative clock speed) and HiP speed as shown in Table 18.
So, we will try to investigate removing the sorting and replacing it with some approximations for more practicality of HiP.

This characteristic is quite good for cost-effectiveness.
Nvidia does not usually reduce CUDA cores on consumer-grade GPUs; therefore, we could achieve the same speed as H100 while reducing GPU costs more than ten times.
Even in server-grade GPUs, there are some great cost-effective alternatives.
For example, L40s has more ALU than 4090 and the same amount of CUDA core.
Therefore, L40s will offer A100-level linear layer computation while offering H100-level attention, which is way more after than flash attention on L40s.
In the L40s, flash attention will be extremely slow, like in A100 and 4090, because they have similar FLOPs due to the price tag.
We wanted to test L40s during submission, but unfortunately, we could not find any possible option to get L40s.

The lower-grade GPUs often struggle with the small size of VRAM.
However, the tiny memory of lower-grade GPU is not a problem with our method due to the powerful KV cache offloading feature without decoding throughput degradation.
We have already shown that we can serve 64K context length with a single RTX 4090 card, and if you put 8 of them together, then we can serve around 512K context length with high decoding throughput.
For example, the tinygrad company offers 8x 4090 workstations with only 40,000$ (tinygrad, ) (we are not them, just for clarification).
The price is almost similar to a single H100 card, but you can serve 512K context length with more than twice TFLOPs!
This means that if you have two nodes of that machine, you can actually run Google Gemini class (Google, ) long context LLM in the home.
And if the tensor parallelism is linearly scaled with two nodes, you can decode 1,527 tokens with 64k context length.
Since our method is almost a logarithm scale with context length during decoding, we can expect to decode around 1K tokens per second with a one million context length.
So, we are really excited to introduce our KV cache offloading feature with HiP in many practical aspects.

## Appendix F Potential Negative Social Impact

In this paper, we do not perform a careful investigation on LLM alignment performance with HiP.
There is the potential that HiP might break the LLM safety guard.
However, as far as we observed during the experiment, the HiP could preserve most of the behavior of trained LLM.
Furthermore, we could always adopt the third-party LLM safety guard model such as LLaMA Guard (Inan et al., ).

## Peer Reviews

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: 1. It would be easier to understand to have a figure illustration showing the tree search (or improve figure 2, the figure 2 step 1 is a bit confusing) for section 3.1. 
2. The algorithm divides the sequence into k segments, and one token will be selected in each segment. Is it correct? If so, then the top k tokens must be distributed in the sequence, and cannot be concentrated on certain regions. Why do you make this design choice? 
3. I am aware of some literatures that also use iterative refinement to dynamically calculate attention for efficiency. Have the authors tried to compare to these literatures?
soundness: 3
strengths: 1. The proposed method uses iterative refinement to dynamically and approximately locate top k tokens, which is interesting. 
2. HiP shows promising efficiency improvement with only small performance drop. 
3. The appendix provides a lot of ablation study to study the behavior of the proposed method. 
4. The method is training free.
summary: This paper proposes Hierarchically Pruned Attention (HiP) to reduce the time complexity of attention to O(T logT) and space complexity to O(T) where T is the sequence length. By exploiting the continuity of token sequence (tokens close together tend to have similar scores), for each query, the HiP use a tree-search like algorithm to approximately search the top k key tokens that yield large attention weights. Further, the author developed a KV cache offloading scheme to offload KV cache to host memory and reduce the GPU memory usage.
weaknesses: see question section

---

confidence: 3
contribution: 3
initial_rating: 8
presentation: 4
questions: * Gemma 2 uses this mix between sliding window and normal attention. it would be great to understand if there are any degradation on non-llama architectures.
* The method does show that MMLU is not degraded when using this method. It would be interesting to see this for a broader set of metrics if possible.
soundness: 4
strengths: * The method being training-free means it can be used as a drop-in to already trained models.
* The paper does careful complexity analysis of its claims but strikes a balance on introducing information in a way to aid presentation (thinking of the informal theorem) while still being rigorous later. 
* It is extremely valuable to have code examples and implementation released.
* The paper is extremely comprehensive when understanding its metrics across different hardware and comparing with the many version of flash attention.
summary: The paper introduces Hierarchically Pruned Attention (HiP) which reduces time and space complexity of the attention mechanism. HiP exploits "attention locality" to estimate top-k key tokens (w/ theoretical justifications as insights) for a given query and does so in a hardware aware way. Moreover, the paper introduces a further KV cache offloading steps which reduces space complexity further.
weaknesses: * It would be great to have the long context benchmarks also for different models -- gemma and mistral are both open source and around similar sizes.

---

confidence: 4
contribution: 2
initial_rating: 3
presentation: 4
questions: 1. How does the choice of chunk sizes in HiP's hierarchical pruning affect the trade-off between accuracy and efficiency?
2. What strategies can be employed to further optimize KV cache offloading, such as using different memory tiers or compression techniques?
3. How well does HiP integrate with other efficiency techniques, such as quantization or model pruning, to further improve serving efficiency?
4. Can HiP be effectively applied to other Transformer architectures beyond the specific LLM model used in the paper?
soundness: 3
strengths: 1. HiP's training-free nature eliminates the need for costly retraining of large LLMs, making it readily applicable to existing models.
2. HiP's hierarchical pruning significantly reduces the computational complexity of attention from quadratic to log-linear, enabling efficient handling of long sequences.
3. KV cache offloading effectively addresses the memory limitations of GPUs, allowing HiP to scale to much longer context lengths.
4. The paper provides thorough experimental results on diverse benchmarks, showcasing HiP's effectiveness in terms of speedup, performance preservation, and context length extension.
5. The paper includes a theoretical analysis of HiP's hierarchical pruning algorithm, providing insights into its superior performance compared to random key selection.
summary: This paper proposes a novel, training-free attention mechanism called Hierarchically Pruned Attention (HiP) to accelerate the serving of pre-trained Transformer-based large language models (LLMs) for long-context tasks. HiP addresses the computational challenges posed by the quadratic time and space complexity of standard attention mechanisms in handling long sequences.
weaknesses: 1. HiP's effectiveness relies on the assumption of attention locality. While this assumption generally holds, there might be cases where it's violated, potentially impacting performance.
2. HiP enforces the same sparsity across all rows of the attention matrix. Exploring mechanisms for dynamic sparsity, where sparsity varies based on the input, could further enhance efficiency and performance.
3. The implementation and optimization of HiP, particularly the KV cache offloading, are tailored for specific hardware platforms (e.g., RTX 4090). Performance and optimal configurations might vary across different hardware accelerators.
4. The paper doesn't specifically address potential LLM alignment issues that might arise from applying HiP. Further investigation is needed to ensure HiP's safety and robustness in practical deployments.

---

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: See the weakness for details.
soundness: 2
strengths: 1. HiP does not require retraining, making it easy to apply to pre-trained models. In addition, by reducing the time complexity to O(T log T) and space complexity to O(T), HiP enables the use of longer context lengths without the associated quadratic cost.
2. Through KV-cache offloading, HiP optimizes GPU memory usage, which is especially beneficial for large models.
3. HiP can dynamically adjust to different sequence lengths, making it suitable for a variety of tasks that involve long contexts.
summary: The paper presents HiP (Hierarchically Pruned Attention), a novel approach aimed at reducing the time and space complexity of the attention mechanism in Large Language Models (LLMs). HiP leverages the observation that tokens close together tend to have similar attention scores to estimate the top-k key tokens for a given query on the fly. This results in sub-quadratic time complexity (O(T log T)) and linear space complexity (O(T)), where T is the sequence length.  Experimental results show that HiP significantly reduces both prefill and decoding latencies while maintaining high performance on benchmarks such as LongBench.
weaknesses: 1. The effectiveness of HiP is contingent upon the presence of "attention localities," which might vary across different LLM architectures or tasks. The robustness of this operation deserves more discussions.
2. While HiP reduces latency in the decoding phase, the iterative pruning process might introduce overhead in the initial stages. How does the proposed method balance these two parts.
3. The authors have already shown improvements for certain sequence lengths, while it is expected to thoroughly explore how HiP scales to extremely long sequences or very large models. The current configuration on the sequence length (128k) and the model size (8B) are relatively small for a paper studies on the efficient decoding. Alternatively speaking, the scalability of this method deserves more experiments to support.

Meta-review: Reviewers find the paper makes a solid contribution towards faster attention computation and solid results on models like Llama and Gemma. Main concerns were around limited models considered for experiments and the generality of the locality hypothesis. Authors presented more results during discussion answering the concerns. Overall I am happy to recommend acceptance.

Decision: Accept (Poster)