INTRODUCTIONLarge language models (LLMs) (Achiam et al., 2023;Touvron et al., 2023a;b) are extensively utilized across a range of tasks like chatbot (Roller et al., 2020), code generation (Mark et al., 2021), reasoning (Yao et al., 2023;Besta et al., 2023;Ning et al., 2023), etc. Traditionally, the interactions between LLMs and application users are sequential: the user sends a new prompt after completion result of the previous prompt is received. However, many applications are now designed to process sequences with an internal tree structure, including self-consistency (Wang et al., 2022), few-shot prompting (Mann et al., 2020), multi-step reasoning (Yao et al., 2023;Hao et al., 2023;Xie et al., 2024), and speculative decoding (Miao et al., 2023;Cai et al., 2024), etc, as shown in Figure 1. Usually, these applications produce substantially more tokens than traditional ones, to provide large space for tree search (Graves, 2012;Lu et al., 2022;Liu et al., 2023) or selection, as shown in Table 1. We need a more efficient decoding algorithm in response to this interaction paradigm change from sequence-based decoding to tree-based decoding.  (Wei et al., 2022) and tree-based ToT (Yao et al., 2023) decoding for a reasoning task. The task is sorting 128 numbers from Besta et al. (2023). The total generated tokens of CoT is only 525 while 38,315 in ToT, resulting in inefficiency in end-to-end latency (second) and IO (TB). IO mainly consists of two parts as follows. (i) KV cache: IO-KV; (ii) Partial results during attention calculation like QK T and softmax: IO-PA; Baselines: (i) Flash-Decoding (Dao et al., 2023); (ii) Tree Attention: tree attention in Medusa (Cai et al., 2024).Latency IO-KV IO When requests have shared prefixes in a tree structure, existing inference systems (Hugging Face; NVIDIA; Kwon et al., 2023) designed for sequence-based decoding introduce redundancy by failing to be prefix-aware at one or more of the following three levels: (1) computation-for instance, the redundant recomputation of KV caches for shared prompts across requests in a batch (Hugging Face); (2) memory storage-for example, the redundant storage of KV caches for shared prefixes (Hugging Face; Kwon et al., 2023; NVIDIA); (3) memory access (IO)-such as repeatedly loading the KV cache of a shared system prompt during attention calculations (Hugging Face; Kwon et al., 2023;NVIDIA). Although some tree-based inference systems (Zheng et al., 2023;Gim et al., 2023;Cai et al., 2024;Miao et al., 2023) address the first two issues, they largely overlook the third and arguably the most crucial aspect: memory access, which is critical in the context of memory-bound LLM inference (Shazeer, 2019;Cai et al., 2024;Kim et al., 2023).Prompt 1Sequence-based decoding Step 2(G 2 ) Step history
Step historyStep 3(G 3 ) To accelerate the tree-structured LLM inference, an important question is whether we can leverage the shared patterns in multi-cascaded prefixes to design a faster and more memory-efficient attention algorithm. This task is challenging due to two key issues as follows. C1: How to ensure prefix-awareness in memory access of KV cache? Current memory-efficient attention algorithms (Dao et al., 2022;2023;Hong et al., 2023) are optimized for sequence-based decoding, which leads to a lack of prefix-awareness during memory access. As a result, shared prefixes in the KV cache are repeatedly loaded. C2: How to split the tree-structured KV cache for load balancing and high GPU utilization? For optimal GPU utilization, the current KV splitting strategy for sequence-based decoding-Flash-Decoding (Dao et al., 2023), which splits sequence KV into chunks-cannot be directly applied to tree-structured KV. Tree-structured KV caches also need to be effectively partitioned: however, if we naively split them by nodes, token lengths across different nodes can vary significantly (e.g., in speculative decoding (Cai et al., 2024), some nodes might only have 1 token while the root node could have thousands), making it difficult to maintain load balance and efficient computation.t0To address the above challenges, we propose DEFT-Flatten, a prefix-aware tree attention algorithm with a flattened tree KV splitting strategy, based on two key insights. • First, how queries and KV caches are grouped for attention calculation significantly impacts memory access. Existing approaches use a Q-Guided Grouping strategy, where each request/query is grouped with all corresponding KV caches. While this eliminates IO redundancy for queries, the prefix KV cache still gets loaded multiple times. To address C1, we propose KV-Guided Grouping: DEFT-Flatten groups the prefix's KV cache with all shared queries, ensuring the prefix KV cache is only loaded once, significantly reducing redundant loading with negligible IO overhead for reloading queries. The IO overhead for queries (Q) is minimal compared to the KV cache, as the maximum query length typically corresponds to the number of root-to-leaf paths in the tree, making the queries relatively short (e.g., dozens of tokens) compared to the KV cache length in each node (e.g., hundreds or thousands of tokens). • Second, since LLM inference is IO-bound, the attention overhead of each QKV group is primarily influenced by the IO of the KV cache. Therefore, it is crucial to ensure that the KV lengths of different QKV groups are nearly balanced. To address C2, we propose a Flattened Tree KV Splitting, which enables balanced partitions by dividing the flattened tree KV into even chunks, using bit causal masks to capture causal relationships between queries and KV cache. We summarize our contributions as follows:• We propose a hardware-efficient tree attention algorithm-DEFT-Flatten, which is IO-aware of shared prefixes' KV cache and load-balanced in computation. • We implement DEFT-Flatten on OpenAI Triton (Tillet et al., 2019) to gain precise management over memory access and fuse all attention operations into a single GPU kernel. • We theoretically justify the superiority of DEFT-Flatten over the existing attention algorithms (Wolf et al., 2019;Dao et al., 2023;Cai et al., 2024;Miao et al., 2023) in terms of IO complexity. • We empirically verify its effectiveness on few-shot prompting, multi-step reasoning, and speculative-decoding tasks. DEFT-Flatten can achieve a decoding latency speedup of 1.3× for few-shot prompting, 2.2× for speculative decoding, 1.1× for multi-step reasoning, due to an up to 3.59× faster attention calculation, with the baseline implementations (Dao et al., 2023;Cai et al., 2024;Zheng et al., 2023). • We compare different tree split strategies-DEFT-Node, DEFT-Node-Chunk, and DEFT-Flatten in ablation studies (see section 4.4), showing the balanced partitioning of QKV groups matters.
RELATED WORKTree-based Decoding. Tree-based decoding, exemplified by beam search (Graves, 2012), has been pivotal in NLP, handling lexical and logical constraints (Anderson et al., 2017;Post & Vilar, 2018;Hokamp & Liu, 2017), mitigating gender bias (Lu et al., 2021), achieving communicative goals (Holtzman et al., 2018), and improving alignment (Liu et al., 2023). Based on the structure feature of queries and KV cache, we can classify tree-based decoding into two patterns: (i) Tree-structured past KV with parallel queries-usually in multi-step reasoning (Yao et al., 2023;Besta et al., 2023;Ning et al., 2023), using search trees with parallel hypothesis generation and selection based on scoring functions, either score candidates per token (Dathathri et al., 2019;Lu et al., 2021;2022) or per reasoning step (Welleck et al., 2022;Uesato et al., 2022;Xie et al., 2024). (ii) Past KV in sequence with tree-structured queries-usually in speculative decoding (Cai et al., 2024;Miao et al., 2023). Further details on these two patterns are discussed in Appendix A.2. Although tree-based search algorithms like A* (Lu et al., 2022) and Monte-Carlo Tree Search (Liu et al., 2023) have been applied, the efficiency of tree-based decoding remains largely under-explored. Memory-efficient Attention Algorithms. Existing memory-efficient attention algorithms target sequence-based decoding. FlashAttention (Dao et al., 2022) improves self-attention computation in LLM training via tiling and kernel fusion, reducing IOs. Flash-Decoding (Dao et al., 2023) extends this, enhancing parallelism by dividing K and V and introducing global reduction to gather partial attention results, enabling efficient decoding for long sequences. Unfortunately, applying these memory-efficient algorithms to the tree-based decoding overlooks redundancy in IO of tree-structured KV cache, which is the focus of DEFT. Tree Attention. Integrated into LLM inference, tree attention reduces computation, storage, and kernel launching overheads (Miao et al., 2023). Tree-structured token candidates undergo parallel decoding, with SpecInfer (Miao et al., 2023) introducing a topology-aware causal masked tree attention algorithm, dynamically updating a causal mask to capture relationships among tokens. Medusa (Cai et al., 2024) uses a similar mechanism with a static causal mask, while other works (Zhao et al., 2023;Liu et al., 2024) adopt analogous approaches to enhance attention calculation efficiency. However, unlike DEFT, these existing works utilizing tree attention do not take memory access into consideration.Storage Optimization of Tree-based Decoding. LLM frameworks optimized for tree-based decoding (Kwon et al., 2023;Zheng et al., 2023) focus on memory storage efficiency. vLLM (Kwon et al., 2023) enhances GPU memory utilization, allowing sequences from the same parent to share KV cache storage. SGLang (Zheng et al., 2023) supports dynamic KV cache management during multi-round interactions with LLMs, improving memory efficiency. Discussion on Concurrent Works. Some concurrent works (Ye et al., 2024a;Juravsky et al., 2024;Athiwaratkun et al., 2024;Ye et al., 2024b;Zhu et al., 2024) also recognize the importance of IO during LLM inference. However, these works have at least one of these flaws: i) they (Ye et al., 2024a;Juravsky et al., 2024;Athiwaratkun et al., 2024;Ye et al., 2024b;Zhu et al., 2024) cannot be easily extended to situations where the decoding tree has more than two levels-they target single-context batch sampling scenarios, a special case of general tree-based decoding with a system prompt as prefix and unique suffixes in the first depth; ii) they (Juravsky et al., 2024;Athiwaratkun et al., 2024) do not consider the inefficiency caused by the lengths of different nodes in the decoding tree. See the comparison of DEFT and concurrent works in Appendix A.3.
DEFTIn this section, we first introduce the background knowledge of LLM inference, upon which we outline the importance of QKV partitions for attention calculation. We then present the overview of DEFT algorithm and Attention Kernel design, with its system support. Finally, we propose efficient QKV partitioning method for DEFT, which not only reduces memory access of prefixes' KV cache and partial results (e.g., Softmax), but also ensures balanced partitions during attention computation.
PRELIMINARYLLM inference and its bottleneck. LLM inference involves two stages: (1) prefill and (2) decoding.During the prefill stage, a prompt is tokenized to initialize LLM. The output of the prefill stage becomes the input for the decoding stage. The decoding stage is auto-regressive, with each output token from the previous step serving as the input token for the next step. Due to the sequential process of auto-regressive decoding, LLM inference is memory-bound (Shazeer, 2019;Kim et al., 2023;Cai et al., 2024), wherein every forward pass requires transferring all model parameters and KV cache from slower but larger High-Bandwidth Memory (HBM) to the faster but much smaller shared memory of the GPU (Jia & Van Sandt, 2021) 2 . Another potential bottleneck is low GPU utilization (Dao et al., 2023), which happens when the parallelism (usually limited by the batch size is much smaller than the number of streaming multiprocessors (SMs) on the GPU (108 for an A100), where the operation will only utilize a small portion of the GPU.The execution pattern of attention algorithms on GPUs. We can separate the execution of attention algorithms into two main phases: (1) QKV PREPARATION PHASE: group Query, Key, and Value (QKV) logically to partitions and map QKV groups to different streaming multiprocessors (SMs) of GPUs;(2) ATTENTION CALCULATION PHASE: load QKV partitions to different SMs' shared memory and apply attention algorithms to each group for final attention results.QKV partitions with segmented attention. In sequence-based decoding, QKV partitioning is crucial when the parallelism (usually limited by the batch size (Dao et al., 2023)) is much smaller than the number of streaming multiprocessors (SMs) on the GPU (108 for an A100), where the operation will only utilize a small portion of the GPU. To enable high GPU utilization, Flash-Decoding (Dao et al., 2023) partitions the queries and KV cache then calculates the attention in parallel. Details are as follows: (1) QKV PREPARATION PHASE: for each query in the batch, split its sequential KV cache into chunks as different QKV partitions.(2) ATTENTION CALCULATION PHASE: it calculates segmented attention A 0 , A 1 , and A 2 over three segments, respectively, and then gets final attention by online Softmax merging (Dao et al., 2022;2023) based on segmented attention from different QKV partitions. We elaborate on the procedure below.• Let's say we have key tensor K ∈ R l kv ×d , value tensor V ∈ R l kv ×d , and query tensor Q ∈ R lq×d . Considering the general case K and V are partitioned across the sequence (row) dimension into three parts for parallel calculation, respectively:K = K 0 ∥ K 1 ∥ K 2 , and V = V 0 ∥ V 1 ∥ V 2 ,with "∥" denoting concatenation along the row axis. • We calculate the attention A 0 , A 1 , and A 2 over KV chunks in different streaming-multiprocessors (SMs) of GPU, whereA 0 = ⟨Q, K 0 , V 0 ⟩, A 1 = ⟨Q, K 1 , V 1 ⟩, A 2 = ⟨Q, K 2 , V 2 ⟩, and ⟨q, k, v⟩ = Softmax qk ⊤ / √ d v . • We calculate LogSumExp (LSE) as a weight of merging A 0 , A 1 , and A 2 . We define LSE(q, k) = log exp qk ⊤ / √ d . • We have ⟨Q, K, V ⟩ = SegAttn(A 0 , A 1 , A 2 ), which means segmented attention with Online Softmax (Dao et al., 2022):SegAttn(A 0 , A 1 , A 2 ) = A0e LSE(Q,K 0 ) +A1e LSE(Q,K 1 ) +A2e LSE(Q,K 2 ) e LSE(Q,K 0 ) +e LSE(Q,K 1 ) +e LSE(Q,K 2 ), where e := exp . (1)
SM i G iLoad QKV group i to SM i
NotationsFigure 2: Overview of DEFT. Input Metadata is prepared in the system elaborated in Appendix A.1. In QKV Preparation Phase (see Section 3.3), the QKV will be grouped logically to partitions with IO-awareness of shared prefixes' KV cache and load-balancing. These partitions will guide the loading of QKV on the Attention Calculation Phase (see Appendix A.4), where the attention calculation will be executed.
OVERVIEW OF DEFTThe importance of QKV partitions. For tree-based decoding, logically partitioning QKV is necessary for attention calculation with high parallelism. The branch number of tree-structured generation requests may be insufficient to fully utilize the GPU when the number of tokens in the tree-structured KV cache is large, due to memory capacity limitations. For example, a request for the reasoning task of sorting 128 numbers (Besta et al., 2023), involves around 40K tokens in a Llama2-7B model, whose KV cache occupies 20GB, which means an 80GB A100 can only process at most 4 requests with such token numbers.
Motivation of DEFT.DEFT aims to address two potential bottlenecks (i.e., IO and GPU utilization) of LLM inference when dealing with tree-structured KV sequences. Let's say we have a simple tree with two cascades, as shown in the left part of Figure 2: for two queries Q a and Q b , the corresponding keys satisfy K a = K 0 ∥ K 1 and K b = K 0 ∥ K 2 , respectively, and values obey the same rule. DEFT is designed to: (1) minimize IO by eliminating redundant memory access of the shared prefix's KV cache (K 0 and V 0 ) for Q a and Q b ; (2) ensure balanced workloads for high GPU utilization, so that the overhead of computing each segmented attention A i remains nearly identical. Since the global reduction in equation 1 requires all partial attention, if the overhead for computing A i is significantly larger than A j , the SM responsible for calculating A j will experience prolonged idleness.Technique overview of DEFT. DEFT aims to be a hardware-efficient attention algorithm by reducing memory access and ensuring load-balancing for tree-based decoding. See details in Figure 2: ➀ In the QKV PREPARATION PHASE, for prefix-aware and load-balanced QKV partitions, we introduce a KV-Guided Grouping strategy to reuse the KV cache IO of the shared prefixes, and a Flattened Tree KV Splitting for high GPU-utilization due to balanced and parallel attention calculation. See details in Section 3.3. ➁ During the ATTENTION CALCULATION PHASE, we design the DEFT ATTENTION KERNEL3 to load QKV splits in a memory efficient way, which is logically grouped by the QKV PREPARATION PHASE, then to perform the attention calculation. Key techniques are as follows, with details deferred in Appendix A.4: 1) Common Kernel Fusion and Tiling strategies avoid significant IO operations for partial results (i.e.. QK ⊤ and Softmax), which Tree Attention-Medusa (Cai et al., 2024) lacks. 2) Tree-Topology-Aware Global Reduction, which extends the global reduction mechanism from Flash-Decoding (Dao et al., 2023). This approach efficiently computes the final attention for each query by aggregating partial attention results from QKV groups while considering the tree structure.System frameworks of DEFT. Apart from efficient DEFT ATTENTION KERNEL, our system for DEFT has other two advantages: 1) efficient memory management of the KV cache in a tree structure, and 2) flexible control of the tree decoding process with arbitrary user-defined functions to decide when and how to branch/prune. The details of key components and their coordinations in the system refer to Appendix A.1.
PREFIX-AWARE AND BALANCED TREE-STRUCTURED KV CACHE PARTITIONSThis section delves into the details of the QKV PREPARATION PHASE, which is a key design aspect of DEFT. The discussion of the ATTENTION CALCULATION PHASE is deferred to Appendix A.4. for KV from KV 0 for KV from KV 1for KV from KV 2 for KV from KV 2 Q a Q b G 0 KV-BCM 0 : 1 1 KV b0 for KV from KV 0 Q a Q b KV b1 G 1 G 2 Q a Q b KV b1Flattened Tree KV Splitting (ours)Two partition strategies for high parallelism Bitmask no mask:1 masked: 0 64 bits in ; low order bits omitted are 0s.
1.Depth-first Flatten Tree KV
3.Get Bitmask (KV b1 for example)KV b1 from KV 0 from KV 1  Note that the partitioning is logically designed without incurring any data movement costs for QKV. The amount of IO between the GPU HBM and shared memory required by each group is highlighted in red rectangles. Part (a) illustrates the dataflow of a two-cascaded decoding tree example and three categories of QKV partitioning strategies: no partition(Vanilla Tree Attention), Q-Guided Grouping and KV-Guided Grouping. The partitioning strategy will guide the loading of QKV during the subsequent Attention calculation phase, where each QKV group Gi will be loaded into SMi on the GPU. Part (b) shows the comparison of Q-Guided Grouping and KV-Guided Grouping, where the latter can be IO-aware of prefix KV cache KV0 and only load it once. DEFT-Node-Chunk is a weak load-balancing improvement of DEFT-Node by splitting large nodes (e.g., KV0) to chunks. Part (c) illustrates the details (discussed in Remark 3.1) of Flattened Tree KV Splitting in DEFT-Flatten for load-balanced partitions, including Depth-first Flatten strategy, Evenly block-wise strategy, and Bit mask. For a summary of baselines and DEFT, see Table 2. See analysis of tree-attention baselines (Cai et al., 2024;Miao et al., 2023) in Remark 3.2.1 0 1 1 Q a Q b Q a Q b KV-BCM 1 (KV-Q a Q b G 0 KV 1 KV2 G 1 G 2 Q a Q b Node KV Splitting DeFT-Node-Chunk Q a Q b G 00 KV b0 Q a Q b G 01 KV b1 G 2 Q a Q b G 1 KV b3 KV b4 KV bi Q-GuidedLet's begin with a decoding example using the tree-structured KV cache shown in Figure 2. If we group the entire tree-structured KV cache and queries into G 0 without any partitions, we can refer to the Vanilla Tree Attention method illustrated in the part (a) of Figure 3. This method calculates attention for all queries simultaneously in a single Streaming Multiprocessor (SM), with the aid of a dense causal mask (DCM). However, this approach is inefficient due to low GPU utilization, as discussed in Section 3.2. To address this inefficiency, effective partitioning of QKV is essential. This process involves two key considerations: (1) prefix awareness to minimize memory access to the KV cache and (2) load balancing to ensure even distribution of workloads across GPUs.Q-Guided vs. KV-Guided Grouping. Most existing memory-efficient attention algorithms (Dao et al., 2022;2023;Zheng et al., 2023) adopt Q-Guided Grouping for QKV partitioning, where each query serves as the indicator for partitioning, grouping with its corresponding KV cache. However, this method is not prefix-aware, e.g., in Flash-Attention (as shown in Figure 3) KV 0 is loaded twice, namely once for Q a and again for Q b . We resort to alternative KV-Guided Grouping approach: by grouping each node's KV cache with all the queries that share it, the partitioning can be made prefix-aware, therefore reducing memory access to the KV cache. For example, DEFT-Node (shown in Figure 3) only loads the prefix KV  3) and DEFT. For IO redundancy, significant issues are highlighted in red, while negligible ones are in blue. "Q" refers to queries, and "KV" refers to the KV cache. "DCM" stands for Dense Causal Mask (a matrix), and "BCM" refers to Bit Causal Mask (a set of 64-bit integers). "PA" represents partial results during attention calculations, including QK T , Softmax, etc. More ⋆ symbols indicate better-balanced workloads for QKV partitions. Details on IO complexity can be found in Appendix A.5.
Attention AlgorithmGrouping Indicator KV Split Granularity IO Redundancy Load-balancing Level Flash-Attention (Dao et al., 2022) Q-guided -KV ⋆ Flash-Decoding (Dao et al., 2023) Q-guided by block KV ⋆ ⋆ ⋆ Radix Attention (Zheng et al., 2023) Q-guided by block KV ⋆ ⋆ ⋆ Tree Attention-S (Miao et al., 2023) Q-guided by block KV and BCM ⋆ ⋆ ⋆ Tree Attention-M (Cai et al., 2024) entire cache KV 0 once for attention computation. The additional IO cost for queries is negligible since each query only contains a single token, while the KV cache may contain thousands of tokens.Tree KV Splitting and Load-Balancing. Thanks to KV-Guided Grouping, DEFT-Node is prefixaware for KV cache IO. However, it introduces a potential bottleneck: unbalanced workloads across different SMs. For example, as seen in DEFT-Node of Figure 3, KV 0 might contain 1,000 tokens, while KV 1 only contains 2 tokens. If G 0 and G 1 are assigned to SM 0 and SM 1 respectively, SM 1 completes computation much earlier and remains idle, leading to low SM utilization4 .To address this, we need to balance the QKV partitions more evenly. A straightforward approach is to chunk K 0 , K 1 , and K 2 at the physical level, while maintaining node-wise partitioning at the logical level, as shown in DEFT-Node-Chunk from Figure 3. However, this load-balancing strategy is weak: it only breaks large nodes (e.g., prompts with around 1k tokens) into smaller KV chunks, and it does not handle cases with many small nodes (e.g., speculative decoding), which could slow down inference due to more rounds of GPU execution for additional QKV groups.As KV cache loading is the primary bottleneck for attention computation (Cai et al., 2024;Tang et al., 2024), it is important to achieve an even token length in each KV cache partition. Therefore, we propose DEFT-Flatten, elaborated in Remark 3.1.Remark 3.1 (Techniques of Flattened Tree KV Splitting). As shown in the part (c) of Figure 3, there are three key components:• Depth-first Flatten strategy. This approach minimizes redundant query IO and computation by leveraging the hierarchical relationship between parent and child KV nodes-for instance, queries for parent KV 0 (e.g., Q a and Q b ) include those for child KV 1 (e.g., Q a ). Depth-first flattening instead of breadth-first, maximizes query overlap across KV cache from different nodes but allocated to the same chunk, reducing redundant computations like masked portions in QK T . • Evenly block-wise strategy. It is the core of the splitting, where it ensures equal lengths of KV in each QKV group for balanced workloads of streaming multiprocessors (SMs) in GPUs. • Bit mask (Miao et al., 2023). It is a set of 64-bit integers used to record causal information of tokens in the tree. Therefore, its IO overhead (e.g., two 64-bit integers in KV-BCM 1 on part (c) of Figure 3) is negligible compared to the dense causal mask (Cai et al., 2024).Remark 3.2 (Discussion on Tree Attention Algorithms). Existing attention algorithms are designed for speculative decoding, where attention is calculated for the entire tree-structured queries. However, these methods are not memory-efficient. For partition details, see Figure 11 in Appendix A.5.• Tree Attention-Medusa (Cai et al., 2024). Based on Vanilla Tree Attention (shown on the left in Figure 3), this method uses PyTorch's General Matrix Multiply (GEMM) to partition Q and KV tensors. It is memory-inefficient for two reasons: (1) it does not utilize Flash-Attention to reduce memory access during the computation of intermediate results (e.g., Softmax); (2) it introduces a dense causal mask, whose memory access is significant. • Tree Attention-SpecInfer (Miao et al., 2023). This algorithm employs Q-Guided Grouping based on Vanilla Tree Attention and partitions the KV sequence through Flash-Decoding. It is memoryinefficient in redundantly loading the entire tree-structured KV cache for each query. ToT-BFS stands for Tree-of-Thoughts (Yao et al., 2023) using breadth-first search. APPS (Hendrycks et al., 2021) is a competitive programming problem dataset. Medusa (Cai et al., 2024) is a speculative decoding framework. "GoT" stands for Graph-of-Thoughts (Besta et al., 2023), which contains iteration records using GPT-3.5 for complex reasoning tasks within ToT-BFS. See more details in Table 13.
Task Prompt Dataset Decoding Tree Source Decoding Tree Collection Method Stopping CriteriaFew-shot prompting APPS -Pad the prompt to 4000 tokens 400 iterations Multi-step reasoning 4 tasks in GoTToT-BFS Reconstruct from interaction records with GPT 3.5 in GoT End of task(∼ 3500 iterations) Speculative decoding APPS Medusa Record token tree shape and accepted token length per step ∼1000 steps(max length=6000)IO complexity analysis. We show DEFT-Flatten is better than existing attention algorithms in IO complexity, including Flash-Decoding (Dao et al., 2023), Tree Attention-Medusa (Cai et al., 2024), and Tree Attention-SpecInfer (Miao et al., 2023). See Appendix A.5.Implementation details. We implement the DEFT attention kernel by OpenAI Triton (Tillet et al., 2019), which enables us to control memory access from global memory to shared memory and attention calculations in a thread block granularity. DEFT-Node and DEFT-Flatten algorithms with two phases in a Python style can be found in Appendix A.8 and Appendix A.9, respectively.
EXPERIMENTSIn this section, to demonstrate the effectiveness of DEFT under different tree topologies, we comprehensively conduct experiments on three types of tree-based decoding tasks, including: (1) few-shot prompting (Mann et al., 2020): a typical case study of tree-structured interactions with two levels-a prefix and several suffixes; (2) multi-step reasoning (Yao et al., 2023;Xie et al., 2024;Hao et al., 2023): tasks characterized by tree-structured past KV with parallel queries; (3) speculative decoding (Cai et al., 2024;Miao et al., 2023): tasks involving past KV in sequence with tree-structured queries.
EXPERIMENTAL SETUPBaselines. We evaluate the performance of DEFT in NVIDIA A100 (80GB) in Llama3-8B model (Touvron et al., 2023b) with the SOTA attention algorithms in sequence-based and treebased decoding, as shown in Table 3. Note that we did not include the tree attention operator of SpecInfer (Miao et al., 2023) to our baselines as its kernel only supports at most 64 tokens in the token tree (the decoding tree except for the past sequence KV part), which is unsuitable for tree-based decoding with tree-structured KV (c.f. details in Appendix A.2).Workloads generation. To ensure fairness for workloads of different baselines, we reconstruct decoding trees from real multi-step reasoning and speculative decoding tasks, as shown in Table 4.For multi-step reasoning, we include these four tasks from Besta et al. ( 2023): (1) Sorting 128 numbers (Sorting in short), (2) Document merging (Document in short), (3) Keyword counting (Keyword in short), and (4) Set intersection (Set in short). The tree decoding process would be forced to branch and prune the tree in certain iterations to get the same shape of the decoding tree as the original decoding tree sources. See workload generation details and analysis in Appendix A.6.
ANALYSIS OF MEMORY MANAGEMENT AND BOTTLENECKAs shown in Table 3, the kernel implementations of different attention algorithms adapt to different memory management. To fairly compare their performance of wall-clock time speedup, we need to analyze the influence of memory management and the bottleneck of the system.A trade-off between memory storage and memory operation. In tree-based decoding, storing the KV cache for each branch is simple but lacks shared storage for the prefix's KV cache. Given the limited GPU memory, not accounting for the tree structure in KV sharing reduces the number of tokens the tree can handle. Although storing KV caches by each tree node significantly improves storage efficiency, most attention kernels are designed for sequence-based decoding (Dao et al., 2022;  Hong et al., 2023;Dao et al., 2023). To use these kernels, KV caches from different nodes must be concatenated into a single tensor, leading to substantial data movement costs (Kwon et al., 2023).The benefits of paged memory for tree-based decoding. For efficient KV cache memory management, paged memory (Kwon et al., 2023;Zheng et al., 2023) is the current mainstream technology. These KV cache tensors are stored in a non-contiguous, paged layout to provide token-level reuse.Besides higher storage efficiency, we note an additional benefit of paged memory management for tree-based decoding: non-contiguous storage in a memory pool is addressed by pointers, ensuring no need to materialize the tree-structured KV into a single tensor before executing the attention kernel. Instead, we only need to record the memory pool addresses of each token's KV cache.Figure 4: Latency breakdown for speculative decoding with a token tree of 32 queries, whose tree topology is from Medusa (Cai et al., 2024). U means unpaged memory.Bottlenecks and trade-offs. We provide support for DEFT and baselines with KV cache in memory management (unpaged or paged) according to their designs. We visualize the latency breakdown for (1) KV cache management, (2) attention, and (3) other operations (including MLP calculation) in Figure 4. We observe that with unpaged KV cache management in tree-based decoding, the bottleneck (69.1-83.4%) is the data movement required to materialize the KV cache. However, when we use paged memory management, attention becomes the new bottleneck (51.1-58.3%), especially when the token tree is large.
DECODING BEHAVIORS: LATENCY AND IOS.We evaluate DEFT's performance on various tree-based decoding tasks by measuring decoding latency (Table 5), which demonstrates DEFT's acceleration of tree attention and wall clock time. See attention latency (Table 16), IO (Table 17), and inference accuracy (Table 15) in Appendix A.7. Notably, decoding latency essentially represents the optimal end-to-end (e2e) latency, excluding other overheads such as prefill latency (which accounts for approximately 5-10% of e2e latency) and framework-induced overheads (roughly 10-15% of e2e latency), including tree search, branching, etc. We exclude these overheads because they are consistent across all baselines and to eliminate the influence of the framework.For few-shot prompting tasks, we used a prompt with 4k tokens and performed 400 decoding iterations, achieving a 1.33× decoding speedup thanks to 1.70× faster attention calculation and an approximately 90% reduction in IO.For speculative decoding tasks, DEFT-Flatten achieved up to a 2.23× decoding speedup due to up to a 3.59× attention speedup, as the entire token tree (all queries) can share IO of the long prefix.For multi-step reasoning tasks. While DEFT-Flatten improves attention speed by up to 1.36×, the decoding acceleration is less pronounced due to two reasons:(1) The narrow tree width (10) restricts KV cache reuse, though increasing it to 50 in few-shot prompting significantly boosts decoding speed (1.2×-1.5× over 100 iterations, see Appendix A.7). ( 2)The small number of tokens in the tree keeps attention at 30% of decoding latency, compared to 50-80% in speculative decoding. A longer prompt length increases attention computation overhead, leading to greater speedup, as shown in Table 7.   15), and model architectures (Table 20 andTable 21).The impact of KV splitting strategy in DEFT. We compared three KV splitting strategies with the baseline Radix Attention, as shown in Table 6. DEFT-Flatten consistently outperforms the others across all tree-structured settings. DEFT-Node-Chunk generally performs better than DEFT-Node because it splits large nodes into smaller chunks for more balanced computations, especially when b ≤ 30 and t ≤ 64, as well as in reasoning tasks like Keyword and Set. However, it struggles with many small nodes (e.g., prompts with around 1k tokens), leading to slower inference due to more GPU execution rounds required for additional QKV groups (see t = 256 for DEFT-Node-Chunk).The influence of prompt length. See Table 7. With a longer prompt, DEFT-Flatten shows a more pronounced speedup in the same model, since the attention overhead is proportional to the token count in the decoding tree, while the FFN overhead remains nearly constant for the same model. See Figure 16, Figure 17 and Figure 18 for more results.The influence of model size. See Table 8. With the larger model, Codellama-34B, DEFT-Flatten achieves slightly reduced but significant (up to 1.78×) decoding speedup. The performance reduction is attributed to a lower A/F-LR, as the FFN overhead is greater due to larger hidden dimensions.
CONCLUSIONWe propose DEFT-Flatten, a hardware-efficient attention algorithm optimized for tree-structured LLM inference. It effectively addresses memory access and GPU utilization bottlenecks by reusing shared prefixes' KV cache and evenly distributing workload across partitions. DEFT-Flatten's key strengths lie in its prefix-sharing awareness and load balancing, making it versatile for various tree-structured tasks. It also scales well with larger search spaces and multiple branches. Our results show that DEFT-Flatten achieves up to 2.23×/3.59× speedup in decoding and attention latency, outperforming baselines in tasks such as few-shot prompting, multi-step reasoning, and speculative decoding. Our ablation studies highlight that: (1) balanced partitioning is critical, (2) DEFT-Flatten delivers significant speedups across various LLM models and GPU architectures, and(3) DEFT-Flatten provides even greater speedups with larger token sizes (e.g., longer prompts) and more branches in tree-structured requests.
CONTENTS OF APPENDIXA branch to two children every 3 iterations, as the example shown in the right of Figure 5). Treesearch-based algorithms can be applied here using the decoding tree's topology information. 2. Sequence Tree Manager: It maintains the topology of the decoding tree based on the tree operations and tokens from the Branch Controller. The tree operations like pruning and branching will be executed by Tree Handler in this component. Branch Result Storage will record token generation results of all branches in the decoding tree, and output when the decoding stops. 3. KV cache Manager: It will maintain KV cache with a tree structure. A map between sequence IDs in the decoding tree and KV cache index is kept, which will be updated based on KV operations5 from the Sequence Tree Manager. We provide both paged (Kwon et al., 2023) and unpaged memory management in this part to fit different attention kernels. 4. Model Interface: pass input metadata to DEFT Attention kernel and MLP module, then return logits and memory pointers of updated KV cache. The right part of Figure 5 further showcases the key data flow of the system through a decoding tree example. For simplicity, we present DEFT-Node here and DEFT-Flatten is similar except for QKV partitioning. Input metadata will be extracted by three components we mentioned above, then loaded from HBM to shared memory in a group manner after the QKV PREPARATION PHASE discussed in Section 3.3. Then QKV groups will be processed by DEFT ATTENTION KERNEL in ATTENTION CALCULATION PHASE of DEFT. See details of techniques in these two phases in Appendix A.4.A.2 DISCUSSION OF TREE-BASED DECODING (a) (Left) Sequence KV with queries in a tree for parallel decoding (Miao et al., 2023;Cai et al., 2024), where a causal mask is applied to record the causal information among queries in a tree of tokens. (Right) Tree KV with parallel queries for shared prefixes in multi-step reasoning.(b) Bit Mask in SpecInfer (Miao et al., 2023) to record the causal information between query tokens in a tree structure. The decoding tree is in the left part of 6a. Figure 6: Discussion of tree-based decoding with tree queries (Miao et al., 2023) and tree KV.Tree-based decoding could have tree-structured KV cache for storage with awareness of shared prefixes (Zheng et al., 2023), or tree-structured queries in parallel/speculative decoding (Miao et al., 2023;Cai et al., 2024), as shown in Figure 6. A general decoding could both do with tree KV and tree queries, which could reduce redundancy (e.g. IO, storage, computation, etc) of shared prefixes, as well as increase the generated tokens per decoding iteration. The existing inference frameworks (Zheng et al., 2023;Gim et al., 2023) focused on tree-based decoding efficiency primarily aim to: (1) reduce memory footprints (Zheng et al., 2023) to enable larger batch sizes for higher throughput; (2) reuse the prompt cache (Gim et al., 2023) to avoid recomputation of the KV cache for faster time-to-first-token (TTFT). However, their designs do not specifically target reducing the latency of the entire decoding process. We observe that the tree-structured feature of LLM inference could provide us with some advantages to speed up the decoding itself.Analysis of speedup potential in tree-based decoding. In tree-based decoding, KV cache and queries can be structured in a tree. Not only can we store KV cache in a tree, but also we can load QKV with awareness of tree topology during attention calculation, to minimize the expensive IO between HBM and on-chip shared memory of GPUs. We explain it in two case studies of complex scenarios with tree-structured interactions: (1) multi-step reasoning (Yao et al., 2023;Xie et al., 2024); (2) speculative decoding (Cai et al., 2024;Miao et al., 2023).Case study 1: multi-step reasoning. As shown in the left part of Figure 7, we can summarize process of multi-step reasoning (Hao et al., 2023;Yao et al., 2023;Besta et al., 2023) to three phases:(1) Thought Generation: generate k candidates for the next thought step based on a generation prompt P g and previous steps S; (2) Thought Evaluation: When presented with a frontier of various thoughts, a LLM as state evaluator measures previous thoughts S based on an evaluation prompt P e towards resolving the problem. This assessment acts as a heuristic for the search algorithm, guiding it on which states to pursue further and the sequence in which to explore them; (3) Tree Search-based Expansion: play different search algorithms (Lu et al., 2022;Liu et al., 2023;Xie et al., 2024) to explore search space, which influences the future tree topology. In both ( 1) and ( 2), we can share IO of KV cache for P g /P e and S during tree attention calculation.P G 1 G 1.1 G 1.2 G 2 G 2.Case study 2: speculative decoding. As shown in the right part of Figure 7, we can summarize the process of speculative decoding (Cai et al., 2024;Miao et al., 2023) to tree phases: (1) Token Tree Generation: multiple small draft models (Miao et al., 2023) or fine-tuned heads (Cai et al., 2024) generate multiple sequences of tokens based on prompt P , then they are merged to a speculated token tree T t , which is very fast (e.g. 1% of time overhead in SpecInfer (Miao et al., 2023)); (2) Token Verification: based on these tree-structured token candidates T t , verify the correctness of its tokens against an LLM's output, where tree-attention calculation is the bottleneck of the process (Miao et al., 2023). In (2), we can share IO of KV cache for P and S during tree attention calculation.Why existing tree-attention algorithms are not enough? The existing tree-attention algorithms are either in-efficient in memory access (Cai et al., 2024;Miao et al., 2023) or not suitable for general tree-based decoding (Miao et al., 2023) with more than 64 tokens in the token tree.• In SpecInfer (Miao et al., 2023), as shown in Figure 6b, a bit mask is utilized to record the causal information among queries of a token tree. Each token t i in queries will have a 64-bit Int as a bit mask, where j-th bit means the causal relationship between query of t i and KV cache of t j . The advantage of this mask design is that it greatly reduces IO, but it results in the maximum number of tree tokens being only 64, which is not practical for scenarios with tree-structured KV cache. What's more, it is not IO-aware for KV cache as it will load KV cache of the entire tree for each query. • Medusa (Cai et al., 2024) is suitable for general tree-based decoding, but it is not hardware-efficient due to significant IOs of a dense causal mask and partial results during attention calculation (e.g. softmax).
A.3 DISCUSSION OF CONCURRENT WORKSThere are some concurrent works (Athiwaratkun et al., 2024;Ye et al., 2024a;Juravsky et al., 2024;Zhu et al., 2024) in attention algorithm design for single-context large-batch sampling, where the goal is to generate multiple sequences from a single context(e.g. system prompt or few-shot examples), which is a special case of tree-based decoding with a depth of 1. The design of their algorithms are based on this feature, which means they can not suit well in attention calculation of a tree with more than two levels of prefixes with efficiency.Insights and techniques in common. Both concurrent works and DEFT have the insight that memory access is the bottleneck of LLM inference, and decomposing attention across subsequences to reduce the memory access of the prefix KV: (1) calculate attention A p , A s over prefix and suffixes, respectively;(2) get finial attention by online softmax merging (Dao et al., 2022;2023) based on A p and A s . Here are the details of the correctness proof: • Let's say we have key tensor d) , and query tensor Q ∈ R (lq,d) . Consider the general case K and V are partitioned across the sequence (row) dimension into two parts for prefix and suffixes, respectively: K = K p ∥ K s , and V = V p ∥ V s , with ∥ denoting concatenation along the row axis. • We calculate the attention A p , A s over prefix and suffixes, whereK ∈ R (l kv ,d) , value tensor V ∈ R (l kv ,A p = ⟨Q, K p , V p ⟩, A s = ⟨Q, K s , V s ⟩, and ⟨q, k, v⟩ = Softmax qk T √ d v.• Based on Equation 1, we can have segmented attention ⟨Q, K, V ⟩ = SegAttn(A p , A s ).  (Ye et al., 2024a), Hygragen (Juravsky et al., 2024) and Bifurcated-Attention (Athiwaratkun et al., 2024). RelayAttention (Zhu et al., 2024) and Cascade-inference (Ye et al., 2024b) are similar to Hygragen. More ⋆ means more balanced workloads after tree split, which also shows how insensitive the acceleration is to the tree topology.
MethodChunk-Attention Hygragen Bifurcated-Attention DEFT-Node DEFT-Node-Chunk DEFT-Flatten IO-aware levels 2 (depth ≤ 1) 2 (depth ≤ 1) 2 (depth ≤ 1) all (every depth) all (every depth) all (every depth) Tree KV split granularity by node first, then by block by tree depth by tree depth by tree node by tree node, then by block flatten tree, then by block Load-balanced level⋆ ⋆ ⋆ ⋆⋆ ⋆⋆ ⋆ ⋆ ⋆ ⋆ ⋆ ⋆ ⋆⋆ Goal metrics throughput throughput latency latency latency latencyComparison of differences. The existing works of single-context large-batch sampling are not hardware-efficient for general tree-based decoding for two reasons, as shown in Table 9:• They are designed for decoding trees with only two levels-prefixes at the root and suffixes at depth 1. For decoding trees with multiple levels of prefixes, their algorithm can only reduce the IO of the prompt at the root of the tree. However, in scenarios such as multi-step reasoning (Yao et al., 2023;Besta et al., 2023;Hao et al., 2023), the token length of non-root prefixes can also be very long (e.g., thousands of tokens), and their KV cache's IO is not reused. DEFT can reuse KV IO of all non-leaf prefixes in a general decoding tree, providing greater acceleration potential. • They have not addressed the unbalanced workload problem in tree-based decoding. Nodes in the decoding tree can vary significantly, making it crucial to split the tree and group QKV in a way that ensures balanced calculations for each QKV group. Simply dividing based on depth alone is insufficient. For example, in speculative decoding, the prefix might contain thousands of tokens, while each layer only processes a few dozen tokens (Cai et al., 2024;Miao et al., 2023). Technique Goal
A.4 DISCUSSION OF TECHNIQUES IN EFFICIENT ATTENTION ALGORITHM DESIGN
KV-Guided GroupingHigh utilization of GPU and minimal KV cache IO between HBM and shared memory.
Flattened Tree KV SplittingBalanced attention calculation for high computation efficiency. Bit Causal Mask (Miao et al., 2023) Record causal information of tokens in the decoding tree with little IO cost.Kernel Fusion (Dao et al., 2022;2023) Reduce partial results IO (e.g. QK T , Mask M , and Softmax, etc ). Tiling (Dao et al., 2022;2023) Enable attention calculation within limited size of GPU's shared memory.
Tree-topology Aware Global ReductionTo get the correct tree attention of the entire decoding tree.In this subsection, we summarize and discuss the common techniques in existing designs of efficient attention algorithms and kernels : (1) Kernel Fusion with Tiling strategy (Dao et al., 2022;Hong et al., 2023;Miao et al., 2023); (2) Tree-topology Aware Causal Mask (Miao et al., 2023;Cai et al., 2024); (3) KV Split with Global Reduction (Hong et al., 2023). Then we explain the details of design in DEFT Attention Kernel, where the techniques are in Table 10.  (Cai et al., 2024). No Kernel Fusion or Tiling strategy is applied, which introduces significant IO of partial results like QK ⊤ , DCM, and Softmax between GPU global memory and on-chip shared memory.Kernel Fusion is a common technique of IO reduction: if multiple operations are performed on the same input, it is more efficient to load the input once from HBM rather than loading it multiple times for each operation; Similarly, the same principle applies when transferring output from shared memory to HBM. To fuse all the attention operations into one GPU kernel with the limited size of shared memory, we further utilize the commonly employed Tiling strategy (Dao et al., 2022;2023): split queries and KV cache within each QKV group to small blocks to prevent materialization of attention matrix in HBM by computing attention within the limited size of shared memory, then incrementally performing the softmax reduction as the formulation in Equation 1to reconstruct the attention.Remark A.1 (Importance of tiling and fused kernel during ATTENTION CALCULATION PHASE).Methods in this phase can be roughly divided into two categories: (1) without tiling and kernel fusion: Tree Attention in Medusa (Cai et al., 2024), which introduces significant IO operations for partial results (i.e.. QK ⊤ and Softmax), as shown in Figure 8; (2) with tiling and a fused kernel: Flash Decoding (Dao et al., 2023), Tree Attention in SpecInfer (Miao et al., 2023) and our DEFT.  Based on the QKV grouping results after KV-Guided Grouping Strategy with Tree Split as mentioned above, each QKV group (Gi) will be allocated to a thread block for Flash Attention (Dao et al., 2022) calculation with common Kernel Fusion and Tiling strategy. Similar to Flash-Decoding (Dao et al., 2023), we not only get partial attention (P Ai) but also return "LogSumExp" (LSEi) as a weight parameter for the next stage's reduction. Stage 2-global reduction. Upon receiving P Ai and LSEi for each QKV group Gi, DEFT now performs a Tree-Topology-Aware Global Reduction (DeF T _reduction). Guided by the tree topology among sequence nodes of KV in the decoding tree, DEFT logically remaps the partial results of attention and LogSumExp to get the correct final attention for each query after reduction. The decoding tree is the same as the one in the left of Figure 3. SMi means the streaming multiprocessor i in GPU.KV 0 Q 1 Q 2 = KV 1 Q 1 Q 2 = = KV2 G 0 G 1 G 2Load PA 0-2 ,LSE 0-2 ， TreeTopo Load G 0 ，G 1 , G 2 Q 1 KV 0 KV1 KV2 Write PA i ,The Tree-topology Aware Causal Mask (Causal Mask for short) is introduced in speculative decoding works (Miao et al., 2023;Cai et al., 2024) to facilitate the calculation of attention for all queries within a decoding tree using a single GPU kernel. It achieves this by recording the causal relationships among queries and KV cache in the decoding tree. As depicted in Figure 6, while originally designed for tree-based decoding with KV cache for a sequence of tokens and tree-structured queries, the Causal Mask can also be adapted to tree decoding with tree-structured KV cache and parallel queries-a configuration targeted by DEFT to enhance efficiency.Remark A.2 (The effects of introducing a causal mask). Causal mask brings two parts of redundancy:• Memory Access. Medusa (Cai et al., 2024) materializes the dense causal mask (DCM) in HBM to record the causal information between n q tokens in queries and n kv tokens in the KV cache, thereby introducing a significant IO cost for loading this n q × n kv -sized mask to shared memory. SpecInfer (Miao et al., 2023) introduces a 64-bit integer as a bit causal mask (BCM) to record the causal information among up to 64 tokens, which incurs minimal IO cost from HBM to shared memory but is not suitable for decoding trees with more than 64 tokens. Details regarding the design of the bit mask in SpecInfer are discussed in Appendix A.2. • Computation. In addition to the computational cost of generating the causal mask itself, there is an additional redundancy in computation: many of the matrix multiplication results of QK ⊤ are masked out and never utilized. Both Medusa and SpecInfer have this issue. DEFT-Flatten in Appendix A.9 adopts a bit causal mask insipred by SpecInfer (Miao et al., 2023) to minimize the IO of the causal mask. Details of the bit mask design are on the left of Figure 3.Splitting is introduced to improve GPU utilization in sequence-based decoding (Hong et al., 2023), which is necessary when the parallelism is limited by a small batch size for long-context scenarios. Flash-Decoding splits long KV and group QKV based on first, then these groups will be allocated to different streaming multi-processors (SMs) in the GPU to get partial attention via Flash Attention (Dao et al., 2022).  To obtain the accurate final attention, partial attentions from QKV groups with identical queries need to be grouped for Global Reduction.Similarly, DEFT also splits the decoding tree to different QKV groups for balanced workloads of SMs in the GPU, which is the Flattened Tree KV Splitting strategy we propose in Section 3.3, as illustrated in the bottom right part of Figure 3. To obtain the correct tree attention, DEFT also requires a global reduction. However, the global reduction in Flash-Decoding is for sequence-based decoding, which cannot aware the tree-topology for global reduction in tree-based decoding. Therefore, we propose Tree-Topology-Aware Global Reduction, as shown in the Figure 10b. Based on the techniques mentioned above, we designed the DEFT Attention Kernel with two stages, as shown in Figure 9, to execute the attention operations after the QKV Preparation Phase of DEFT, which we elaborated on in Section 3.3. For more details on the DEFT Attention Kernel, see Figure 10. The attention operations of DEFT-Flatten are omitted because they are very similar to those of DEFT-Node, except for the usage of the bit causal mask for tree attention calculation.
A.5 ANALYSIS: IO COMPLEXITY OF DEFTThis section analyzes the IO complexity of DEFT, showing a significant reduction in HBM accesses compared to existing attention algorithms. Note that it is non-trivial to summarize the IO cost of the entire tree decoding process, thus we only compare IOs based on the decoding tree snapshot in a single iteration. Consider a decoding tree with the features outlined in Table 11, and we summarize the corresponding IO breakdown in Table 12. 
l nNumber of leaf nodes in a decoding tree, which means how many queries are in this decoding iteration.
N iTotal token length from the root node to leaf node i.
N treeTotal token length the entire tree.
#nodeTotal number of nodes in entire tree.n i The token length of node i.d head Head dimension of LLM.s c Scale factor for scaled dot-product attention, typically denoted as √ d head .F s Shared factor of reusing prefixes in tree attention, which means to which extent we can reduce IOs of KV cache:F s = ( ln i=1 N i )/N tree .It can be observed that due to the lack of tree-topology awareness, sequence-based decoding methods, such as naive attention and Flash-Decoding, incur F s times more memory access overheads for KV cache compared to DEFT-Node/Node-Chunk/Flatten and Tree Attention-Medusa (Cai et al., 2024). However, Tree Attention-Medusa entails higher IO overheads for partial results like QK ⊤ and Softmax due to the lack of tiling and kernel fusion6 . What's more, a dense mask is introduced to record the causal information of tokens in the tree, with significant IO costs, as shown in the left of Figure 11.When the number of leaf nodes/queries ln is sufficiently large, the IO cost of partial results might become comparable to that of the KV cache. For instance, in the Llama models (Touvron et al., 2023a;b), where d head = 128, with l n = 29, the total IO cost of QK T , M , QK ⊤ sc , M + QK ⊤ sc , and Softmax matches that of the KV cache.Remark A.3 (KV IO in SpecInfer). Though similar to DEFT, SpecInfer (Miao et al., 2023) also employs a fused kernel for tree attention. As shown in Figure 11, SpecInfer adopts Q-Guided Grouping. Therefore, no IO is sharing for KV cache among queries in SpecInfer: instead, each query will load the entire KV cache of the tree independently, bringing significant IOs of the KV cache as in Table 12.  3) QKV partitioning of Tree Attention (Cai et al., 2024;Miao et al., 2023) and memory access. Tree Attention-Medusa (Cai et al., 2024) partitions QKV by General Matrix Multiply(GEMM) in PyTorch. Tree Attention-SpecInfer (Miao et al., 2023) adopts Q-Guided Grouping. Q-BCM is the Q-Guided bit causal mask for SpecInfer, where each bit represents the causal relationship between a query and a segment of tokens in the KV cache. For example,Q-BCM for Qa is "110" which means the first two segments of KV cache KV0 and KV1 is valid for Qa's attention. The Qi and Kj in the figure are the same as the ones in Figure 3. ceil(ni/bs), which is the node number after chunk wise; for DEFT-Flatten, k = N tree/bs, where bs is the block size of KV; for others, k = 1. M in Tree Attention-M is short for Medusa (Cai et al., 2024), while S in Tree Attention-S is short for SpecInfer (Miao et al., 2023). Remark A.4 (IO in Radix Attention). Radix Attention (Zheng et al., 2023) is essentially an implementation of Flash-Decoding (Dao et al., 2023) utilizing paged and tree-structured memory management. As a result, the IO behavior is identical to that of Flash-Decoding, as shown in Table 12.Remark A.5 (Causal mask IO). DEFT-Node splits the decoding tree by nodes without the need for causal masks. For more balanced calculations among SMs in GPUs, DEFT-Flatten evenly splits the decoding tree into blocks, with minimal IO cost for masks inspired by SpecInfer. This design reduces the IO overhead of masks significantly compared to the dense mask design in Medusa, as shown in Table 12.A.6 DISCUSSION OF WORKLOADS GENERATIONThe rationality of workload settings. To validate DEFT's acceleration across various decoding tree topologies, we compiled decoding trees from real tasks, covering the following three aspects:• Few-shot prompting: This involves a two-level tree with a prompt prefix and multiple branches for suffix generation. As a case study, we fixed the prompt length at approximately 4000 tokens and varied the number of branches. (2) the token length associated with each thought; and (3) the best thought at each depth along with its corresponding score. For the task of document merging, the tree depth is set to d = 3, with a width of w = 10 at each depth.For sorting 128 numbers, the depth is reduced to d = 10, while maintaining the same width of w = 10. See details of tree topology for other multi-step reasoning tasks in Table 13. (Right) Utilizing the extracted thought information from Left, we can generate tree templates for decoding, encompassing branch records and prune records. These records are instrumental in guiding the tree decoding process to produce decoding trees that faithfully replicate the structure of the tree-of-thoughts.• Multi-step reasoning (Yao et al., 2023;Hao et al., 2023;Besta et al., 2023): We recorded the tree shapes, prompts, and lengths of all thoughts from real reasoning task interactions (Besta et al., 2023), using these as guidance for tree decoding to validate DEFT's acceleration in thought generation of reasoning (the thought evaluation phase follows a similar pattern). See details of generation in Figure 12. • Speculative decoding (Cai et al., 2024;Miao et al., 2023): We used the token tree topology from Medusa (Cai et al., 2024) and recorded real interaction data with APPS (Hendrycks et al., 2021) as prompt dataset, including the length of accepted tokens at each step. This served as guidance to simulate the bottleneck of speculative decoding-the attention computation during the token verification phase. (3) Keyword counting (keyword in short); (4) Set intersection (set in short). d, and w means depth and width of the tree, respectively. t means the token tree size for speculative decoding, where the tree topology is from Medusa (Cai et al., 2024).
Task Tree Shape Decoding Tree Source Records ContentsMulti-step reasoning sorting: d = 10, w = 10 ToT-BFS in Besta et al. (2023) Prompt (Besta et al., 2023), tree shape, thought size, branch records,prune records  32, 64, 128, 256 Medusa (Cai et al., 2024) APPS (Hendrycks et al., 2021) Prompt, token tree shape, accepted token length per stepThe rationality of our experiment paradigm. Our experimental paradigm involves: first, obtaining decoding trees from real tree-based decoding tasks, and second, replicating these decoding trees exactly within the same framework by enforcing LLM inference, to investigate the impact of attention acceleration on wall clock time performance. This paradigm has two advantages:• We can utilize decoding trees from real tasks as a benchmark within a unified system, enabling fair comparison of different attention algorithms in terms of decoding latency. This comparison is possible despite the algorithms being based on distinct systems, such as variations in memory management implementations for their kernels.• We consider both the unique characteristics of tasks with diverse tree structures and the broader applicability of general tree-based decoding. See details of generated workloads for other multistep reasoning tasks in Table 13.
A.7 ADDITIONAL RESULTSMicrobench of DEFT-Node for GPU utilization. We test the DEFT-Node and DEFT-Flatten on a speculative decoding with 64 queries and a prompt with 4k tokens. For DEFT-Node, the QKV partitioning is unbalanced as the node of the prompt is much longer than others (1 token for each query). As shown in Table 14, the metrics of GPU utilization are measured by NVIDIA Nsight Compute (NVIDIA, 2024). We can see DEFT-Flatten is better than DEFT-Node in both memory utilization (Memory Throughput Ratio) and calculation utilization (Compute Throughput Ratio and Low Utilization Time Ratio). Attention latency and IOs with breakdowns. The details of attention latency and IO comparison among DEFT and baselines are in Table 5 and Table 17, respectively. Note that the attention latency does not include the memory management overheads, which is the bottleneck for Tree Attention-Medusa. For example, it takes more than 80% of end to end latency in speculative decoding with 32 queries. Inference accuracy of DEFT-Node-Chunk and DEFT-Flatten. In Section 3.1, equation 1 shows DEFT (including DEFT-Node, DEFT-Node-Chunk and DEFT-Flatten ) and vanilla attention are mathematically equivalent, which means DEFT is accurate. As demonstrated in Table 15, the DEFT attention scores may slightly differ (around 0.4% relative error) compared to vanilla attention in Huggingface Transformers, but the generated tokens will hardly be different as well as PPL (1e-6 relative PPL error in the right part of Table 15). This discrepancy arises because floating-point operations on GPUs do not adhere to the associative law, even when two calculation processes are mathematically equivalent. Similar issues occur in other methods like radix attention and Flash-Decoding that introduce online Softmax and reduction as well, resulting in approximately 0.5% relative attention score errors.Dynamic behaviors: per iteration latency. We visualize the per-iteration latency of DEFT-Node and DEFT-Flatten for a tree in the multi-step reasoning task-sorting in Figure 13, as the size and topology of the decoding tree change with each iteration. This comparison highlights the sensitivity of these two split strategies to changes in tree size. We observe a strong positive correlation between the ratio of per-iteration latency of DEFT-Node and DEFT-Flatten (Speedup Ratio) and the dispersion of tree node sizes. This correlation arises because the performance of DEFT-Flatten remains relatively stable, whereas the performance of DEFT-Node is more strongly influenced by the topology of the tree. DEFT-Flatten provides a stable speedup of approximately 1.75× compared to DEFT-Node.Table 16: Average attention latency (in seconds) for tree-based decoding and its impact on decoding latency.Here, b represents the tree width, and t denotes the token tree size (i.e., the number of tree-structured queries).Attention Speedup over the best attention refers to the speedup of DEFT-Flatten compared to the best baseline (typically Tree Attention-Medusa) in attention calculation. Radix Attention is the best baseline for decoding latency. Note that KV cache management is not included in the attention latency. ⋆ denotes out-of-memory (OOM) errors for the A100 80GB GPU. For more details on decoding latency, see Table 5.   Ablation: The influence of width in decoding trees. We observe that the effectiveness of attention speedup varies with different decoding tree topologies. Considering the simplest tree structure, a prompt with several suffixes-given a prompt that is not very short, one of the most important factors for speedup is the extent to which we can reuse its KV cache IO. This can be measured by the width of the tree. More specifically, it is determined by the number of queries per iteration. Therefore, we fix the prompt length at 4000 and vary the width of the decoding tree in few-shot prompting (which also indicates how many requests share the same prompt). Then, as shown in Figure 14, we evaluate DEFT-Flatten with the best baseline in attention calculation-Tree Attention-Medusa (Cai et al., 2024) (Medusa-Attn in the figure), as well as the best baseline in decoding latency-Radix Attention (Zheng et al., 2023), for the per-iteration latency over time. We have the following observations: 1. When the tree width is 10, the attention overhead of DEFT-Flatten is nearly the same as Tree Attention-Medusa because the IO overhead of the dense causal mask (DCM) is small compared to that of the KV cache, but it is still 2× faster in attention latency than Radix Attention thanks to the KV IO reuse. 2. As the tree width increases, the attention computation overhead of Tree Attention-Medusa grows faster because the size of the DCM is directly related to the tree width. A larger tree width means the IO of the DCM grows rapidly. 3. Since the tree topology consists of a fixed prefix with several suffixes, a larger tree width allows the prompt prefix's KV cache to be reused more frequently during IO. This leads to a more significant decoding speedup-1.24× with a width of w = 20, and 1.33× with a width of w = 50-compared to Radix Attention. 4. As iterations progress, the length of the suffixes gradually approaches the length of the prefix, leading to a decrease in the speedup of DEFT-Flatten compared with Radix Attention. Ablation: The influence of prompt length. We set the prompt length from 1k to 20k tokens, and the generation length is set to 1k tokens, to simulate a long prompt short generation case. Our workloads are speculative decoding with token tree size of 32 and 64. The ablation is based on Llama3.1-8B model and NVIDIA A100 80GB. We have three metrics: time per output token (Figure 16), decoding latency (Figure 17) and attention latency (Figure 18).
Ablation:The influence of both model size and prompt length. In Table 6 and Table 8 of Section 4.4, we show the influence of prompt length and model size, individually. Here, we present the ablation study of both model size and prompt length for sorting task, as shown in Table 18. With a longer prompt, DeFT shows more pronounced speedup in the same model, since the attention overhead is proportional to the token count in the decoding tree, while the FFN overhead remains nearly constant for the same model. For a fixed prompt length, with the larger model-Codellama-34B, DEFT-Flatten achieves slightly reduced but still significant (up to 1.28x) decoding speedup.   The performance reduction is attributed to a lower A/F-LR, as the FFN overhead is greater in larger models.Ablation: Different GPUs. See Table 19. DEFT-Flatten can have obvious speedup in RTX 4090 as well because the memory hierarchy of GPUs is nearly the same-large but slow global memory and small but fast shared memory.    Algorithm 1 DEFT-Node Algorithm-Phase 1: QKV Preparation.Input: query Q ∈ R (bq,d) , Key cache list KL = (K 0 , ...K N -1 ), Value cache list V L = (V 0 , ...V N -1 ) for each sequence node in the tree, where N is the total number of sequences in a tree, and Tree T with its topology information.for each q in Q with its global index idx do /*Get KV indices of all prefixes' for a query.*/ QM apKV [idx]=GetPrefixKVIndices(q, KL, V L, T ) end for for each seq's KV cache K i , V i in KL, V L with its KV indice i do /*Group each sequence's KV with all queries that share it.*/Q i = GroupQueryToKV(Q, K i , V i , T ) ∈ R bi,d ⊂ Q KV M apQ[i] = Q i end for Return QMapKV, KVMapQDEFT-Node has two phases-Phase 1-QKV Preparation and Phase 2-Attention Calculation. Phase 2-Attention Calculation of DEFT has two stages. 1. Stage 1: Calculate Partial Attentions. We will apply Flash Attention of all QKV groups obtained after Phase 1-QKV Preparation of DEFT, to get partial attention and LogSumExp. 2. Stage 2: Global Reduction. We will remap partial attention and LogSumExp based on each query, and get final attention based on global reduction similar to Flash-Decoding (Dao et al., 2023).Figure 1 :1Figure 1: An illustration of Sequence-based decoding and Tree-based decoding.
Dataflow of a two-cascaded decoding tree and its different partition strategies for QKV preparation.(b) Q-Guided grouping V.S. KV-Guided grouping. KV splitting is for additional parallelism.
Figure 3 :3Figure3: Comparison of QKV partitioning strategies during the QKV Preparation Phase between DEFT-Node/Node-Chunk/Flatten and different attention algorithm baselines. Note that the partitioning is logically designed without incurring any data movement costs for QKV. The amount of IO between the GPU HBM and shared memory required by each group is highlighted in red rectangles. Part (a) illustrates the dataflow of a two-cascaded decoding tree example and three categories of QKV partitioning strategies: no partition(Vanilla Tree Attention), Q-Guided Grouping and KV-Guided Grouping. The partitioning strategy will guide the loading of QKV during the subsequent Attention calculation phase, where each QKV group Gi will be loaded into SMi on the GPU. Part (b) shows the comparison of Q-Guided Grouping and KV-Guided Grouping, where the latter can be IO-aware of prefix KV cache KV0 and only load it once. DEFT-Node-Chunk is a weak load-balancing improvement of DEFT-Node by splitting large nodes (e.g., KV0) to chunks. Part (c) illustrates the details (discussed in Remark 3.1) of Flattened Tree KV Splitting in DEFT-Flatten for load-balanced partitions, including Depth-first Flatten strategy, Evenly block-wise strategy, and Bit mask. For a summary of baselines and DEFT, see Table2. See analysis of tree-attention baselines(Cai et al., 2024;Miao et al., 2023) in Remark 3.2.
Appendix 15 A.1 Components of System Support for DEFT . . . . . . . . . . . . . . . . . . . . . . 15 A.2 Discussion of Tree-based Decoding . . . . . . . . . . . . . . . . . . . . . . . . . 16 A.3 Discussion of Concurrent Works . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 A.4 Discussion of Techniques in Efficient Attention Algorithm Design . . . . . . . . . 18 A.5 Analysis: IO Complexity of DEFT . . . . . . . . . . . . . . . . . . . . . . . . . . 21 A.6 Discussion of Workloads Generation . . . . . . . . . . . . . . . . . . . . . . . . . 22 A.7 Additional Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 A.8 DeFT-Node Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 A.9 DEFT-Flatten Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 A APPENDIX A.1 COMPONENTS OF SYSTEM SUPPORT FOR DEFT The left part of Figure 5 shows the coordination of different components for efficient and flexible tree-based decoding. The details of functions for system components of DEFT are as below: 1. Branch Controller: It makes the tree decoding process forced by a user-defined function (e.g.
Figure 5 :5Figure 5: Illustration of DEFT. (Left) System overview. (Right) The data flow of DEFT-Node (DEFT-Flatten is similar except for QKV partitioning) using a decoding tree example.
Figure 8 :8Figure8: Operations of Tree Attention-Medusa(Cai et al., 2024). No Kernel Fusion or Tiling strategy is applied, which introduces significant IO of partial results like QK ⊤ , DCM, and Softmax between GPU global memory and on-chip shared memory.
Figure 9 :9Figure9: Overview of two stages in DEFT Attention Kernel (DEFT-Node for example, and DEFT-Flatten is similar). Stage 1-calculate partial attentions. Based on the QKV grouping results after KV-Guided Grouping Strategy with Tree Split as mentioned above, each QKV group (Gi) will be allocated to a thread block for Flash Attention(Dao et al., 2022) calculation with common Kernel Fusion and Tiling strategy. Similar to Flash-Decoding(Dao et al., 2023), we not only get partial attention (P Ai) but also return "LogSumExp" (LSEi) as a weight parameter for the next stage's reduction. Stage 2-global reduction. Upon receiving P Ai and LSEi for each QKV group Gi, DEFT now performs a Tree-Topology-Aware Global Reduction (DeF T _reduction). Guided by the tree topology among sequence nodes of KV in the decoding tree, DEFT logically remaps the partial results of attention and LogSumExp to get the correct final attention for each query after reduction. The decoding tree is the same as the one in the left of Figure3. SMi means the streaming multiprocessor i in GPU.
(a) Left: Illustration of DEFT Attention Kernel with two stages. Right: Global reduction kernel called in DEFT stage 2 illustrated in Figure 10b. QKV Groups G0,G1 and G2 are from DEFT QKV groups in Figure 3. (b) Stage 2 of DEFT: Global Reduction (DEFT-Node for example). Based on tree topology in Figure 3, we can group LogSumExp and Partial Attention based on Query, then we call the Global reduction kernel in the right of Figure 10a to get the final attention.
Figure 10 :10Figure 10: Detailed attention operations of DEFT kernel (DEFT-Node for example, and DEFT-Flatten is similar). Based on the same decoding tree in Figure 3.
Figure 11 :11Figure11: (Supplementary to Figure3) QKV partitioning of Tree Attention(Cai et al., 2024;Miao et al., 2023) and memory access. Tree Attention-Medusa(Cai et al., 2024) partitions QKV by General Matrix Multiply(GEMM) in PyTorch. Tree Attention-SpecInfer(Miao et al., 2023) adopts Q-Guided Grouping. Q-BCM is the Q-Guided bit causal mask for SpecInfer, where each bit represents the causal relationship between a query and a segment of tokens in the KV cache. For example,Q-BCM for Qa is "110" which means the first two segments of KV cache KV0 and KV1 is valid for Qa's attention. The Qi and Kj in the figure are the same as the ones in Figure3.
Figure 12 :12Figure12: The detailed procedure of reconstructing tree templates for multi-step reasoning. (Left) Reconstructing reasoning trees from practical reasoning records as outlined in(Besta et al., 2023) involves capturing the following aspects: (1) the structure of trees, characterized by their depth d and width w; (2) the token length associated with each thought; and (3) the best thought at each depth along with its corresponding score. For the task of document merging, the tree depth is set to d = 3, with a width of w = 10 at each depth. For sorting 128 numbers, the depth is reduced to d = 10, while maintaining the same width of w = 10. See details of tree topology for other multi-step reasoning tasks in Table13. (Right) Utilizing the extracted thought information from Left, we can generate tree templates for decoding, encompassing branch records and prune records. These records are instrumental in guiding the tree decoding process to produce decoding trees that faithfully replicate the structure of the tree-of-thoughts.
document: d = 3, w = 10 keyword:d = 5, w = 10 set:d = 8, w = 10 Few-shot prompting d = 1, w = 10, 20, 30 --Speculative decoding t =
Figure 13 :13Figure 13: Comparison of split strategies DEFT-Node and DEFT-Flatten in sorting task. Speedup ratio refers to the ratio between the per iteration latency of DEFT-Node and DEFT-Flatten. Tree Node Len std represents the standard deviation of the tree node lengths for each iteration.
(a) Tree width is 10. (b) Tree width is 20.(c) Tree width is 30.. (d) Tree width is 50. Figure14: Per iteration latency for few-shot prompting tasks with different tree width. e2e means decoding latency(optimal end-to-end latency), while Attn means only the attention overhead.Ablation: The influence of chunk size in KV splitting. In the implementation of DEFT-Flatten and DEFT-Node-Chunk, we selected a regular size (128) in General matrix multiply (GEMM) as the block/chunk size of KV cache during the attention calculation. We added an ablation study of chunk size influence on speedup, as shown in Figure15. The chunk size selection is a trade-off between IO redundancy and threadblock scheduling: a larger chunk size means less redundancy of Query IO but may cause potential idle SMs of GPUs due to fewer threadblocks during GPU scheduling. Conclusions of Figure15:(1) The best chunk size is influenced by both sequence length and query numbers (batch size); (2) DeFT-Flatten can outperform DeFT-Node-Chunk in all chunk sizes we test.
Figure 15 :15Figure 15: Ablation study for KV chunk size with DEFT. t is the token tree size in speculative decoding.
Figure 16 :16Figure 16: Time per output token(TPOT) of DEFT with different prompt lengths in speculative decoding.
Figure 17 :17Figure 17: Decoding latency of DEFT with different prompt lengths in speculative decoding.
Figure 18 :18Figure 18: Attention latency of DEFT with different prompt lengths in speculative decoding.
Table 1 :1Comparison of efficiency in sequence-based CoT
Table 2 :2Comparison of QKV partitioning strategies for baselines (most of which are shown in Figure
Table 3 :3Comparison of baselines and DEFT. Attention kernels of baselines are implemented to fit its memory management. Therefore, for a fair comparison with baselines, we implement DEFT-Node and DEFT-Flatten that fit both paged(Kwon et al., 2023)/unpaged memory management.MethodFlash-Decoding Tree Attention-Medusa Radix Attention(Zheng et al., 2023)DEFTMemoryunpagedunpagedpagedunpaged/pagedImplementationTritonPyTorchTritonTriton
Table 4 :4Workloads generation.
Table 5 :5Comparison of DEFT-Flatten and baselines in average decoding latency (in seconds) for tree-based decoding. Here, b represents the tree width, and t denotes the token tree size (i.e., the number of tree-structured queries). The fastest method is in bold, and the second fastest is underlined. Radix Attention is the best baseline in decoding latency. ⋆ denotes out-of-memory (OOM) errors for the A100 80GB GPU. Speedup Upper-bound (no attention) refers to the maximum speedup we could achieve for Radix Attention if we exclude the attention computation and only run other components including MLP. For more details on attention speedup, see Table16.MemoryMethodFew-shot PromptingMulti-Step ReasoningSpeculative Decodingb=20 b=30 b=50 Sorting Document Keyword Set t=32 t=64 t=128 t=256UnpagedFlash-Decoding Tree Attention-Medusa78.96 131.19 191.09 429.65 241.20 52.58 103.90 144.07 380.87 236.8632.75 51.76 574.50 1128.45 33.52 50.10 263.40 483.35 924.97 1881.51 ⋆ ⋆Radix Attention12.37 14.08 16.54 104.79 69.6111.25 17.03 54.66 69.75 108.56 188.66PagedDEFT-Flatten9.98 10.99 12.48 94.6766.9510.90 16.10 42.23 46.60 56.96 84.27Attention Speedup over Radix Attention 1.73× 1.63× 1.70× 1.39× 1.15×1.21× 1.34× 1.96× 2.41× 3.11× 3.59×Decoding Speedup over Radix Attention 1.24× 1.28× 1.33× 1.10× 1.03×1.03× 1.05× 1.29× 1.50× 1.91× 2.23×Speedup Upper-bound(no attention) 1.71× 2.08× 2.51× 1.96× 1.82×1.70× 1.76× 1.89× 2.89× 3.34× 4.36×
Table 6 :6[Different KV Splitting Strategies]  Comparison of DEFT-Node, DEFT-Node-Chunk and DEFT-Flatten in average attention latency (second) with NVIDIA A100 (80GB) for Llama3-8B model(GQA). This table is supplementary to Table16. The fastest method is in bold, and the second fastest is underlined. Radix Attention is the best baseline in decoding latency. See details of more baselines in Table16.MemoryMethodFew-shot PromptingMulti-Step ReasoningSpeculative Decodingb=20 b=30 b=50 Sorting Document Keyword Set t=32 t=64 t=128 t=256Radix Attention5.99 7.30 9.96 39.3724.693.11 5.13 25.73 40.47 76.10 145.43PagedDEFT-Node10.59 10.62 10.85 42.9633.296.16 9.58 34.59 34.41 34.96 41.78DEFT-Node-Chunk 8.52 9.69 13.45 49.6336.374.77 7.40 14.54 20.28 32.57 57.26DEFT-Flatten3.47 4.07 5.87 28.4121.452.57 3.83 13.15 16.79 24.46 40.56Table 7: [Different Prompt Lengths]Comparison of DEFT-Flatten andRadix Attention in the efficiency ofmulti-step reasoning task sorting.The original prompt length is approx-imately 1K tokens, and we pad it tolengths of 5K, 8K, or 10K tokens.SpeedupPrompt length LL=1k L=5k L=8k L=10kAttention 1.39× 1.71× 1.97× 1.84×Decoding 1.09× 1.37× 1.53× 1.67×
Table 8 :8[Different Model Sizes]  Comparison of decoding latency speedup and Attention/FFN latency ratio (in short as A/F-LR) between DEFT and Radix Attention for Codellama-34B and Codellama-7B models. Radix Attention is the best baseline in decoding latency. b represents the tree width, and t denotes the token tree size. For multi-step reasoning, we test the task sorting whose prompt length is about 1k tokens.MetricModel Size Few-shot Prompting b=30Multi-step Reasoning SortingSpeculative Decoding t=64Decoding Time7B1.34×1.09×1.85×Speedup34B1.23×1.03×1.78×Radix Attention's7B1.271.122.12A/F-LR34B0.800.481.66DEFT-Flatten's7B0.680.890.69A/F-LR34B0.450.420.494.4 ABLATION STUDYWe evaluate the influence of different KV splitting strategies, model sizes, and prompt lengths in this subsection. See more ablations in Appendix A.6, including the influence of different GPUs (Table19), chunk sizes during KV splitting (Figure
Table 9 :9Comparison among DEFT and concurrent works in single-context large-batch sampling scenarios, including Chunk-Attention
Table 10 :10Technique list of DEFT. What we propose is in red. The details of the first four techniques are in Section 3.3, while the details of the following techniques are discussed in this chapter.
Stage 1: calculate partial attention For i=0:2: 1) load QKV Group G i in SM i ; 2) PA i ,LSE i =FlashAttn(G i ); 3) Output PA i ,LSE i Global Memory (HBM) Compute in SMs (with shared memory)
Table 11 :11Notations.
Table 12 :12IO complexity breakdown for various methods. O(1) denotes the IO cost for a single data in the tensor across all layers and heads, which is equivalent to #heads * #layer * dtype_size. The best among all methods in the table is in red, while the (potential) worst is in blue. Query IO is omitted as it is O(klnd head ) for all methods. Here, k is the number of QKV groups: for DEFT-Node k = #node;for DEFT-Node-Chunk k = #node i=1
Table 13 :13Details of generated workloads. For multi-step reasoning, we include these 4 tasks fromBesta et al.   (2023): (1) Sorting 128 numbers (sorting in short); (2) Document merging (document in short);
Table 14 :14[GPU Utilization Microbenchmark]  Latency of a single layer of Attention (in µs), SM Compute Throughput Ratio, Memory Throughput Ratio, and Low Utilization Ratio for DEFT on an NVIDIA A100 (80GB) using the LLama3-8B model (GQA). The workload is speculative decoding with 64 queries and a prompt with 4k tokens. The Compute Throughput Ratio refers to the utilization of the Streaming Multiprocessors (SMs) in the GPU. The Memory Throughput Ratio represents the ratio between actual memory throughput and maximum bandwidth. The Low Utilization Time Ratio is defined as the proportion of time when the Compute Throughput Ratio falls below 5%.MethodAttention Latency Compute Throughout Ratio Memory Throughout Ratio Low Utilization Time RatioDEFT-Node961.387.60%17.39%82.35%DEFT-Flatten226.8221.19%51.91%0.00%
Table 15 :15Inference accuracy of DEFT in attention score and perplexity (PPL). PPL is calculated after 400 iterations of decoding. Vanilla Attention is the implementation from Huggingface Transformers.Relative Attention Error (↓) Perplexity (PPL) (↓) Relative PPL Error (↓)Attention MethodAttention VariationsMHAGQAMHAGQAMHAGQAVanilla Attention--1.0001.002--Radix Attention0.545%0.540%1.0001.0021 × 10 -6 1 × 10 -6DEFT-Node-Chunk 0.403%0.403%1.0001.0021 × 10 -6 4 × 10 -6DEFT-Flatten0.407%0.404%1.0001.0021 × 10 -6 9 × 10 -7
Table 17 :17Average end-to-end IO (TB) during decoding. Data format is Left/Right: (Left) KV Cache IO; (Right) partial results IO, including QK T ,QK ⊤ /sc, Mask M , M + QK ⊤ /sc and Softmax. b means tree width. t denotes the token tree size (i.e., the number of tree-structured queries).⋆ means out of memory for A100 80GB.MethodFew-shot PromptingMulti-Step ReasoningSpeculative Decodingb=20b=30b=50SortingDocumentKeywordSett=32t=64t=128t=256Flash-Decoding17.62/0.00 26.43/0.00 44.05/0.00 59.96/0.00 39.74/0.00 4.68/0.007.01/0.00 128.72/0.00 255.16/0.00⋆⋆Tree Attention-Medusa1.68/1.052.10/1.982.94/4.61 12.40/3.69 10.57/3.24 0.58/0.181.04/0.274.02/4.034.15/8.334.18/16.77 4.32/34.70Radix Attention17.62/0.00 26.43/0.00 44.05/0.00 59.96/0.00 39.74/0.00 4.68/0.00 7.01/0.00 131.45/0.00 256.79/0.00 522.05/0.00 1044.10/0.00 DEFT-Flatten 1.68/0.00 2.10/0.00 2.94/0.00 12.40/0.01 10.57/0.01 0.58/0.00 1.04/0.00 4.10/0.00 4.11/0.00 4.16/0.00 4.35/0.00 IO reduction of DEFT-Flatten(%) 90.47/100.00 92.1/100.00 93.33/100.00 79.32/99.73 73.40/99.70 87.61/100.00 85.16/100.00 96.88/100.00 98.40/100.00 99.20100.00 99.58/100.00
Table 18 :18[Ablation Study of Model Size and Prompt Length] Comparison of decoding speedup and Attention/FFN latency ratio (A/F-LR) between DEFT and Radix Attention for Codellama-34B and Codellama-7B across varying prompt lengths in the sorting reasoning task. Radix Attention is the best baseline in decoding latency.MetricModel Size Prompt Length=1k Prompt Length=5k Prompt Length=8kDecoding latency Speedup7B 34B1.09× 1.03×1.37× 1.18×1.53× 1.28×Radix Attention's A/F-LR7B 34B1.12 0.481.89 0.862.50 1.16DEFT-Flatten's A/F-LR7B 34B0.89 0.421.09 0.571.25 0.67
Table 19 :19[Different GPUs] Speedup of DEFT in average attention latency (second) with NVIDIA RTX 4090 (24GB) for LLama3-8B model(GQA). Radix Attention is the best baseline in decoding latency.Ablation: Different Model Architectures. See Table20 and Table 21. DEFT-Flatten can both accelerate the attention computation of LLM models with different architectures (MHA and GQA) significantly.MemoryMethodFew-shot Prompting-b=30 Multi-Step Reasoning-Sorting Speculative Decoding-t=64Radix Attention4.2626.3633.63PagedDEFT-Node-Chunk3.0724.6115.39DEFT-Flatten2.9523.8614.04Attention Speedup over the best decoding1.44×1.10×2.40×
Table 20 :20[Different Model Architectures(GQA)] Speedup of DEFT in average attention latency (second) with NVIDIA A100(80GB) for Codellama-34B model(GQA). Radix Attention is the best baseline in decoding latency.MemoryMethodFew-shot Prompting-b=30 Multi-Step Reasoning-Sorting Speculative Decoding-t=64Radix Attention16.8595.14164.33PagedDEFT-Node-Chunk16.15103.1581.74DEFT-Flatten9.6284.3048.76Attention Speedup over the best decoding1.75×1.13 ×3.37×A.8 DEFT-NODE ALGORITHM
Table 21 :21[Different Model Architectures(MHA)] Speedup of DEFT in average attention latency (second) with NVIDIA A100(80GB) for Codellama-7B model(MHA). Radix Attention is the best baseline in decoding latency.MemoryMethodFew-shot Prompting-b=30 Multi-Step Reasoning-Sorting Speculative Decoding-t=64Radix Attention12.3953.9696.55PagedDEFT-Node-Chunk10.1254.2048.96DEFT-Flatten8.2443.9136.48Attention Speedup over the best decoding1.50×1.23×2.65×
			A100's HBM has 1.5-2TB/s bandwidth and 40-80GB; its shared memory has 19TB/s bandwidth and 20MB.
			GPUs utilize a vast array of threads to execute operations known as kernels
			Considering a microbenchmark that DEFT-Node with 64 queries shares a prompt of 4k tokens, the SM utilization is below
			5% for 82.35% time of attention computation, as shown in Table14.
			e.g. when a node is pruned in the decoding tree, its KV space will be evicted using a Remove operation.
			Note that QK T , QK ⊤ sc , M + QK ⊤ sc and Softmax will load and write, so the IO cost contains a round-trip of memory access between HBM and shared memory, as shown in Figure8.