Sitemap
Towards AI

We train AI Engineers. We deploy Enterprise AI. Join 100K+ AI practitioners at Towards AI Academy or reach out for help making your company AI native. towardsai.com

Member-only story

The KV Cache by Hand

15 min readMar 28, 2026

--

🔓 Free link for non-members — click here to read without a paywall

Press enter or click to view image in full size

Every time you generate a token with an LLM, the model runs attention.

Attention requires K and V vectors for every token that came before.

Without a cache: recompute every K and V vector from scratch at every step. For token 1000, that is 999 redundant matrix multiplications.

With the KV cache: store the K and V vectors the first time. Never recompute them.

That storage is not free.

For GPT-3 at 2048-token context: 800 GB of cache. Per request.

For Llama-2–7B at 4096 tokens: 2 GB. Per request.

For GPT-4 at 128K context: roughly 128 GB. Per request.

This is why inference is expensive. Not the model weights. The cache.

This article shows you — by hand, with the same toy numbers from the hand-tracing series — exactly what gets cached, what gets reused, and how to derive the memory formula from first principles.

--

--

Dr Swarnendu AI
Dr Swarnendu AI

Written by Dr Swarnendu AI

AI Learner and Ph.D.(in not so famous domain). I demystify AI using First Principles, Causal ML, and the beauty of classical math. Let’s make machines reason.

Towards AI
Towards AI

Published in Towards AI

We train AI Engineers. We deploy Enterprise AI. Join 100K+ AI practitioners at Towards AI Academy or reach out for help making your company AI native. towardsai.com