🤖 AI/ML

KV Cache

A key-value cache; a technique for speeding up Transformer inference

📖 Detailed Explanation

KV Cache (Key-Value Cache) is a technique that dramatically improves the inference speed of Transformer models. By storing and reusing the Key and Value tensors of previous tokens in the Attention computation, it eliminates the redundant computation of recalculating the entire sequence each time a new token is generated.

When an LLM generates text, it outputs one token at a time in an autoregressive manner. Without a KV Cache, generating the Nth token requires recomputing the K and V of tokens 1 to N-1 every time, resulting in O(N^2) complexity. A KV Cache can reduce this to O(N).

In 2023, vLLM's PagedAttention revolutionized KV Cache memory management. By dynamically allocating GPU memory in page units, it reduced memory fragmentation to under 4% (previously 70%), making it possible to handle 2-4 times more requests on the same GPU.

As of 2025, with a 128K-token context becoming the standard, KV Cache optimization has become even more important. LMCache achieved a 15x throughput improvement by using tiered storage across GPU HBM, CPU RAM, and SSD, and llm-d's KV Cache Aware Routing reduced TTFT by 88% with an 87% cache hit rate.

💻 Code Example

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import time

# 모델 로드
model_name = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.float16,
    device_map="auto"
)

prompt = "인공지능의 미래에 대해 설명해주세요:"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)

# KV Cache 비활성화 (비교용 - 매우 느림)
print("=== KV Cache 비활성화 ===")
start = time.time()
with torch.no_grad():
    output_no_cache = model.generate(
        **inputs,
        max_new_tokens=100,
        use_cache=False,  # KV Cache 비활성화
        do_sample=False
    )
time_no_cache = time.time() - start
print(f"생성 시간: {time_no_cache:.2f}초")

# KV Cache 활성화 (기본값 - 빠름)
print("\n=== KV Cache 활성화 ===")
start = time.time()
with torch.no_grad():
    output_with_cache = model.generate(
        **inputs,
        max_new_tokens=100,
        use_cache=True,   # KV Cache 활성화 (기본값)
        do_sample=False
    )
time_with_cache = time.time() - start
print(f"생성 시간: {time_with_cache:.2f}초")

speedup = time_no_cache / time_with_cache
print(f"\n속도 향상: {speedup:.1f}배")

# KV Cache 직접 관리 (streaming 용도)
past_key_values = None
generated_tokens = []

for _ in range(50):
    with torch.no_grad():
        outputs = model(
            **inputs if past_key_values is None else {"input_ids": next_token_id},
            past_key_values=past_key_values,
            use_cache=True
        )
    past_key_values = outputs.past_key_values  # KV Cache 저장
    next_token_id = outputs.logits[:, -1, :].argmax(dim=-1, keepdim=True)
    generated_tokens.append(next_token_id.item())

    # KV Cache 크기 확인 (첫 레이어 기준)
    if len(generated_tokens) == 1:
        kv_shape = past_key_values[0][0].shape
        print(f"KV Cache shape: {kv_shape} (layer, batch, heads, seq, dim)")

🗣️ Say It Like This in Practice

💬 In a Meeting
"Our current LLM service is limited in handling concurrent requests due to a lack of GPU memory. If we switch to vLLM's PagedAttention, KV Cache memory efficiency improves from 70% to 96%, allowing us to handle 3 times more requests on the same GPU."
💬 In an Interview
"KV Cache stores the Keys and Values of previous tokens so they can be reused. Without it, generating the Nth token requires recomputing all of tokens 1 to N-1, which makes it O(N^2), but a KV Cache can reduce that to O(N). The downside is increased memory usage."
💬 In a Technical Discussion
"With a 128K context, the KV Cache can grow to tens of GB. You can offload it to CPU RAM or SSD like LMCache does, or use Entropy-Guided Caching to reduce the cache of less important layers."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring out-of-memory issues in long contexts

At 32K tokens or more, the KV Cache alone can take up 10GB or more. Apply a max_length limit or cache compression.

❌
Caching padding tokens during batch processing

Storing even padding tokens in the KV Cache wastes memory. Set attention_mask correctly.

✅
Using vLLM or TensorRT-LLM

In production environments, use an inference engine that implements PagedAttention to maximize memory efficiency and throughput.

🔗 Related Terms

📚 Learn More