A model may accept a long context without serving it efficiently or using it reliably. Long prompts increase prefill work, KV cache memory, and time to first token. They can also delay short requests that share the same accelerator.
Long-context inference first requires a model that supports the intended sequence length. Positional encodings and the range used during training limit the positions a checkpoint can handle reliably. The combined prompt and generated output must remain within that supported context window. This post assumes that requirement is satisfied and focuses on serving the supported context efficiently, not on extending the model beyond its designed limit.
Long-context inference therefore raises two separate questions. Can the runtime process and retain the tokens within its memory and latency budget? Can the model find and use the relevant information across those tokens? A larger configured context window answers neither question by itself.
In this post, you will learn about:
- How long prompts affect prefill time and KV cache memory
- How chunked prefill and cache policies make long requests easier to schedule
- How to select useful context without exceeding the model limit
Let’s get started.

Long-Context Inference.
Photo by Mike Erskine. Some rights reserved.
Overview
This post is divided into four parts; they are:
- The Cost of a Long Context
- Chunked Prefill
- Managing Long-Lived KV State
- Selecting Useful Context
The Cost of a Long Context
For full causal attention over a prompt of $N$ tokens, prefill attention computes a triangular portion of an $N \times N$ score matrix. The arithmetic therefore grows approximately with $N^2$, although tiled kernels such as FlashAttention avoid storing the complete matrix.
After prefill, each decode query attends over the cached sequence. Its attention work grows approximately linearly with the current sequence length. As the sequence grows, the runtime retains more KV data and the attention operation reads more of it.
For a model with $L$ layers, $H_{\text{KV}}$ key-value heads, head dimension $D$, and $b$ bytes per cache element, the KV cache for $N$ tokens is approximately:
$$
M_{\text{KV}} = 2 L H_{\text{KV}} D N b
$$
The factor of two accounts for keys and values. Attention Variants and Memory Efficiency derived this equation for different attention architectures. For a batch of requests, calculate each retained length separately and then include block rounding, allocator headroom, weights, and temporary workspace.
This estimate covers persistent KV tensors, not the temporary memory used by attention kernels. It also assumes that every layer retains every token. Sliding-window or mixed attention changes the retained length per layer.
Chunked Prefill
A runtime does not need to schedule an entire long prompt in one iteration. Chunked prefill divides it into smaller token ranges while preserving one logical causal prefill and one growing KV cache.
If the chunks are $x_{1:c}$, $x_{c+1:2c}$, and so on, each later chunk attends to the cache produced by all earlier chunks. Chunking does not reset positions or make chunks independent. It changes scheduling and peak intermediate work, not the model’s logical context.
Chunking allows a serving engine to interleave a long prefill with decode work from other requests. This reduces head-of-line blocking and can improve GPU utilization. The trade-off is more scheduling steps and possibly more kernel-launch overhead.
You can check the logical equivalence on a small model without downloading weights. GPT-2’s forward pass uses the cache length to continue position IDs across chunks:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import torch from transformers import GPT2Config, GPT2LMHeadModel torch.manual_seed(42) model = GPT2LMHeadModel(GPT2Config( vocab_size=128, n_positions=128, n_layer=2, n_head=2, n_embd=32, )).eval() tokens = torch.randint(0, 128, (1, 48)) with torch.no_grad(): full = model(tokens, use_cache=True).logits[:, -1, :] cache = None for chunk in tokens.split(12, dim=1): output = model(chunk, past_key_values=cache, use_cache=True) cache = output.past_key_values chunked = output.logits[:, -1, :] torch.testing.assert_close(chunked, full, rtol=1e-4, atol=1e-5) cache_length = ( cache.get_seq_length() if hasattr(cache, "get_seq_length") else cache[0][0].size(-2) ) print("cached prompt tokens:", cache_length) |
Run the comparison in evaluation mode with dropout disabled. Small floating-point differences can still occur because kernels use different shapes. This example shows the model computation, not a serving scheduler: it does not interleave requests or reduce the total attention work.
The following vLLM example enables chunked prefill explicitly and limits the number of tokens scheduled in one iteration:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from vllm import LLM, SamplingParams model_name = "Qwen/Qwen2.5-0.5B-Instruct" llm = LLM( model=model_name, max_model_len=8192, enable_chunked_prefill=True, max_num_batched_tokens=512, ) long_document = "Transformer inference moves data through memory. " * 700 prompt = ( "Summarize the following document in three sentences.\n\n" + long_document ) params = SamplingParams(temperature=0.0, max_tokens=96) output = llm.generate([prompt], params)[0] print(output.outputs[0].text) |
The tokenizer, not the number of characters or words, determines whether the request fits within max_model_len. You should check the tokenized prompt length together with the requested output allowance.
In current vLLM v1 releases, chunked prefill is enabled by default when the model and backend support it. Setting it explicitly documents the intended behavior. The parameter max_num_batched_tokens is a scheduler budget, not the model’s context length. Smaller budgets make long prefills yield more often to decode requests; larger budgets can improve prefill throughput but may worsen inter-token latency for other requests.
Managing Long-Lived KV State
Full attention retains every token at every full-attention layer. Several alternatives bound or relocate that state:
- Sliding-window attention: Retain only a recent window in layers trained for that attention pattern.
- Mixed attention: Use local windows in some layers and full attention in others, as fixed by the checkpoint.
- Attention-sink streaming: Many pretrained language models assign substantial attention to the first few tokens even when those tokens are not semantically important. A StreamingLLM-style cache retains the KV states of these initial sink tokens together with a rolling window of recent tokens and evicts the intervening states.
- KV cache eviction: Remove selected old states and accept that future tokens cannot attend to them directly.
- KV cache quantization: Store cached values in fewer bits, with kernel and quality trade-offs.
- CPU offload: Move cold cache blocks to host memory and transfer them back when needed.
These methods are not interchangeable. A runtime can use sliding-window retention only when it matches the model architecture or a validated approximation. Arbitrary eviction changes the attention context. Offload preserves state but adds transfer latency. Quantization preserves the positions but changes numerical precision.
An attention sink is an observed model behavior, not merely any token kept at the start of the cache. Ordinary window attention can become unstable after evicting the initial tokens on which the model has learned to place attention. Preserving a small sink prefix gives that attention a consistent destination while the recent-token window moves forward. Some models are trained with a dedicated sink token.
This cache policy bounds memory and can sustain generation over a continuing stream, but it does not preserve a full long context. The model cannot retrieve content from the evicted middle of the stream. Attention-sink streaming is therefore a bounded-history approximation, not a way to give the model unlimited factual recall.
Offload is useful only when transfer time and bandwidth fit the latency target. During decode, repeatedly fetching old blocks over a slow link can cost more than keeping a smaller active context or recomputing selected state.
Selecting Useful Context
The cheapest token is often the token you do not send. A long context is appropriate when the task needs broad access to the source and the model can use it. Otherwise, retrieval, summarization, or prompt compression can reduce prefill time and cache memory.
Common choices include:
- Retrieval: Select a small set of passages relevant to the query.
- Summarization: Replace older or repetitive material with a shorter representation.
- Prompt compression: Remove low-value tokens while preserving task-specific evidence.
- Hierarchical processing: Process sections separately, then combine their summaries or extracted facts.
- Full context: Preserve all source material when omission risk is unacceptable and capacity allows it.
Retrieval can miss relevant evidence. Summaries can discard details. Full context can bury the answer among distractors. The choice is an application-quality trade-off, not only a token-count optimization.
Prompt layout matters as well. Models may use evidence differently depending on its position. A model with a nominally long context window can still perform worse when relevant information appears in the middle. Evaluate the positions and distractor patterns that occur in the real application.
Further Reading
Below are some resources you may find useful:
- vLLM documentation. Optimization and Tuning: Chunked Prefill. This guide explains current scheduling behavior and the max_num_batched_tokens trade-off.
- Guangxuan Xiao et al. (2023). Efficient Streaming Language Models with Attention Sinks. This paper identifies the early-token attention-sink phenomenon and uses it for bounded-memory streaming inference.
- Nelson F. Liu et al. (2023). Lost in the Middle: How Language Models Use Long Contexts. This paper evaluates how the position of relevant information affects long-context performance.
- Cheng-Ping Hsieh et al. (2024). RULER: What’s the Real Context Size of Your Long-Context Language Models?. This benchmark tests retrieval and aggregation across sequence lengths.
Summary
In this post, you learned that long-context inference increases prefill attention work, persistent KV cache memory, and interference with other requests. Chunked prefill preserves one logical context while scheduling the prompt in smaller pieces, trading prefill throughput against fairness and decode latency.
You also learned that sliding windows, attention-sink streaming, quantization, eviction, and offload address different parts of the memory problem, while retrieval and compression reduce the input itself.






No comments yet.