KV Cache Hierarchical Storage: Reducing Memory Redundancy in Long-Context Parallel Inference

    This article explores the challenge of KV Cache memory bottlenecks in large language model (LLM) long-context inference. It introduces a hierarchical storage approach where each GPU stores only a subset of layers to eliminate redundant KV Cache across multiple GPUs. The article covers the core concept, communication overhead management via compute-communication overlap, pseudocode implementation, and practical considerations for deployment, including benefits, risks, and an implementation checklist.

    1. Background: Memory Pressure in Long-Context Inference

    During autoregressive generation, Large Language Models (LLMs) must save the Key and Value tensors produced by the attention mechanism in each layer, known as the KV Cache. Its memory footprint scales proportionally with sequence length, number of layers, number of KV heads, and head dimension. Let’s estimate using a sample configuration: 80 layers, 8 KV heads, a head dimension of 128, and FP16 data type (2 bytes per element).

    The KV memory required per token is:

    1. Bytes per token = 2 (K & V) × Layers × KV Heads × Head Dimension × Bytes per element
    2. = 2 × 80 × 8 × 128 × 2
    3. = 327,680 bytes (approx. 320 KB)

    When the context reaches 128K tokens, the KV Cache for a single request is about:

    1. 327,680 × 131,072 ≈ 42.9 GB

    This calculation excludes model weights, intermediate activations, and additional batch processing overhead. For scenarios like long-document Q&A, codebase analysis, and extended multi-turn conversations, single-GPU memory quickly becomes a bottleneck. Developers typically mitigate this through quantization, paged management, or offloading to host memory, but these methods come with their own trade-offs. This article focuses on an alternative approach: reducing the duplicated data stored on each GPU under the premise of multi-GPU parallel inference.

    2. Sources of Redundancy in Context Parallelism

    Context Parallelism (CP) splits a long sequence across multiple devices to distribute the compute and memory pressure caused by long contexts. It can be implemented in various ways, which significantly affect how the KV Cache is stored.

    In some implementations, to enable each GPU to compute attention over the full context, each GPU must hold the KV data for all layers, or at least the majority of data required for its calculations. As a result, the KV data for the same context is repeatedly stored across multiple GPUs, causing memory utilization to decline as the number of GPUs increases. This phenomenon is known as KV Cache redundant storage.

    The degree of redundancy depends on three factors:

    • The parallel splitting dimension: whether the split is by sequence, by head, or by layer;
    • The KV reuse frequency per layer: how many times a layer’s KV is read during a single forward pass;
    • The communication bandwidth: which determines whether the cost of fetching data from other GPUs is acceptable.

    Understanding these three points is essential to determine which redundancies can be eliminated and which must be converted into communication overhead.

    3. Core Concept: Per-GPU Partial Layer Storage

    The core idea of hierarchical storage is straightforward: each GPU only saves a portion of the layers’ KV Cache, rather than all of them. This reduces the per-GPU KV memory footprint to approximately 1/N of the full amount (where N is the number of GPUs participating in the layer split), assuming the layers are divided evenly.

    This approach needs to address two main issues.

    The first is the layer allocation strategy. There are two common methods:

    • Continuous allocation: Layers 0 to 9 are placed on GPU 0, layers 10 to 19 on GPU 1, and so on. This is simple to implement, but the computation time and dependencies between different layers may be unbalanced.
    • Interleaved allocation: Layers 0, N, 2N are placed on GPU 0, while layers 1, N+1 are placed on GPU 1. This balances the load better, but requires more frequent data movement between adjacent layers.

    The second issue is how to fetch missing data. When a GPU needs to compute a layer whose KV is held by another GPU, it must obtain that data via communication. This leads to the design of broadcasting and compute-communication overlap.

    4. Communication Overhead and Compute Overlap

    Hierarchical storage shifts part of the memory pressure into communication pressure. For this trade-off to be worthwhile, the key is to hide communication behind computation.

    A typical approach is: the GPU holding a specific layer’s KV broadcasts the data to other GPUs that need it before that layer is processed. While waiting for the data to arrive, the receiving GPU executes computations that do not depend on that layer. As long as the communication time does not exceed the available overlapping compute time, the overall latency remains almost unaffected.

    A forward pass timeline can be simplified as follows:

    1. Time ──────────────────────────────────────────►
    2. GPU 0: [Compute Layer 0] [Broadcast Layer 1 KV] [Compute Layer 2] ...
    3. GPU 1: [Compute Layer 1 ] [Wait/Receive Layer 1 KV] ...
    4. └── Communication overlaps with other compute ──┘

    When implementing this overlap, note the following:

    • Use independent communication streams to prevent serial waiting between communication and computation in the same queue;
    • Plan broadcast timing in advance to ensure data arrives before it is read;
    • Control the number of in-flight broadcasts to prevent bandwidth contention from increasing tail latency;
    • Profile the overlap effect to confirm that actual wait time is hidden, rather than introducing additional synchronization overhead.

    5. Pseudocode Example

    The following pseudocode illustrates the scheduling logic and is not tied to any specific framework’s API.

    1. def forward_with_layer_sharding(model, hidden, kv_store, rank, world_size):
    2. for layer_idx, layer in enumerate(model.layers):
    3. owner = layer_idx % world_size # Interleaved allocation example
    4. if owner == rank:
    5. # This GPU owns the KV for this layer; broadcast in the background, then continue local compute
    6. handle = kv_store.broadcast_async(layer_idx, src=rank)
    7. else:
    8. # Non-owners must wait for the corresponding layer KV to arrive
    9. handle = kv_store.recv_async(layer_idx, src=owner)
    10. # Overlap with communication: execute compute that does not depend on this layer's KV
    11. overlap_out = model.compute_independent_part(layer_idx, hidden)
    12. kv = handle.wait() # Ensure KV is available
    13. hidden = layer.attention(hidden, kv) + overlap_out
    14. hidden = layer.mlp(hidden)
    15. return hidden

    There are three key points in this code: first, the wait position of the asynchronous communication handle determines the degree of overlap; second, it is necessary to ensure that only the owner GPU saves that layer’s KV to avoid introducing new redundancy; third, real-world systems must also handle KV write timing, garbage collection strategies, and error recovery, which are omitted in this schematic example.

    6. Factors Determining the Benefits

    Hierarchical storage is not advantageous for all scenarios. Its benefits are determined by the difference between memory savings and communication overhead. The following factors have the greatest impact:

    Context length. The longer the context, the larger the KV per layer, and the more memory saved by hierarchical storage. Simultaneously, longer sequences mean longer attention computation times per layer, providing a larger time window to hide communication. Therefore, long contexts typically yield more significant benefits than short ones.

    Network bandwidth and topology. GPUs connected via high-speed interconnects within a single node have far lower broadcast costs than cross-node Ethernet links. For cross-node deployments, you must first measure communication latency and bandwidth to confirm the overlap window is sufficiently large.

    Batch size. As batch size increases, memory pressure grows, and the absolute memory savings from hierarchical storage become more substantial. However, communication volume also increases, requiring empirical testing to find the balance point.

    Model architecture. Models using Grouped-Query Attention (GQA) with fewer KV heads have inherently smaller KV per layer, so the relative benefit of hierarchical storage is limited. Models with more layers and more KV heads have a larger potential for gains.

    Public test results indicate that under specific conditions, such solutions can provide considerable throughput improvements, with benefits becoming more pronounced as context length increases. However, specific numbers depend on hardware, models, workloads, and implementation details, and should not be directly adopted. The most reliable approach is to benchmark on your target workload.

    7. Risks and Limitations

    Introducing hierarchical storage increases system complexity. The following risks should be evaluated in advance:

    • Increased synchronization complexity: Cross-GPU dependencies require the scheduler to be aware of layer ownership, making exception paths harder to reason about.
    • Tail latency risk: If one GPU is slower than the others, all GPUs waiting on it will be affected.
    • Debugging and observability difficulty: Once KV data is distributed, a single GPU’s logs cannot fully reconstruct the state of a request, necessitating distributed tracing.
    • Coupling with other optimizations: Technologies like paged caching, prefix reuse, and speculative decoding all alter the KV access patterns and must be verified for compatibility one by one.
    • Fault recovery: If a GPU holding a specific layer’s KV fails, recomputing or restoring from a backup can be highly costly.

    8. Deployment Checklist

    Before deciding to adopt hierarchical storage, you can proceed with the following steps:

    1. Analyze the context length distribution of your target business to confirm that the proportion of long-context requests is sufficiently high.
    2. Measure the current per-GPU KV memory usage to determine whether the bottleneck is memory capacity or bandwidth.
    3. Evaluate the cluster’s inter-GPU interconnect topology and record the actual latency and bandwidth for point-to-point and broadcast communications.
    4. Implement a prototype in a small-scale environment: verify correctness first, then measure end-to-end throughput and time-to-first-token (TTFT).
    5. Compare the performance of hierarchical vs. non-hierarchical configurations across different context lengths and plot a benefit curve.
    6. Design fallback strategies for exception paths, such as falling back to full-storage mode upon communication timeout.
    7. Incorporate KV distribution, communication duration, and overlap ratio into monitoring metrics to continuously track production performance.

    The value of hierarchical storage lies in converting memory pressure into communication costs that can be hidden by computation. Whether to adopt it depends on the context length of your target workload, hardware topology, and your team’s operational capability with distributed systems.