Overview

8 Attention optimization

This chapter focuses on attention as the main inference bottleneck in large language models, especially when contexts get longer. It explains that attention is expensive not only because of computation, but also because the KV cache grows dynamically with every generated token and can quickly consume GPU memory. To address that, the chapter first explores KV cache quantization as a practical optimization, then moves on to a more structural approach: identifying and removing redundant attention layers.

In the first part, the chapter shows how KV cache quantization works in practice with Hugging Face and vLLM, using different GPUs to highlight that the best choice depends heavily on hardware. Quantizing the cache lowers dynamic memory use and can substantially increase the number of tokens a model can handle, but it may also hurt throughput if the hardware lacks native support for the chosen precision. The experiments also make a key point clear: weight quantization and KV cache quantization are separate levers. Weight quantization can improve throughput and free static memory, while cache quantization mainly expands context capacity.

The second part analyzes attention redundancy by measuring each attention module’s contribution through cosine similarity between its input and output, then removing the least important ones. The chapter shows how to physically delete attention submodules, redefine the model’s forward pass, and save and reload the modified architecture safely through custom model classes and config changes. Results show that moderate attention pruning can preserve many benchmark scores while reducing memory, but aggressive pruning harms long-form generation and can cause repetition loops. The chapter concludes that attention reduction and cache quantization can complement each other, but the right trade-off depends on model size, hardware, and whether the task is classification-like or truly generative.

KV cache quantization write-read cycle. At each generation step, the K and V tensors produced by the Attention module are compressed from FP16 to 4-bit before being written to GPU memory. When the next token is processed, the cached values are dequantized back to FP16 before the attention computation. The cycle repeats for every generated token.
KV cache quantization write-read cycle. At each generation step, the K and V tensors produced by the Attention module are compressed from FP16 to 4-bit before being written to GPU memory. When the next token is processed, the cached values are dequantized back to FP16 before the attention computation. The cycle repeats for every generated token.
Three bar charts comparing static VRAM, dynamic VRAM delta, and throughput across three inference configurations of Llama-3.2-3B on a T4 GPU: FP16 baseline, 4-bit weight quantization (BitsAndBytes), and FP16 with 4-bit KV cache quantization (HQQ).
Three bar charts comparing static VRAM, dynamic VRAM delta, and throughput across three inference configurations of Llama-3.2-3B on a T4 GPU: FP16 baseline, 4-bit weight quantization (BitsAndBytes), and FP16 with 4-bit KV cache quantization (HQQ).
Three bar charts comparing static VRAM, dynamic VRAM delta, and throughput across three inference configurations of Llama-3.2-3B on an L4 GPU: BF16 baseline, 4-bit weight quantization (BitsAndBytes), and BF16 with 4-bit KV cache quantization (HQQ).
Three bar charts comparing static VRAM, dynamic VRAM delta, and throughput across three inference configurations of Llama-3.2-3B on an L4 GPU: BF16 baseline, 4-bit weight quantization (BitsAndBytes), and BF16 with 4-bit KV cache quantization (HQQ).
VRAM allocation across inference engines and quantization strategies. In Hugging Face, the KV cache grows dynamically into available memory. In vLLM, a fixed memory budget is divided at startup between model weights and a pre-allocated KV block pool. Reducing weight precision to NF4 shrinks the weight footprint, expanding the KV block pool within the same budget. Quantizing the KV blocks themselves reduces each block's size, fitting more tokens into the same pool.
VRAM allocation across inference engines and quantization strategies. In Hugging Face, the KV cache grows dynamically into available memory. In vLLM, a fixed memory budget is divided at startup between model weights and a pre-allocated KV block pool. Reducing weight precision to NF4 shrinks the weight footprint, expanding the KV block pool within the same budget. Quantizing the KV blocks themselves reduces each block's size, fitting more tokens into the same pool.
Comparison of the three configurations run on a T4 GPU: KV cache capacity in tokens (left), percentage gain over baseline (center), and generation throughput in tokens per second (right). On this GPU, FP8 delivers the highest capacity gain (+111.1%) but penalizes throughput, while NF4 triples the baseline throughput.
Comparison of the three configurations run on a T4 GPU: KV cache capacity in tokens (left), percentage gain over baseline (center), and generation throughput in tokens per second (right). On this GPU, FP8 delivers the highest capacity gain (+111.1%) but penalizes throughput, while NF4 triples the baseline throughput.
The same three experiments run on an L4 GPU. On this GPU with native FP8 support, KV cache quantization doubles the available capacity (+105.2%) while keeping throughput virtually identical to the baseline (35.8 vs 35.6 tok/s). NF4 weight quantization offers a different profile: lower capacity gain (+31.8%), but throughput more than twice the baseline (82.5 tok/s). Each technique serves a different goal.
The same three experiments run on an L4 GPU. On this GPU with native FP8 support, KV cache quantization doubles the available capacity (+105.2%) while keeping throughput virtually identical to the baseline (35.8 vs 35.6 tok/s). NF4 weight quantization offers a different profile: lower capacity gain (+31.8%), but throughput more than twice the baseline (82.5 tok/s). Each technique serves a different goal.
Internal structure of a LlamaDecoderLayer showing the two hook anchor points used to measure attention layer importance. Hook 1 intercepts the hidden state at input_layernorm, capturing X_A before the attention computation. Hook 2 intercepts the tensor at post_attention_layernorm, capturing Y_A after the attention output has been added back through the residual connection.
Internal structure of a LlamaDecoderLayer showing the two hook anchor points used to measure attention layer importance. Hook 1 intercepts the hidden state at input_layernorm, capturing X_A before the attention computation. Hook 2 intercepts the tensor at post_attention_layernorm, capturing Y_A after the attention output has been added back through the residual connection.
Attention Module importance in Llama-3.2-3B, sorted by layer index. Layers 0 and 1 stand clearly above the rest. Layers 2 through 17 form a moderately active band. The genuinely low-score region concentrates in layers 18 to 25, where the three removal candidates (marked with a different pattern) fall below the dashed threshold line. Layers 26 and 27 show a slight recovery..
Attention Module importance in Llama-3.2-3B, sorted by layer index. Layers 0 and 1 stand clearly above the rest. Layers 2 through 17 form a moderately active band. The genuinely low-score region concentrates in layers 18 to 25, where the three removal candidates (marked with a different pattern) fall below the dashed threshold line. Layers 26 and 27 show a slight recovery..
Save and reload pipeline for a structurally modified model. During the save phase, the pruned layer indices and the custom class reference are registered in config.json before serializing the weights. During the load phase, PrunedLlamaForCausalLM rebuilds the patched architecture before the weights are loaded, so attention keys with no target in the skeleton are skipped.
Save and reload pipeline for a structurally modified model. During the save phase, the pruned layer indices and the custom class reference are registered in config.json before serializing the weights. During the load phase, PrunedLlamaForCausalLM rebuilds the patched architecture before the weights are loaded, so attention keys with no target in the skeleton are skipped.
Benchmark scores for Llama-3.2-3B across four configurations. Degradation between 3 and 6 layers removed is negligible across all benchmarks, but Lambada shows progressive sensitivity to attention pruning at all ratios, and collapses almost completely at 15 layers removed, along with the rest of the tasks.
Benchmark scores for Llama-3.2-3B across four configurations. Degradation between 3 and 6 layers removed is negligible across all benchmarks, but Lambada shows progressive sensitivity to attention pruning at all ratios, and collapses almost completely at 15 layers removed, along with the rest of the tasks.
The four pruning strategies explored in He et al. (2024). Each column shows which modules are removed from a Transformer block (crossed out) and which are preserved. The bar at the bottom represents the SDR (Speedup Degradation Ratio). A shorter bar indicates a better trade-off between speed gain and quality loss. Attention Drop achieves the lowest SDR by a wide margin, making it the most efficient strategy despite leaving MLP layers intact.
The four pruning strategies explored in He et al. (2024). Each column shows which modules are removed from a Transformer block (crossed out) and which are preserved. The bar at the bottom represents the SDR (Speedup Degradation Ratio). A shorter bar indicates a better trade-off between speed gain and quality loss. Attention Drop achieves the lowest SDR by a wide margin, making it the most efficient strategy despite leaving MLP layers intact.

Summary

  • The dynamic memory consumption of the attention mechanism scales with context length. Quantizing the KV cache reduces this memory footprint without altering the model weights, allowing longer prompts to be processed and batch sizes to be increased in production engines like vLLM.
  • Weight quantization and KV cache quantization are independent levers that act on different areas of GPU memory. Applying one does not interfere with the other, and both can be combined in the same inference pipeline.
  • The effectiveness of KV cache quantization depends on both the inference engine and the GPU architecture. On GPUs with native FP8 support, vLLM doubles the available KV token capacity with no throughput penalty; on older architectures like the T4, the same operation introduces a software overhead that penalizes generation speed.
  • Attention layers are significantly more redundant than MLP layers. Anchoring PyTorch hooks at input_layernorm and post_attention_layernorm gives finer-grained importance scores than block-level measurement.
  • You can modify a model's execution flow without retraining it by creating a custom class that inherits from the original architecture and overrides its forward() method. This technique is reusable across any structural modification that requires bypassing or replacing internal modules.
  • Saving and reloading a structurally modified model requires registering the pruned layer indices in config.json and shipping a custom class alongside the weights. Without this mechanism, from_pretrained reconstructs the original architecture and fails at the first forward pass.
  • Multiple-choice benchmarks do not reveal the full cost of attention pruning. Benchmarks like Lambada and free-text generation expose a degradation that static, closed-set evaluation hides entirely.
  • The optimal pruning strategy depends on the production task. The cosine similarity metric that identifies attention layers as redundant in generative models points to MLP layers as the expendable component in dense retrieval architectures, where the conclusions are precisely inverted.

FAQ

What is the main performance bottleneck in LLM attention during inference?The attention mechanism is a major bottleneck because both its computation and its dynamic memory usage grow as the context length increases. This limits how much text the model can process and how large a batch it can handle.
What is KV cache quantization?KV cache quantization compresses the Key and Value tensors stored during generation from their default 16-bit precision to smaller formats such as FP8 or even 4-bit. This reduces dynamic memory consumption while preserving the cache needed for fast autoregressive decoding.
Why does the KV cache need to stay enabled during generation?Disabling the KV cache would force the model to recompute attention tensors for every new token, which severely slows inference. Keeping the cache lets the model reuse previously computed K and V tensors and maintain decoding speed.
How does Hugging Face enable quantized KV cache support?In Transformers, quantized KV cache support is enabled by passing a QuantizedCacheConfig together with cache_implementation="quantized" to model.generate(). Without the cache implementation flag, the cache configuration is ignored.
Why does quantized KV cache sometimes increase static VRAM on a T4?The increase is caused by the HQQ kernel reserving some memory up front. That extra static allocation is offset by the reduction in dynamic VRAM growth during generation, and it does not appear on the L4 in the same way.
How do T4 and L4 GPUs differ in KV cache quantization behavior?On the T4, FP8 KV cache quantization increases capacity but can reduce throughput because the GPU lacks native FP8 acceleration. On the L4, FP8 is handled efficiently, so capacity roughly doubles with almost no speed loss.
Why is attention importance measured with cosine similarity between two activations?The method compares the input to the attention phase with the output after attention and its residual connection. A lower similarity means the attention layer changed the representation more, which indicates higher importance; higher similarity suggests redundancy.
How are attention layers selected for removal?Layers are scored by attention importance, sorted in ascending order, and the lowest-scoring layers are chosen. In the chapter’s example, layers 21, 22, and 23 were selected because they had the smallest importance scores.
Why is custom model code needed after physically removing attention modules?Saving a modified model only stores weights and configuration, not the custom Python logic that changes the forward pass. A custom class is needed to rebuild the pruned architecture on reload and avoid missing-key or random-initialization issues.
What is the main trade-off of attention pruning?Attention pruning reduces memory use and can improve efficiency, but it may hurt generation quality, especially in long-form autoregressive text. Small pruning ratios can be tolerated well, while aggressive pruning can cause repetition loops or collapse in output quality.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free