From 300KB to 69KB per Token: How LLM Architectures Solve the KV Cache Problem
TL;DR Highlight
A breakdown of how LLM KV Cache architecture has evolved from GPT-2 to DeepSeek V3, comparing per-token memory costs across architectures as they dropped from 300KB to 69KB.
Who Should Read
ML engineers who serve LLMs directly or need to optimize inference costs, as well as backend/infrastructure developers who want to understand the internal workings of LLM architectures.
Core Mechanics
- KV Cache is not just an abstract concept — it's physical bytes residing in GPU memory. For each token, query, key, and value vectors are computed, and storing the key-value pairs in GPU memory eliminates the need to recompute all previous tokens when generating the next one. This reduces computational complexity from O(n²) to O(n).
- Without KV Cache, processing a 2,000-token conversation requires reprocessing all 2,000 tokens from scratch for every single token generated — meaning the entire history is read 2,000 times over. KV Cache eliminates this redundant computation.
- GPT-2 (2019) used the simplest form of Multi-Head Attention, where every attention head maintained independent key-value pairs. This resulted in a KV Cache cost of 300KiB per token, meaning a single 4,000-token conversation occupied approximately 1.2GB of GPU memory, separate from model weights.
- Llama 3 (2024) introduced GQA (Grouped-Query Attention) across all model sizes. By having multiple query heads share the same key-value pairs, the per-token cost dropped to 128KiB — less than half of GPT-2. Benchmark quality loss was minimal, as many attention heads had already been learning redundant representations.
- DeepSeek V3 (2024) adopted MLA (Multi-Head Latent Attention), which instead of caching key-value tensors directly, compresses them into a low-dimensional latent space for storage and decompresses at inference time. Despite being a 671B parameter model (with only 37B activated per token via MoE routing), the per-token cache cost dropped to 68.6KiB. Notably, despite being lossy compression, it slightly outperformed standard MHA on some benchmarks.
- Gemma 3 (2025) combined GQA with a sliding window approach. Local-to-global attention layer ratio is set at 5:1, with local layers processing only the most recent 1,024 tokens. Older context is only accessible through narrow global attention layers. Despite this aggressive filtering, perplexity loss was negligible.
- There are also approaches that eliminate KV Cache entirely. State Space Models (SSMs) like Mamba (2023) maintain a fixed-size hidden state that is updated token by token. The tradeoff is that memory doesn't grow, but the model must decide in real time what to compress and discard.
Evidence
- "A research project called 'Cartridges' — which optimizes KV Cache directly via gradient descent — was introduced in the comments. Developed by Stanford's Hazy Research team, this approach keeps network weights frozen and instead trains the KV Cache itself to compress large documents or entire codebases into a smaller set of tokens. Commenters found it compelling that this enables more systematic compression than ad-hoc LLM summarization. Beyond architecture-level optimizations, a practical tip was shared about quantizing the KV Cache at inference time. In llama.cpp, quantizing keys to q8 and values to q4 can cut memory nearly in half on top of savings already achieved by GQA or MLA. One user reported running a Qwen 70B 4-bit model on an M2 Max 96GB machine where KV quantization allowed long contexts to fit within unified memory. An asymmetric quantization strategy — applying different precision levels to keys and values — was also discussed. Because keys directly determine attention scores, they require higher precision, while values are far more tolerant of lossy compression. This makes the asymmetric approach of q8 for keys and q4 for values practically effective. A fun fact was noted in the comments: Voyager 1's RAM capacity is 69KB — the same as DeepSeek V3's per-token KV Cache size — humorously highlighting the scale of memory consumption in modern AI models."
How to Apply
- "When serving large models (70B+) locally or on-premises with llama.cpp and long context is required, enable KV Cache quantization options (key: q8, value: q4) to reduce memory by roughly half on top of savings already provided by GQA/MLA. This is especially effective on Apple Silicon with unified memory. When comparing new models by architecture, refer to Sebastian Raschka's LLM Architecture Gallery to find per-token KV Cache costs for each model. Since GQA support and MLA adoption directly impact long-context serving costs, include these figures in your pre-deployment checklist for cost-sensitive services. If you're running a RAG pipeline that repeatedly references large documents or codebases, consider reviewing Stanford's Cartridges approach (https://hazyresearch.stanford.edu/blog/2025-06-08-cartridges). Directly optimizing KV Cache via gradients to cache documents in a more compressed form can improve memory efficiency compared to stuffing entire documents into context every time."
Terminology
Related Papers
Show HN: Bash4LLM+ – A lightweight, dependency-free Bash wrapper for LLM APIs
Python이나 Node.js 없이 순수 Bash만으로 Groq 등 OpenAI 호환 LLM API를 호출할 수 있는 단일 스크립트 도구로, Termux(Android)를 포함한 모든 Unix 환경에서 동작한다.
Wayfinder Router: deterministic routing of queries between local and hosted LLM
프롬프트의 복잡도를 모델 호출 없이 오프라인으로 점수화해서 간단한 쿼리는 로컬 모델로, 어려운 쿼리는 유료 모델로 자동 라우팅하는 CLI 도구다. LLM 비용을 줄이면서도 응답 품질을 유지하고 싶은 개발자에게 유용하다.
Apple Neural Engine: Architecture, Programming, and Performance
Apple 기기에 내장된 AI 전용 칩인 ANE(Apple Neural Engine)를 리버스 엔지니어링으로 분석한 302페이지짜리 기술 문서로, Core ML 아래 숨겨진 내부 구조와 직접 접근 경로를 처음으로 공개한다.
DSpark: Speculative decoding accelerates LLM inference [pdf]
DeepSeek이 Speculative Decoding을 개선한 DSpark 기법을 공개했는데, 같은 시스템 용량 기준으로 사용자당 생성 속도가 57~78% 빨라졌다고 한다. 이게 DeepSeek이 경쟁사 대비 훨씬 싼 가격으로 Pro 모델을 제공할 수 있는 핵심 기술 중 하나일 가능성이 높다.
Show HN: Smart model routing directly in Claude, Codex and Cursor
프롬프트마다 적합한 AI 모델을 50ms 이내에 자동으로 선택해주는 프록시 라우터로, API 비용을 40~70% 절감할 수 있다고 주장하는 오픈소스 도구다. 단, 프롬프트 캐싱 손실 문제로 커뮤니티 반응은 엇갈린다.
Show HN: Overfitted a 900KB Transformer to Compress a 100MB CSV into 7MB
단일 파일을 통째로 암기하도록 Transformer를 과적합(overfitting)시킨 뒤 arithmetic coding으로 압축하는 실험으로, 100MB CSV를 7MB(~0.5 bits/byte)까지 줄이는 데 성공했다. 모델이 '범용 이해' 대신 '특정 파일 완전 암기'를 목표로 한다는 점에서 전통적 ML 학습과 정반대 방향이라 흥미롭다.