Million-Token Context Inference: Compute, Memory, and Four Architectural Approaches

    This article explains the cost model behind long-context LLM inference and how to choose between four architectural approaches. It breaks down why attention computation grows quadratically during prefill, why decoding costs scale linearly with context length, and how KV cache dominates GPU memory at million-token contexts, with a worked estimation formula and code example. It then compares sliding window, sparse retrieval, hybrid attention, and state space approaches, and outlines selection paths for low-latency and high-throughput serving scenarios.

    The cost of long-context inference can be summarized in one sentence: attention score computation during prefill grows quadratically with context length, the data read at each decoding step grows linearly, and GPU memory is primarily consumed by the KV cache.

    As context windows expand from tens of thousands of tokens to a million, the question shifts from “can the model accept long input” to “how much compute and memory does each token cost, and can the serving infrastructure sustain it.” Before choosing an approach, you should work through both of these budgets.

    1. Two Core Bottlenecks of Long-Context Inference

    1.1 Compute Cost

    In standard self-attention, every token computes correlation scores against all previous tokens. The two phases behave differently:

    • Prefill: the model processes the entire input at once, and the size of the attention score matrix scales quadratically with context length. The longer the input, the faster the time-to-first-token grows.
    • Decode: the model generates output tokens one at a time, reading all historical KVs and running attention at every step. Both computation and memory access scale linearly with context length.

    The quadratic term applies only to the attention score portion. Total prefill time also includes linear projections and MLP computation, which scale linearly with length. For short inputs, overall latency is dominated by these linear terms; only at long inputs does the quadratic attention term meaningfully inflate latency. The exact crossover point depends on model architecture and hardware, so measure it yourself.

    Take decoding as an example. Scaling context from 128K to 1M (K = 1024, M = 1024 × 1024) makes the per-step attention read roughly 8× larger. This multiplier depends only on context length, not on parameter count. Model weight reads do not change with context, so at short contexts weights typically dominate memory traffic, while at long contexts KV reads gradually take over.

    1.2 Memory Cost

    Autoregressive generation stores Key and Value vectors for every historical token at every layer. This data is the KV cache, estimated as:

    KV cache bytes = 2 × number of layers × number of KV heads × head dimension × bytes per element × number of tokens

    The factor of 2 accounts for storing K and V separately. The number of KV heads is typically smaller than the number of query heads in GQA or MQA architectures.

    Assume a model with 60 layers, 8 KV heads, 128 dimensions per head, using BF16 (2 bytes per element). The KV cache per token is 245,760 bytes, roughly 245.8 KB. One million tokens require about 245.76 GB—245.8 GB in decimal units, or about 228.9 GiB. This is a hypothetical configuration used only to illustrate the order of magnitude.

    1. def kv_cache_bytes(num_tokens, num_layers, num_kv_heads, head_dim, bytes_per_elem=2):
    2. # The factor of 2 accounts for storing K and V separately
    3. per_token = 2 * num_layers * num_kv_heads * head_dim * bytes_per_elem
    4. return per_token * num_tokens
    5. # Example configuration is hypothetical, for magnitude illustration only
    6. size = kv_cache_bytes(1_000_000, num_layers=60, num_kv_heads=8, head_dim=128)
    7. print(f"{size / 1e9:.1f} GB") # Decimal GB, outputs 245.8 GB
    8. print(f"{size / 2**30:.1f} GiB") # Binary GiB, outputs 228.9 GiB

    This estimate covers only the KV cache. Actual memory usage also includes model weights, activations, allocator fragmentation, and framework overhead. Batching on the server multiplies KV usage, since each concurrent request maintains its own cache. With the configuration above, 4 concurrent requests at 1M tokens each would require roughly 983 GB of KV cache.

    2. Cost Comparison of Four Approaches

    The table below is a qualitative comparison at the mechanism level. Replace any performance figures with your own benchmark data.

    Approach Core Mechanism Per-Step Decode Cost KV Memory Long-Range Retrieval Best Fit
    Sliding window Each token attends only to the most recent W tokens Related to W, does not grow with total length Only KV within the window is kept; memory scales with W Information outside the window is inaccessible; poor exact recall Strong local dependencies, e.g., log tail analysis, nearby code context
    Sparse retrieval Selects top-k relevant tokens from history at each step Related to k and index overhead Full KV must still be stored; can be offloaded to CPU or SSD Depends on retrieval recall; key information not selected is lost Q&A that needs to locate a few key passages in long documents
    Hybrid attention Some layers use full attention, others use sliding window or linear attention Between full attention and linear approaches Only KV of full-attention layers grows with length Depends on the proportion of full-attention layers and training method Balancing long-range quality and memory, with tolerance for architecture dependence
    State space methods Recurrently compress history into a fixed-size state, e.g., SSM-type models Essentially independent of length Fixed state size, does not grow with length Weaker at exact verbatim recall; requires dedicated evaluation Ultra-long streaming input, highly sensitive to latency and memory

    3. Three Selection Paths

    3.1 Low Latency First

    When to choose: the product has hard requirements on time-to-first-token (TTFT) or time-per-output-token (TPOT), such as interactive chat.

    Recommended practices: first control the effective context length and include only genuinely relevant material. Enable prefix caching for fixed system prompts and document prefixes to avoid redundant prefill. Sliding window or hybrid attention approaches reduce memory access during decoding.

    Not suitable for: tasks requiring precise reasoning over an entire book at once. Simply compressing the input may lose critical information.

    3.2 High Throughput First

    When to choose: offline batch processing or bulk document analysis, where tokens processed per second is the priority.

    Recommended practices: concurrency is usually bounded by KV memory, so first calculate the per-request KV footprint and derive the maximum batch size. GQA, KV quantization, and paged caching reduce per-request usage. Sliding window or state space approaches can substantially raise the concurrency ceiling.

    Not suitable for: