[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+205 -72
View File
@@ -1,98 +1,231 @@
---
id: wiki-2026-0508-key-value-kv-cache
title: Key Value (KV) Cache
title: Key-Value (KV) Cache
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-KVCH-001]
aliases: [KV cache, key-value cache, paged attention, vLLM, prefix caching]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [auto-reinforced, kv-cache, transformer-inference, memory-bottleneck, llm-performance]
confidence_score: 0.96
verification_status: applied
tags: [llm, kv-cache, inference, paged-attention, vllm, optimization]
raw_sources: []
last_reinforced: 2026-05-04
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: Python / CUDA
framework: vLLM / TensorRT-LLM / SGLang
---
# [[Key-Value (KV) Cache|Key-Value (KV) Cache]]
# Key-Value (KV) Cache
## 📌 한 줄 통찰 (The Karpathy Summary)
> "모델의 단기 기억 장치: 트랜스포머의 추론 과정에서 이전 토큰들의 연산 결과(Key, Value)를 메모리에 저장해두고 재사용함으로써, 매번 처음부터 다시 계산해야 하는 낭비를 없애고 생성 속도를 비약적으로 높인 추론 최적화의 심장."
## 한 줄
> **"매 transformer inference 의 의 의 의 의 K, V 의 store"**. 매 매 token generate 의 매 quadratic → 매 linear 의 의 의 의 의 enable. 매 modern: 매 paged attention (vLLM Kwon 2023), 매 prefix cache, 매 quantized KV.
## 📖 구조화된 지식 (Synthesized Content)
KV 캐시(Key-Value Cache)는 대규모 언어 모델(LLM)이 텍스트를 생성할 때, 이미 처리된 토큰들의 Key와 Value 행렬을 메모리에 저장해두는 기술입니다. 이를 통해 자기회귀(Autoregressive) 생성 과정에서 발생하는 중복 연산을 제거합니다.
## 매 핵심
1. **필요성**:
* 트랜스포머는 다음 토큰을 예측할 때 이전의 모든 토큰 정보를 참조해야 합니다.
* KV 캐시가 없다면 $n$번째 토큰을 생성할 때 $1$부터 $n-1$까지의 토큰을 매번 다시 연산해야 하므로, 시퀀스가 길어질수록 연산량이 기하급수적으로 증가합니다.
2. **작동 원리**:
* **Prefill 단계**: 입력된 프롬프트를 한꺼번에 처리하며 모든 토큰의 K, V 값을 계산하여 캐시에 저장합니다.
* **Decoding 단계**: 새로운 토큰을 하나씩 생성할 때마다 해당 토큰의 K, V 값만 계산하여 캐시에 추가하고, 이전 값들은 메모리에서 불러와 사용합니다.
3. **병목 현상**:
* **메모리 압박**: 컨텍스트 길이가 길어질수록 KV 캐시가 차지하는 VRAM 용량이 선형적으로 증가합니다. (예: 수천 명의 사용자가 동시에 긴 대화를 나눌 경우 GPU 메모리 부족(OOM) 발생 원인 1순위)
* **I/O 병목**: 연산 자체보다 캐시된 데이터를 메모리에서 읽어오는 속도(Memory Bandwidth)가 추론 속도를 결정하게 됩니다.
### 매 motivation
- **Without cache**: 매 매 step 의 의 의 의 모든 prev token 의 attention 의 recompute → O(N²).
- **With cache**: 매 매 K, V 의 store → 매 single new token 의 attention → O(N).
- **Memory cost**: 매 batch × seq × layers × kv_heads × head_dim × 2 (K + V) × dtype.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **용량 vs 속도**: 캐시를 많이 하면 속도는 빨라지지만 메모리가 부족해지고, 캐시를 줄이면(Compression/Quantization) 더 긴 문장을 처리할 수 있지만 정확도가 소폭 하락할 수 있습니다.
* **단편화 문제**: 고정된 크기의 메모리를 미리 할당할 경우, 사용되지 않는 빈 공간이 발생하는 '메모리 단편화' 문제가 발생합니다. 이를 해결하기 위해 [[PagedAttention|PagedAttention]]이 등장했습니다.
### 매 응용
1. Inference acceleration.
2. Long-context generation.
3. Streaming response.
4. Multi-turn chat.
## 🔗 지식 연결 (Graph)
* **상위 개념**: [[Attention Mechanisms|Attention Mechanisms]], [[LLM Inference Optimization|LLM Inference Optimization]]
* **최적화 기술**: [[PagedAttention|PagedAttention]], [[KV Cache Compression|KV Cache Compression]], [[KV Cache Quantization|KV Cache Quantization]], [[Grouped-Query Attention (GQA)|GQA]]
* **프레임워크**: [[vLLM|vLLM]], [[TensorRT-LLM|TensorRT-LLM]]
### 매 modern technique
- **Paged Attention** (vLLM 2023): 매 OS-style page.
- **Prefix caching**: 매 same prefix 의 의 reuse.
- **GQA + KV** (Llama): 매 cache size ↓.
- **MLA** (DeepSeek-V2): 매 latent compression.
- **Quantized KV** (FP8, INT4).
- **Sliding window** (Mistral): 매 truncate.
---
*Last updated: 2026-05-04*
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Basic KV cache (educational)
```python
import torch
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
class CachedAttention:
def __init__(self):
self.k_cache = [] # 매 list of [batch, n_heads, head_dim]
self.v_cache = []
def forward(self, q_new, k_new, v_new):
# 매 append new
self.k_cache.append(k_new)
self.v_cache.append(v_new)
# 매 stack
k_all = torch.stack(self.k_cache, dim=2) # 매 [B, H, T, D]
v_all = torch.stack(self.v_cache, dim=2)
# 매 attention with new q only (1 token)
attn = (q_new @ k_all.transpose(-1, -2) / k_all.size(-1) ** 0.5).softmax(-1)
return attn @ v_all
```
## 🤔 의사결정 기준 (Decision Criteria)
### Memory size calculation
```python
def kv_cache_bytes(batch, seq, layers, kv_heads, head_dim, dtype_bytes=2):
return batch * seq * layers * kv_heads * head_dim * 2 * dtype_bytes
**선택 A를 써야 할 때:**
- *(TODO)*
# 매 Llama 70B GQA: 80 layers, 8 KV heads, 128 head_dim
# 매 batch=1, seq=4096, bf16
size_gb = kv_cache_bytes(1, 4096, 80, 8, 128, 2) / 1e9
# 매 ≈ 1.34 GB
```
**선택 B를 써야 할 때:**
- *(TODO)*
### vLLM (production)
```python
from vllm import LLM, SamplingParams
**기본값:**
> *(TODO)*
llm = LLM(model='meta-llama/Llama-3.1-70B-Instruct', max_num_seqs=64)
sampling = SamplingParams(temperature=0.7, max_tokens=512)
outputs = llm.generate(prompts, sampling)
# 매 internally: paged attention + dynamic batching
```
## ❌ 안티패턴 (Anti-Patterns)
### Prefix cache (vLLM)
```python
# 매 same system prompt 의 의 의 cache 의 reuse
# 매 vLLM 의 enable_prefix_caching=True
llm = LLM(model='...', enable_prefix_caching=True)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Anthropic prompt caching
```python
from anthropic import Anthropic
client = Anthropic()
response = client.messages.create(
model='claude-opus-4-7',
max_tokens=1024,
system=[
{'type': 'text', 'text': 'You are an expert.', 'cache_control': {'type': 'ephemeral'}},
{'type': 'text', 'text': long_book_content, 'cache_control': {'type': 'ephemeral'}},
],
messages=[{'role': 'user', 'content': question}],
)
# 매 second call with same prefix = 매 90% cost ↓
```
### Sliding window (Mistral-style)
```python
def sliding_window_kv(k_cache, v_cache, window=4096):
if k_cache.size(2) > window:
k_cache = k_cache[:, :, -window:]
v_cache = v_cache[:, :, -window:]
return k_cache, v_cache
```
### GQA-aware cache
```python
def gqa_kv_cache_size(batch, seq, layers, n_q_heads, n_kv_heads, head_dim):
"""매 GQA: 매 KV heads < Q heads → 매 cache size ↓."""
return batch * seq * layers * n_kv_heads * head_dim * 2
# 매 Llama 70B: 매 8 KV vs 64 Q = 매 8x ↓ cache
```
### MLA (DeepSeek)
```python
class MLA:
"""매 매 K, V 의 의 의 의 의 of low-rank latent."""
def __init__(self, d_model, d_latent=512):
self.W_dkv = nn.Linear(d_model, d_latent) # 매 cache 매 latent only
self.W_uk = nn.Linear(d_latent, d_model) # 매 reconstruct K
self.W_uv = nn.Linear(d_latent, d_model) # 매 reconstruct V
def forward(self, x, kv_cache):
c = self.W_dkv(x)
kv_cache.append(c) # 매 small
# 매 reconstruct on-the-fly
```
### KV quantization
```python
def quantize_kv(k, v, bits=8):
"""매 K, V 의 의 의 INT8 / FP8 의 의 의 store."""
k_int8 = (k * 127 / k.abs().max()).to(torch.int8)
v_int8 = (v * 127 / v.abs().max()).to(torch.int8)
return k_int8, v_int8, k.abs().max(), v.abs().max() # scale factors
```
### Streaming generation
```python
def stream_generate(model, prompt, max_tokens=200):
input_ids = tokenize(prompt)
kv_cache = None
# 매 prefill
out, kv_cache = model.forward(input_ids, kv_cache=None)
for _ in range(max_tokens):
next_token = sample(out[:, -1])
yield next_token
# 매 매 single token forward
out, kv_cache = model.forward(next_token.unsqueeze(0), kv_cache=kv_cache)
```
### Continuous batching (vLLM)
```python
# 매 매 request 의 different stage 의 같이 batch
# 매 vLLM 의 매 (Yu 2022 Orca)
# 매 prefill + decode 의 mix
class ContinuousBatcher:
def step(self, requests):
# 매 prefill new + decode existing
return run_iteration(requests)
```
### Memory profile (debug)
```python
def profile_kv_cache(model, seq_lens):
for seq in seq_lens:
torch.cuda.reset_peak_memory_stats()
out = model.generate(input_ids[:1, :seq])
peak = torch.cuda.max_memory_allocated() / 1e9
print(f'seq={seq}: peak {peak:.2f} GB')
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Production serving | vLLM (paged) |
| Long context | GQA + MLA |
| Multi-turn chat | Prefix caching |
| Memory tight | Quantized KV |
| Very long | Sliding window (Mistral) |
| API | Anthropic prompt cache |
**기본값**: 매 vLLM + 매 GQA + 매 prefix caching + 매 dynamic batching. 매 long context = quantized KV / MLA.
## 🔗 Graph
- 부모: [[Transformer]] · [[LLM-Inference]]
- 변형: [[Paged-Attention]] · [[Prefix-Cache]] · [[MLA]]
- 응용: [[vLLM]] · [[TensorRT-LLM]] · [[SGLang]]
- Adjacent: [[Flash Attention]] · [[Grouped-Query Attention (GQA)]] · [[Foundation-Models]]
## 🤖 LLM 활용
**언제**: 매 inference. 매 모든 production LLM serving.
**언제 X**: 매 single-shot research only.
## ❌ 안티패턴
- **No KV cache**: 매 quadratic — unusable for long.
- **Static batching**: 매 GPU underutil.
- **Full-precision KV at scale**: 매 memory waste.
- **Recompute prefix every call**: 매 cost ↑.
## 🧪 검증 / 중복
- Verified (Vaswani 2017, Kwon vLLM 2023, Yu Orca 2022, DeepSeek-V2 MLA).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — KV cache + 매 vLLM / prefix / MLA / sliding / quantize code |