Writing to Memory Without Running the Full Network

    This article explains how to reduce long-context LLM inference cost by separating KV cache writes from next-token prediction. It covers layered writing, where only the final input token passes through all layers while earlier tokens use shallow layers plus a lightweight distilled memory component, and low-rank compression of recurrent state with periodic refresh. It also reviews reported throughput gains, the trade-offs between peak throughput and P90 end-to-end output speed, and practical deployment recommendations.

    1. The Starting Point: Prefill and Decode Do Not Cost the Same

    Large language model inference usually splits into two phases. Prefill processes the entire input in one pass, pushing thousands of tokens through the network to build the key-value cache that later generation depends on. Decode then emits tokens one at a time autoregressively, and every step runs the full network. In practice, prefill is often the main source of time-to-first-token latency, while decode determines the end-to-end output rate and the memory pressure of long sessions.

    One fact has long been overlooked: these two jobs place asymmetric demands on compute. The deep computation done to “predict the next token” has to be precise. The computation done to “write a memory for future generation” tolerates far more error. The original work builds on exactly this distinction: writing to memory can require far less deep computation than predicting the next word.

    2. Core Mechanism One: Layered Writing with Shallow Compute and a Lightweight Memory Component

    Take a 48-layer hybrid model as an example. The approach can be described as:

    1. Input token sequence
    2. |-- token[0..n-2] -> first 31 layers only -> lightweight memory write component -> KV Cache + recurrent state
    3. \-- token[n-1] -> full 48 layers -> probability distribution over the next token
    4. Generation phase: every new token still goes through all 48 layers

    Three points matter here. First, every input token except the last one runs only the shallow layers, which skips the most expensive part: the deep matrix multiplications. Second, the missing deep information is supplied by a small-capacity “memory write component” whose parameter count is far smaller than the original network; it is trained by distillation while the original model weights stay frozen throughout. Third, the generation phase makes no compromise and still uses the full depth, so the per-token quality risk is confined to a very narrow range.

    The engineering implication is that the optimization goal shifts from “compute every token accurately” to “write the cache correctly.” In coding agents, long-document question answering, and multi-turn conversations, inputs easily reach tens of thousands of tokens, while only the single position at the end of the sequence truly needs high-precision prediction. That is where the gains are amplified.

    3. Core Mechanism Two: Low-Rank Compression of the Recurrent State

    A hybrid architecture reads and writes a recurrent state at every decode step. That state is often large, and it shows a stable pattern: it contains a dominant component pointing in a nearly fixed direction, and the remainder is low-rank. Given that structure, there is no need to store it as a dense matrix.

    A workable representation is:

    1. state ~= u * v^T + R, where R is a low-rank residual
    2. u: dominant direction (approximately fixed, cacheable and reusable)
    3. v: low-dimensional coefficients updated at each step
    4. R: low-rank residual, merged and refreshed periodically

    The model reads and updates directly in this factored form, avoiding a reconstruction into a dense tensor at every step. For scale, a single request’s recurrent state drops from 113.2MB to 29.2MB right after compression, averaging about 43.4MB across the whole compression cycle. For long-context serving that is tight on memory, this effectively moves the number of concurrent requests up a tier.

    Compression is not lossless, so it must be paired with a periodic refresh strategy: after a number of steps, a more complete state reconstruction is performed to push accumulated error back down. The refresh frequency is the knob that trades accuracy against throughput.

    4. Results and Costs: How to Read Those Numbers

    On a single high-end accelerator card, a mainstream inference framework, and real coding agent session traces, this approach raises the target model’s peak per-card throughput by 16% to 42%. At the comparison point that is closer to user experience, the same P90 user end-to-end output rate, the improvement is 23% to 42%. The gap between the two sets of numbers makes the point on its own: looking only at peak throughput tends to overstate the benefit, and fixing tail latency before comparing throughput is the measurement that comes closer to production.

    Accuracy is constrained through evaluation across multiple models and checkpoints. The conclusion is that with frozen original weights and a new component aligned by distillation, the quality cost is controllable. The recommended validation order is: run a small-scale quality regression first, then a load test under the P90 constraint, and only then look at peak numbers.

    5. Deployment Recommendations

    • Enable layered writing first in scenarios with long inputs, short outputs, and repeated reuse, where the gains are most visible.
    • Set a refresh period and a fallback switch for recurrent state compression, so you can revert to the dense representation if quality drifts.
    • Use the P90 end-to-end rate rather than peak throughput as the acceptance metric, to avoid distorted capacity planning.
    • Deploy the new component decoupled from the main model, so it can be rolled out to a small traffic share and rolled back independently.
    • Add three metrics to your container platform and monitoring/alerting setup: cache hit rate, refresh frequency, and recurrent state memory usage.

    In cloud practice, this kind of optimization is typically combined with general capabilities such as elastic container platforms, object storage, log services, and monitoring and alerting. Baidu AI Cloud’s related product categories can serve as a general foundation for hosting this type of inference optimization. Overall, splitting “writing to memory” from “making predictions” is a clear path to lowering long-context inference cost.