{"slug": "long-context-inference", "title": "Long-Context Inference", "summary": "A technical post on long-context inference argues that a model accepting a long context does not mean it serves that context efficiently or uses it reliably, because prefill attention work grows roughly with the square of prompt length N while KV cache memory grows linearly. The post gives the KV cache estimate M_KV = 2·L·H_KV·D·N·b for N tokens, and describes chunked prefill — splitting a long prompt into token ranges that each attend to the cache of earlier chunks — as a way to interleave long prefills with decode work and reduce head-of-line blocking for short requests sharing an accelerator. The post also covers managing long-lived KV state and selecting useful context within the model's supported window, noting that positional encodings and the training range limit the positions a checkpoint handles reliably.", "body_md": "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.\n\nLong-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.\n\nLong-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.\n\nIn this post, you will learn about:\n\n- How long prompts affect prefill time and KV cache memory\n- How chunked prefill and cache policies make long requests easier to schedule\n- How to select useful context without exceeding the model limit\n\nLet’s get started.\n\n## Overview\n\nThis post is divided into four parts; they are:\n\n- The Cost of a Long Context\n- Chunked Prefill\n- Managing Long-Lived KV State\n- Selecting Useful Context\n\n## The Cost of a Long Context\n\nFor 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.\n\nAfter 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.\n\nFor 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:\n\n$$\n\nM_{\\text{KV}} = 2 L H_{\\text{KV}} D N b\n\n$$\n\nThe factor of two accounts for keys and values. [*Attention Variants and Memory Efficiency*](https://machinelearningmastery.com/attention-variants-for-efficient-inference/) 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.\n\nThis 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.\n\n## Chunked Prefill\n\nA 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.\n\nIf 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.\n\nChunking 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.\n\nYou 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:\n\n``` python\nCompare full and chunked prompt processing on a small GPT-2 model.\n\nimport torch\nfrom transformers import GPT2Config, GPT2LMHeadModel\n\ntorch.manual_seed(42)\nmodel = GPT2LMHeadModel(GPT2Config(\n    vocab_size=128, n_positions=128, n_layer=2, n_head=2, n_embd=32,\n)).eval()\ntokens = torch.randint(0, 128, (1, 48))\n\nwith torch.no_grad():\n    full = model(tokens, use_cache=True).logits[:, -1, :]\n    cache = None\n    for chunk in tokens.split(12, dim=1):\n        output = model(chunk, past_key_values=cache, use_cache=True)\n        cache = output.past_key_values\n    chunked = output.logits[:, -1, :]\n\ntorch.testing.assert_close(chunked, full, rtol=1e-4, atol=1e-5)\ncache_length = (\n    cache.get_seq_length() if hasattr(cache, \"get_seq_length\")\n    else cache[0][0].size(-2)\n)\nprint(\"cached prompt tokens:\", cache_length)\n\n1234567891011121314151617181920212223\n\nimport torchfrom 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)\n```\n\nRun 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.\n\nThe following vLLM example enables chunked prefill explicitly and limits the number of tokens scheduled in one iteration:\n\n``` python\nGenerate text with vLLM using chunked prefill.\n\nfrom vllm import LLM, SamplingParams\n\nmodel_name = \"Qwen/Qwen2.5-0.5B-Instruct\"\nllm = LLM(\n    model=model_name,\n    max_model_len=8192,\n    enable_chunked_prefill=True,\n    max_num_batched_tokens=512,\n)\n\nlong_document = \"Transformer inference moves data through memory. \" * 700\nprompt = (\n    \"Summarize the following document in three sentences.\\n\\n\"\n    + long_document\n)\nparams = SamplingParams(temperature=0.0, max_tokens=96)\n\noutput = llm.generate([prompt], params)[0]\nprint(output.outputs[0].text)\n\n12345678910111213141516171819\n\nfrom 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. \" * 700prompt = (    \"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)\n```\n\nThe 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.\n\nIn 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.\n\n## Managing Long-Lived KV State\n\nFull attention retains every token at every full-attention layer. Several alternatives bound or relocate that state:\n\n- *Sliding-window attention:* Retain only a recent window in layers trained for that attention pattern.\n- *Mixed attention:* Use local windows in some layers and full attention in others, as fixed by the checkpoint.\n- *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.\n- *KV cache eviction:* Remove selected old states and accept that future tokens cannot attend to them directly.\n- *KV cache quantization:* Store cached values in fewer bits, with kernel and quality trade-offs.\n- *CPU offload:* Move cold cache blocks to host memory and transfer them back when needed.\n\nThese 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.\n\nAn 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.\n\nThis 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.\n\nOffload 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.\n\n## Selecting Useful Context\n\nThe 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.\n\nCommon choices include:\n\n- *Retrieval:* Select a small set of passages relevant to the query.\n- *Summarization:* Replace older or repetitive material with a shorter representation.\n- *Prompt compression:* Remove low-value tokens while preserving task-specific evidence.\n- *Hierarchical processing:* Process sections separately, then combine their summaries or extracted facts.\n- *Full context:* Preserve all source material when omission risk is unacceptable and capacity allows it.\n\nRetrieval 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.\n\nPrompt 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.\n\n## Further Reading\n\nBelow are some resources you may find useful:\n\n- vLLM documentation. [Optimization and Tuning: Chunked Prefill](https://docs.vllm.ai/en/latest/configuration/optimization/#chunked-prefill) . This guide explains current scheduling behavior and the max_num_batched_tokens trade-off.\n- Guangxuan Xiao et al. (2023). [Efficient Streaming Language Models with Attention Sinks](https://arxiv.org/abs/2309.17453) . This paper identifies the early-token attention-sink phenomenon and uses it for bounded-memory streaming inference.\n- Nelson F. Liu et al. (2023). [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172) . This paper evaluates how the position of relevant information affects long-context performance.\n- Cheng-Ping Hsieh et al. (2024). [RULER: What’s the Real Context Size of Your Long-Context Language Models?](https://arxiv.org/abs/2404.06654) . This benchmark tests retrieval and aggregation across sequence lengths.\n\n## Summary\n\nIn 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.\n\nYou 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.", "url": "https://wpnews.pro/news/long-context-inference", "canonical_source": "https://machinelearningmastery.com/long-context-inference/", "published_at": "2026-11-28 22:06:56+00:00", "updated_at": "2026-11-29 00:44:27.959921+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "machine-learning", "ai-research"], "entities": ["FlashAttention", "GPT-2", "Hugging Face Transformers", "PyTorch"], "also_reported_by": [], "takeaway": "Chunked prefill splits a long prompt into token ranges that each attend to the KV cache of earlier chunks, preserving one logical causal prefill while letting the engine interleave long prefills with other requests' decode work to cut head-of-line blocking, at the cost of more scheduling steps and k", "recommendation": {"advice": "Use chunked prefill to interleave long prompts with decode work from other requests and cut head-of-line blocking, and size KV memory with M_KV = 2·L·H_KV·D·N·b before admitting long contexts.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/long-context-inference", "markdown": "https://wpnews.pro/news/long-context-inference.md", "text": "https://wpnews.pro/news/long-context-inference.txt", "jsonld": "https://wpnews.pro/news/long-context-inference.jsonld"}}