When generating sequences with LLMs, how can you handle long context lengths efficiently? Discuss techniques for managing long inputs during real-time inference.
Efficient long-context LLM inference addresses two distinct bottlenecks: quadratic O(n^2) prefill compute and linear O(L n) KV-cache HBM bandwidth/capacity during autoregressive decoding. Production systems combine FlashAttention and chunked prefill to bound prefill activation memory, GQA/MLA and KV-cache quantization (FP8/INT8) with PagedAttention to shrink and pack the KV cache, and Sliding Window Attention or StreamingLLM attention sinks when bounding cache size.
Study Card: Handling Long Context Lengths in LLMs
Direct Answer
Serving long-context LLMs in real time splits into two phases with different bottlenecks: prefill (processing the long prompt in parallel, compute-bound ) and decode (generating tokens autoregressively, memory-bandwidth-bound by loading the KV cache at every step). Production inference engines combine several complementary techniques:
- KV Caching & Memory-Efficient Attention Layouts:
- KV Caching + PagedAttention (vLLM): Cache previously computed keys and values across steps; PagedAttention stores KV blocks in non-contiguous virtual memory pages to eliminate internal fragmentation and enable prefix caching across shared system prompts.
- Grouped-Query / Multi-Head Latent Attention (GQA / MQA / MLA): Share key/value heads across query groups (or compress KV into a low-rank latent vector as in DeepSeek MLA), shrinking KV-cache size by –.
- KV-Cache Quantization (FP8 / INT8 / INT4): Halves or quarters KV-cache memory bandwidth—the primary determinant of time-per-output-token (TPOT).
- Bounded-Memory Attention Patterns:
- Sliding Window Attention (SWA): Restricts attention to the most recent tokens per layer (e.g., Mistral), capping KV-cache size at (with stacked layers expanding receptive field linearly).
- StreamingLLM (Attention Sinks): Keeps the first few initial tokens (“attention sinks”, typically 4 tokens that absorb disproportionate softmax mass) alongside the most recent sliding-window tokens so streaming generation stays stable far beyond training length.
- Prefill & Context Extension Techniques:
- FlashAttention & Chunked Prefill: Reduces prefill HBM footprint from to and chunks massive prompts across decode batches to protect real-time latency (TTFT / TPOT).
- RoPE Scaling (PI, NTK-aware, YaRN) & RAG/Prompt Compression: Extends positional range or retrieves only top- relevant chunks instead of stuffing full corpora into the context window.
Key Terms
- KV Cache: Cached per-layer key and value tensors enabling incremental decoding per generated token instead of full recomputation.
- PagedAttention: Virtual-memory paging for KV caches eliminating contiguous pre-allocation waste and supporting prefix sharing.
- Sliding Window Attention (SWA): Bounding each token’s local attention span to recent tokens for complexity and fixed cache footprint.
- Attention Sinks (StreamingLLM): Preserving initial prompt tokens in the KV cache alongside a rolling recent window to prevent perplexity collapse during infinite streaming.
- Chunked Prefill: Splitting long prompt prefill into smaller chunks interleaved with decode iterations to avoid stalling real-time users.
Example
Suppose an LLM serving system processes 64K-token codebases or multi-turn chats in real time. Using standard Multi-Head Attention in fp16, a 32-layer, 32-head model with would consume of KV cache for a single request! Switching to GQA (8 KV heads, savings), fp8 KV-cache quantization ( savings), and PagedAttention with prefix caching cuts that to ~4.3 GB while sharing common system prompts across concurrent users—and chunked prefill + FlashAttention keeps decode latency smooth.
Code Implementation
import torch
torch.manual_seed(0)
# 1. Self-contained StreamingLLM-style KV-Cache Manager (Attention Sinks + Sliding Window)
class RollingSinkKVCache:
"""Maintains fixed-size KV cache = [initial sink tokens] + [recent sliding window]."""
def __init__(self, sink_size: int = 4, window_size: int = 16):
self.sink_size = sink_size
self.window_size = window_size
self.max_cache_len = sink_size + window_size
self.k_cache = None
self.v_cache = None
def update(self, new_k: torch.Tensor, new_v: torch.Tensor):
# new_k, new_v: (batch, num_kv_heads, new_tokens, head_dim)
if self.k_cache is None:
self.k_cache, self.v_cache = new_k, new_v
else:
self.k_cache = torch.cat([self.k_cache, new_k], dim=2)
self.v_cache = torch.cat([self.v_cache, new_v], dim=2)
# Evict middle tokens once cache exceeds sink_size + window_size
cur_len = self.k_cache.size(2)
if cur_len > self.max_cache_len:
k_sink = self.k_cache[:, :, :self.sink_size, :]
k_recent = self.k_cache[:, :, -self.window_size:, :]
v_sink = self.v_cache[:, :, :self.sink_size, :]
v_recent = self.v_cache[:, :, -self.window_size:, :]
self.k_cache = torch.cat([k_sink, k_recent], dim=2)
self.v_cache = torch.cat([v_sink, v_recent], dim=2)
return self.k_cache, self.v_cache
kv_cache = RollingSinkKVCache(sink_size=4, window_size=16)
# Prefill 12 tokens, then decode 30 tokens one by one
k_prefill, v_prefill = torch.randn(1, 8, 12, 64), torch.randn(1, 8, 12, 64)
k, v = kv_cache.update(k_prefill, v_prefill)
for _ in range(30):
k, v = kv_cache.update(torch.randn(1, 8, 1, 64), torch.randn(1, 8, 1, 64))
print("Bounded KV-cache length after 42 total tokens:", k.size(2)) # Always capped at 20 (4 + 16)
# 2. Long-sequence encoder inference with Longformer (requires network/cache)
# from transformers import AutoTokenizer, LongformerForSequenceClassification
# tok = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
# model = LongformerForSequenceClassification.from_pretrained("allenai/longformer-base-4096", num_labels=3)
# inputs = tok("Very long document...", return_tensors="pt", truncation=True, max_length=4096)
# global_attention_mask = torch.zeros_like(inputs["input_ids"])
# global_attention_mask[:, 0] = 1 # Global attention on [CLS] token
# outputs = model(**inputs, global_attention_mask=global_attention_mask)
Related Concepts
- FlashAttention & FlashDecoding: Tiled SRAM kernels optimizing both quadratic prefill and parallel KV-cache decode splits.
- Speculative Decoding: Accelerates memory-bound autoregressive generation by verifying multiple draft tokens in parallel.
- RoPE Scaling (PI, NTK-Aware, YaRN): Adapting Rotary Position Embeddings to handle contexts longer than training lengths.
- Retrieval-Augmented Generation (RAG) & Context Caching: Selecting only relevant excerpts or caching static KV prefixes across requests.