Deep Learning Inference Architecture: KV Cache Costs and Engineering Optimization
This article explains how to analyze cache costs in deep learning inference without confusing module names with overall architecture. It covers why autoregressive generation needs a key-value cache, how to determine whether encoding and decoding are truly separated, and which capacity, bandwidth, and lifecycle factors drive cache cost. It then reviews the main optimization paths—reducing KV heads, lowering cache precision, reusing identical prefixes, paged memory management, and shortening or compressing effective context—and distinguishes lower cache cost from lower inference cost. The article closes with a reproducible evaluation and optimization process based on realistic workloads, stage-level metrics, controlled experiments, and failure scenarios.
1. Discussing Inference Architecture: Separate Facts from Terminology
When reading technical material about deep learning models, a common mistake is to see the word “encoder” and conclude that the model has abandoned a decoder-only architecture and moved to an encoder-decoder structure. In reality, module names, computational responsibilities, and overall architecture are not the same level of concept.
“Encoding” can broadly refer to the process of converting input into an internal representation; an “encoder” may also refer to a component responsible for context processing. Only by further confirming the attention connections, data flow between modules, training objective, and execution path during generation can you determine which architecture class the overall system belongs to.
Therefore, when analyzing any new scheme that claims to reduce cache cost, three questions should be answered first:
- How is the input context processed, and what attention constraints are used?
- In what form is historical information stored, and how does subsequent generation read it?
- Does the cost reduction come from a structural change, a change in numerical representation, or a server-side reuse mechanism?
Without a public and verifiable structural explanation, you should not infer specific technology from module names alone, and you should not use unconfirmed release information, performance marketing, or price changes as the basis for architectural conclusions. The following discussion focuses on general principles and does not correspond to any specific product implementation.
2. Why Autoregressive Generation Needs a Cache
2.1 From Input Processing to Token-by-Token Generation
An autoregressive language model predicts the next token based on the existing context, then adds the new token to the context and continues predicting:
P(x1, …, xn) = ∏ P(xt | x1, …, xt−1)
In common decoder-only models, causal attention ensures that the current position cannot read future tokens. The model can use information from earlier input, but it does not see later answers in advance during training or generation.
In engineering terms, inference is usually divided into two stages:
- Prefill stage: processes the existing input and builds the internal state used for subsequent generation.
- Decoding stage: processes new tokens step by step, continuously updates the state, and produces output.
Prefill can compute multiple input positions in parallel. With ordinary dense attention, increasing sequence length significantly increases attention computation; however, actual runtime also depends on how computation is organized, whether intermediate results are explicitly stored, and hardware utilization.
The decoding stage is constrained by generation dependencies: the next step for the same sequence usually has to wait for the current step to finish. Batching can advance multiple requests in parallel, but it cannot directly eliminate the autoregressive dependency within a single sequence.
2.2 What the Key-Value Cache Stores
Attention maps hidden states to queries, keys, and values, usually denoted as Q, K, and V. For a newly generated position, its query needs to match the keys of visible historical positions, and then the corresponding values are aggregated with weights.
In common causal attention inference, the representations of historical positions are not affected by later tokens, so the keys and values already computed at each layer can be retained. When generating the next step, only the state for the new position is computed, and the existing cache is read.
This state is called the key-value cache, often written as the KV cache. It mainly avoids recomputing the keys and values of historical positions, but it does not mean that historical context no longer incurs overhead: every generation step still needs to access the relevant historical state.
There is also an important boundary here: if a component uses bidirectional attention, appending input may change the representations of earlier positions, so its cache update rules cannot simply copy the approach used in causal decoding. Whether a cache can be reused must be determined by computational dependencies.
3. How to Judge Whether Encoding and Decoding Are Truly Separated
3.1 Decoder-Only Structure
A decoder-only structure usually uses causal attention to process input and already generated content, and then predicts the next token. Prompt text and output text form a continuous sequence computationally.
Even if the system has a dedicated path for input processing or calls context processing “encoding,” that does not necessarily change the model’s overall classification. The key is to check whether these paths form independent computational modules and how the generation stage accesses their outputs.
3.2 Encoder-Decoder Structure
A typical encoder-decoder structure first obtains an input representation through an encoder, and then the decoder generates output. The decoder usually uses both:
- causal self-attention over already generated content;
- cross-attention over the encoder output.
This structure cannot simply be equated with a “dual tower.” In retrieval and similar scenarios, “dual tower” usually means two branches separately produce representations and then compute similarity; it has a different data flow and objective from a token-by-token encoder-decoder generation structure.
3.3 Context Processing and Generation Reads Can Be Organized Differently
From an engineering perspective, processing long input and step-by-step generation have different requirements. The former emphasizes parallel computation and context understanding, while the latter focuses more on per-step latency, state reads, and continuous generation.
Therefore, research schemes can try to design different computational organizations for the two stages. However, whether cache is reduced, whether expressive capability changes, and whether retraining is required must all be judged in the context of the specific structure. In particular, “storing less” cannot be directly understood as “information remains completely unchanged”: whether the compressed state is sufficient to support the task requires experimental validation.
4. What Actually Determines Cache Cost
4.1 Capacity Cost: More Than Context Length
For a common implementation that stores keys and values at every layer, cache capacity can be approximated as:
M ≈ 2 × L × B × T × H_kv × D × S
Where:
- L is the number of layers;
- B is the number of sequences whose states are stored simultaneously;
- T is the cached sequence length;
- H_kv is the number of attention heads for keys and values;
- D is the dimension of each head;
- S is the number of bytes per element;
- the factor 2 represents storing both keys and values.
This expression is used to understand the order of magnitude and does not apply to all models. Actual deployment must also consider memory alignment, paged management, metadata, quantization scales, allocation fragmentation, and temporary workspace. If different layers use different structures, the calculation also needs to be done layer by layer.
It reveals a direct engineering problem: long context and high concurrency jointly amplify cache occupancy. Even if model weights can fit into device memory, that does not mean the service can support the expected concurrent requests.
4.2 Bandwidth Cost: Fitting in Memory Does Not Mean Fast Reads
In common full-context attention, a new token needs to access historical keys and values. The longer the context, the larger the per-step read volume usually becomes.
Under conditions such as small batch size and long context, decoding may be limited by memory bandwidth rather than pure compute capacity. Therefore, cache compression has the opportunity to reduce both capacity and read volume, but it may also introduce decompression, format conversion, or additional computation.
Evaluation must observe both cache bytes and decoding latency. Reporting memory reduction alone cannot prove end-to-end performance improvement.
4.3 Lifecycle Cost: Invalid State Occupies Resources for Too Long
Cache cost is also related to retention time. Whether state is released immediately after a session ends, whether it is reclaimed promptly after a user cancels a request, and whether shared prefixes are stored repeatedly all affect service resource utilization.
Cache policy should be designed around actual access probability, rather than retaining all historical state indefinitely. Lifecycle management is often the highest-priority optimization point to check outside the architecture itself.
5. Main Technical Paths for Reducing Cache Cost
5.1 Reduce the Number of Key-Value Heads
Grouped-query attention lets multiple query heads share one set of keys and values; multi-query attention further reduces the number of key-value heads. These structures can reduce cache size and related read volume, but the effect depends on model training, task type, and specific implementation.
For an already trained model, reducing the number of key-value heads usually cannot be treated as a zero-cost deployment switch. Structural conversion may require weight adjustment and additional training, and may affect quality.
5.2 Lower the Numerical Precision of the Cache
Cache quantization represents keys and values with lower bit width to reduce occupancy. Evaluation should focus not only on average task scores, but also on:
- information retrieval accuracy in long contexts;
- fidelity of numbers, symbols, and identifiers;
- consistency in multi-turn conversations;
- stability in long-output tasks;
- additional latency caused by quantization and dequantization.
Weights and caches have different numerical distributions and access patterns. The effectiveness of weight quantization does not mean that the same quantization settings are suitable for the cache.
5.3 Reuse Exactly Matching Shared Prefixes
If multiple requests share the same system instructions, templates, or document beginnings, the server can reuse already computed prefix state when conditions are met, thereby avoiding repeated prefill.
However, text looking the same is not enough to guarantee cache compatibility. Factors such as token sequence, positional handling, model version, relevant adapter weights, and attention configuration usually need to be checked.
Security boundaries are equally important. Cache sharing cannot bypass access control, nor should it expose other users’ input content or usage. In practice, risks should be controlled through tenant isolation, permission checks, and explicit cache scope.
5.4 Use Paged Management to Reduce Fragmentation
Paged cache divides state into fixed-size blocks and manages the mapping between logical sequences and physical memory. This helps with dynamic growth, request exit, and shared prefix reuse, and can reduce waste caused by contiguous allocation.
However, paging mainly improves allocation efficiency; it does not automatically reduce the amount of information the model needs to store. It also introduces overhead for mapping maintenance, block scheduling, and access organization.
5.5 Shorten or Compress the Effective Context
Retrieval filtering, history summarization, and trimming of task-relevant content can reduce the effective input that enters the model, thereby lowering prefill and subsequent cache cost.
This path requires particular attention to information loss. For example, summaries may omit exception clauses, and retrieval may miss key evidence. In contract review, auditing, or precise code analysis, necessary original text should be retained and task results after trimming should be validated, rather than simply pursuing shorter input.
6. Cheap Cache Is Not the Same as Cheap Model Inference
Cost analysis should distinguish at least three levels:
- Model level: computation, cache size, and the state that must be read per token.
- Service level: cache hit rate, batching efficiency, scheduling method, and resource utilization.
- Business level: task completion rate, retry count, output length, and human review cost.
Shared prefix reuse can reduce repeated prefill overhead, but it cannot eliminate subsequent generation computation. Cache compression can increase serving capacity, but if output quality drops and causes repeated retries, total business cost may instead rise.
Therefore, a reasonable evaluation metric is not the isolated cost of a single request, but the total cost of completing an effective task under quality requirements and latency constraints. Any billing change also cannot by itself prove that a particular architecture has a specific advantage.
7. Build a Reproducible Evaluation and Optimization Process
7.1 Build Realistic Workloads First
The test set should cover short input with short output, long input with short output, long input with long output, multi-turn conversations, and repeated requests with shared prefixes. At the same time, keep scenarios with no cache hits to avoid evaluating only under ideal conditions.
In addition to input and output lengths, record arrival rate, concurrency changes, and cancellation ratio. Fixed-concurrency tests easily miss queueing and resource reclamation problems under burst traffic.
7.2 Measure Different Stages Separately
The following metrics are recommended:
- prefill time;
- time to first token;
- inter-token latency;
- request completion time;
- peak cache occupancy;
- prefix cache hit rate;
- service throughput;
- high-percentile latency;
- task quality and retry rate.
Time to first token is not equal to prefill time; it may also include queueing, input processing, and scheduling wait. Only by separating these factors can bottlenecks be located.
7.3 Change Only One Class of Conditions at a Time
First establish a baseline without the target optimization, then test prefix reuse, cache precision, memory management, or scheduling strategy separately. Each group of tests should keep model configuration, workload, generation settings, and quality standards as consistent as possible.
Otherwise, even if an obvious improvement is observed, it is difficult to determine whether the gain comes from the cache strategy or from other changes.
7.4 Design Failure Scenarios
Production systems should also test mid-request cancellation, cache invalidation, model version switching, burst long requests, and multi-tenant contention.
These scenarios can reveal problems hidden by average performance metrics: whether state is released after cancellation, whether low-value cache crowds out resources for active requests, whether stale state is mistakenly used after a version change, and whether long requests continuously block short requests.
8. Conclusion: Understand Inference Optimization Around Information Flow and Resource Flow
When analyzing deep learning inference architecture, the most important question is not what the modules are called, but how input information forms an internal representation, how historical state is stored, and how the generation stage reads that state.
For common autoregressive models, the KV cache reduces repeated computation over history, but it also introduces capacity, bandwidth, and lifecycle management problems. Cost reduction can come from structural design, low-precision representation, shared prefix reuse, paged management, and context filtering; different paths address different bottlenecks.
Reliable technical judgment should follow a clear order: first confirm structure and cache semantics, then analyze resource overhead, then validate latency and quality with realistic workloads, and finally calculate business benefit. Only by placing model mechanisms, service implementation, and task results within the same framework can you distinguish truly effective optimizations from metric improvements that hold only under specific conditions.
