Why Long Conversations Exhaust GPU Memory: KV Cache Principles and Optimization Methods

    Recently, a large language model platform introduced usage limits for long conversations on its App and web versions, accompanied by multiple service disruptions. According to user feedback, the platform implemented three main restrictions: discarding long conversations inactive for over 7 days, reducing the single-input context limit to approximately 40,000 characters, and prompting daily quota limits due to server congestion. These measures serve as defensive mechanisms during resource shortages. This article explains the principles behind GPU memory consumption in long conversations, provides a practical estimation formula, and outlines actionable optimization parameters.

    1. Why Usage Limits Are Implemented

    When a large language model generates a new token, it requires attention information from all previously generated tokens. As concurrent users increase, the GPU memory occupied by long conversations grows continuously. When the remaining memory is insufficient to support new requests, the system must implement rate limiting or service degradation to prevent a total crash. Therefore, the primary purpose of these limits is to ensure that the majority of users can continue to use the service normally.

    2. Why KV Cache Fills Up GPU Memory

    To avoid recalculating historical tokens, inference frameworks store the Key and Value matrices for each layer in GPU memory. This stored data is known as the KV Cache. Its size is directly proportional to the context length; the longer the conversation, the more memory it consumes.

    The estimation formula is as follows:

    1. kv_cache_bytes = 2 * num_layers * num_kv_heads * head_dim * seq_len * batch_size * dtype_size

    The parameters are defined as follows:

    • 2: Stores two sets of matrices, K and V.
    • num_layers: The number of Transformer layers.
    • num_kv_heads: The number of KV heads. In Multi-Head Attention (MHA), this equals the number of attention heads. In Grouped-Query Attention (GQA) or Multi-Query Attention (MQA), this number is significantly smaller.
    • head_dim: The dimension of a single attention head. When GQA is not used, num_kv_heads × head_dim equals the hidden_size.
    • seq_len: The total number of tokens in the current session.
    • batch_size: The number of requests processed simultaneously.
    • dtype_size: The number of bytes per element. FP16 and BF16 use 2 bytes, while FP8 and INT8 use 1 byte.

    Example: Assuming a model with 32 layers, 32 KV heads, a head_dim of 128, and using FP16 precision. For a context of 32,768 tokens and a batch_size of 1, the calculation is:

    2 × 32 × 32 × 128 × 32,768 × 1 × 2 = 17,179,869,184 bytes, which is approximately 16 GiB.

    If switching to GQA with 8 KV heads under the same conditions, the usage drops to approximately 4 GiB. This illustrates how model architecture impacts memory consumption.

    When using this formula, note two key points. First, the formula only calculates the KV Cache and does not include model weights, temporary activations, or memory fragmentation. The actual peak usage will be higher, so a buffer should be reserved during deployment. Second, dtype_size relates to the KV quantization scheme. Quantizing the KV Cache from FP16 to FP8 can theoretically halve this memory usage, but the generation quality must be validated on the target model.

    3. Two Types of Failures Caused by Resource Bottlenecks

    Performance Degradation. When the GPU is at full load or memory approaches its limit, requests queue up, response times increase, and occasional request failures occur. These issues typically manifest first as an increase in P99 latency.

    Service Interruption. Memory overflow triggers an Out of Memory (OOM) error, causing the inference process to crash. If the scheduling system experiences a resource deadlock, the entire node may become unavailable. Similar incidents have been reported publicly, though the exact frequency and duration should be based on official platform announcements.

    4. Optimization Methods and Parameter Starting Points

    4.1 What is KV Cache and How to Control Its Growth?

    KV Cache is a design that trades memory for computation time. There are four common methods to control its growth: reducing the number of KV heads (GQA or MQA, at the model architecture level), using inference frameworks with block-level allocation (like PagedAttention, which reduces memory fragmentation), quantizing the KV Cache, and limiting the effective length of the session (sliding window or summarization).

    4.2 How to Choose a Solution?

    Solution Effect Trade-off Considerations
    Paged KV Management (e.g., PagedAttention, vLLM) Reduces fragmentation, increases concurrency Depends on inference framework support Ensure compatibility with existing models and hardware
    Sliding Window Fixes upper limit of KV usage Loses information outside the window Requires a strategy to retain key information
    Summary Compression Retains long-term semantics, shortens input Requires extra model calls, potential distortion Requires factual consistency evaluation
    KV Quantization Reduces per-token memory usage May affect generation quality Requires comparison on business evaluation datasets
    Idle Session Offloading Frees memory for active users Latency upon recovery Inform users of potential wait times in advance

    4.3 How to Reclaim Idle Sessions?

    Below are starting parameters that should be adjusted based on actual stress testing results:

    • Active Session TTL: Retain sessions in memory with no interaction for 30 minutes; offload them after timeout.
    • Archive TTL: Move sessions inactive for over 7 days to low-cost storage, or clean them up according to platform rules.
    • Eviction Watermark: Begin evicting sessions using the LRU (Least Recently Used) strategy when memory usage exceeds 80%; accelerate eviction when it exceeds 90%.
    • Offload Medium: Prioritize CPU memory; use object storage when capacity is insufficient.
    • Recovery Strategy: When a user reactivates a session, preload the KV Cache for the most recent turns. Recovery will increase first-response latency, so the frontend should display a loading state.

    4.4 How to Perform Context Truncation?

    • Sliding Window: Retain the system prompt plus the most recent N turns of dialogue. The starting point for N can be set based on a token budget, such as retaining the last 8K tokens of history.
    • Summary Trigger: When the history length exceeds 60% of the model’s context limit, compress early dialogue into a summary.
    • Distortion Evaluation: Construct a labeled set of multi-turn test conversations to check the retention rate of key information after summarization, including user constraints, numbers, and names, while checking answer consistency. If the retention rate falls below the threshold, adjust the summary template or reduce the compression ratio.

    Summaries easily lose early constraints set by the user. A list of “explicit user requirements” should be maintained separately in the summary and used as a fixed input for each inference.

    4.5 How to Configure Scaling and Rate Limiting?

    • Monitoring Metrics: GPU utilization, memory usage, request queue time, P99 latency, and OOM count. Monitoring only GPU utilization cannot reveal memory risks.
    • Scaling Threshold: Trigger scaling when memory usage exceeds 75% continuously for 5 minutes. Since model loading takes time, pre-warmed nodes should be maintained.
    • Rate Limiting Strategy: Set quotas based on user tiers and request types. Return clear prompts when limits are exceeded to prevent infinite request queuing.
    • Degradation Order: Under high load, first disable long-context and high-cost features to prioritize the availability of basic dialogue.

    4.6 What Are Common Mistakes?

    1. Only monitoring compute power, not GPU memory, leading to no early warning before an OOM occurs.
    2. No recovery path after offloading idle sessions, causing conversation loss when users return.
    3. Unreasonable batch_size configurations.