Prefill Memory-Write Optimization and State Compression for Large Model Inference

    This article examines two optimization opportunities for large model inference: reducing prefill cost by writing memory from shallow representations for most tokens while reserving full-depth computation for anchor tokens, and compressing recurrent state into a principal component plus a low-rank residual during decode. It covers the underlying asymmetry between prefill and decode, pseudocode for both optimizations, a distillation-based setup with frozen model weights, reported throughput results under specific conditions, and engineering considerations around anchor selection, component capacity, error control, batching, and P90 metrics. It also outlines applicable boundaries and risks.

    Prefill Memory-Write Optimization and State Compression for Large Model Inference

    1. Background: Computational Asymmetry Between Prefill and Decode

    Large model inference is typically divided into two stages: prefill and decode. In the prefill stage, the entire input is processed at once, generating the KV Cache and recurrent state required by later layers for each token. In the decode stage, tokens are generated one at a time, and each step reads and updates the existing memory. In conventional implementations, prefill often runs the full network depth for every input token. As context length and batch size grow, prefill can quickly become a throughput bottleneck.

    However, prefill and decode do not have exactly the same computational goal. Each decode step must predict the next token based on the full context and therefore needs complete deep representations. A primary task of prefill is to “write” input information into memory that later generation can read. This creates an exploitable opportunity: writing memory for later generation may not require the same amount of deep computation as per-token next-token prediction. In other words, not every token in prefill needs to pass through all deep layers. Some tokens can complete memory writes using shallow representations plus a lightweight mapping.

    This approach is not simply “skipping computation.” It reallocates computation: deep computation for most tokens is compressed into lightweight memory writes, while full deep computation is reserved for a small number of key anchor tokens. The goal is to reduce prefill FLOPs while preserving memory quality as much as possible.

    2. Key Observation: Writing Memory Is Not the Same as Per-Token Prediction

    In an experimental description of a 48-layer mixture-of-experts model, the prefill stage uses a segmented strategy: except for the last token, all other tokens run only the first 31 layers, and a lightweight memory-write component then generates the KV Cache and recurrent state for the remaining 17 layers. The last token still runs all 48 layers. In the generation stage, every token still runs all 48 layers.

    The key is to distinguish two types of computation:

    1. Per-token prediction computation: In decode, every token needs complete deep representations to maintain next-step prediction quality.
    2. Memory-write computation: In prefill, KV Cache and recurrent state must be prepared for later layers, but deep representations can be approximated from shallow representations plus a lightweight component.

    Keeping the last token on the full path provides a high-quality anchor representation. The lightweight memory-write component uses shallow outputs and anchor information as conditions to predict the KV Cache and recurrent state that should be written for later layers. This way, most tokens do not need to bear full deep computation, prefill overhead drops significantly, and the generation stage still keeps full-layer computation so that decode quality is not directly weakened.

    The pseudocode is as follows:

    1. def prefill(tokens, model, memory_writer):
    2. # Most tokens run only shallow layers; the last token runs full layers
    3. shallow_states = []
    4. for token in tokens[:-1]:
    5. h = model.run_layers(token, start=0, end=31)
    6. shallow_states.append(h)
    7. anchor = model.run_layers(tokens[-1], start=0, end=48)
    8. # The lightweight component generates later-layer KV Cache and recurrent state for shallow tokens
    9. kv_cache, recurrent_state = memory_writer(
    10. shallow_states=shallow_states,
    11. anchor=anchor,
    12. target_layers=range(31, 48)
    13. )
    14. return kv_cache, recurrent_state
    15. def decode_step(token, model, kv_cache, recurrent_state):
    16. # During generation, every token still runs all layers
    17. h = model.run_layers(token, start=0, end=48,
    18. kv_cache=kv_cache,
    19. recurrent_state=recurrent_state)
    20. return h

    The effectiveness of this scheme depends on an empirical judgment: the marginal contribution of deep computation to “memory writes” is lower than its marginal contribution to “per-token prediction.” If this judgment holds for the target model and task distribution, it can trade a small quality cost for a clear throughput gain. If it does not hold, the shallow-layer ratio, anchor selection, or lightweight component capacity must be adjusted.

    3. Decode-Side Opportunity: Principal Components and Low-Rank Residuals in Recurrent State

    Beyond prefill, there is another optimization opportunity on the decode side. The recurrent state read and written at each step often contains a principal component with a nearly fixed direction, while the remaining content has a low-rank structure. In other words, the state is not fully high-rank and dense; it can be expressed in a decomposed form of “principal component + low-rank residual.”

    Therefore, the state can be stored in decomposed form, allowing the model to read and update the principal component and low-rank residual directly instead of reading and writing the full high-dimensional state at every step. On a specific 48-layer mixture-of-experts model, the per-request recurrent state dropped from 113.2 MB to 29.2 MB immediately after compression, with an average of 43.4 MB over the entire compression cycle. Here, “average over the compression cycle” indicates that the state periodically changes between compressed and expanded forms, and average occupancy reflects actual memory pressure better than peak occupancy.

    From an engineering perspective, state updates can be written as:

    1. def update_state(state, delta):
    2. principal, residual = state.decompose()
    3. principal = principal + delta.project_to_principal()
    4. residual = residual + delta.project_to_low_rank()
    5. return state.compose(principal, residual)
    6. def read_state(state):
    7. principal, residual = state.decompose()
    8. return state.reconstruct(principal, residual)

    This decomposition is not a simple substitute for lossless compression. It restricts state reads and writes to a more compact representation space. Benefits include lower state memory usage, reduced per-step state read/write bandwidth, and potentially better cache locality during batching. The costs are extra operator overhead from decomposition and reconstruction, plus approximation error introduced by low-rank truncation. Quality evaluation is needed to determine the rank size and update frequency.

    4. Experimental Design and Results

    Experiments were conducted on five trained hybrid-architecture models and six checkpoints for quality evaluation to test the accuracy cost of these changes. The original model weights remained frozen throughout, and the new components were trained through distillation. This point is important: the approach does not retrain the main model. Instead, lightweight components learn “how to write deep memory from shallow representations” and “how to read and write decomposed states,” reducing damage to the original model’s capabilities.

    On a specific accelerator, inference runtime, and coding agent session traces, this approach improved the per-card peak throughput of a 48-layer mixture-of-experts model by 16% to 42%. At the comparison point of the same P90 end-to-end output rate, throughput improved by 23% to 42%. The P90 metric emphasizes tail experience, indicating that the gains are not limited to average throughput but also appear under a user-perceived end-to-end output rate constraint.

    It should be emphasized that these numbers come from specific experimental conditions and cannot be directly extrapolated to all models, context lengths, and batch configurations. Before deployment, a small-scale A/B evaluation should be run to observe prefill time, decode step time, state memory usage, P90 end-to-end rate, and quality regression, and then decide the shallow-layer ratio, anchor strategy, and state rank size.

    5. Engineering Implementation Considerations

    1. Anchor token selection should be stable. Using the last token as the full-path anchor is a simple strategy, but in multi-turn conversations, tool calls, and long document inputs, the last token may not carry all key information. Consider evaluating anchors by position, attention salience, or multi-anchor sampling, and ensure consistency between training and inference.

    2. The lightweight memory-write component should have a capacity limit. This component generates KV Cache and recurrent state for later layers. Too little capacity limits memory quality, while too much capacity offsets prefill gains. It is recommended to run ablations under the constraint of “extra computation per token / saved deep computation.”

    3. State compression should control error accumulation. Principal-component and low-rank-residual decomposition requires monitoring reconstruction error, state norm drift, and long-sequence tail quality. Periodic full-state calibration can be set, or the system can fall back to the full-state path when error exceeds a threshold.

    4. Batching and cache consistency. Different requests in prefill may use different shallow-layer ratios, so batching must handle differences in computation graphs. The layout of KV Cache and recurrent state should remain consistent to avoid extra copies caused by frequent switching between compression and expansion.

    5. Metrics should focus on P90, not only the mean. If throughput gains come at the cost of tail latency degradation, user experience may suffer. It is recommended to report per-card peak throughput, P90 end-to-end output rate, first-token latency, peak state memory, and quality evaluation scores together.

    6. Applicable Boundaries and Risks

    This method is suitable for scenarios with a high prefill proportion, long contexts, and obvious state read/write bandwidth pressure, such as long-document question answering, multi-turn conversations, and coding agent session traces. For short inputs, strict real-time first-token latency, or scenarios with very low quality tolerance, the gains may be limited, or the lightweight component overhead may outweigh the benefits.

    Main risks include: an excessively high shallow-layer ratio causing memory-write bias; poor anchor selection causing loss of key information; low-rank compression accumulating error over long sequences; and the distillation component overfitting the training distribution. In engineering practice, keep a full-path fallback switch, roll out gradually by model, task, and traffic, and use quality evaluation as the launch gate.

    Overall, the core of this type of optimization is not “computing less” but “placing compute where it is more needed”: prefill uses shallow encoding plus lightweight memory writes to reduce write cost, decode uses principal components and low-rank residuals to reduce state read/write cost, and generation still keeps full computation to protect the quality floor. For inference systems pursuing per-card throughput and long-context efficiency, this is an optimization path worth systematic evaluation.