How Hierarchical Memory Writes Improve LLM Inference Throughput

    This article explains how hierarchical memory writes can improve large language model inference throughput by treating prefill and decode as two distinct workloads. It covers running only shallow layers during prefill with a lightweight memory writer, compressing recurrent states into a main direction plus low-rank residuals, and combining both changes to reduce compute and memory costs. Readers will find pseudocode, engineering caveats, quality evaluation dimensions, and practical deployment advice for coding agent workloads.

    1. Background: Prefill and Decode Are Two Different Compute Bills

    LLM inference is often treated as a single forward pass. From a resource consumption perspective, however, it contains two stages with very different characteristics.

    The prefill stage processes the entire input. Its compute cost scales roughly with input length, and all tokens can be processed in parallel. This makes it a compute-intensive workload that directly determines time to first token. The decode stage generates tokens one by one. Each step processes only one new position but repeatedly moves weights and historical state, making it a memory-intensive workload that directly determines output speed and per-GPU concurrency.

    In coding agent sessions, the gap between these two stages becomes even larger. A single task often involves long context injection, multiple tool calls, and repeated rewrites. The input side can easily reach tens of thousands of tokens, while the actual new output may be only a few hundred to a few thousand tokens. With a naive implementation where every token passes through the full network depth, a large amount of compute is spent “writing memory for future steps” rather than “deciding the next token.”

    This leads to the core question of this article: does writing memory really require reading the entire network?

    2. Core Insight 1: Writing Memory Requires Far Less Depth Than Predicting the Next Token

    A trained hybrid-architecture LLM typically has dozens of layers. Take a 48-layer model as an example. A naive implementation requires every input token to pass through all 48 layers before the corresponding key-value cache and recurrent state can be written.

    These two tasks do not place equal demands on representation quality:

    • Predicting the next token requires a high degree of integration of semantics, syntax, facts, and world knowledge, often relying on the deepest layers.
    • Preparing “good enough memory” for subsequent steps only requires compressing the context at that position into the cache and state, with significantly lower dependence on deep abstraction.

    This suggests an asymmetric strategy: except for the last position, all other tokens run only the first several layers (for example, 31 layers). A lightweight memory writing component then fills in the key-value cache and recurrent state required for the remaining 17 layers. During generation, each new token still goes through all 48 layers, ensuring output quality is not weakened.

    The control flow can be expressed in pseudocode:

    1. # Prefill: shallow backbone + lightweight memory completion
    2. def prefill(hidden, layers, writer, split=31):
    3. for i in range(split):
    4. hidden = layers[i](hidden)
    5. kv_cache, recurrent_state = writer(hidden, target_depth=len(layers))
    6. return kv_cache, recurrent_state
    7. # Decode: full depth, token-by-token generation
    8. def decode(last_hidden, layers, cache, state):
    9. for t in range(max_new_tokens):
    10. h = last_hidden
    11. for layer in layers:
    12. h = layer(h, cache, state)
    13. last_hidden = h
    14. yield argmax(h)

    Three engineering points deserve attention. First, the split point is not a mysterious hyperparameter. It should be determined by whether memory quality still drops noticeably after that layer, usually evaluated through layer-by-layer probing. Second, the memory writing component must strictly align with the model’s inter-layer normalization and positional encoding; otherwise, the cache distribution will drift. Third, the last position must go through the full depth because it directly determines the distribution of the first output token.

    3. Core Insight 2: Recurrent States Have a “Main Direction + Low-Rank Residual” Structure

    The recurrent state read and written at each step in a hybrid-architecture model is the main source of memory access overhead on the decode side. Observations show that this state typically exhibits two characteristics along the time dimension:

    1. There is a main component close to a fixed direction that changes little as steps increase.
    2. The residual matrix after removing the main component has clear low-rank properties.

    The state can therefore be stored in a decomposed form rather than as a dense matrix:

    1. S_t ≈ u * c_t + A_t B_t
    2. # u: approximately fixed main direction (can be cached and reused)
    3. # c_t: scalar or low-dimensional coefficient
    4. # A_t (d×r), B_t (r×d): low-rank residual, r << d

    The model operates directly on this decomposition when reading and updating. The main direction is materialized once and kept resident, while updates mainly fall on the low-rank factors. The source material provides a reference magnitude: the recurrent state per request drops from 113.2MB to 29.2MB right after compression, with an average of about 43.4MB over the entire compression cycle—nearly a 2.6x reduction in resident GPU memory, which translates directly into higher concurrent batches and less swapping in and out.

    Implementation recommendations: refresh the main direction periodically with a moving average; treat the low-rank rank r as an explicit quality-memory tradeoff knob; and periodically re-orthogonalize the residual to avoid factor degradation during long sessions.

    4. Combined Effect: Why the Two Changes Should Be Made Together

    On their own, shallow prefill optimizes compute, while state compression optimizes memory and bandwidth. Only when combined do they form a closed loop: after prefill becomes cheaper, more requests can be accepted per unit time; after the state becomes smaller, the resident cost of these requests is low enough to open larger batches. This is why throughput gains amplify nonlinearly.

    In a combined environment of a single GPU, an inference framework, and real coding agent traces, one class of public measurements shows: peak throughput per GPU improves by about 16%–42%; when the comparison point is aligned to the same P90 user end-to-end output speed, the improvement range is 23%–42%. The latter metric is more meaningful from an engineering perspective—it answers “how many more requests can I serve without slowing down the user experience.”

    5. How to Evaluate the Quality Cost: Don’t Look Only at Average Scores

    Any scheme that trades compute for efficiency must provide an accuracy ledger. At least four dimensions should be covered:

    • Benchmark tasks: decomposed evaluation of commonsense, math, code, and long-text understanding, rather than a single overall score.
    • Long context: recall and multi-hop reasoning performance at different input lengths.
    • Session consistency: whether style drift or factual forgetting occurs after multiple rounds of rewriting.
    • Sampling stability: shifts in the output distribution under changes in temperature and sampling parameters.

    The evaluation matrix should cover multiple model sizes and multiple training checkpoints to distinguish “problems with the method itself” from “random fluctuations of a particular checkpoint.”

    6. Deployment Advice and Common Pitfalls

    1. Profile before acting: use monitoring and logging services to confirm whether your workload is prefill-dominated or decode-dominated. The ratio determines the upper bound of the gains.
    2. Canary and rollback: make the number of split layers and the low-rank rank configurable, roll out gradually by traffic percentage, and keep a one-click fallback.
    3. Cache consistency: prefix reuse, paged cache, and state compression should be designed together to avoid repeatedly materializing the main direction.
    4. Capacity planning: memory savings should be converted into larger batches and more concurrency, not left idle.
    5. Observability: separately instrument time to first token, P90 output speed, cache hit rate, and state compression cycle time.

    When deployed in the cloud, this type of optimization usually works with common capabilities such as container platforms, object storage, message queues, logging services, and monitoring alerts: container platforms host elastic inference instances, object storage stores models and checkpoints, message queues smooth out peaks and fill valleys, and logging and monitoring help locate the actual behavior of split points and rank values.

    7. Conclusion

    The value of the judgment “writing memory does not require reading the entire network” is that it moves inference optimization from “overall acceleration” to “stage-by-stage decomposition.” Prefill uses a shallow backbone plus lightweight writing, and decode uses a main direction plus low-rank residuals. Together they reduce both the compute bill and the memory bill. For developers, the real takeaway is not a particular percentage but a reusable methodology: first identify the workload structure, then make asymmetric investment in asymmetric stages, and finally back efficiency with a strict quality matrix.