Long Context Inference: Index Acceleration Techniques for Million-Token Prefill

    This article examines why the indexer stage dominates prefill cost in long-context LLM inference and outlines four practical optimization paths: predictable sparse sampling, hierarchical two-stage retrieval, cache reuse across requests, and kernel fusion with asynchronous pipelining. It also covers the key metrics to track beyond total latency and how these optimizations fit with cloud infrastructure. The goal is to shift the bottleneck from expensive selection to near-linear filtering, reducing both TTFT and compute cost.

    1. The Problem: Long Context Shifts the Cost to Reading

    The smallest unit a large language model processes is a token, roughly corresponding to a character, a word, or a subword. Prefill refers to the stage before the model generates the first output token, where it runs the entire input through once and builds its internal representation (the KV cache). This stage is compute-intensive and almost fully parallel, so it sets the lower bound on time to first token (TTFT).

    When the context grows from a few thousand tokens to nearly one million, the nature of the problem changes. Attention computation scales quadratically with sequence length, but in engineering practice the real time sink is often not attention itself. It is the filtering step that comes before it: the indexer. Its job is to pick a small set of candidates from a massive history of tokens that are worth including in later computation, so that not every token has to participate in full interaction.

    Published papers give a direct picture: at a context length approaching one million tokens, the indexer accounts for about 73% of prefill time in one general-purpose large model, and in another sparse-attention architecture model of the same generation, that share reaches 90.8%. In other words, most of the model’s compute goes not into understanding, but into deciding where to look.

    2. Why It Degrades: Three Structural Costs of Indexing

    First, scoring is global. The index must compute a relevance score for every query position against all historical positions. This is itself a quadratic operation, and the intermediate results are hard to reuse.

    Second, memory access is fragmented. The full KV usually resides in GPU memory or tiered storage, and the indexing stage requires repeated random reads. Bandwidth utilization is far below that of large contiguous reads, creating a classic memory-bound bottleneck.

    Third, scheduling is synchronous. Indexing must fully complete before attention can begin, forming a hard serial dependency that cannot be hidden through pipelining.

    Schematically, a naive implementation looks like this. Note the nested loop and the synchronization point:

    1. # Naive indexing: O(L^2) scoring + synchronous wait
    2. scores = q @ k_all.T / sqrt(d) # [L, L], pressure on both memory and bandwidth
    3. idx = topk(scores, k=chunk) # needs the full scores before it can start
    4. out = sparse_attention(q, k_all, v_all, idx)

    3. Optimization Path 1: Replace Full Scoring with Predictable Sparse Sampling

    The core idea is to stop treating all historical positions equally. Common approaches include coarse-grained summaries at a fixed block granularity, selecting blocks first and refining within them; learnable gating or hash buckets that compress candidates to a constant size; and a hybrid layout that stays dense within a local window and sparse for distant tokens. The engineering gains come from two things: the candidate set shrinks from L to k, bringing complexity back to near-linear, and block-level summaries can be precomputed and cached for reuse across requests.

    4. Optimization Path 2: Hierarchical and Two-Stage Retrieval

    Split indexing into two levels: coarse filtering and fine ranking. Coarse filtering uses low-dimensional projections or mean-pooled block representations at very low cost; fine ranking runs full scoring only on the few selected blocks. Most of the indexing computation then happens in a low-precision, low-dimensional space, with only a small fraction taking the high-precision path. Combined with quantization (for example, compressing the keys used for indexing to 8-bit or lower), bandwidth pressure can drop by another order of magnitude. Because indexing only affects which tokens are selected, the perturbation to final generation quality is usually manageable.

    5. Optimization Path 3: Cache Reuse and Cross-Request Amortization

    In long-context scenarios, system prompts, knowledge base snippets, and code repository context are often submitted repeatedly. Making block-level summaries, index structures, and the KV cache into addressable cache objects (prefix caching plus block caching) lets the second and later requests skip most of the indexing work. In practice this requires eviction policies and consistency checks to avoid serving stale data.

    6. Optimization Path 4: Operator Fusion and Asynchronous Pipelining

    Fuse scoring, TopK, and mask generation into a single kernel so the [L, L] intermediate tensor never lands in GPU memory. Split indexing and attention by chunk into a pipeline so that indexing for chunk i overlaps with computation for chunk i-1, turning the synchronization point into hidden latency. Sketch:

    1. for i, chunk in enumerate(chunks):
    2. idx_i = indexer(chunk) # launched asynchronously
    3. if i > 0:
    4. out[i-1] = attention(chunks[i-1], idx_prev)
    5. idx_prev = idx_i

    7. How to Evaluate: Look Beyond Total Latency

    Track at least four metrics: the share of time spent in indexing, the effective candidate rate (the fraction of selected tokens that actually influence the output), TTFT, and peak GPU memory per unit of context. If the indexing share stays above 50% over time, the filtering strategy does not match the hardware characteristics. Adjust block granularity and quantization bit width first, rather than adding more compute.

    8. Deployment Notes and Cloud Infrastructure

    In real deployments, this optimization usually needs to work with infrastructure: object storage for long documents and raw knowledge base data, a container platform for elastic inference instances to absorb peaks from long requests, and logging and monitoring with alerting to observe the indexing time distribution and cache hit rate. Baidu AI Cloud can provide standardized resources and observability support for these general capabilities, helping teams focus on the algorithms and strategy themselves.

    To summarize: for million-token contexts, the bottleneck has moved from slow computation to expensive selection. Whoever can push filtering cost down to near-linear and reuse it effectively will get both low latency and controlled cost in long-document understanding, code repository question answering, and multi-turn long conversations.