Compute Bottlenecks and KV Cache Management in LLM Inference

    This article explains where compute and memory bottlenecks arise during large language model inference, covering the distinct resource profiles of the prefill and decode phases, how to estimate KV Cache memory consumption and concurrency limits, three session caching strategies, and scheduling techniques such as continuous batching and chunked prefill that improve GPU utilization.

    1. Background

    In chat-oriented LLM serving, how many users a single accelerator card can serve concurrently often determines service cost and user experience more directly than the model’s parameter count. When resources are tight, operators must trade off between admitting more new requests and preserving response quality for existing sessions. Understanding this trade-off requires a clear picture of how different resources are consumed during inference.

    2. The Two Phases of Inference and Their Resource Profiles

    2.1 The Prefill Phase

    The model reads the user’s input together with the conversation history in a single pass and computes the key-value vectors for every input token. This phase is compute-intensive, and its latency scales roughly linearly with input length. Because the attention computation grows quadratically with input length, time to first token rises noticeably for very long contexts.

    2.2 The Decode Phase

    The model generates output tokens one at a time. Producing each token requires reading the KV vectors of all preceding tokens. The per-step computation is small, but the volume of memory reads is large, so this phase is typically bounded by memory bandwidth and GPU compute utilization stays low.

    This characteristic implies that keeping more decode requests in the batch at the same time is the primary way to improve hardware utilization.

    2.3 The Role of KV Cache

    The KV Cache stores previously computed key and value vectors, avoiding redundant recomputation of the history each time a new token is generated. It trades space for time: the cost is that memory usage grows linearly with context length and the number of concurrent sessions.

    3. Estimating Memory Usage and the Concurrency Ceiling

    The bytes occupied per token in the KV Cache can be estimated as:

    KV bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element

    The factor of 2 accounts for the separate key and value caches. The following is an example configuration, not the parameters of any specific model: 32 layers, 8 KV heads, head dimension 128, stored in 16-bit floating point. The per-token footprint is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 128 KiB. A session with 4,096 tokens therefore occupies roughly 512 MiB of KV Cache.

    From this, the concurrency ceiling can be roughly estimated:

    Concurrent sessions ≈ (available memory − model weight footprint − runtime overhead) ÷ per-session KV footprint

    Illustrative code:

    1. def estimate_max_sessions(
    2. gpu_mem_gib, weight_gib, runtime_overhead_gib,
    3. layers, kv_heads, head_dim, bytes_per_elem, avg_context_tokens
    4. ):
    5. bytes_per_token = 2 * layers * kv_heads * head_dim * bytes_per_elem
    6. per_session_gib = bytes_per_token * avg_context_tokens / (1024 ** 3)
    7. free_gib = gpu_mem_gib - weight_gib - runtime_overhead_gib
    8. if free_gib <= 0 or per_session_gib <= 0:
    9. return 0
    10. return int(free_gib // per_session_gib)
    11. # Example: 80 GiB of GPU memory, 16 GiB of weights, 4 GiB of runtime overhead,
    12. # average context of 4096 tokens
    13. # Per session is about 0.5 GiB, so the theoretical concurrency is 60 / 0.5 = 120

    This result is only a theoretical upper bound. Real deployments must also account for memory fragmentation, traffic bursts, and scheduling overhead, so a safety margin is usually reserved.

    The formula also shows that the concurrency ceiling is highly sensitive to average context length. Doubling the average context roughly halves the concurrency ceiling. As a result, the same hardware can serve several times more users under a “mostly short Q&A” workload than under a “mostly long-document conversation” workload.

    4. Three Strategies for Session Caching

    Session characteristics determine the value of caching. One-off Q&A has almost no reuse value. Multi-turn conversations with continuous interaction over a short period have high reuse value. For sessions that resume only after a long interval, the reuse window has usually expired.

    Strategy Approach Memory usage Recovery latency Suitable scenarios
    Long-term retention Session KV stays resident in GPU memory High Low High-frequency continuous interaction
    Tiered offloading Cold data is moved to host memory or local SSD and loaded back when needed Medium Medium, depends on I/O bandwidth Moderate reuse probability, moderate intervals
    Evict and recompute KV is released; on resumption, prefill is rerun over the history Low High, grows with history length Infrequently accessed sessions with short histories

    The core trade-off among the three strategies: offloading trades I/O cost for memory, while recomputation trades compute cost for memory. Recomputation cost is proportional to history length, so recomputing long sessions is expensive. In practice, systems usually make decisions based on length thresholds—for example, recompute short histories directly and prefer offloading for long histories.

    Below is illustrative code for tiered cache management, with concurrency control and error handling omitted:

    1. from collections import OrderedDict
    2. class SessionKVManager:
    3. def __init__(self, gpu_budget, host_budget):
    4. self.gpu = OrderedDict() # session_id -> (kv_blob, size), ordered by recency
    5. self.host = OrderedDict()
    6. self.gpu_budget = gpu_budget
    7. self.host_budget = host_budget
    8. def put(self, session_id, kv_blob, size):
    9. self._evict_gpu_if_needed(size)
    10. self.gpu[session_id] = (kv_blob, size)
    11. self.gpu.move_to_end(session_id)
    12. def _evict_gpu_if_needed(self, need):
    13. used = sum(s for _, s in self.gpu.values())
    14. while used + need > self.gpu_budget and self.gpu:
    15. sid, (blob, s) = self.gpu.popitem(last=False) # evict the least recently used session
    16. used -= s
    17. self._spill_to_host(sid, blob, s)
    18. def _spill_to_host(self, sid, blob, size):
    19. # Illustrative: a real implementation must check host_budget and,
    20. # when exceeded, spill to local storage or drop the data
    21. self.host[sid] = (blob, size)
    22. def get(self, session_id, transcript_tokens, prefill_fn):
    23. if session_id in self.gpu:
    24. self.gpu.move_to_end(session_id)
    25. return self.gpu[session_id][0]
    26. if session_id in self.host:
    27. blob, size = self.host.pop(session_id)
    28. self.put(session_id, blob, size)
    29. return blob
    30. # Cache has expired; recompute from the conversation history
    31. return prefill_fn(transcript_tokens)

    5. Scheduling Techniques for Improving GPU Utilization

    Caching strategy only addresses how memory is allocated. The scheduling layer determines how GPU compute time is allocated. Common techniques include:

    • Continuous batching: as soon as a request finishes, a new request takes its place, avoiding the whole batch waiting on the slowest request.
    • Chunked prefill: long inputs are split into chunks and executed interleaved with decode requests, reducing the blocking that long inputs impose on other users.
    • Token budget: a total token limit is set for each scheduling step, balancing time to first token against generation throughput.
    • Admission control: when memory usage exceeds a threshold, new requests are queued or rejected to prevent overall degradation of experience for existing sessions.

    Evaluating the effectiveness of these techniques typically focuses on the following metrics:

    • TTFT (time to first token)