KV Cache Sharing and Efficient LLM Inference: Architecture Evolution Explained

    This article examines how large language model architecture evolution is driven not only by parameter count but by more efficient use of memory, compute, and runtime resources. It explains KV cache capacity for long contexts, cross-layer KV cache sharing, related cache optimizations, dense versus mixture-of-experts architectures, deployment priorities for edge, local server, and centralized serving, and a reproducible evaluation process for balancing quality, latency, throughput, and cost.

    1. Architecture Evolution: More Than More Parameters

    The practical capability of a large language model cannot be measured by parameter count alone. For deployment teams, whether a model is usable also depends on whether it can support the target context length on given hardware, meet response latency requirements, and maintain stable throughput under multi-user concurrency.

    This has pushed architecture design toward three interrelated directions:

    1. Reduce the state overhead that keeps growing during inference, especially the key-value cache.
    2. Establish a more flexible relationship between total parameter capacity and per-token computation, for example through mixture-of-experts architectures.
    3. Adjust model size, attention structure, and execution mode for different scenarios such as edge devices, local servers, and centralized serving.

    These directions do not mean that one architecture is universally superior to another. They address efficiency problems under different resource constraints, and each ultimately involves tradeoffs among model quality, hardware fit, operating cost, and maintenance complexity.

    2. Understanding the KV Cache: Why Long Contexts Consume Memory

    2.1 What the Cache Stores

    In autoregressive models with causal self-attention, each layer generates queries, keys, and values from input representations, usually denoted as Q, K, and V.

    When generating a new token, the current query must match keys from historical positions, and the corresponding values are then weighted and summed. If the keys and values for all historical positions were recomputed for every generated token, a large amount of duplicate computation would result.

    The key-value cache, or KV cache, stores the K and V states for historical positions. During subsequent generation, the model mainly computes the state of the new position and reads the existing cache to complete attention computation.

    The cache therefore trades additional memory for less repeated computation, but its capacity grows with context length and the number of concurrent requests.

    2.2 Estimating Cache Capacity

    For the common case where each layer has the same cache structure and there is no cross-layer sharing, KV cache capacity can be approximated as:

    M ≈ 2 × L × B × T × Hkv × D × S

    Where:

    • L: number of attention layers that store independent key-value caches;
    • B: number of sequences processed simultaneously;
    • T: cached length of each sequence;
    • Hkv: number of key-value heads;
    • D: dimension of each key-value head;
    • S: bytes occupied by each cache element;
    • The factor 2 accounts for keys and values separately.

    For example, assume a model has 32 attention layers, each with 8 key-value heads, a head dimension of 128, and cache elements stored using 2 bytes. For a sequence of length 32,768, the theoretical cache capacity is approximately 4 GiB.

    This number only illustrates the formula and does not represent the actual configuration of any specific model. Real serving also needs to account for cache allocation granularity, metadata, workspace, memory fragmentation, and different attention structures across layers.

    2.3 Cache Capacity Is Not the Only Bottleneck

    The cache not only occupies space but must also be continuously read. During token-by-token decoding with long contexts, the model may still read a large number of historical key-value states even when the number of newly added tokens is small.

    Long-context inference can therefore be limited by both memory capacity and memory bandwidth. Reducing cache occupancy often helps increase the supported context length or concurrency, but it should not be directly equated with a proportional improvement in response speed.

    3. Cross-Layer Cache Sharing: From Per-Layer Storage to Multi-Layer Reuse

    3.1 Core Mechanism

    Traditional structures usually generate and store separate K and V states for different attention layers. Cross-layer cache sharing changes this arrangement: some layers generate key-value states, while other designated layers reuse those states instead of maintaining fully independent KV caches.

    This can be understood as follows.

    Traditional approach:

    Layer A → generate and store K_A, V_A
    Layer B → generate and store K_B, V_B
    Layer C → generate and store K_C, V_C

    One illustrative sharing approach:

    Layer A → generate and store K_A, V_A
    Layer B → use its own query and read K_A, V_A
    Layer C → reuse key-value states from designated layers according to the architecture design

    Sharing does not mean that all layers perform identical computation. Layers that read the same set of key-value states may still have different query transformations, output transformations, and feed-forward networks, allowing them to form different attention distributions and feature updates.

    3.2 Why It Saves Memory

    Suppose L layers originally store caches separately, and after the change only G independent key-value groups are retained, with other configurations unchanged. The main storage term for the cache can then be approximately reduced from L times to G times.

    The idealized capacity ratio is:

    Shared cache capacity / Unshared cache capacity ≈ G / L

    However, this ratio applies only to the main cache data items. It is not the memory ratio for the entire inference process. Model weights, activation workspace, and runtime overhead do not shrink in sync with the number of sharing groups.

    In addition, some structures may share only across part of the layers or use different cache shapes for different sharing groups. In such cases, capacity must be summed group by group rather than applying a single uniform ratio.

    3.3 Why It Is Not a Simple Deployment Switch

    Hidden representations at different layers are usually different, and the key-value states they generate also carry information at different levels. Forcing some layers of an already trained model to read caches from other layers changes the original computation path, and model quality cannot be assumed to remain unchanged.

    Reliable cross-layer sharing schemes usually need to be considered jointly during architecture design and training, or validated through dedicated adaptation and training. For teams that can only modify the inference service and cannot adjust model structure, more practical optimization directions are usually cache allocation, batching, and validated cache compression rather than directly merging states across layers.

    4. Do Not Confuse Different Cache Optimizations

    4.1 Key-Value Head Sharing

    Grouped-query attention allows multiple query heads to share a smaller number of key-value heads, mainly reducing Hkv in the formula above.

    Cross-layer sharing mainly reduces the number of layers or groups with independent caches. The two act on different dimensions and can be combined when structures are compatible, but the combined quality and efficiency still need separate validation.

    4.2 Cache Quantization

    Cache quantization reduces the number of bytes per element by lowering the storage precision of K and V. Its advantage is that it directly affects cache size, but it introduces numerical error and may add overhead for storing quantization parameters, conversion, and computation.

    Tasks involving long-range information retrieval, multi-step reasoning, and sensitivity to small score differences require particular evaluation of post-quantization behavior. A smaller cache does not automatically mean that all tasks maintain equivalent quality.

    4.3 Local Window Attention

    Local window attention restricts some layers to accessing only a recent segment of context, reducing the historical state that those layers need to retain or read.

    It changes the visible range of attention, not just the data representation. Therefore, when a workload requires precise association of information across very long text, teams need to confirm whether the model has other mechanisms for global information exchange.

    4.4 Block Management and Prefix Reuse

    Block-based cache management mainly reduces memory allocation and fragmentation problems. Prefix reuse attempts to let requests with the same prefix reuse existing computation results.

    These methods are closer to runtime management and should not be confused with internal cross-layer key-value sharing. Prefix reuse must also ensure compatibility of token prefixes, position handling, model configuration, and relevant execution conditions, and it should set reasonable access isolation policies to avoid cross-tenant information leakage.

    5. Dense Architectures and Mixture-of-Experts: Another Line of Compute Efficiency

    5.1 The Value of Dense Architectures

    Dense architectures usually let every token pass through the complete feed-forward computation path in each layer. Their computation graphs are relatively regular, making hardware adaptation and performance analysis more straightforward.

    For teams that frequently perform domain adaptation, tuning, and quality regression, dense architectures often have lower engineering understanding cost. However, this does not mean they are necessarily simpler in all training or post-training tasks; actual difficulty still depends on model scale, training methods, and infrastructure.

    5.2 Benefits and Costs of Mixture-of-Experts

    Mixture-of-experts architectures usually place multiple experts in some feed-forward modules, and a routing mechanism selects a subset of experts to participate in computation for each token.

    An important characteristic is that total parameter count and the number of parameters actually activated per token are no longer fully identical. This makes it possible to increase model parameter capacity while controlling per-token computation.

    Deployment should not focus only on activated parameters:

    • All expert weights still need to be stored or provided through an additional data movement mechanism;
    • Different experts may be selected at uneven frequencies;
    • Distributing experts across devices introduces communication;
    • Small batches may not fully utilize compute resources;
    • Routing behavior may change with input distribution and affect tail latency.

    Mixture-of-experts architectures therefore do not inherently mean low memory usage, nor do they inherently mean lower response latency. In particular, weight storage cost, per-token compute cost, and KV cache cost must be distinguished; these three cannot substitute for one another.

    6. What to Optimize First in Different Deployment Scenarios

    6.1 Edge and Embedded Devices

    Edge deployment is usually constrained simultaneously by memory, memory bandwidth, power, and thermal limits. Teams should first clarify whether long context, sustained multi-turn conversation, and fully offline operation are required.

    If the task only needs short-text understanding and limited-turn interaction, a compact model with appropriate context management may be more reasonable than pursuing extremely long context. If long history must be retained, cache sharing, cache precision, and history trimming strategies become more important.

    6.2 Local Server Inference

    Local deployment requires calculating the sum of weights, cache, runtime workspace, and safety margin, rather than ending the evaluation after confirming that “the weights fit.”

    For services shared by multiple users, teams should also consider queuing and resource contention when long and short requests are mixed. Excessively increasing concurrency may raise total throughput while significantly worsening individual request response time.

    6.3 Centralized Online Serving

    Centralized serving focuses more on sustained throughput, time to first token, per-token latency, and service stability. Cache optimization should be designed together with request scheduling, dynamic batching, quota limits, and monitoring and alerting.

    For enterprises, the most meaningful result is not the highest generation speed in a single test, but how many real requests the system can stably handle under target quality and latency constraints.

    7. Building a Reproducible Evaluation Process

    Step 1: Fix Business Constraints

    Define input length distribution, output length distribution, target concurrency, quality requirements, and latency budget. Do not test only with a single short prompt, because this cannot expose long-context cache pressure.

    Step 2: Separate Prefill and Decode

    The prefill stage processes input text, while the decode stage generates output step by step. Their computation and memory-access characteristics differ, so their timings should be recorded separately rather than hiding the real bottleneck behind a single average speed.

    Step 3: Measure Capacity, Performance, and Quality Together

    Capacity metrics include peak memory, cache occupancy, and supported concurrency. Performance metrics include time to first token, per-token latency, throughput, and tail latency. Quality metrics should cover real business accuracy, long-range retrieval, and multi-turn context consistency.

    For optimizations that change model structure or numerical precision, measuring performance without measuring quality is incomplete.

    Step 4: Use Single-Variable Controls

    Keep the model version, hardware, input set, sampling settings, and service configuration as consistent as possible, and change only one major mechanism at a time.

    If cache precision, batching strategy, and context length are modified simultaneously, it is difficult to determine which adjustment brought the benefit even if speed improves.

    Step 5: Observe Long-Running Behavior

    Continuous operation can expose problems that short tests do not reveal, such as cache fragmentation accumulation, queuing caused by burst traffic, resource reclamation after request cancellation, and tail-latency degradation as concurrency increases.

    8. Conclusion: Let Architecture Choices Serve Practical Constraints

    The evolution of large language model architecture can be summarized as reorganizing three types of resources: reducing duplicate state through key-value sharing, adjusting the relationship between parameters and computation through sparse activation, and improving hardware utilization through runtime management.

    Cross-layer key-value cache sharing offers an important idea: the cost of long context depends not only on how many tokens are stored, but also on whether the model must store fully independent historical representations at every layer. However, this is first a structure and training problem, not a universal inference trick that can simply be switched on.

    For developers, a reasonable path is to identify the bottleneck first, then choose the mechanism, and finally validate it with both business quality and system metrics. Only by putting cache capacity, memory bandwidth, compute overhead, training adaptation, and deployment complexity into the same evaluation table can teams determine whether an architectural change truly delivers usable value.