Track VIII · Inference & Optimisation · 03/09

KV cache 관리KV-cache management

KV cache를 메모리 관리 문제로 다룬다. paging이 예약·내부 단편화를 어떻게 없애는지, hash chain과 radix tree prefix cache가 GRPO 그룹과 multi-turn agent의 prefill을 얼마나 줄이는지 시뮬레이션하고, 공유 KV 저장소로의 offload, KV 양자화(KIVI), 축출(StreamingLLM, H2O)을 계산과 코드로 비교한다.Treat the KV cache as a memory-management problem. Simulate how paging removes reservation and internal fragmentation and how hash-chain and radix-tree prefix caches cut prefill for GRPO groups and multi-turn agents; compare offload to a shared KV store, KV quantisation (KIVI) and eviction (StreamingLLM, H2O) with arithmetic and code.

45 분min KV cache · PagedAttention · prefix caching · RadixAttention · Mooncake · offload · KV quantization · KIVI · StreamingLLM · H2O · agents 먼저 볼 것:Before this: Roofline과 추론 지표The roofline and inference metrics, Attention kernelAttention kernels, 추론 최적화Inference optimisation

The roofline lesson showed that beyond Bkv=Nbw/(Lκ)B_{kv} = N b_w / (L\kappa) sequences the KV cache, not the weights, sets decode speed; the intro gave the per-token size κ=2 nlayer nkv dh b\kappa = 2\,n_{\text{layer}}\, n_{kv}\, d_h\, b and attention & KV shows how architectures shrink it. This lesson is about everything a serving engine does around a given κ\kappa: allocate it without waste, reuse it across requests, move it to cheaper memory, store it in fewer bits, or throw part of it away.

How big, and why management matters

Per token, all layers (computed in the code below): an 8B GQA model needs 128 KiB, a 70B GQA model 320 KiB, DeepSeek-V3’s MLA 68.6 KiB in bf16 (34.3 KiB in fp8). A single 128K-token context of the 70B model is 40 GiB. The cache is also dynamic: it grows by one token per sequence per step, and nobody knows in advance how long an answer will be. That second property is what makes it a memory-management problem rather than a sizing problem.

Paging

Early servers allocated each request a contiguous KV buffer for the maximum length it might reach. Three kinds of waste follow: reservation (slots reserved for tokens not yet, or never, generated), internal fragmentation (the request ends before its reservation), and external fragmentation (holes between buffers of different sizes). The vLLM paper measured that in existing systems only 20.4–38.2% of KV memory held actual token states.

PagedAttention borrows virtual memory: the cache is a pool of fixed-size blocks of bb tokens; each sequence owns a block table mapping logical block ii to a physical block; a new block is taken from the free list only when the last one fills. Waste is now at most one partially filled block per sequence, on average (b−1)/2(b-1)/2 tokens, and there is no external fragmentation because all blocks are the same size. Blocks also get reference counts, so several sequences can point at the same physical block — parallel sampling and beam search share the prompt’s blocks and copy a block only when a sequence writes into a shared one (copy-on-write); the paper reports up to 55% memory saving for beam search. The cost moves into the kernel (the gather through the block table, previous lesson), which is why bb is not 1: vLLM’s default is 16, and 16–128 performed best on the ShareGPT trace.

roofline 레슨은 시퀀스 수가 Bkv=Nbw/(Lκ)B_{kv} = N b_w / (L\kappa)를 넘으면 decode 속도를 정하는 것이 가중치가 아니라 KV cache임을 보였다. 입문 레슨은 토큰당 크기 κ=2 nlayer nkv dh b\kappa = 2\,n_{\text{layer}}\, n_{kv}\, d_h\, b를 줬고, attention과 KV는 아키텍처가 그것을 어떻게 줄이는지 보여 준다. 이 레슨은 κ\kappa가 정해진 뒤 서빙 엔진이 그 주변에서 하는 모든 일에 대한 것이다. 낭비 없이 할당하고, 요청끼리 재사용하고, 더 싼 메모리로 옮기고, 더 적은 비트로 저장하거나, 일부를 버린다.

얼마나 크고, 왜 관리가 문제인가

토큰당, 모든 층 합계(아래 코드에서 계산): 8B GQA 모델은 128 KiB, 70B GQA 모델은 320 KiB, DeepSeek-V3의 MLA는 bf16에서 68.6 KiB(fp8이면 34.3 KiB)다. 70B 모델의 128K 토큰 문맥 하나가 40 GiB다. 게다가 cache는 동적이다. step마다 시퀀스당 한 토큰씩 자라고, 답이 얼마나 길어질지는 아무도 미리 모른다. 이 두 번째 성질이 이것을 크기 문제가 아니라 메모리 관리 문제로 만든다.

Paging

초기 서버는 요청마다 도달할 수 있는 최대 길이만큼 연속 KV 버퍼를 할당했다. 세 종류의 낭비가 생긴다. 예약(아직, 혹은 영영 생성되지 않을 토큰을 위해 잡아 둔 칸), 내부 단편화(요청이 예약보다 먼저 끝남), 외부 단편화(크기가 다른 버퍼 사이의 구멍). vLLM 논문은 기존 시스템에서 KV 메모리의 20.4–38.2%만 실제 토큰 상태를 담고 있었다고 측정했다.

PagedAttention은 가상 메모리를 빌려 온다. cache는 bb토큰짜리 고정 크기 블록의 pool이고, 시퀀스마다 논리 블록 ii를 물리 블록에 대응시키는 block table을 가진다. 새 블록은 마지막 블록이 찰 때만 free list에서 가져온다. 이제 낭비는 시퀀스당 부분적으로 찬 블록 하나, 평균 (b−1)/2(b-1)/2토큰이 전부이고, 블록 크기가 모두 같으니 외부 단편화도 없다. 블록에는 참조 카운트도 붙어서 여러 시퀀스가 같은 물리 블록을 가리킬 수 있다. parallel sampling과 beam search는 프롬프트 블록을 공유하고, 시퀀스가 공유 블록에 쓸 때만 그 블록을 복사한다(copy-on-write). 논문은 beam search에서 최대 55%의 메모리 절감을 보고한다. 비용은 kernel로 옮겨 간다(block table을 통한 gather, 이전 레슨). bb가 1이 아닌 이유다. vLLM 기본값은 16이고, ShareGPT trace에서는 16–128이 가장 좋았다.

Sequences (current lengths drawn from a log-normal) are admitted in order until the KV pool is full. Top: how the pool is spent — tokens actually stored (blue), reserved but not yet (or never) used (red), the unfilled tail of each sequence's last block (amber), free (grey). Bottom: utilisation and admitted sequences against block size. Contiguous max-length reservation wastes most of the pool whenever typical lengths are far below max_len; paging wastes at most one partial block per sequence, so drag the block size: waste grows only as b/2 per sequence. 시퀀스(현재 길이는 로그정규분포에서 뽑음)를 KV pool이 찰 때까지 순서대로 받아들인다. 위: pool이 어떻게 쓰이는지. 실제로 저장된 토큰(파랑), 예약했지만 아직(혹은 영영) 안 쓰는 칸(빨강), 시퀀스마다 마지막 블록의 빈 꼬리(주황), 빈 공간(회색). 아래: 블록 크기에 따른 활용률과 받아들인 시퀀스 수. 최대 길이로 연속 예약하면 보통 길이가 max_len보다 한참 짧을 때 pool 대부분이 낭비된다. paging은 시퀀스마다 부분 블록 하나만큼만 낭비하므로, 블록 크기를 끌어 보면 낭비가 시퀀스당 b/2로만 늘어난다.

At the defaults (128K-token pool, max_len 8K, median length 512) contiguous reservation admits 16 sequences and stores real tokens in under 10% of the pool — the same regime as, and worse than, the paper’s 20–38% — while paging at b=16b = 16 fits roughly 10× more sequences at ~99% utilisation. Raise the median length towards max_len and the gap closes: paging pays off exactly when lengths are unpredictable and usually short, which is the normal case for chat and for RL rollouts with long-tailed lengths. A larger batch is the whole point: by the roofline, decode throughput grows with BB until BkvB_{kv}.

Prefix caching

Paging makes blocks shareable; prefix caching makes them findable across requests. Two designs:

  • Hash chain (vLLM automatic prefix caching): each full block is keyed by a hash of its own tokens and the prefix before it (plus extra keys such as LoRA id or a cache salt). A new request walks its blocks from the start and reuses every leading block whose key is present. Only full blocks are cached; free blocks are evicted LRU.
  • Radix tree (SGLang’s RadixAttention): token sequences are stored in a radix tree whose edges are KV segments; matching is a tree walk, nodes carry reference counts, and eviction removes the least recently used leaf first. The scheduler sorts waiting requests by matched prefix length (longest-shared-prefix-first, equivalent to a DFS of the tree) to maximise reuse. The paper reports up to 6.4× higher throughput on structured LLM programs.

Both evict deep, private suffixes before shared roots, because a child block is useless without its parent. The interesting part is the workload:

  • Shared system prompts and tool schemas. Every request of an agent product starts with the same thousands of tokens.
  • Multi-turn sessions. Turn tt re-sends the whole history. Without a cache, prefill over a session grows quadratically with the number of turns; with a cache only the new tool result is prefilled (the model’s own outputs are already in the cache).
  • GRPO groups. The GG samples of one prompt share the prompt’s blocks, saving 1−1/G1 - 1/G of prompt prefill.

기본값(128K 토큰 pool, max_len 8K, 길이 중앙값 512)에서 연속 예약은 시퀀스 16개를 받아 pool의 10%도 실제 토큰에 쓰지 못한다. 논문의 20–38%와 같은 영역이고 그보다 나쁘다. 반면 b=16b = 16 paging은 약 10배 많은 시퀀스를 ~99% 활용률로 담는다. 길이 중앙값을 max_len 쪽으로 올리면 차이가 줄어든다. paging은 길이를 예측할 수 없고 대개 짧을 때 이득이다. 채팅과, 길이 분포 꼬리가 긴 RL rollout이 바로 그런 경우다. 배치가 커지는 것이 핵심이다. roofline에 따르면 decode 처리량은 BkvB_{kv}까지 BB와 함께 커진다.

Prefix caching

paging은 블록을 공유 가능하게 만들고, prefix caching은 요청들 사이에서 블록을 찾을 수 있게 만든다. 두 가지 설계가 있다.

  • Hash chain(vLLM automatic prefix caching): 꽉 찬 블록마다 자기 토큰과 그 앞 prefix의 hash(그리고 LoRA id, cache salt 같은 추가 키)를 키로 쓴다. 새 요청은 처음부터 블록을 따라가며 키가 있는 앞쪽 블록을 모두 재사용한다. 꽉 찬 블록만 cache하고, 빈 블록은 LRU로 내보낸다.
  • Radix tree(SGLang의 RadixAttention): 토큰 시퀀스를 간선이 KV 조각인 radix tree에 저장한다. 매칭은 트리 탐색이고, 노드에는 참조 카운트가 있으며, 축출은 가장 오래 안 쓴 leaf부터 한다. 스케줄러는 대기 요청을 일치하는 prefix 길이로 정렬해(가장 긴 공유 prefix 우선, 트리의 DFS와 동치) 재사용을 최대화한다. 논문은 구조화된 LLM 프로그램에서 처리량이 최대 6.4배 높다고 보고한다.

둘 다 공유된 뿌리보다 깊고 개인적인 꼬리를 먼저 내보낸다. 부모 없는 자식 블록은 쓸모가 없기 때문이다. 흥미로운 것은 작업 부하다.

  • 공유 시스템 프롬프트와 도구 스키마. agent 제품의 모든 요청은 같은 수천 토큰으로 시작한다.
  • Multi-turn 세션. turn tt는 이력 전체를 다시 보낸다. cache가 없으면 세션의 prefill이 turn 수에 대해 제곱으로 자라고, cache가 있으면 새 도구 결과만 prefill한다(모델 자신의 출력은 이미 cache에 있다).
  • GRPO 그룹. 한 프롬프트의 샘플 GG개가 프롬프트 블록을 공유해 프롬프트 prefill의 1−1/G1 - 1/G를 아낀다.
Each session is an agent loop: turn t sends system prompt + all previous turns + a new tool result, and the model answers 300 tokens. Sessions interleave randomly. The cache keeps full blocks only and evicts the least recently used session's deepest blocks first. Left: prefix hit rate (share of prompt tokens not recomputed) against cache capacity. Right: per turn, prompt tokens served from cache (green) vs prefilled (red), averaged over sessions. Shrink the cache below the working set (sessions × history) and hits collapse to the shared system prompt. Tick the timestamp box: one changing token at the very top invalidates every block after it — the hit rate goes to zero. 세션 하나가 agent loop다. turn t는 시스템 프롬프트 + 이전 turn 전부 + 새 도구 결과를 보내고, 모델은 300토큰으로 답한다. 세션들은 무작위로 섞여 들어온다. cache는 꽉 찬 블록만 보관하고, 가장 오래 안 쓴 세션의 가장 깊은 블록부터 내보낸다. 왼쪽: cache 용량에 따른 prefix hit rate(다시 계산하지 않은 프롬프트 토큰 비율). 오른쪽: turn별로 cache에서 온 프롬프트 토큰(초록)과 prefill한 토큰(빨강), 세션 평균. cache를 작업 집합(세션 × 이력)보다 작게 줄이면 hit이 공유 시스템 프롬프트만 남는다. timestamp 칸을 체크하면 맨 앞의 바뀌는 토큰 하나가 그 뒤의 모든 블록을 무효화해서 hit rate가 0이 된다.

Things to try: at the defaults (256K-token cache) the cache holds the working set and the hit rate is above 90% — each turn prefills little more than its new tool output. Drag the capacity left past the dashed working-set line: whole sessions get evicted between their turns and the per-turn bars turn red from the top down, leaving only the system prompt as a hit. Raise the number of sessions at fixed capacity: same effect — this is why serving fleets route a session back to the replica that holds its cache (cache-aware routing). Finally tick timestamp: putting anything that changes per request (a date, a request id, a shuffled tool list) before the stable prefix destroys every hit. Stable content first, volatile content last.

Offload and a shared KV store

When HBM is full, the next tier is host DRAM, then local SSD, then a remote pool. Whether a cached prefix is worth fetching is a roofline question. Recomputing a token of prefill costs 2N2N FLOPs; reloading it costs κ\kappa bytes over the link. For the 70B model on an H100 at an assumed 60% MFU, recomputing is ≈ 236 µs per token while reloading 320 KiB over a PCIe 5.0 ×16 link (~64 GB/s nominal) is ≈ 5 µs, and even a ~7 GB/s NVMe drive is ≈ 47 µs (our estimates). Reloading wins by 5–50×, and MLA’s smaller κ\kappa widens the gap. The transfer must be overlapped with compute (layer-by-layer prefetch) to realise it.

Mooncake (the serving platform behind Kimi) builds on this: a KVCache-centric disaggregated architecture that separates prefill and decode clusters and pools the cluster’s otherwise idle CPU, DRAM and SSD into a distributed KV store. Instances look up cached prefixes in the shared store, so a prefix computed on one replica is reusable on another; the paper reports that it let Kimi handle 75% more requests under real workloads (and up to +525% throughput in simulated scenarios). vLLM exposes the same idea through a Mooncake store connector: a shared KV pool with CPU/disk offload, hash-based matching across instances, combinable with prefill–decode disaggregation (next lesson).

KV quantisation

Storing KV in fewer bits shrinks κ\kappa directly, and since decode attention’s intensity is 2g/bkv2g/b_{kv} it also doubles attention throughput per halving. FP8 KV with a per-tensor (or per-head) scale is the default in most engines. Below 8 bits the axis of the scale matters. KIVI observed that keys have a few channels with consistently large magnitude, while values do not: quantise keys per channel (one scale per channel across tokens) so an outlier channel does not crush the others, and values per token. With 2-bit KV the paper reports 2.6× less peak memory (including weights), up to 4× larger batches and 2.35–3.47× throughput. The code below reproduces the asymmetry on synthetic keys with outlier channels. (Quantisation covers the formats.)

Eviction

The lossy option is to keep only some tokens. StreamingLLM found that a pure sliding window collapses because models dump attention mass on the first tokens (attention sinks); keeping 4 initial tokens plus a rolling window of recent ones keeps generation stable for up to 4 million tokens, with up to 22.2× speedup over sliding-window recomputation. H2O keeps the recent tokens plus “heavy hitters” — the tokens that have received the most accumulated attention — and reports up to 29× throughput over offloading-based systems with a 20% heavy-hitter budget. Both discard information permanently, so a fact that was evicted cannot be retrieved later; for long-context retrieval the trend is architectural instead (sparse attention, long-context serving).

Computing it yourself

NumPy KV sizes, paging utilisation, prefix reuse, KIVI-style quantisation, eviction, offload
import numpy as np
rng = np.random.default_rng(0)

# 1) KV bytes per token
def kv_gqa(L, n_kv, d_h, b=2): return 2 * L * n_kv * d_h * b
def kv_mla(L, d_c, d_r, b=2):  return L * (d_c + d_r) * b      # one shared latent + RoPE key per layer
for name, v in [("8B GQA (32L, 8 kv)", kv_gqa(32, 8, 128)), ("70B GQA (80L, 8 kv)", kv_gqa(80, 8, 128)),
                ("DeepSeek-V3 MLA (61L)", kv_mla(61, 512, 64)), ("DeepSeek-V3 MLA, fp8", kv_mla(61, 512, 64, 1))]:
    print(f"{name:<24} {v / 1024:6.1f} KiB/token   128K context = {v * 131072 / 2**30:5.1f} GiB")

# 2) contiguous reservation vs paging: a snapshot of 64 running sequences
cur = (rng.lognormal(6.5, 1.0, size=64)).astype(int) + 1    # current lengths (prompt + generated so far)
max_len = 8192
used = cur.clip(max=max_len).sum()
print(f"\nused tokens {used:,}; contiguous reservation of max_len={max_len}: utilisation {used / (64 * max_len):.1%}")
for b in [1, 16, 64, 256]:
    alloc = (np.ceil(cur / b) * b).sum()
    print(f"  paged, block {b:3d}: utilisation {used / alloc:.1%}  (expected waste/seq ≈ (b-1)/2 = {(b - 1) / 2:.1f})")

# 3) prefix caching: tokens that must be prefilled with and without reuse
G, P, O = 8, 2000, 4000                                       # GRPO: 8 samples share a 2000-token prompt
print(f"\nGRPO group: prefill {G * P:,} tokens without cache, {P:,} with  ({1 - 1 / G:.0%} saved)")
sys_p, turns, u, o = 6000, 20, 300, 400                       # agent: system+tools, turns, tool/user and model tokens
no_cache = sum(sys_p + t * (u + o) + u for t in range(turns))  # whole history re-prefilled every turn
with_cache = sys_p + turns * u                                # only new tokens (model outputs are already cached)
print(f"agent, {turns} turns: prefill {no_cache:,} tokens without cache vs {with_cache:,} with ({no_cache / with_cache:.0f}x)")

# 4) KV quantisation: keys have outlier *channels*, so quantise keys per-channel and values per-token (KIVI)
def quant(x, bits, axis):
    lo, hi = x.min(axis=axis, keepdims=True), x.max(axis=axis, keepdims=True)
    scale = (hi - lo) / (2**bits - 1)
    return np.round((x - lo) / scale) * scale + lo
T, d = 1024, 128
K = rng.normal(size=(T, d)); K[:, [3, 17, 70]] += rng.normal(8, 1, size=3)  # fixed-offset outlier channels
V = rng.normal(size=(T, d)); q = rng.normal(size=(64, d))
def attn(q, K, V):
    s = q @ K.T / np.sqrt(d); p = np.exp(s - s.max(1, keepdims=True)); return (p / p.sum(1, keepdims=True)) @ V
ref = attn(q, K, V)
for bits in [4, 2]:
    e_tok = np.abs(attn(q, quant(K, bits, 1), quant(V, bits, 1)) - ref).mean()
    e_ch = np.abs(attn(q, quant(K, bits, 0), quant(V, bits, 1)) - ref).mean()
    print(f"{bits}-bit KV: keys per-token err {e_tok:.4f} | keys per-channel err {e_ch:.4f}")

# 5) eviction on a toy stream: attention with a sink token and a recency bias (synthetic, for illustration)
T, budget = 2048, 256
Kt, Vt = rng.normal(size=(T, 64)), rng.normal(size=(T, 64))
bias = np.zeros(T); bias[0] = 6.0                             # a sink: position 0 absorbs mass
def out(qi, t, keep):
    idx = np.array(sorted(keep)); s = Kt[idx] @ qi / 8 + bias[idx] + 0.002 * (idx - t)
    p = np.exp(s - s.max()); return (p / p.sum()) @ Vt[idx]
errs = {"window": [], "sink+window": [], "H2O": []}
acc = np.zeros(T)                                             # H2O: accumulated attention per position
for t in range(budget, T, 64):
    qi = rng.normal(size=64)
    full = out(qi, t, range(t + 1))
    s = Kt[:t + 1] @ qi / 8 + bias[:t + 1] + 0.002 * (np.arange(t + 1) - t)
    acc[:t + 1] += np.exp(s - s.max()) / np.exp(s - s.max()).sum()
    win = range(t - budget + 1, t + 1)
    sink = [0, 1, 2, 3] + list(range(t - budget + 5, t + 1))
    heavy = list(np.argsort(acc[:t + 1])[-budget // 2:]) + list(range(t - budget // 2 + 1, t + 1))
    for k, keep in [("window", win), ("sink+window", sink), ("H2O", set(heavy))]:
        errs[k].append(np.abs(out(qi, t, keep) - full).mean())
print("\neviction, budget 256 of up to 2048 tokens: " + "  ".join(f"{k} err {np.mean(v):.3f}" for k, v in errs.items()))

# 6) offload: reload a cached prefix vs recompute it (nominal link speeds; our estimates)
flops_tok, kv_tok = 2 * 70e9, kv_gqa(80, 8, 128)              # 70B dense
recompute = flops_tok / (989e12 * 0.6)                        # H100 at an assumed 60% MFU
for tier, bw in [("host DRAM over PCIe 5.0 x16 (~64 GB/s)", 64e9), ("local NVMe SSD (~7 GB/s)", 7e9)]:
    print(f"per token: recompute {recompute * 1e6:6.1f} us  vs  load from {tier}: {kv_tok / bw * 1e6:5.1f} us")
 

The eviction toy is synthetic — a planted sink and a recency bias — so read it as an illustration of the mechanism (dropping the sink shifts mass onto the window), not as a benchmark of the methods.

확인 문제Check yourself

An agent product prepends the current date and time to the system prompt of every request. What happens to prefix caching?

In both hash-chain and radix-tree caches a block is identified by its tokens and everything before it, since its K and V depend on the whole prefix through attention. A changing first token changes the identity of every later block, so the history of the conversation misses too. Put volatile content at the end.

확인 문제Check yourself

Why does KIVI quantise keys per channel but values per token?

A per-token scale is the max over the dd channels of that token; with an outlier channel present, every other channel gets a coarse grid. A per-channel scale is the max over tokens of that channel, so an outlier channel only affects itself. Values have no such channel structure, and the output is a per-token weighted sum of value rows, so per-token scales match how errors propagate.

Summary

  • KV per token: 128 KiB (8B GQA) to 320 KiB (70B GQA); MLA 69 KiB in bf16. It grows dynamically with unknown final length.
  • Paging removes reservation and external fragmentation; waste is ≤ one partial block per sequence. Reference counts give copy-on-write sharing.
  • Prefix caching (hash chain or radix tree) reuses blocks keyed by the whole prefix; agents, multi-turn sessions and GRPO groups are its best cases. Stable content first.
  • Reloading a cached prefix from DRAM or SSD is 5–50× cheaper than recomputing it; Mooncake-style shared stores make prefixes reusable across replicas.
  • KV quantisation shrinks bytes and raises decode-attention intensity; quantise keys per channel, values per token.
  • Eviction (sinks + window, heavy hitters) is lossy; keep the sinks.

해 볼 것: 기본값(256K 토큰 cache)에서는 cache가 작업 집합을 담아 hit rate가 90%를 넘는다. turn마다 새 도구 출력 정도만 prefill한다. 용량을 점선(작업 집합)보다 왼쪽으로 끌면 turn 사이에 세션 전체가 쫓겨나고, turn별 막대가 위에서부터 빨개져 시스템 프롬프트만 hit으로 남는다. 용량을 고정하고 세션 수를 늘려도 마찬가지다. 서빙 fleet이 세션을 그 cache를 가진 replica로 다시 보내는(cache-aware routing) 이유다. 마지막으로 timestamp를 체크하라. 요청마다 바뀌는 것(날짜, 요청 id, 순서가 섞인 도구 목록)을 안정된 prefix 앞에 두면 모든 hit이 사라진다. 안정된 내용은 앞에, 바뀌는 내용은 뒤에.

Offload와 공유 KV 저장소

HBM이 차면 다음 계층은 host DRAM, 그다음 로컬 SSD, 그다음 원격 pool이다. cache된 prefix를 가져올 가치가 있는지는 roofline 질문이다. prefill 토큰 하나를 다시 계산하면 2N2N FLOPs, 다시 불러오면 링크로 κ\kappa바이트다. H100에서 MFU 60%를 가정한 70B 모델이면 재계산이 토큰당 ≈ 236 µs인데, 320 KiB를 PCIe 5.0 ×16(명목 ~64 GB/s)으로 다시 읽으면 ≈ 5 µs, ~7 GB/s NVMe 드라이브로도 ≈ 47 µs다(우리의 추정). 다시 읽는 쪽이 5–50배 싸고, κ\kappa가 작은 MLA에서는 차이가 더 벌어진다. 이 이득을 실현하려면 전송을 계산과 겹쳐야 한다(층 단위 prefetch).

Mooncake(Kimi 뒤의 서빙 플랫폼)는 이 위에 서 있다. prefill과 decode 클러스터를 분리하고, 클러스터에서 놀고 있던 CPU·DRAM·SSD를 분산 KV 저장소로 묶는 KVCache 중심의 분리형 아키텍처다. 인스턴스들이 공유 저장소에서 cache된 prefix를 찾으므로, 한 replica에서 계산한 prefix를 다른 replica가 재사용할 수 있다. 논문은 실제 부하에서 Kimi가 75% 더 많은 요청을 처리하게 됐다고 보고한다(시뮬레이션 시나리오에서는 처리량 최대 +525%). vLLM은 같은 아이디어를 Mooncake store connector로 노출한다. CPU/디스크 offload가 되는 공유 KV pool, 인스턴스 간 hash 기반 매칭, prefill–decode 분리(다음 레슨)와의 결합.

KV 양자화

KV를 더 적은 비트로 저장하면 κ\kappa가 직접 줄고, decode attention의 산술 강도가 2g/bkv2g/b_{kv}이므로 절반으로 줄일 때마다 attention 처리량이 두 배가 된다. 대부분의 엔진에서 기본은 tensor(또는 head)별 scale을 쓰는 FP8 KV다. 8비트 아래로 가면 scale의 축이 중요해진다. KIVI는 key에는 크기가 꾸준히 큰 channel이 몇 개 있고 value에는 그런 것이 없다는 것을 관찰했다. key는 channel별(토큰들에 걸쳐 channel마다 scale 하나)로 양자화해 outlier channel이 다른 channel을 뭉개지 않게 하고, value는 토큰별로 양자화한다. 2비트 KV에서 논문은 peak 메모리 2.6배 감소(가중치 포함), 최대 4배 큰 배치, 2.35–3.47배 처리량을 보고한다. 아래 코드가 outlier channel이 있는 합성 key에서 이 비대칭을 재현한다. (형식은 양자화에서 다룬다.)

축출(Eviction)

손실을 감수하는 선택지는 일부 토큰만 남기는 것이다. StreamingLLM은 순수 sliding window가 무너지는 이유가, 모델이 attention 질량을 처음 토큰들에 쏟아붓기 때문(attention sink)임을 발견했다. 처음 4토큰과 최근 토큰의 rolling window를 함께 남기면 최대 4백만 토큰까지 생성이 안정적이고, sliding-window 재계산보다 최대 22.2배 빠르다. H2O는 최근 토큰과 “heavy hitter”(누적 attention을 가장 많이 받은 토큰)를 남기며, heavy hitter 20% 예산으로 offloading 기반 시스템보다 처리량이 최대 29배라고 보고한다. 둘 다 정보를 영구히 버리므로, 쫓겨난 사실은 나중에 꺼낼 수 없다. 긴 문맥 검색에서는 추세가 오히려 아키텍처 쪽이다(sparse attention, 긴 문맥 서빙).

직접 계산하기

NumPy KV 크기, paging 활용률, prefix 재사용, KIVI식 양자화, 축출, offload
import numpy as np
rng = np.random.default_rng(0)

# 1) KV bytes per token
def kv_gqa(L, n_kv, d_h, b=2): return 2 * L * n_kv * d_h * b
def kv_mla(L, d_c, d_r, b=2):  return L * (d_c + d_r) * b      # one shared latent + RoPE key per layer
for name, v in [("8B GQA (32L, 8 kv)", kv_gqa(32, 8, 128)), ("70B GQA (80L, 8 kv)", kv_gqa(80, 8, 128)),
                ("DeepSeek-V3 MLA (61L)", kv_mla(61, 512, 64)), ("DeepSeek-V3 MLA, fp8", kv_mla(61, 512, 64, 1))]:
    print(f"{name:<24} {v / 1024:6.1f} KiB/token   128K context = {v * 131072 / 2**30:5.1f} GiB")

# 2) contiguous reservation vs paging: a snapshot of 64 running sequences
cur = (rng.lognormal(6.5, 1.0, size=64)).astype(int) + 1    # current lengths (prompt + generated so far)
max_len = 8192
used = cur.clip(max=max_len).sum()
print(f"\nused tokens {used:,}; contiguous reservation of max_len={max_len}: utilisation {used / (64 * max_len):.1%}")
for b in [1, 16, 64, 256]:
    alloc = (np.ceil(cur / b) * b).sum()
    print(f"  paged, block {b:3d}: utilisation {used / alloc:.1%}  (expected waste/seq ≈ (b-1)/2 = {(b - 1) / 2:.1f})")

# 3) prefix caching: tokens that must be prefilled with and without reuse
G, P, O = 8, 2000, 4000                                       # GRPO: 8 samples share a 2000-token prompt
print(f"\nGRPO group: prefill {G * P:,} tokens without cache, {P:,} with  ({1 - 1 / G:.0%} saved)")
sys_p, turns, u, o = 6000, 20, 300, 400                       # agent: system+tools, turns, tool/user and model tokens
no_cache = sum(sys_p + t * (u + o) + u for t in range(turns))  # whole history re-prefilled every turn
with_cache = sys_p + turns * u                                # only new tokens (model outputs are already cached)
print(f"agent, {turns} turns: prefill {no_cache:,} tokens without cache vs {with_cache:,} with ({no_cache / with_cache:.0f}x)")

# 4) KV quantisation: keys have outlier *channels*, so quantise keys per-channel and values per-token (KIVI)
def quant(x, bits, axis):
    lo, hi = x.min(axis=axis, keepdims=True), x.max(axis=axis, keepdims=True)
    scale = (hi - lo) / (2**bits - 1)
    return np.round((x - lo) / scale) * scale + lo
T, d = 1024, 128
K = rng.normal(size=(T, d)); K[:, [3, 17, 70]] += rng.normal(8, 1, size=3)  # fixed-offset outlier channels
V = rng.normal(size=(T, d)); q = rng.normal(size=(64, d))
def attn(q, K, V):
    s = q @ K.T / np.sqrt(d); p = np.exp(s - s.max(1, keepdims=True)); return (p / p.sum(1, keepdims=True)) @ V
ref = attn(q, K, V)
for bits in [4, 2]:
    e_tok = np.abs(attn(q, quant(K, bits, 1), quant(V, bits, 1)) - ref).mean()
    e_ch = np.abs(attn(q, quant(K, bits, 0), quant(V, bits, 1)) - ref).mean()
    print(f"{bits}-bit KV: keys per-token err {e_tok:.4f} | keys per-channel err {e_ch:.4f}")

# 5) eviction on a toy stream: attention with a sink token and a recency bias (synthetic, for illustration)
T, budget = 2048, 256
Kt, Vt = rng.normal(size=(T, 64)), rng.normal(size=(T, 64))
bias = np.zeros(T); bias[0] = 6.0                             # a sink: position 0 absorbs mass
def out(qi, t, keep):
    idx = np.array(sorted(keep)); s = Kt[idx] @ qi / 8 + bias[idx] + 0.002 * (idx - t)
    p = np.exp(s - s.max()); return (p / p.sum()) @ Vt[idx]
errs = {"window": [], "sink+window": [], "H2O": []}
acc = np.zeros(T)                                             # H2O: accumulated attention per position
for t in range(budget, T, 64):
    qi = rng.normal(size=64)
    full = out(qi, t, range(t + 1))
    s = Kt[:t + 1] @ qi / 8 + bias[:t + 1] + 0.002 * (np.arange(t + 1) - t)
    acc[:t + 1] += np.exp(s - s.max()) / np.exp(s - s.max()).sum()
    win = range(t - budget + 1, t + 1)
    sink = [0, 1, 2, 3] + list(range(t - budget + 5, t + 1))
    heavy = list(np.argsort(acc[:t + 1])[-budget // 2:]) + list(range(t - budget // 2 + 1, t + 1))
    for k, keep in [("window", win), ("sink+window", sink), ("H2O", set(heavy))]:
        errs[k].append(np.abs(out(qi, t, keep) - full).mean())
print("\neviction, budget 256 of up to 2048 tokens: " + "  ".join(f"{k} err {np.mean(v):.3f}" for k, v in errs.items()))

# 6) offload: reload a cached prefix vs recompute it (nominal link speeds; our estimates)
flops_tok, kv_tok = 2 * 70e9, kv_gqa(80, 8, 128)              # 70B dense
recompute = flops_tok / (989e12 * 0.6)                        # H100 at an assumed 60% MFU
for tier, bw in [("host DRAM over PCIe 5.0 x16 (~64 GB/s)", 64e9), ("local NVMe SSD (~7 GB/s)", 7e9)]:
    print(f"per token: recompute {recompute * 1e6:6.1f} us  vs  load from {tier}: {kv_tok / bw * 1e6:5.1f} us")
 

축출 예제는 합성이다(심어 둔 sink와 최근성 편향). 방법들의 벤치마크가 아니라 메커니즘(sink를 버리면 질량이 window로 몰린다)의 예시로 읽어야 한다.

확인 문제Check yourself

어떤 agent 제품이 모든 요청의 시스템 프롬프트 맨 앞에 현재 날짜와 시각을 붙인다. prefix caching은 어떻게 되나?

hash chain과 radix tree cache 모두에서 블록은 자기 토큰과 그 앞의 모든 것으로 식별된다. 블록의 K와 V가 attention을 통해 prefix 전체에 의존하기 때문이다. 첫 토큰이 바뀌면 이후 모든 블록의 정체가 바뀌므로 대화 이력도 miss가 된다. 바뀌는 내용은 끝에 둬라.

확인 문제Check yourself

KIVI가 key는 channel별로, value는 토큰별로 양자화하는 이유는?

토큰별 scale은 그 토큰의 dd개 channel에 대한 최댓값이다. outlier channel이 있으면 다른 channel은 모두 성긴 격자를 받는다. channel별 scale은 그 channel의 토큰들에 대한 최댓값이므로 outlier channel은 자기 자신에게만 영향을 준다. value에는 그런 channel 구조가 없고, 출력은 value 행들의 토큰별 가중합이므로 토큰별 scale이 오차가 전파되는 방식과 맞는다.

정리

  • 토큰당 KV: 128 KiB(8B GQA)부터 320 KiB(70B GQA). MLA는 bf16에서 69 KiB. 최종 길이를 모른 채 동적으로 자란다.
  • paging은 예약과 외부 단편화를 없앤다. 낭비는 시퀀스당 부분 블록 하나 이하다. 참조 카운트로 copy-on-write 공유를 한다.
  • prefix caching(hash chain 또는 radix tree)은 prefix 전체를 키로 한 블록을 재사용한다. agent, multi-turn 세션, GRPO 그룹이 가장 좋은 경우다. 안정된 내용을 앞에.
  • cache된 prefix를 DRAM이나 SSD에서 다시 읽는 것은 재계산보다 5–50배 싸다. Mooncake식 공유 저장소는 replica 사이에서 prefix를 재사용하게 한다.
  • KV 양자화는 바이트를 줄이고 decode attention의 산술 강도를 올린다. key는 channel별, value는 토큰별로.
  • 축출(sink + window, heavy hitter)은 손실이 있다. sink는 남겨라.

더 읽을거리Further reading