Reducing LLM Inference Costs with Lightweight Memory Writing and State Compression

    Long-context LLM inference faces two distinct costs: computing context state during prefill and accessing that state during decoding. This article explains how partial-depth prefill with a lightweight memory writer and low-rank recurrent-state compression address these bottlenecks. It covers their execution paths, training requirements, reported performance, quality evaluation, and practical deployment considerations.

    1. Why Long Contexts Make Inference Expensive

    Large language model inference typically has two stages. Prefill processes the input tokens together to establish the context state needed for generation. Decode generates output tokens one at a time, accessing the accumulated state at every step.

    Longer inputs increase the cost of both stages. Prefill requires more computation, while the key-value cache (KV cache) and recurrent states consume substantial GPU memory. In coding-agent workloads, a single session may contain dozens of tool calls and code snippets, easily reaching tens of thousands of tokens. GPU memory capacity and bandwidth can then become bottlenecks before compute capacity does.

    This creates two relatively independent opportunities for optimization:

    1. Reduce deep-layer computation during prefill. If the memory needed for subsequent generation can be written with less computation, not every input token needs to pass through the entire network.
    2. Reduce the state accessed during decoding. If recurrent states contain structural redundancy, a more compact representation can reduce memory traffic at each step.

    The following sections examine these approaches and how they can work together.

    2. The Core Observation: Writing Memory Requires Less Computation Than Predicting the Next Token

    Most model layers contribute to the final output distribution. Deeper layers increasingly specialize in determining the next token. Writing memory for later generation, however, is a different task: it encodes input information into caches or states without necessarily requiring a complete deep representation at every input position.

    The implication is that all input tokens except the final one may need to pass through only an initial subset of layers. Their intermediate representations can then be used to construct the caches required by deeper layers. The final input token still needs the full network because its output directly determines the distribution for the first generated token.

    This observation must be validated experimentally. The best split point varies by architecture. Skipping too many layers can degrade memory quality; skipping too few produces limited savings. An implementation should therefore measure the target model layer by layer rather than apply a fixed depth ratio.

    3. Prefill: Partial-Depth Computation with a Lightweight Memory Writer

    3.1 Execution Flow

    The proposed prefill path has three steps:

    1. Run all input positions except the last through only the first (k) layers.
    2. Use a small memory-writing component to generate the KV caches and recurrent states required by the remaining (L-k) layers from those intermediate representations.
    3. Run the final input position through all (L) layers to produce the distribution for the first generated token.

    During decoding, every token again passes through all (L) layers. This avoids additional layer skipping during generation, although quality still depends on the accuracy of the approximated prefill state.

    The following pseudocode illustrates the data flow. It is not an API for any specific framework.

    1. def prefill(tokens, model, writer, k):
    2. # 1. Run all but the final token through only the first k layers
    3. h = model.embed(tokens[:-1])
    4. for layer in model.layers[:k]:
    5. h = layer(h)
    6. # 2. Use a lightweight writer to construct deeper-layer caches and states
    7. kv_rest, state_rest = writer(h)
    8. # 3. Run the final token through the full network
    9. # to produce the first output distribution
    10. last = model.embed(tokens[-1:])
    11. cache = {"prefix": (h, kv_rest), "state": state_rest}
    12. for layer in model.layers:
    13. last = layer(last, cache)
    14. return last, cache

    3.2 Memory Writer Design

    The writer replaces the skipped deep-layer computation, so it must meet two requirements:

    • Low overhead. If the writer approaches the cost of a full Transformer layer, it can erase the intended savings. Shallow linear mappings or small projection structures are more appropriate.
    • Trainability through distillation. The writer learns to reproduce the caches and states produced by the full model at the corresponding layers. The original model remains frozen, and only the writer parameters are updated.

    Distillation losses generally measure numerical differences between the predicted and reference caches or states. An output-distribution consistency constraint can also be used.

    Training data should reflect the target workload, including code, long documents, or multi-turn conversations as appropriate. Otherwise, writer errors may become more pronounced on out-of-distribution inputs.

    3.3 Choosing the Split Point

    The split point (k) is the central hyperparameter.

    Factor What to evaluate
    Quality Compare output differences across candidate values of (k) on representative benchmarks.
    Compute savings Skipping a larger share of layers reduces prefill computation.
    Writer complexity Replacing more deep layers requires the writer to reconstruct more information.
    Architecture Hybrid models have different arrangements of attention and recurrent layers, requiring architecture-specific measurements.

    In one experiment with a 48-layer hybrid model, the first 31 layers processed the non-final input tokens, while a writer supplied the state for the remaining 17 layers. This is one experimental configuration, not a universal ratio.

    4. Decode: Low-Rank Compression of Recurrent State

    4.1 Structure in Recurrent States

    Architectures such as linear attention and state-space models read and update recurrent state matrices at every step. Unlike a KV cache, which grows with context length, a recurrent state has a context-length-independent size. Its absolute memory footprint can nevertheless be substantial.

    The state structure described here has two useful properties:

    • A dominant component points in a nearly fixed direction across many time steps.
    • After removing that component, the residual has a low effective rank and can be approximated with a small number of basis vectors.

    Together, these properties suggest that the state matrix contains significant compressible redundancy.

    4.2 A Factored Representation

    A state matrix (S) can be approximated as:

    [
    S \approx \sigma u v^{\top} + U V^{\top}
    ]

    Here, (u) and (v) are unit vectors describing the dominant directions, (\sigma) is a scalar coefficient, and (U) and (V) are rank-(r) factors.

    For a (d \times d) state, full storage requires (d^2) elements. The factored representation requires approximately (2dr + 2d) elements, plus the scalar coefficient. Storage falls substantially when (r) is much smaller than (d).

    The following schematic code shows reads and updates operating on the factored representation rather than reconstructing the full matrix at every step:

    1. class FactoredState:
    2. def __init__(self, u, v, sigma, U, V):
    3. self.u, self.v, self.sigma = u, v, sigma
    4. self.U, self.V = U, V # Low-rank factors with rank r
    5. def read(self, q):
    6. # Apply the query vector directly to the factored representation
    7. main = self.sigma * self.u * (self.v @ q)
    8. low = self.U @ (self.V.T @ q)
    9. return main + low
    10. def update(self, k, val, lr_proj):
    11. # Update only the low-rank component; keep the main component fixed
    12. self.U = self.U + lr_proj(k, val)

    The important principle is that both reads and writes stay in factored space. Reconstructing the full matrix at every step can offset the memory benefits with additional computation and temporary allocations.

    4.3 Compression Cycles and Error Control

    Approximation error can accumulate as the low-rank state is updated. A practical system can periodically recompress the state, decomposing and truncating it after a set number of steps to keep error within acceptable limits. Consequently, the per-request state footprint varies over the compression cycle.

    In the 48-layer hybrid-model experiment, recurrent-state storage per request fell from 113.2 MB to 29.2 MB immediately after compression. The average footprint across the compression cycle was approximately 43.4 MB.

    These figures illustrate an important distinction: the post-compression minimum is not the sustained memory footprint. Capacity estimates should account for the cycle average and its peak rather than assume that every request remains at the compressed minimum.

    5. Combining the Two Approaches

    Partial-depth prefill reduces computation, while recurrent-state compression reduces memory use and traffic. Because they address different bottlenecks, their benefits can be combined.

    • Less prefill computation can reduce time to first token and ease queueing pressure.
    • Smaller recurrent states allow more concurrent requests to fit on a GPU, enabling larger batches.
    • Together, the changes can improve per-GPU throughput.

    In the same reported testing, peak per-GPU throughput improved by 16%–42% on a newer-generation data-center GPU, using a mainstream inference framework and workloads based on coding-agent session traces. At a fixed P90 user-level end-to-end output-rate comparison point, throughput improved by 23%–42%.

    These results are workload-dependent. Long coding-agent sessions with high prefix reuse can behave very differently from short-context question answering. Performance figures should always be presented alongside their workload conditions.

    6. Quality Evaluation: Speed Is Not Enough

    An inference optimization is useful only if its quality cost is acceptable. Evaluation should cover several dimensions.

    1. Multiple models and checkpoints. Architectures differ in their sensitivity to layer skipping and state compression. Results from one model do not automatically generalize. The testing described here covered six checkpoints across five models.
    2. Task-specific results. Code generation, mathematical reasoning, and long-document question answering place different demands on state accuracy and should be evaluated separately.
    3. Long-range consistency. Compression error may accumulate over longer generations, so testing must include long outputs.
    4. Comparison with the original model. Examine the distribution of output differences rather than relying only on average benchmark scores.

    With the original model frozen and only the added components trained, a major risk is the memory writer’s ability to generalize. Inputs outside its training distribution may produce systematic errors. An independent held-out test set is therefore essential before deployment.

    7. Practical Deployment Guidance

    7.1 Measure Before Modifying

    Start by characterizing the target model and workload:

    • Measure the importance of intermediate representations layer by layer to identify how much depth can safely be skipped.
    • Perform spectral analysis of recurrent states to examine the dominant component and effective-rank distribution.
    • Build benchmarks from real application requests rather than relying exclusively on synthetic inputs.

    7.2 Roll Out in Stages

    A staged deployment makes it easier to isolate regressions:

    1. Introduce state compression first. It leaves the prefill logic unchanged and has a relatively straightforward rollback path.
    2. Add partial-depth prefill next. Use a limited traffic rollout to compare output quality against the full-computation path.
    3. Keep independent feature switches. Each optimization should be reversible if quality deteriorates.

    7.3 Monitor Operational and Quality Metrics

    Track the following after deployment:

    • Time-to-first-token percentiles, especially P90 and P99.
    • Concurrent requests per GPU, along with average and peak GPU memory use.
    • Offline quality-regression scores.
    • Error accumulation across each compression cycle.

    These metrics interact. Higher throughput accompanied by worse P99 latency often indicates that batch scheduling needs to be retuned.

    8. Suitable Workloads and Limitations

    These techniques are most relevant when:

    • Inputs are long and prefix reuse is high, as in repository question answering and multi-turn agent sessions.
    • GPU memory is a primary bottleneck, and the team can support distillation training.
    • Output quality can be evaluated quantitatively so regressions can be detected promptly.

    The limitations are equally important:

    • The memory writer requires additional training and depends on the quality and coverage of its training data.
    • Split points and compression thresholds are architecture-dependent and must be remeasured when moving to a new model.
    • Low-rank approximations may become unreliable when state distributions change sharply, requiring error monitoring and a fallback path.

    These methods are therefore better treated as optional inference-system optimizations than as unconditional replacements for the original execution path.

    9. How to Decide Whether the Optimization Is Worthwhile

    Three questions provide a practical decision framework:

    1. Does the optimization reduce computation, memory use, or both?
    2. Can its quality cost be measured on the target tasks?
    3. Can its performance benefit be reproduced under the application’s real workload?

    Lightweight memory writing and recurrent-state compression address distinct resource costs, and the evaluation methods above provide a way to assess their quality trade-offs. Whether the combined benefit holds in production must be established in the target environment.

    Start with representative benchmarks and a small traffic rollout, then expand only if both quality and performance remain acceptable.