Optimizing Prefill and Decode Asymmetry in Large Language Model Inference

    This article explains why the prefill and decode stages of LLM inference have different compute and memory characteristics, and how to optimize each one at the operator, scheduling, and deployment levels. It also covers KV cache capacity estimation, admission control, and an evaluation approach based on time to first token, inter-token latency, and effective throughput.

    1. Start by Separating the Two Inference Stages

    When people discuss LLM inference performance, they often focus on parameter count, numerical precision, or hardware configuration. They overlook a more basic point: within a single generation request, the work done in each stage is different.

    For autoregressive language models that use causal self-attention, a typical request has two stages.

    The first stage is prefill. The system processes the input sequence the user has already submitted. The model reads the prompt, computes the key-value (KV) cache for each layer, and produces the output at the last input position. That output is used to predict the next token.

    The second stage is decoding. The model generates subsequent tokens step by step, building on the existing context. At each new position, the model reads the cached history and appends the new key and value for that position to the cache.

    The two stages differ in several ways:

    • Prefill processes many known positions at once, so it can use large-scale parallel computation.
    • Decoding usually advances one position per sequence at each step, and a single request has strict generation dependencies.
    • Prefill builds the cache for the input context. Decoding repeatedly reads the cache and appends to it.
    • Prefill determines how long it takes to produce the first token. Decoding determines the pace at which the rest of the output arrives.

    The asymmetry between prefill and decoding is first a natural property of the workload. It does not necessarily mean the model uses a special architecture. The real questions are whether the system recognizes and exploits this difference, and whether its method of exploitation preserves the original computation semantics.

    2. Understanding Computational Dependencies: What Work Is Actually Necessary

    2.1 The KV cache is not a simple copy of the input

    In a typical multi-layer decoder model, each layer generates queries, keys, and values from that layer’s input hidden states. The keys and values for earlier positions can be stored and reused by attention computations at later positions.

    Let H_l be the input hidden states of layer l. The relevant computation can be simplified as:

    K_l = H_l × W_K,l

    V_l = H_l × W_V,l

    However, H_l usually already includes the results of earlier attention layers, feed-forward networks, normalization, and residual connections.

    This means cache construction cannot be fully separated from the rest of the model. To get correct keys and values at higher layers, the correct hidden states from lower layers are typically required first.

    2.2 The output projection usually only needs the final position

    The output projection maps the final hidden states to vocabulary scores. For ordinary continuous generation requests, the prefill stage only needs the output at the last input position to determine the probability distribution for the first generated token.

    Therefore, there is no need to run the full vocabulary projection for every input position just to generate the first token.

    This optimization does not change the model architecture. It avoids computing outputs the current task does not need. It does have clear limits, however. If a task requires per-position probabilities, scores for an entire text, or per-position loss, those outputs may be necessary and cannot simply be skipped.

    This leads to a general principle:

    Whether a computation can be skipped depends on what the final task needs and whether later computations depend on the result.

    2.3 “Feed-forward networks do not write to the cache directly” does not mean they can all be skipped

    Feed-forward networks usually do not output the keys and values for the current layer directly. However, they change the hidden states passed to the next layer.

    Suppose a middle layer or a feed-forward computation at one input position is omitted. The input to the next layer at that position changes, and its KV cache may change too. During later generation, the model would then read a history of representations that no longer matches the original model.

    So you cannot conclude from “feed-forward networks do not write to the cache directly” that all positions except the last one can skip feed-forward computation during prefill. That reasoning confuses direct dependencies with indirect ones.

    For some common position-wise feed-forward structures, if no cross-position computation needs historical position representations after the last layer, and the task only needs the final output, part of the computation at non-final positions in the last layer may be prunable. The exact boundary depends on the actual computation graph and cannot be applied to every layer or every architecture.

    3. Why the Two Stages Need Different Optimization Strategies

    3.1 Prefill more easily forms large-scale parallel computation

    The full input sequence is known in advance. As a result, projections, feed-forward computations, and attention computations that respect the causal constraint can be organized in parallel within one phase of execution.

    When the input length and batch size are large enough, prefill often makes it easier to keep compute units busy. However, long contexts also increase pressure on attention computation, temporary workspace, and cache writes.

    For standard dense causal attention, the amount of computation grows quickly with input length. Optimized implementations can reduce intermediate reads and writes to GPU memory, but they do not eliminate the full computational complexity.

    Therefore, “prefill is compute-bound” should be treated as a common pattern, not a law that holds in every scenario.

    3.2 Decoding more easily exposes bandwidth and scheduling issues

    During decoding, each sequence’s new position must read the historical keys and values. The longer the context, the more historical data typically needs to be read.

    When the number of active requests is small, each step processes only a few new positions. Large matrix operations cannot fully utilize the hardware. In this case, the costs of reading model weights, accessing the cache, and scheduling execution can become prominent.

    Moderately increasing concurrency can improve weight reuse and hardware utilization. It also brings new problems: higher cache usage, interference between requests, and longer queueing time.

    For this reason, decoding optimization cannot focus only on generating more tokens per unit of time. It must also control the interval between output tokens for each request.

    3.3 Bottlenecks are not fixed labels

    Model size, context length, batch size, hardware bandwidth, cache precision, and parallelism strategy all change where the real bottleneck lies.

    The same model may be limited mainly by scheduling and weight access in a scenario with short inputs and low concurrency. In a long-context scenario, the same model may be significantly constrained by cache reads and attention computation.

    In engineering practice, bottlenecks should be identified through measurement. Deployment decisions should not rely only on the simplified idea that prefill is compute-bound and decoding is memory-bound.

    4. Three Levels for Implementing Asymmetric Optimization

    4.1 Operator and computation graph level: remove unnecessary results

    This level aims to keep the model’s function unchanged. The main techniques include:

    • Computing vocabulary outputs only for the positions the task actually needs.
    • Fusing adjacent operators to reduce intermediate tensor reads and writes.
    • Adjusting tensor layouts to lower the cost of cache access.
    • Pruning branches that do not affect the final output, when dependencies allow it.

    These optimizations are usually a good starting point because they do not require complex cross-node scheduling. However, “mathematically equivalent” does not always mean “bitwise identical in numerical output.” Operator fusion and changes in execution order can still introduce floating-point errors, so output consistency must be verified.

    4.2 Scheduling level: coordinate large and small tasks

    Prefill is usually a relatively concentrated block of work, while decoding consists of many small steps that repeat. If the two are scheduled together without care, a long-input request can cause noticeable pauses for requests that are currently generating output.

    A common approach is chunked prefill. The system splits a long input into several chunks and gives decoding tasks chances to run between chunks.

    The benefit is less blocking of decoding by long prefill work. The costs may include more scheduling overhead, additional state management, and changes in the completion time of individual prefill requests.

    A good strategy does not use one fixed chunk size. It adjusts dynamically based on the waiting queue, the number of active sequences, the remaining cache capacity, and latency targets.

    4.3 Deployment level: use separate resource pools for the two stages

    Separating prefill and decoding onto different deployments lets each type of task use batch sizes, parallelism strategies, and resource ratios that suit it.

    Separation is not free, however. After prefill finishes, the decoding side must be able to access the corresponding KV cache. The system therefore needs to transfer the cache or provide a cache mechanism that both sides can access efficiently.

    If the transfer, synchronization, and queueing overhead of the cache handoff is too high, the benefit of stage separation can be cancelled out. For workloads with very short inputs and low request volume, co-located deployment may be simpler and more efficient.

    For this reason, the comparison should cover the full request path, not only the execution time of each stage on its own.

    5. Cache Management Determines How Much Concurrency the System Can Handle

    5.1 Estimating cache capacity

    Under simplified conditions, where all layers share the same structure and keys and values use the same precision, the KV cache size for a single sequence can be approximated as:

    Cache bytes ≈ 2 × number of layers × number of cached tokens × number of KV heads × head dimension × bytes per element

    The factor of 2 accounts for the keys and the values.

    A real deployment must also account for memory alignment, block-based allocation, metadata, and temporary space used during execution. The result of this formula should not be treated as the total GPU memory requirement of the system.

    5.2 Long contexts reduce the room for concurrency

    As the context of a single request keeps growing, the cache space it occupies also grows. If the system limits concurrency only by request count and ignores the actual length of each request, GPU memory pressure can get out of control, and resource use can become uneven.

    A more reasonable admission control policy should consider:

    • The cache capacity already allocated;
    • The input length of the new request;
    • The expected output length and its uncertainty;
    • The safety margin to reserve;
    • The priority and latency targets of the request.

    Output length is hard to predict precisely. Admission policies therefore need to work together with runtime monitoring, reclamation, and exception handling.

    5.3 Shared cache requires strict matching conditions

    When several requests share the same prefix, reusing the prefix cache can reduce repeated computation, provided the model and execution conditions match.

    However, textual similarity does not mean a cache can be shared. The token sequence, position handling, model version, and any configuration that affects the computation must all meet the reuse requirements.

    In addition, multi-tenant systems should define clear isolation boundaries. Cache mechanisms must not expose data or behavioral information from other users.

    6. Building an Evaluation Method for Real Workloads

    A single throughput metric cannot show whether an inference service performs well. A complete evaluation should cover at least the following dimensions.

    6.1 Time to first token

    Time to first token (TTFT) includes more than prefill computation. It can also include request queueing, input processing, resource allocation, cache handoff, and the time to return the first result.

    If prefill operators are optimized but scheduling wait time increases, users may not perceive a faster response.

    6.2 Inter-token latency and output stability

    Average inter-token latency reflects the sustained generation speed. Teams should also track high-percentile latency and noticeable pauses.

    For interactive use, stable output often matters more than a slightly higher average speed with frequent stalls. During evaluation, record whether the output pace of existing requests changes when a long-input task enters the system.

    6.3 Effective throughput under service targets

    Measure how many requests or tokens the system can sustain while meeting the targets for TTFT, inter-token latency, success rate, and quality.

    Peak throughput without service targets may only come from increased queueing and worse interactive experience.

    6.4 Total cost and output quality

    Cost per effective request should include compute, cache, transfer, and necessary redundancy, not just the short-term utilization of a single device.

    Any approach involving low precision, cache compression, approximate computation, or changes to the model structure must also be evaluated for task quality. Lower resource consumption after output quality drops should not be counted as an optimization gain under equal conditions.

    7. A Lower-Risk Rollout Path

    Step 1: Establish a baseline. Collect the distribution of input and output lengths, changes in concurrency, stage timings, cache usage, and high-percentile latency. Confirm the actual workload instead of relying on a few demonstration requests.

    Step 2: Find wasted computation. Check whether vocabulary outputs are computed for positions that are not needed, whether any processing is duplicated, and whether the cache is reused as expected.

    Step 3: Optimize single-instance scheduling. Adjust continuous batching, chunked prefill, and admission control based on the real request distribution. Observe how throughput and latency change together.

    Step 4: Then evaluate stage separation. Include cache handoff, cross-node communication, and fault recovery in the tests. Confirm that the gains come from the full request path, not from a local metric.

    Step 5: Run continuous regression testing. After any change in model version, context length, concurrency pattern, or cache strategy, retest performance and quality. Do not carry old conclusions forward without verification.

    Conclusion

    The asymmetry between prefill and decoding is an important entry point for understanding LLM inference systems. It does not offer a shortcut for removing computation at will. It describes a set of dependencies and resource differences that require careful analysis.

    Effective optimization starts with three questions: which results truly do not need to be computed, which resources actually limit performance, and whether a local speedup translates into end-to-end gains.

    Only by measuring the computation graph, cache management, scheduling policy, and business goals within one framework can teams improve inference efficiency in a verifiable and sustainable way, while preserving correctness and output quality.