Optimizing LLM Prefilling: Shallow Memory Writing and State Compression
This article explores an optimization strategy for Large Language Model (LLM) inference systems aimed at reducing the computational and storage overhead of the prefilling phase. By decoupling the requirements of memory writing from next-token prediction, the approach utilizes shallow prefilling combined with a lightweight memory writer and recurrent state compression. The article details the methodology, system benefits, evaluation metrics, and practical engineering recommendations for implementing this technique while maintaining generation quality.
In Large Language Model (LLM) inference systems, prefilling and decoding are two phases with vastly different computational characteristics. Prefilling processes long inputs simultaneously, featuring high computational volume and parallelism, which often determines the Time To First Token (TTFT) and overall throughput limits. Decoding, on the other hand, generates tokens sequentially with a smaller per-step computational footprint, but is highly sensitive to cache read/write operations, state updates, and end-to-end latency. A compelling question arises: since the decoding phase still needs to run the full network, is it truly necessary for every input token to pass through all deep layers during the prefilling phase? This article discusses a neutral optimization approach—using shallow prefilling with lightweight memory writing, combined with recurrent state compression—to reduce prefilling computation and state storage overhead while maintaining the complete network path during the generation phase.
1. Background: Compute Asymmetry in Prefilling and Decoding
In traditional inference workflows, the input sequence first passes through all network layers to generate the KV Cache and recurrent state for each layer, before entering the token-by-token decoding phase. The computational load of the prefilling phase grows with input length, and every layer must prepare caches for subsequent decoding. For scenarios such as long-context processing, code agent sessions, and multi-turn conversations where inputs are often lengthy, prefilling easily becomes a throughput bottleneck.
However, the goal of prefilling is not entirely equivalent to “understanding and predicting the next token.” It is more akin to “writing memory” for subsequent generation: compressing useful information from the input into caches and states for the decoding phase to read. The deep computation required for writing memory does not necessarily need to be identical to that required for predicting the next token. In other words, there is a computational redundancy in the prefilling phase that can be exploited: the marginal contribution of some deep transformations to cache writing may be lower than their contribution to next-token prediction.
2. Key Insight: Different Needs for Memory Writing vs. Next-Token Prediction
Predicting the next token typically requires deep semantic integration, context disambiguation, and output distribution calibration. Conversely, generating the KV Cache and recurrent state for subsequent layers relies more on feature projection, summarization, and state initialization. These two tasks have different sensitivities to network depth. If most tokens in the prefilling phase only pass through shallow layers, and a lightweight component learns “how to generate caches for subsequent deep layers,” there is an opportunity to reduce computation.
This is not equivalent to simply truncating the network. Truncation would destroy deep representations. The lightweight component must be trained to map from shallow representations to the caches and states required by subsequent layers. The main weights of the original model can remain frozen, while the new component is trained via distillation, using the full model’s behavior as the supervisory signal. This reduces training costs and minimizes disturbance to the original model’s capabilities.
3. Shallow Prefilling and Lightweight Memory Writing
Taking a 48-layer hybrid architecture model as an example, a feasible workflow is: during prefilling, all input tokens except the last one only run the first 31 layers; the last token retains the full path to maintain complete semantics at the boundary. Subsequently, a lightweight memory writing component generates the KV Cache and recurrent state for the remaining 17 layers based on the representations from the first 31 layers. Once the generation phase begins, each token still runs the full 48 layers.
The pseudocode can be abstracted as follows:
L = 48SPLIT = 31def prefill(tokens):shallow = run_layers(tokens[:-1], 0, SPLIT)last = run_layers(tokens[-1:], 0, L)tail_cache, tail_state = memory_writer(shallow, layers=range(SPLIT, L))return merge_cache(last, tail_cache, tail_state)def decode_step(token, cache, state):# Decoding phase does not truncate; still runs the full networkreturn run_layers(token, 0, L, cache=cache, state=state)
The core here is not a fixed number of layers, but “selecting the truncation layer based on sensitivity.” Different layers contribute differently to cache writing; a truncation layer that is too shallow will lose information, while one that is too deep yields limited benefits. In engineering, offline evaluation can determine each layer’s sensitivity, followed by selecting a global or module-specific truncation strategy. The capacity of the lightweight memory writing component should also be controlled; otherwise, the newly added computation will offset the prefilling savings.
4. Decomposed Storage of Recurrent State
There is another optimization space on the decoding side: the recurrent state read and written by the model at each step often contains a near-fixed principal component, with the remaining content exhibiting a low-rank structure. If the state is saved in a decomposed form as “principal component + low-rank residual,” the model can directly read and update the decomposed form instead of expanding the full high-dimensional state every time.
This can be represented as:
S ≈ d · u + U · V
Where d·u represents the near-fixed principal direction, and U·V represents the low-rank residual. In the given example, the recurrent state per request was reduced from 113.2MB to 29.2MB immediately after compression, averaging 43.4MB throughout the compression cycle. This benefit comes from reduced storage and read/write bandwidth. However, the compression rank, update frequency, and error accumulation require joint tuning. State compression is not lossless; quality evaluation is needed to confirm its impact on long-range dependencies and generation stability.
5. System Benefits and Evaluation Methods
In a test environment utilizing a specific accelerator, inference framework, and code agent session traces, the proposed scheme increased the peak throughput per accelerator of the 48-layer hybrid architecture model by 16% to 42%. At the comparison point of the same P90 client end-to-end output rate, throughput increased by 23% to 42%. The P90 comparison point means evaluating not just average throughput but also constraining the tail user experience, avoiding trading high-latency requests for better averages.
The evaluation should cover five trained hybrid architecture models and six checkpoints, assessing throughput, TTFT, state memory footprint, and generation quality. Quality evaluation must include general capabilities, long context, code, and structured output tasks, while distinguishing the accuracy cost of prefilling truncation from that of state compression.
6. Accuracy Cost and Training Strategy
Keeping the original model weights frozen and training the new component via distillation is a relatively robust strategy. The training objective can be understood as making the shallow representation, after passing through the memory writer, approximate the cache and state generated by the full deep layers as closely as possible; meanwhile, ensuring that reading and updating under the compressed state maintains the original model’s behavior. Three types of risks need attention: information bottlenecks caused by improper truncation layer selection; training complexity if the memory writer is too strong, or quality degradation if it is too weak; and error accumulation from low-rank state compression on long sequences.
From an engineering perspective, a phased rollout is recommended: start with offline evaluation, followed by small-traffic canary testing; set switches based on request types; retain a fallback to the full path for quality-sensitive tasks; and monitor P90 latency, state memory, cache hit rate, and output quality metrics.
7. Engineering Implementation Recommendations
- Select the truncation layer based on layer sensitivity; do not blindly fix a ratio.
- Keep the memory writing component lightweight, prioritizing the reuse of existing features to avoid adding too many operators.
- Tune the state compression rank according to the model and task, paying attention to error accumulation in long sequences.
- Evaluate throughput benefits jointly with P90 latency and TTFT to avoid single-metric optimization.
- Retain a fallback path so that highly sensitive requests can switch back to full prefilling.
- Ensure training and evaluation data cover real session traces, especially mixed scenarios of long input/short output and long decoding.
8. Applicable Boundaries and Conclusion
This approach is more suitable for inference scenarios with a high prefilling ratio, long inputs, and frequent state read/writes. For tasks with extremely short inputs or extreme sensitivity to quality, the benefits may be limited and require cautious evaluation. Its essence is decoupling the computational requirements of “prefilling memory writing” from “decoding next-token prediction”: prefilling does not require all tokens to run the full network, while decoding maintains the complete path. Simultaneously, decomposed state storage reduces read/write overhead. Through distillation compensation and system-level evaluation, higher throughput can be exchanged for at a controllable accuracy cost. For engineering teams pursuing inference efficiency, this is an optimization path worth validating.
