LLM Inference Acceleration: Layered Memory Writing and State Compression in Practice

    This article explores a general optimization approach for large language model inference: distinguishing the compute requirements of "writing memory" from "predicting the next token." During prefill, only shallow layers run full computation for most tokens, while a lightweight, distillation-trained memory writer generates KV cache and recurrent states for the skipped layers. During decoding, recurrent states are compressed via principal-component and low-rank decomposition. With original model weights frozen throughout, this combination delivers roughly 16%–42% throughput gains per GPU in coding-agent workloads and over 60% state memory compression—without sacrificing model capability.

    LLM Inference Acceleration: Layered Memory Writing and State Compression in Practice

    Introduction: The Structural Tension in Inference Costs

    LLM inference typically proceeds in two phases: prefill and decode. The prefill phase processes the entire input in parallel, generating key-value caches (KV Cache) and recurrent states for every layer. The decode phase then generates tokens autoregressively, one at a time. As input lengths keep growing, the compute cost of prefill and the memory footprint of stored states quickly become throughput bottlenecks.

    A question worth pondering: to “write memory” for subsequent generation, does every token really need to traverse the entire network? This article discusses one representative optimization idea built around that question: by distinguishing between two types of compute demand—“writing memory” and “predicting the next token”—the prefill phase runs only the shallow layers for most tokens, supplemented by a lightweight memory-writing component; meanwhile, the decode phase applies structured compression to recurrent states. Note that this article discusses only general technical methods, not any specific vendor or model product.

    Core Insight: Writing Memory and Predicting Tokens Have Different Compute Requirements

    The conventional inference pipeline assumes that every token performs a full forward pass through every layer. Research, however, has found that the compute requirements of these two tasks are not equal:

    • Predicting the next token requires high-level semantic representations from the model—the attention and nonlinear transformations of deep layers are indispensable.
    • Writing memory (i.e., preparing KV Cache and recurrent states for subsequent generation) often requires far less deep-layer computation.

    Based on this distinction, a layered execution strategy can be designed. Take a 48-layer hybrid-architecture model as an example: during prefill, all tokens except the last one in the sequence run only the first 31 layers. A lightweight “memory writer” component then generates the KV Cache and recurrent states for the remaining 17 layers. The last token still traverses the full network, because it is responsible for predicting the next token. Once decoding begins, each newly generated token again runs all 48 layers, ensuring generation quality is unaffected.

    The essence of this design is converting deep-layer computation from “applied to every token” into “applied only to the tokens that need it,” significantly reducing prefill compute. Related research has measured this compute-requirement gap across multiple trained hybrid-architecture models, validating the generality of the hypothesis.

    Key Mechanism 1: A Lightweight Memory Writer Trained via Distillation

    For the layered execution strategy to work, the memory writer must supply memory to the deeper layers at sufficiently low cost and sufficiently high fidelity. Its design principles include:

    1. Original model weights remain frozen throughout: no parameters of the trained model are modified, preserving existing capabilities and reducing deployment risk.
    2. The new component is trained via distillation: the lightweight component learns the mapping from “shallow-layer output → deep-layer memory,” using the KV Cache and recurrent states produced by the original model’s full forward pass as distillation targets.
    3. The component is much smaller than the layers it replaces: only this guarantees a net compute gain.

    A typical distillation training procedure can be sketched as follows:

    1. # Pseudocode: distillation training of the memory writer
    2. for batch in prefill_data:
    3. # Teacher path: full forward pass, collecting memory from the last 17 layers
    4. with torch.no_grad():
    5. teacher_kv, teacher_state = full_forward(batch)
    6. # Student path: shallow forward pass + memory writer
    7. hidden_shallow = shallow_forward(batch, layers=31)
    8. student_kv, student_state = memory_writer(hidden_shallow)
    9. # Reconstruction error on memory tensors as the loss
    10. loss = mse(student_kv, teacher_kv) + mse(student_state, teacher_state)
    11. loss.backward()
    12. optimizer.step()

    The advantages of this approach are a clear training objective, decoupling from downstream tasks, and the ability to reuse the same training pipeline across multiple model checkpoints.

    Key Mechanism 2: Principal-Component + Low-Rank Compression of Recurrent States

    The decode phase also offers substantial room for optimization. Hybrid-architecture models read and write recurrent states at every step, and analysis of these state tensors reveals that they typically contain a principal component aligned with a nearly fixed direction, while the remainder exhibits low-rank structure. This means the state can be decomposed as:

    1. State ≈ Principal component (fixed direction × scalar coefficient) + Low-rank residual (U × V)

    By storing the recurrent state in this decomposed form and having the model read and update it directly in that form, memory usage can be greatly compressed. In actual measurements, the recurrent state per request dropped from roughly 113MB to about 29MB after compression; accounting for overheads such as periodic reconstruction, the average across the full compression cycle is about 43MB—a compression rate exceeding 60%.

    The benefits of state compression go beyond memory: during decoding, every step reads the state from memory and writes back the updated state. Shrinking the state directly reduces memory bandwidth pressure—and bandwidth is precisely one of the main constraints on decode throughput. Two engineering considerations deserve attention:

    • Stability of the principal-component direction: if the direction drifts over time, the state must be periodically re-estimated and reconstructed, and this overhead must be included in the overall benefit calculation.
    • Numerical precision: the choice of rank for the low-rank approximation involves a trade-off between compression ratio and reconstruction error; it should be determined in combination with accuracy evaluation.

    Accuracy Cost and Quality Evaluation

    Every inference optimization must answer one question: how much accuracy is lost? For the two types of changes described above, systematic evaluation should be conducted across multiple model families and checkpoints, covering typical capability dimensions such as general understanding, code generation, and long-context performance. Since the original model weights are frozen and the new component is aligned through distillation, the evaluation focus is twofold: whether the gap between layered-written memory and full-forward memory gets amplified during long-sequence generation, and whether low-rank state compression produces error accumulation over multiple rounds of decoding. The practical recommendation is to make accuracy evaluation a hard gate in the release process—any adjustment to compression ratio or the number of skipped layers must be accompanied by a full re-run of the evaluation suite.

    Measured Gains and Applicable Scenarios

    Tests on high-end data-center GPUs with mainstream inference frameworks, targeting coding-agent session traces, show that this combined optimization improves peak per-GPU throughput by roughly 16%–42%. At comparison points with the same P90 user-perceived end-to-end output rate, throughput improves by roughly 23%–42%. The wide range indicates that the optimization effect is closely tied to workload characteristics—the longer the input and the higher the prefill share, the more pronounced the gains from layered execution; the higher the concurrency and the larger the total state volume, the more valuable state compression becomes.

    For enterprise deployment, these optimizations can be layered on top of general-purpose container platforms and inference services, with monitoring and alerting systems tracking changes in throughput, latency, and memory usage while gradually ramping up traffic.

    Conclusion

    The core of LLM inference optimization is finding the parts of computation and storage that are “done but not necessary.” Layered memory writing exploits the structural difference that writing memory requires far less deep-layer computation than predicting tokens; principal-component and low-rank state compression exploits the intrinsic structure of state tensors. Neither modifies the original model weights—both are implemented through distillation and decomposition, keeping engineering risk manageable. For teams building LLM inference services, this approach offers a viable path to higher throughput and lower cost without sacrificing model capability.