Загрузка видео...

Не удалось загрузить видео

На главную

KV caching is the fundamental optimization underpinning autoregressive LLM inference. Transformer layers store keys and values from earlier tokens, then reuse them as new tokens are generated. This avoids recomputation, but at the cost of memory capacity and bandwidth.

36,159 просмотров • 11 дней назад •via X (Twitter)

Комментарии: 20

Фото профиля Alex Zverianskii
Alex Zverianskii11 дней назад

I kind of expected a twist that "we can do better than KV cache."

Фото профиля Devil
Devil11 дней назад

Which software you used for this animation?

Фото профиля Alec Helbling
Alec Helbling11 дней назад

I made it from scratch using JavaScript.

Фото профиля XERV
XERV10 дней назад

@ThisIs_KroY What JavaScript frameworks did you use?

Фото профиля Alec Helbling
Alec Helbling9 дней назад

@ThisIs_KroY I use svelte and a combination of d3 js as well as the canvas api and custom shaders.

Фото профиля AI Apps API
AI Apps API10 дней назад

The part that bites in agent workloads is not the memory, it is invalidation. Reuse only happens on an exact prefix, so anything that shifts near the front, a reordered tool list, a timestamp in the system prompt, a retrieved doc pasted above the history, throws the whole thing away and you recompute a context you already paid for. Keeping the stable parts first and appending only at the tail buys more in practice than most of the tuning that gets attention.

Фото профиля Manuel Brack
Manuel Brack11 дней назад

I mean… That’s the reason linear attention exists, no? Memory becomes O(1), so does bandwidth (per token).

Фото профиля fj_nm | AI Systems & Automation
fj_nm | AI Systems & Automation10 дней назад

the memory-bandwidth tradeoff is the real bottleneck most teams ignore. we switched to paged attention (vLLM style) and cut our KV cache memory by 60% without touching the model. the inference cost problem is mostly an infrastructure problem, not a model problem.

Фото профиля Swapnil Tiwari 🌏
Swapnil Tiwari 🌏10 дней назад

This is closest animation i have seen how kv cache is actually goes through attention layers

Фото профиля Vikrant Guleria
Vikrant Guleria5 дней назад

KV cache growth is the real scaling bottleneck once you push context length up. Techniques like multi-query and grouped-query attention exist basically to trade off a bit of quality for a much smaller cache footprint.

Фото профиля DEV
DEV11 дней назад

The trade-off between memory capacity and bandwidth is often overlooked. It's a balancing act.

Фото профиля Ojasvi Yadav
Ojasvi Yadav10 дней назад

Can you please share the prompt you used to generate this animation?

Фото профиля Tony 🎋
Tony 🎋10 дней назад

the bandwidth half is doing more work than it looks: decode reads the whole kv cache per token, so tokens/sec tracks cache bytes, not flops. it's why mqa became gqa became mla — when the cache is the bill, you shrink the cache instead of buying more bandwidth.

Фото профиля Buswe
Buswe10 дней назад

That memory cost is where PagedAttention pays off: vLLM keeps the KV cache in blocks, so far less fragmentation and many more concurrent requests.

Фото профиля cordivai | Machine Learning & AI
cordivai | Machine Learning & AI10 дней назад

Good framing for LLM research work. The practical part is not just trying a stronger model, but logging baselines, data splits, task-specific metrics, and failure cases so the result is reproducible.

Фото профиля Jonathan Sandhu
Jonathan Sandhu11 дней назад

Exactly. Once KV is treated as a first-class execution artifact, inference stops being “run the model on a GPU” and becomes a routing problem: where to prefill, where to decode, when to move state, and when transfer cost makes staying put cheaper.

Фото профиля Modelplane
Modelplane10 дней назад

The memory/bandwidth tradeoff is the real bottleneck in practice. Techniques like PagedAttention and sliding windows help, but they shift the pressure to scheduling. Curious how you see the balance between cache size and throughput evolving as context windows grow.

Фото профиля Harley Lewis Foote
Harley Lewis Foote10 дней назад

Everyone quotes FLOPs. The invoice says memory.

Фото профиля Mai 麦尔彦
Mai 麦尔彦10 дней назад

This animation breaks down the memory vs. compute trade-off so well. Saved! 👏

Фото профиля anurag
anurag11 дней назад

the interesting part is that KV caching turns autoregressive decoding into a memory bandwidth-bound problem rather than a pure FLOPs problem. With long contexts, KV cache size can dominate GPU memory, i think thats why KV quantization is becoming increasingly important

Похожие видео

A tricky LLM interview question: You're serving a reasoning model on vLLM, and it keeps running out of GPU memory on long traces. So you add KV cache compression and evict 90% of the cached tokens. VRAM usage stays as is and GPU still runs out of memory. Why? (answer below) Evicting 90% of the KV cache can free almost none of the memory it was using. This sounds counterintuitive, but it follows directly from how production servers store the cache today. The KV cache grows with every token a model generates. Each token appends its key and value vectors across every layer, and nothing is freed while generation continues. This is the dominant memory cost for reasoning models. If a 32K-token CoT caches ~32K tokens of KV vectors, a Qwen3-32B with 4-bit weights will run out-of-memory around 24K tokens on a 24GB GPU. One obvious solution is to keep the important tokens and drop the rest, since attention is sparse enough to allow it. But this does not solve the memory problem yet. The reason is paged attention, which is the memory manager behind vLLM and most production servers. Under the hood, it splits GPU memory into fixed physical blocks, each one holds the KV for about 16 tokens. This block returns to the allocator only when every slot inside it is empty. Since the eviction logic selects tokens by importance, and such tokens are scattered across blocks... ...so despite eviction, almost every block is left with at least some survivor tokens. For instance, if the logic evicts 14k of 16k tokens across 1,000 blocks, most likely every block will still have a token. This means the allocator frees almost nothing. Placing the new tokens into those freed slots is not ideal because it breaks the cache's layout. Say token 16,001 arrives, and it's placed in the slot the 40th token used to hold. The cache now reads position 38, then 16,001, then 41, so the cache is no longer in token order. Attention can still compute the right answer from that, but only if every slot now carries a separate note recording which position it actually holds. This introduces another bookkeeping cost that an in-order layout inherently avoids. So the cache is logically 90% smaller and still physically the same size. Many compression results miss this because they measure on pre-allocated contiguous tensors rather than a paged server. There's another problem. Eviction methods pick which tokens to keep by looking at the attention scores themselves (as expected). But fast attention kernels used in production, like FlashAttention, never save those scores. They compute attention in small pieces and throw the full score grid away as they go, which is also why they're fast. So the exact signal eviction methods need isn't available in memory. The workaround is to fall back to eager attention and build the full matrix, which gives up the speed FlashAttention was there to provide. NVIDIA published a method called TriAttention to solve both these problems. It never needs attention scores. Instead, it scores tokens from the geometry of the model's key and query vectors before RoPE is applied, where those vectors sit in stable clusters. For the memory problem, it runs a compaction pass every 128 decoded tokens. The surviving tokens slide forward to close the holes eviction creates, so whole blocks empty out and return to the allocator while the cache stays in token order. On long reasoning traces, the approach matches full-attention accuracy while decoding 2.5x faster and using 10.7x less KV memory. KV cache compression is a big infrastructure problem. The number that decides whether it works is the count of freed blocks, not the count of evicted tokens. You can find the NVIDIA write-up here: I wrote a first-principles breakdown of how the KV cache works. It walks through why the model stores keys and values at all, why the cache grows with every token, and a comparison of LLM generation speed with and without KV caching. Read it below.

Avi Chawla

271,839 просмотров • 2 месяцев назад

Researchers found a way to make LLMs 8.5x faster! (without compromising accuracy) Speculative decoding is quite an effective way to address the single-token bottleneck in traditional LLM inference. A small "draft" model first generates the next several tokens, then the large model verifies all of them at once in a single forward pass. If a token at any position is wrong, you keep everything before it and restart from there. This never does worse than normal decoding. But current drafters in Speculative decoding still guess one token at a time. That makes the drafting step itself a bottleneck, capping real-world speedups at 2-3x. DFlash is a new technique that swaps the autoregressive drafter with a lightweight block diffusion model that guesses all tokens in one parallel shot. Drafting cost stays flat no matter how many tokens you speculate. On top of that, the drafter is conditioned on hidden features pulled from multiple layers of the target model and injected into every draft layer, so it makes significantly better guesses than a drafter working from scratch. In the side-by-side demo below, vanilla decoding runs at 48.5 tokens/sec. DFlash hits 415 tokens/sec on the same model, with zero quality loss. It's already integrated with vLLM, SGLang, and Transformers, with draft models on HuggingFace for several models like Qwen3, Qwen3.5, Llama 3.1, Kimi-K2.5, gpt-oss, and many more. I have shared the GitHub repo in the replies! KV caching is another must-know technique to boost LLM inference. I recently wrote an article about it. Read it below. 👉 Over to you: What use case are you working on that can benefit from this new technique?

Avi Chawla

157,390 просмотров • 4 месяцев назад

Researchers made LLM inference 14x faster and 90% cheaper. The video below depicts the speed up in action. Providers discount cached input tokens by as much as 90% because a cache hit skips prefill compute entirely. For stable system prompts and tool definitions, hit rates of 60 to 85% are achievable, which makes it the highest-leverage inference optimization. But the cost saving only works when the cached text is an exact, byte-for-byte prefix of the new request. If you change one character anywhere before it, the entire cached region is missed. Three common request patterns produce full cache misses: - A query that needs documents A and B together can't reuse B's standalone cache, because those KV entries were computed without A in front of them. - The same three documents retrieved in a different order produce a full cache miss, even though nothing about the documents changed. - In multi-turn conversations, every new turn invalidates whatever was cached beyond the stable prefix. Alibaba's production data did a study on this and found that just 10% of cached KV blocks serve 77% of all cache hits. So most of what gets cached sits in storage and is never used a single time. And the root cause is that KV entries are position-dependent. Each token's KV encodes attention to everything before it, so a cached block is only valid in the exact context it was computed in. There's a second, less discussed problem as well. Cache management runs inside the inference engine's process. Moving KV tensors between GPU, CPU, and disk competes with inference for the same resources. This is why Google's TurboQuant compresses KV caches to 3 bits with no accuracy loss and still causes a 20%+ slowdown when it runs in-process. Fixing both problems means restructuring where caching lives. Cache management moves into its own process, the engine only exchanges block IDs over shared GPU memory, and heavy data movement runs across GPU, CPU, disk, and remote storage in parallel. Non-prefix reuse gets handled by selectively recomputing only the small set of tokens that attend across document boundaries. LMCache is the open-source project (10k+ stars) that implements this exact architecture, and it plugs into vLLM, SGLang, and TensorRT-LLM. The selective recomputation part is implemented in its CacheBlend technique, which makes cached docs in any order and combination, with 2-4x faster multi-document processing. On H200s running Qwen3-235B with 50 concurrent users, LMCache's multiprocess mode delivers 14x faster time-to-first-token and 4x faster decoding compared to in-process caching. GitHub repo: (don't forget to star 🌟) My co-founder wrote a full breakdown of KV cache management. It covers the disaggregated architecture behind the 14x speed up, how CacheBlend preserves generation quality while skipping recomputation, and how to turn every document in a knowledge base into a reusable cached asset. Read it below.

Avi Chawla

30,692 просмотров • 2 месяцев назад