Long-Context Inference: Asymmetric Computation and Throughput Optimization
This article examines why long-context agent and document workloads require a stage-aware view of inference cost. It distinguishes the computational characteristics of prefill and decode, introduces asymmetric computation between encoder-side and decoder-side paths, and discusses conditional memory via N-gram hashing, sparse attention with two-level indexing, benchmarking methodology, and engineering practices for deployment. It concludes with a checklist for evaluating long-context inference optimizations.
1. Background: Why Long-Context Workloads Require a New View of Inference Cost
LLM inference cost has long been simplified as “more parameters means higher cost.” In agent and long-document scenarios, this view is no longer sufficient. A typical agent task often reads tens of thousands of tokens or more of context, including conversation history, tool results, retrieved chunks, and intermediate state, while producing only hundreds to thousands of output tokens. The read/write ratio is severely imbalanced, and the main source of inference cost changes accordingly.
To understand this, it is necessary to distinguish the two stages of inference. The prefill stage processes all input tokens at once. Its computation can be highly parallel and is mainly compute-bound. The decode stage generates output tokens one by one. Each step must read the existing KV cache, so it is mainly bound by memory bandwidth and memory access latency. The two stages have different bottlenecks and therefore require different optimizations.
When evaluating an inference optimization, the first question should be which stage it improves, followed by the magnitude of the improvement and its cost.
2. Computational Characteristics of Prefill and Decode
2.1 Prefill Stage
The computation in the prefill stage scales approximately linearly with input length, while the attention part grows quadratically with length. The longer the input, the more noticeable the time spent in this stage and the higher the time to first token (TTFT). In multi-turn agent conversations, if the full history is re-prefilled every turn, cost accumulates quickly.
2.2 Decode Stage
In the decode stage, each generated token requires a full read of the model weights, especially at small batch sizes, as well as the KV cache corresponding to the current context. The longer the context, the larger the per-step memory traffic. Throughput in this stage is usually measured as generated tokens per second.
2.3 End-to-End Cost Model
A simplified model can be used to estimate end-to-end cost:
Total cost ≈ P × c_prefill + D × c_decode
Here, P is the number of input tokens, D is the number of output tokens, and c_prefill and c_decode are the per-token prefill and decode costs, respectively. In read-heavy scenarios, P is much larger than D, so the benefit of reducing c_prefill is amplified. Conversely, if the task produces long outputs, such as code generation or long-form writing, priority should be given to c_decode.
This model is only a tool for direction. Actual cost is also affected by batch size, cache hit rate, and hardware configuration.
3. Design Approach for Asymmetric Computation
Asymmetric computation means that the model uses different computation paths or parameter counts during prefill and decode. In a symmetric design, every token follows exactly the same forward path in every layer. An asymmetric design allows the two stages to use different divisions of labor.
3.1 Encoder-Side and Decoder-Side Division
A common approach is to divide the network into two parts:
- Encoder side (layers near the input): runs only during prefill and compresses the long context into a compact intermediate representation.
- Decoder side (layers near the output): carries the main computation during generation and obtains global information from the encoder side.
The core benefit of this division is that the decode stage does not need to construct a complete global KV for every layer. Decoder layers can project the global KV directly from the final hidden state of the encoder side, reducing cache size and per-step computation.
3.2 A Simplified Illustrative Implementation
The code below illustrates the data flow only and does not represent any specific implementation:
def prefill(tokens, encoder_layers):hidden = embed(tokens)for layer in encoder_layers:hidden = layer(hidden)# Keep only the final encoder-side output to generate the global KVreturn hiddendef decode_step(token, decoder_layers, global_kv):hidden = embed([token])for layer in decoder_layers:hidden = layer(hidden, global_kv)return sample(hidden)
As the code suggests, prefill executes the full forward pass across the encoder and decoder sides, while each decode step executes only the decoder side. If the decoder side has more layers, per-step decode computation is larger, but total prefill overhead does not necessarily increase in proportion.
3.3 Applicability and Caveats
Asymmetric design is not free. The representation capacity of the encoder side directly limits the quality of information available to the decoder side. If compression is too aggressive, details of long-distance dependencies may be lost, so validation with an evaluation set is required. In addition, such architectures usually require a dedicated training process and cannot simply be switched on in an existing model.
4. Conditional Memory: Separating Inference from Memory
Language contains a large amount of local, high-frequency, fixed-pattern content, such as entity names, fixed collocations, and common phrases. This content needs to be “remembered” but does not require deep reasoning. If all of it is handled by Transformer attention layers, it consumes substantial compute.
4.1 N-Gram Hash Lookup
A general approach is to use the most recent n tokens as a key, map it through a hash function to a fixed-size embedding table, and retrieve the corresponding vector as a supplementary feature.
import hashlibdef ngram_bucket(tokens, n, num_buckets):window = tokens[-n:]key = ",".join(map(str, window)).encode("utf-8")digest = hashlib.blake2b(key, digest_size=8).digest()return int.from_bytes(digest, "little") % num_bucketsdef lookup_memory(tokens, table, n=3):idx = ngram_bucket(tokens, n, table.shape[0])return table[idx]
hashlib is used here instead of Python’s built-in hash because the built-in hash produces inconsistent results across processes and cannot guarantee reproducible inference results.
4.2 Hash Collisions and Capacity Planning
The hash table has a fixed size, and different n-grams may map to the same bucket. The collision rate depends on the ratio between the number of buckets and the number of distinct n-grams that actually appear. Collisions introduce noise, so table capacity should be assessed together with corpus scale. Common practices include averaging multiple hash functions or reserving separate entries for high-frequency patterns.
4.3 Applicability Boundaries
Conditional memory is well suited to content that can be looked up rather than reasoned about. For tasks that require multi-step reasoning, cross-paragraph logic, or numerical computation, its benefit is limited, and attention and deep computation are still required.
5. Sparse Attention and Two-Level Indexing
Full attention computation grows quadratically with context length. Sparse attention computes relationships only among a subset of tokens, reducing computation and memory access overhead.
5.1 Basic Structure of Two-Level Indexing
A common organization is two-level retrieval:
- Coarse filtering: use low-cost representations, such as block-level summaries, to quickly filter candidate regions.
- Fine ranking: compute full attention within the candidate regions.
The key to this structure is the recall of coarse filtering. If coarse filtering misses key information, finer ranking cannot recover it. Therefore, retrieval recall should be evaluated as an independent metric.
5.2 Value of Shared KV
When multiple attention heads or multiple layers share the same KV representation, memory usage decreases, and cache read/write pressure is reduced accordingly. The cost is that representation capacity may be limited, and whether this is acceptable must be validated through downstream tasks.
6. How to Benchmark Inference Speed Scientifically
Public speed data is often incomparable because test conditions differ. A credible benchmark report should specify at least the following elements.
6.1 Key Metrics
- Total latency: time from request submission to complete result return.
- Time to first token (TTFT): reflects prefill cost.
- Generation speed (tokens/s): reflects decode throughput; it is recommended to measure only the decode stage.
- Output token count: for the same task, shorter output means lower total latency, so it should be listed for comparison.
- Cache hit rate: prefix caching can significantly reduce repeated prefill and should be recorded separately.
6.2 Consistency of Test Conditions
When comparing two systems, the following variables should be fixed: input length distribution, output length limit, sampling parameters, concurrency, whether caching is enabled, and the warm-up state of the cache. Speed numbers without this information are difficult to use for decision-making.
6.3 A Basic Benchmarking Script
import timedef benchmark(generate_fn, prompts, max_new_tokens=512, warmup=2):for p in prompts[:warmup]:generate_fn(p, max_new_tokens=max_new_tokens) # Warm up to exclude cold-start effectstotal_out, total_time = 0, 0.0for p in prompts:start = time.perf_counter()result = generate_fn(p, max_new_tokens=max_new_tokens)total_time += time.perf_counter() - starttotal_out += len(result.output_token_ids)return {"output_tokens": total_out,"elapsed_s": round(total_time, 2),"tokens_per_s": round(total_out / total_time, 1),}
The script warms up before timing to avoid cold start pulling down the results. It uses output token count rather than character count for consistent units across model comparisons.
7. Engineering Deployment Recommendations
7.1 Design Prefix Structure for Long Context
Place immutable system instructions, tool descriptions, and history summaries at the front of the prompt, and place per-turn changing content later. The more stable the prefix, the higher the cache hit rate and the less repeated prefill computation.
7.2 Control Context Growth
In multi-turn calls, agents can easily let context grow without bound. Common methods include truncating and summarizing tool results, periodically compressing history into structured state, and setting a context budget for each task type.
7.3 Model and Runtime Framework Collaboration
Inference performance often depends on the coordination between the model and the runtime framework. Changes in scheduling strategy, batching method, and tool-calling protocol can all affect actual throughput and output quality. After each runtime configuration change, regression tests should be rerun rather than relying only on offline model metrics.
7.4 Cost-Quality Tradeoff
Lowering inference cost usually comes at the expense of some quality metrics. During deployment, an evaluation set covering accuracy, factual consistency, and format compliance should be established, and speed and quality should be compared in the same table.
8. Selection Checklist
When evaluating whether a long-context inference optimization fits your business, answer the following questions in order:
- Is my task read-heavy or write-heavy? This determines whether to prioritize prefill or decode optimization.
- How much of my context is a stable prefix that can be reused through caching?
- Does the task contain many fixed patterns, entities, or terminology? Conditional memory methods may help.
- Does the evaluation set cover key scenarios such as long-distance dependencies, numerical reasoning, and format constraints?
- Are the test conditions for speed data consistent with my production environment?
- What is the rollback cost of switching solutions? Can it be rolled out gradually while keeping the old solution?
There are no universal answers to these questions, but clear answers make technology selection better grounded and make tradeoffs easier to explain to the team.
