LLM Inference Optimization: How to Write to Memory Without Running the Full Network

    This article explains how to reduce prefill overhead in large language model inference by separating memory writes from prediction. It covers a shallow-forward plus lightweight memory-write design for hybrid models, low-rank compression of recurrent states to save memory bandwidth, a frozen-weight distillation approach for preserving output quality, and evaluation guidance for throughput and P90 latency. A deployment checklist and notes on running these optimizations on a cloud platform are also included.

    1. The Starting Point: Prefill and Decode Are Two Different Kinds of Compute Cost

    In large model inference serving, a request is usually split into two phases: prefill and decode. Prefill ingests the entire input at once and writes the key-value cache (KV Cache) and recurrent state for every position. Decode is autoregressive, one token at a time, and every step runs the full network depth.

    A common engineering mistake is to apply the same “must run all layers” assumption to both phases. In long-input, short-output encoding sessions, prefill then consumes most of the compute, even though that compute is not all spent on “predicting the next token.”

    The key distinction is this: preparing memory for later generation requires significantly less deep computation than producing a prediction at the current step. Handling these two things separately is the core optimization space discussed in this article.

    2. The Core Idea: Decouple “Writing to Memory” from “Making a Prediction”

    Take a 48-layer hybrid model as an example. When processing the input, every position except the last one runs only the first 31 layers. A lightweight memory-write component then fills in the KV Cache and recurrent state for the remaining 17 layers. In the actual generation phase, each token still runs all 48 layers, so output quality is unaffected.

    The scheduling logic looks like this (pseudocode, expressing the scheduling idea only):

    1. # Prefill: most positions go through shallow layers; the last position runs all layers
    2. for i, token in enumerate(input_tokens):
    3. h = shallow_forward(token, upto_layer=31)
    4. if i == len(input_tokens) - 1:
    5. kv, state = full_forward(token) # real prediction needed, run all 48 layers
    6. else:
    7. kv, state = memory_write(h, target_layers=range(31, 48))
    8. cache.append(kv); state_store.update(state)
    9. # Decode: full layers at every step, quality first
    10. while not done:
    11. kv, state, logits = full_forward(next_token, cache, state_store)

    The benefit comes from a repeatedly validated observation: the deep computation needed to write memory can be far less than the deep computation needed to predict. Assigning the cheap part to a lightweight component and reserving the expensive part for the actual generation steps lowers overall prefill cost.

    3. A Second Opportunity on the Decode Side: Low-Rank Compression of Recurrent States

    The recurrent state that a hybrid model reads and writes at every step often has a dominant component pointing in a nearly fixed direction, with the remainder forming a low-rank structure. Given that structure, there is no need to move it around repeatedly in dense form. Keeping the state in a decomposed form of “dominant direction plus low-rank residual” lets the model read and update it directly, saving a large amount of memory bandwidth and copy overhead.

    The compression effect is order-of-magnitude: a single request’s recurrent state drops from about 113MB to about 29MB right after compression, averaging about 43MB over the full compression cycle. For long sessions and multi-turn encoding scenarios, these savings translate directly into larger batch capacity and more stable tail latency.

    4. How Quality Is Preserved: Freeze the Original Weights and Distill the New Components

    Any approach that “computes a little less” has to answer for its accuracy cost. A workable engineering practice is to keep the original model weights frozen throughout and train only the new lightweight write component and the state encode/decode component, using distillation to align with the original model’s behavior. This leaves trained capabilities untouched while bringing the new components close to the output distribution of the original deep computation. Evaluation should cover multiple trained hybrid models and multiple checkpoints to form a reproducible quality baseline, rather than looking at a single metric.

    5. Engineering Deployment: How to Measure Throughput and Latency

    On a single accelerator card, with a mainstream inference framework and encoding session traces, this class of method delivers roughly 16% to 42% higher peak throughput per card; at an iso-speed comparison point on P90 user end-to-end output rate, the improvement is roughly 23% to 42%. Always fix the measurement setup when evaluating: the same set of requests, the same P90 constraint, and the same input/output length distribution. Otherwise the numbers are not comparable.

    Deployment checklist:

    • Quantify the prefill share first, and confirm the bottleneck is really memory writing rather than decoding;
    • Use shadow traffic to compare quality and latency between “full-layer prefill” and “shallow layers plus write component”;
    • Set a cycle and a fallback strategy for recurrent state compression to avoid accumulated error in long sessions;
    • Bring the new components into monitoring, alerting, and logging so anomalies are easy to locate.

    6. Working with General Cloud Capabilities

    To run this kind of optimization on your own platform, you can rely on general-purpose capabilities: a container platform for elastic scaling and canary releases, object storage for checkpoints and distillation artifacts, a message queue for smoothing traffic peaks, and monitoring, alerting, and logging services to observe P90 and throughput changes. Baidu AI Cloud has mature practice in these general capabilities and can serve as a reference foundation for hosting this kind of inference optimization.

    7. Summary

    Separating “writing to memory” from “making a prediction,” filling in deep-layer states with a lightweight component, and then applying low-rank compression to the recurrent state is a viable path to improving both throughput and tail latency without sacrificing generation quality. The key points are: freeze the original weights, align through distillation, fix the evaluation setup, and make the new components observable and able to fall back.