BASS: Batched Attention-optimized Speculative Sampling
Haifeng Qian Sujan Kumar Gonugondla Sungsoo Ha Mingyue Shang Sanjay Krishna Gouda Ramesh Nallapati Sudipta Sengupta Xiaofei Ma Anoop Deoras

A self-consistent model for dust settling and the vertical shear instability in protoplanetary disks
    Satoshi Okuzumi1
    
====================================================================================================



*Equal contribution.
^1AWS AI Labs.
^2AWS NGDE.
^3Amazon AGI (work done at AWS).
Correspondence to: Haifeng Qian <qianhf@amazon.com>, Sujan Kumar Gonugondla <gsujan@amazon.com>.
footnote


Speculative decoding has emerged as a powerful method to improve latency and throughput in hosting large language models.
However, most existing implementations focus on generating a single sequence.
Real-world generative AI applications often require multiple responses and how to perform speculative decoding in a batched setting while preserving its latency benefits poses non-trivial challenges.
This paper describes a system of batched speculative decoding that sets a new state of the art in multi-sequence generation latency and that demonstrates superior GPU utilization as well as quality of generations within a time budget.
For example, for a 7.8B-size model on a single A100 GPU and with a batch size of 8, each sequence is generated at an average speed of 5.8ms per token, the overall throughput being 1.1K tokens per second.
These results represent state-of-the-art latency and a 2.15× speed-up over optimized regular decoding.
Within a time budget that regular decoding does not finish, our system is able to generate sequences with HumanEval Pass@First of 43% and Pass@All of 61%, far exceeding what's feasible with single-sequence speculative decoding.
Our peak GPU utilization during decoding reaches as high as 15.8%, more than 3× the highest of that of regular decoding and around 10× of single-sequence speculative decoding.




§ INTRODUCTION


In recent years, generative large language models (LLMs) have rapidly gained popularity due to their ability to generalize across a wide variety of tasks. These models are increasingly deployed commercially for applications such as coding assistants, writing aids, conversational agents, search and summarization tools and more. The accuracy performance of LLMs has been shown to scale with model size, with larger models demonstrating improved capabilities <cit.>. However, this improvement comes at the cost of greater latency during inference and increased computational requirements.



Most popular LLMs are transformer-based decoder models. The inference speed of these models is often limited by memory bandwidth on typical hardware like GPUs.  This is because GPUs tend to have much higher compute throughput relative to memory bandwidth. The auto-regressive decoding process of these models, where each output token is generated sequentially conditioned on previous tokens, means the entire model parameters need to be fetched from memory for each generated token. This sequential nature prevents parallelization during inference, resulting in under-utilization of available compute resources. For example, for both models in Figure <ref>, single-sequence regular decoding utilizes only 0.4% of GPU FLOPS.

To improve GPU utilization, batching multiple sequences is often employed to amortize the memory I/O costs across a batch and thereby utilize more FLOPS per memory I/O. However, large batch sizes are needed to effective utilize GPU compute, resulting in higher latency for individual sequences that are batched as well as bigger memory footprints.  With larger model sizes, memory bottleneck becomes a challenge and limits allowable batch sizes.
In Figure <ref> for example, the highest GPU utilization by batched regular coding is only 4.8% before going out-of-memory.

Speculative decoding has emerged as an effective approach to improve latency of LLMs by increasing GPU utilization. The key idea is to draft a few tokens (typically by using a smaller LLM) and verify their correctness with the main LLM. By processing the draft tokens in parallel, speculative decoding amortizes the memory I/O of model parameters across the tokens. Despite its advantages, speculative decoding has limitations: It processes a single sequence at a time, restricting the parallelism to the number of draft tokens. This caps the potential GPU utilization improvements.

To address this, we present  () – a parallel speculative decoder that handles multiple sequences simultaneously.
 increases GPU utilization by parallelism across both the batch dimension and the draft-token dimension.
We implement customized CUDA kernels to handle ragged tensors during attention calculation, which are a challenge posed by batched speculative decoding, and design a heuristic to dynamically adjust draft length for each step.
As illustrated in Figure <ref>,  achieves latency and GPU utilization that are substantially improved from prior regular and speculative decoders.
By comprehensive experiments on three different models including CodeGen and OPT, we study these trends as well as accuracy benefits of .
We study the impact of draft model design on overall system performance as well as that of algorithmic choices in attention kernels and draft lengths.
I think we need to briefly summarize the design of proposed methods in high level. Also list the contributions of this paper in the end of Introduction.



§ BACKGROUND




 §.§ Inference with LLMs





This paper focuses on transformer-based <cit.> decoder-only generative LLMs. The standard inference of these LLMs can be divided into two phases:
(a) Context encoding phase where the input prompt is processed in parallel to encode contextual information, and
(b) Incremental decoding phase where the model auto-regressively generates output tokens one by one based on the encoded context (Figure <ref>(a)).

Consider a decoder-only transformer <cit.> architecture with alternatively stacked feed-forward network layers and attention layers. In the attention mechanism (Figure <ref>(b)), key (k_i), value (v_i), and query (q_i) vectors are first computed by projecting the token embeddings for each position i. The queries are then used to calculate the relevance of the current token with past positions, by estimating their correlation with the past keys.

During the context encoding phase, all prompt tokens are processed in parallel. The attention keys and values for all context tokens (K and V tensors) are cached during this phase. This phase exhibits high GPU utilization.

The incremental decoding phase is bottlenecked by memory I/O from repeated fetching of model parameters and the KV cache as each output token is decoded.
This phase is typically the dominant portion of inference time and exhibits low GPU utilization.
It is the focus of our optimizations.



 §.§ Speculative decoding


Speculative decoding <cit.> is a popular technique to reduce latency of LLM inference. As illustrated in Figure <ref>, the idea is to use a small draft model to generate k draft tokens. They are then processed by the main model as incremental context encoding to decide which draft tokens to accept.



The number of draft tokens to accept is decided based on the probabilities of generating these tokens according to the main and draft models. In the case of rejection, a corrected token is sampled from the outputs of the main model. Overall, this decision process is stochastic and is designed to be equivalent to sampling from the main model’s distribution <cit.>. For example, we may accept the first five tokens, correct the sixth token, and then generate new draft tokens from the seventh position.

Latency benefit comes from the higher GPU utilization associated with incremental context encoding rather than auto-regressive decoding. More than 2× latency reduction has been reported in  literature <cit.>.



  §.§.§ Limitations of speculative decoding


A major limitation of speculative decoding is that batch size of the main model's generation
is preferably just 1, which is the setting in most existing works. It is straightforward to see why. In a naive implementation with batch size more than 1, we stop accepting tokens at the first reject position in the batch and hence lose some latency benefit. For illustration, let’s make a simplistic assumption that each token generated by the draft model has an independent chance p of getting accepted, then the number of output tokens per draft has a geometric distribution with an expected value of 1/(1-p). For example, if p=80%, then on average the decoding process moves forward by 5 tokens per draft. With a batch size of b, the probability of acceptance per position becomes p^b. For a batch size of five as an example, the probability of acceptance per position becomes 33% and on average the decoding process moves forward by merely 1.5 tokens per draft, and we have lost most, if not all, of the latency benefit.

To retain the latency benefit with b>1, we need to accept variable numbers of draft tokens across a batch.
This poses challenges that no prior work has addressed efficiently and the existing systems remain single-sequence inference.



§ 



 () extends speculative decoding by enabling batch processing across multiple sequences. While speculative sampling improves GPU utilization for a single sequence, parallelism is limited to the small number of draft tokens per sequence (typically 5-10). Batching sequences with speculative decoding can further maximize GPU usage. To fully realize these benefits, specialized tensor manipulations and CUDA kernels are required.



 §.§ Challenges with batching


One challenge with batched speculative decoding stems from the uncertainty in the numbers of acceptable draft tokens for each sequence, which vary across the batch.
LLM inference kernels are designed to handle regular shaped tensors, primarily driven by CUDA restrictions.
If we enforce a uniform sequence length across the batch, that would result in less accepted draft tokens and in diminishing benefits as discussed in Section <ref>. 

In order to maintain the performance gains of speculative sampling, we need to be able to accept variable numbers of tokens across the batch.
This will result in variable sequence lengths across the batch and consequently ragged-shape K and V tensors.
In particular, this will affect the computations in the attention layer where we may not be able to batch the operations into a single kernel.
Handling this effectively needs careful design considerations.

Another challenge is the choice of draft lengths.
Although prior experimental systems tend to use a fixed draft length, real-life deployment requires adaptive draft lengths because different prompts may lead to different degrees of alignment between draft and main models during generation and hence different optimal draft lengths.
For efficient incremental context encoding by the main model, we need to choose a uniform draft length across the batch at each step, and this decision needs to balance the needs of the multiple sequences.



 §.§ Proposed method




The attention computation flow, illustrated in Figure <ref>(a), involves a GEMM[General matrix multiplication (GEMM).] operation between the query tensor Q of the current tokens and the key tensor K of all tokens processed so far, a softmax operation that outputs P =softmax (Q^TK/c), and another GEMM operation between P and value tensor V of all tokens processed so far.
There are three ragged tensors, K, V and P.
We propose two variants: -PAD and -SPLIT as illustrated in Figure <ref>(b) and Figure <ref>(c) respectively.
They implement the two GEMMs differently and share the same softmax operation: we simply launch separate softmax kernels, one for each sequence.

In the -PAD approach, we pad the K, V and P tensors along the sequence length dimension to match the longest sequence of the batch and use the padded tensors for computations.
We assign zero probabilities for the padded tokens in P.
-PAD does not incur additional cost of launching kernels, but we waste some compute to perform dummy computations with the padded elements.

The -SPLIT approach is derived from the insight that attention operation is not associated with any model parameters and therefore applying batching to attention has no benefit of reducing the amount of GPU memory reads.
In this approach, we break up the KQ GEMM and the PV GEMM into smaller per-sequence kernels, so that we can handle the variable sequence-length dimension in K, V and P tensors, as shown in Figure <ref>(c).
Note that these separate kernels can be launched and executed in parallel.
Since there is no sharing of memory reads among these separate kernels, the only extra cost that we pay is the cost of launching them.
-SPLIT does not waste any compute.

-PAD and -SPLIT apply to both the main and the draft models and apply to both token generation and incremental context encoding. With either approach, we can now let each sequence proceed at its own pace according to its own reject points and let sequences in the batch have different lengths.

Note that other steps, including the feed-forward network, the KQV projection layer, and the projection layer at end of attention, all remain the same and remain regularly batched to share memory reads of model parameters.

The comparison between -PAD and -SPLIT depends on the application scenario.
We find -PAD more attractive when the sequence lengths are closer to each other and -SPLIT more favorable when the sequence lengths across batch vary by a large margin.
Most results in Section <ref> are based on -PAD and their comparison results are in Section <ref>.



Algorithm <ref> describes the heuristic that we use to dynamically adjust draft lengths.
The rationale is to increase draft length when at least one sequence has accepted all draft tokens in the last speculative decoding step and to decrease it otherwise.
The speed of decrease is larger when the current draft length is larger and when it is a consecutive step of decrease.
However, the next draft length is never decreased to be less than the max number of accepted tokens in the batch.
We empirically chose the parameters of l_0=7, l_incre=2, l_mod=10 and l_limit=32.
Comparisons against constant draft lengths are in Section <ref>.



§ EXPERIMENTS


In this section we demonstrate the benefits of  over batched auto-regressive regular decoding (RD) and single-sequence speculative decoding.

If space allows, it's better to add a paragraph here talking about the structure of this section. e.g. in this section, we first describe the experimental settings and then we report the results on different down-stream tasks including xxx, xxx and xxxx. Our experiments shows (high-level observations.)




 §.§ Setup


Inference setup and CUDA kernels:
All experiments throughout this paper are conducted on a single A100 GPU with 40GB memory.
All inference runs, except for the “vLLM” rows in Tables <ref> and <ref>, use a modified version of DeepSpeed[<https://github.com/microsoft/DeepSpeed>] (DS), including both regular decoding and  runs.
As can be seen in the tables, the regular decoding latencies are at the state of the art and comparable to those reported in <cit.> for both FP16 and INT8.
The vLLM runs use the latest vLLM version[<https://github.com/vllm-project/vllm>] (v0.3.0) and all sequences start immediately and hence result in the best possible latencies.
Our modifications to DeepSpeed include:


  * Kernels for quantizing both weights and activations to INT8 for all linear layers. We use CUTLASS[<https://github.com/NVIDIA/cutlass>] INT8→INT32 kernels for GEMM calls and modify them and other layers to fuse quantization and de-quantization operators.

  * Kernels for attention calculations to address the ragged-tensor challenge in batched speculative decoding without sacrificing latency, as discussed in Section <ref>.


Models and tasks: We report experimental results on three main models with their respective draft models and tasks:


  * OPT 13B as the main model and OPT 125M or 350M as the draft model <cit.>.
Following the same experimental setting as <cit.>, we use the XSum task with 11,334 test examples <cit.>, use 1-shot prompting, generate 128 tokens per sequence, and use ROUGE-2 <cit.> as the metric to verify accuracy.

  * CodeGen-Mono 16B as the main model and CodeGen-Mono 350M as the draft model.
We use the HumanEval task with 164 examples and use the Pass@K accuracy metric <cit.>,
and we generate 256 tokens for each sequence.

  * A 7.8B model trained on text and code as the main model and one of three draft models with sizes 310M, 510M and 1B.
We again use the HumanEval task.


Latency metrics: We use the metric of per-token latency for each generated sequence.
For regular decoding, this value is the same across a batch.
For speculative decoding, it varies within a batch and therefore we report three metrics: per-token latency of the first finished sequence in a batch, per-token latency of the last finished sequence in a batch, and per-token latency averaged across a batch, where each of the three is then averaged across examples in a task dataset.



 §.§ OPT on XSum


Table <ref> shows the accuracy and latency results of the OPT 13B model on the XSum task, with OPT 125M as the draft model.
As expected, the results suggest neutral accuracy between regular decoding and speculative decoding, while speculative decoding provides up to 2.81× speed up for finishing the first sequence and up to 2.34× speed up on average for all sequences.
In a real-life application, and particularly in the scenario of generating multiple sequences for the same prompt, we can respond to the user as soon as the first sequence finishes while the other additional recommendations continue to generate.
Therefore, speeding up the first sequence by 2.05×–2.81× implies a significant improvement in user-perceived latency.

The latency divergence between the first and last finished sequences increases with batch size. However, the last sequence latency is not as important in a real-life application because, when generating multiple sequences for the same prompt, we can simply choose a cut-off latency limit and return, e.g., five finished sequences out of a batch of eight.





 §.§ Performance on code generation


Table <ref> shows the accuracy and latency results of the CodeGen-Mono 16B model on the HumanEval task, with CodeGen-Mono 350M as the draft model.
The trends are similar to Table <ref>: accuracy is neutral between regular decoding and speculative decoding; the first finished sequence is sped up by up to 2.65×, representing a significant improvement in user-perceived latency; the average latency of all sequences is reduced by up to 2.43×; the latency divergence between the first and last finished sequences increases with batch size.

Unlike Table <ref>, the accuracy metric in Table <ref> increases with batch size: it is the percentage of examples where at least one correct generation exists in the batch. It represents an accuracy benefit of batched over single-sequence speculative decoding and more results will be presented in Section <ref>.

Overall the speed-up ratios in Table <ref> are less than those in Table <ref>, and we hypothesize that the main factor is the larger size of the draft model. 


    

Table <ref> shows the accuracy and latency results of a custom 7.8B model, which was trained on text and code, on the HumanEval task, with a 310M-size draft model which is the first in Table <ref>.
The overall trends are similar to those in Table <ref> except that the speed-up ratios are substantially higher: the first finished sequence is sped up by up to 3.23×, and the average latency of all sequences is reduced by up to 2.94×.
We hypothesize that the draft model architecture choice is the main reason and we will look at impact of draft model designs next.



 §.§ Impact of draft model choices



Table <ref> compares three draft models, all GPT2-like models with different architecture parameters as listed in the first three rows.
They are trained with the same data and for the same amount of tokens.
According to the fifth row, i.e., their stand-alone accuracy performance on HumanEval, the second draft model is more performant, likely due to its greater depth.
This is also supported by the sixth row which shows the chance of a draft token getting accepted during speculative decoding, and indeed the second draft model aligns better with the main model.
However, because the second draft model itself takes higher latency to generate draft tokens, the overall latency of speculative decoding is increased despite accepting more draft tokens.

Table <ref> is a similar comparison between two OPT draft models.
Surprisingly OPT 350M is worse than OPT 125M in both stand-alone ROUGE-2 score on XSum and token acceptance rate which represents worse alignment with the main model of OPT 13B.







 §.§ Benefits of batched speculative decoding



Figure <ref> emulates an application scenario where we have an end-to-end time budget of 2.5 seconds to generate 256-long sequences for any given prompt from HumanEval.
According to Table <ref>, regular decoding under any setting would be unable to finish before time runs out, while single-sequence speculative decoding is able to return an answer with accuracy that corresponds to the left end point of the curves.
As the batch size increases, the probability (Pass@Finished) that at least one returned sequence solves the coding task is increased up to 61%, and the probability (Pass@First) that we display a correct answer first to user is increased up to 43% with a simple ranking strategy using model confidence of mean-logP value.
Both numbers are substantially higher than the mid-thirties accuracy by single-sequence speculative decoding.
A real-life application would use a domain-specific stopping criteria instead of a fixed length and a more sophisticated ranking method, but the relative comparisons among the competing methods are as captured by Figure <ref> and  is clearly superior.





 §.§ Ablation studies



In Table <ref>, we compare latency  when certain alternative implementation choices are used.
With -SPLIT, we launch per-sequence kernels to handle ragged tensors as illustrated in Figure <ref>(c).
The results suggest that the cost of launching more CUDA kernels in -SPLIT out-weights the cost of wasted compute in -PAD.
Note that this relation is task dependent and may change when the sequence lengths across a batch vary by a large margin.
With “fixed draft size”, we use a constant draft length instead of Algorithm <ref> that dynamically modifies draft length.
The results suggest that both the efficient attention calculation and the draft-length heuristic are important to the performance of .





§ RELATED WORK


Efficient inference of LLMs has been a popular research topic in recent years. 
Model quantization techniques <cit.> employ lower-precision representations for model parameters (e.g., INT8, INT4, FP8) without significantly compromising accuracy. Pruning <cit.> reduces memory footprints via sparsity.
Sparse attention techniques <cit.> limit the number of tokens to attend to in order to reduce the complexity of attention layers, and thereby extend the maximum allowable sequence length.

Since its introduction, speculative decoding has seen numerous variations and improvements. Some proposals take a draft-model-free approach, by using an n-gram model to predict draft tokens <cit.>, or by using the model embedding to predict drafts <cit.>. SpecInfer <cit.> uses a draft tree to generate and organize multiple drafts for the main-model sequence in order to maximize the number of tokens accepted per step. <cit.> study the relation between batch size and the optimal fixed draft length for max throughput; it is however based on a primitive prototype implementation: rejected draft tokens are masked rather than discarded, which achieve sequence lengths that are uniform across a batch yet are unnecessarily large and inefficient.
The above works on speculative decoding are orthogonal to the discussions and ideas in this paper and can be combined. The conclusion presented in <cit.> may change with the kernel implementations in this paper.




§ CONCLUSION


This paper presents  (), a system that advances the state of the art in fast multi-sequence generation by LLMs.
By addressing the unique challenges of extending speculative decoding to batched inference without sacrificing latency, we demonstrate superior latency, GPU utilization as well as accuracy of generations within a time limit.




§ LIMITATIONS


This work, while advancing the state of the art, does not solve the efficient inference challenge of LLMs.
For example, GPU utilization during the context encoding phase of LLM inference can be over 70% in our system, while the best achievable utilization during the incremental decoding phase is 15.8% in this paper.
Although this is already significantly better than previous works, there is clearly substantial room to innovate and improve.



§ ETHICAL IMPACT


This work aims to increase the efficiency of deploying LLMs by utilizing the compute resources efficiently.
It can reduce carbon emissions associated with LLM deployment.
Additionally, driving down infrastructure costs can potentially encourage broader LLM adoption.
Impact of increased LLM usage on the society and associated risks are difficult to forecast.








§ APPENDIX





 §.§ Quantization schemes and mechanisms


This section describes the quantization schemes and kernels used for INT8 inference. Since granular assignment of precision improves the accuracy of quantized models, we assign the quantization ranges to the smallest granularity that allows us to compute the matrix multiplications in integer arithmetic, i.e., the granularity is set to the inner-product dimension. This translates to per-channel quantization for weights, dynamic per-token quantization for activation, and dynamic per-head and per-token quantization for keys, queries, and values.

To mitigate the overheads associated with quantize and dequantize operations in the inference pipeline on a GPU, we have employed kernel fusion techniques as shown in Figure <ref>. This involves amalgamating multiple operations to minimize CUDA kernel calls and memory fetches, thereby minimizing computation time.

Dynamic quantization can incur substantial overheads unless it is integrated with other operations in the inference pipeline. We fuse the quantize operation with layer-norm, GeLU, and transpose operations across the network. This approach eliminates the need for redundant memory reads, for example, reading the same data for layer-norm and quantization separately.

We use CUTLASS INT8 GEMM kernels to fuse the dequantize operation and other element-wise computations, such as bias and residual additions with the GEMM operations. To optimize performance for small batch sizes, we adopt a strategy of pre-multiplying the weights and activation scales during the activation quantization operation, and subsequently retrieving them during the epilogue phase of the GEMM operations. The resulting fused GEMM blocks yield floating-point precision outputs, namely FP16, BF16 or FP32, depending on the selected format. 








 §.§ Draft model choice and training


For a draft model to be effective we need to maximize the number of tokens accepted by the main model while maintaining low per-token latency. Given the requirement, we have investigated architecture selection and observed that, at a fixed parameter count, having more attention heads (wider model) is better than having more layers with fewer attention heads (deeper model) since we have similar representation capabilities with wider-but-shallow models as narrow-but-deep models but at a much lower latency. We summarize the draft model architecture choices in Table <ref>.

We trained each of these draft models using the same data for the main model with a context size of 2048 and a global 512 batch size across 8 servers each with 8 40GB Nvidia A100 GPUs. This translates to approximately 1 million tokens per batch. Using a learning rate of 3.5 × 10^-4 we train for 300k steps.
We use AdamW optimizer <cit.> with β_1 = 0.9, β_2 = 0.95, and ϵ = 10^-8. The warm-up steps were set to 2000, and a cosine annealing learning rate schedule was employed after reaching the peak learning rate.
The minimum learning rate was set to 10% of the peak learning rate.
We use BF16 <cit.> precision and set gradient clipping to 1.0 to enhance training stability.


