It has been revealed that we have implemented KV Caching from scratch in our nanoVLM repository (a small codebase to train your own Vision Language Model with pure PyTorch). This gave us a 38% speedup in generation. In this blog post we cover KV Caching and all our experiences while implementing it. The lessons learnt are general and can be applied to all autoregressive language model generations. Implementing from scratch on a small codebase is a great learning experience, come along for the ride!

According to recent reports, autoregressive language models generate text by sampling one token at a time. During inference, the model processes a given input sequence, predicts the next token, appends it to the sequence, and repeats this process until some stopping criterion:. (Related: How to train a new language model from scratch using Tr...)

This step-by-step generation is inherently sequential:. (Related: Building the next generation of multimodal AI experienc...)

It has been revealed that this repetition also leads to computational redundancy. In this post, we explore KV Caching, an optimisation technique that mitigates this inefficiency.

Recent findings suggest that before diving into caching, let’s revisit how attention operates in transformer models. A Transformer language model consists of stacked layers, each composed of:.

To understand where KV Caching helps, we focus on the self-attention mechanism, specifically within a single attention head.

Let’s walk through a simple PyTorch implementation to visualise the key computations.

For a sequence of T T T input embeddings represented as X∈RT×D X \in \mathbb{R}^{T \times D} X∈RT×D, self-attention is computed as:.

Attention(X;Q,K,V)=softmax(QK⊤⋅Mdk)V \text{Attention}(X; Q, K, V) = \text{softmax}\left( \frac{QK^\top \cdot M}{\sqrt{d_k}} \right)V Attention(X;Q,K,V)=softmax(dk​​QK⊤⋅M​)V.

Here’s a minimal PyTorch equivalent using a causal mask:.

In a recent development, in autoregressive generation, the model generates one token at a time. With each step, it recomputes Q Q Q, K K K, and V V V for the entire sequence, even though the earlier tokens haven’t changed.

These checks show that for all but the newest token, K K K and V V V are identical to previously computed values.

According to recent reports, most of the attention computation is repeated needlessly. This gets more expensive as sequences grow.

To eliminate this inefficiency, we use KV Caching:.

This changes generation from full-sequence re-computation to a lightweight, incremental revision.

✅ In practice, this cache is a per-layer dictionary with keys "key" and "value", each of shape (batch_size, num_heads, seq_len_cached, head_dim).

This is the foundation of how modern LLMs can generate long outputs efficiently.

Recent findings suggest that now that we understand the theory behind KV Caching, let’s see how it’s implemented in practice inside our nanoVLM repository. This is an ideal testbed, as it's a super concise and self-contained codebase.

KV caching is enabled across three key components in our model:.

In the LanguageModelGroupedAttention class, we modify the forward function to accept and update a cache of keys and values (block_kv_cache).

Recent findings suggest that previously, the model recomputed K K K and V V V at every generation step. Now we only compute Knew K_{\text{new}} Knew​, Vnew V_{\text{new}} Vnew​ for the current token, and append them to the cached values.

In the LanguageModel class, we introduce layer-wise cache tracking. The start_pos argument helps the model compute correct rotary positional encodings for newly generated tokens.

The biggest architectural change is in the generate() method of the VisionLanguageModel.

We split generation into two stages:.

By separating these phases, we avoid redundant computation and dramatically speed up inference, especially for long prompts.

KV caching eliminates unnecessary computation during autoregressive generation, enabling faster and more efficient inference, especially in long sequences and real-time applications. This is a trade-off between speed and memory, and its drawbacks can be more complex code and restricting fancier inference schemes, like beam-search, etc. KV caching is a popular method for speeding up LLM inference, making it possible to run them on consumer hardware, and now you know how it works too!

Special thanks to Tushar Dhar for their comment and helping us make the blog better.

Industry observers note that thanks for this great article! I'm learning a lot from the nanoVLM project.I'm not an expert in gen ai but I noticed the attention calculation example seems to be missing the scaling √(d_k). Is this intentional for simplification?

From my understanding this scaling prevents the dot product growing too large and control the softmax region.

Would you like to raise a PR to the blog post with the changes to the code?

Here is the source for the blog post: https://github.com/huggingface/blog/blob/main/kv-cache.md.

Nice read, I found the prefill and decode explanation very intuitive. Good job 👏.

made this visual representation of what happens inside the attention mechanism when using kv caching.thought i'd share it with the community 🤗.

Industry observers note that hi Team,kv_cache only for text? Is it doing for images in this Articles.

caching results can be used for diffusion applications as well, although not similar to KV caching since kv caching is optimized for next token prediction while in diffusion the full sequence already exists.the short answer to your question is yes kv caching is only for next token prediction but there are other caching techniques out there for other taskstry checking what PrunaAI has been doing to optimize diffusion models, here's a link to one of their previous presentations : LINKEDIN_POST.

Hi,Thanks for helping me understand KV caching,.

I just had a clarifying question,in the diagram for this attention matrix (mentioned above in the article):.

Original (5×5): Extended (6×6):■ ■ ■ ■ ■ -> ■ ■ ■ ■ ■ □■ ■ ■ ■ ■ -> ■ ■ ■ ■ ■ □■ ■ ■ ■ ■ -> ■ ■ ■ ■ ■ □■ ■ ■ ■ ■ -> ■ ■ ■ ■ ■ □■ ■ ■ ■ ■ -> ■ ■ ■ ■ ■ □....................... □ □ □ □ □ □.

you say that :"□ = Recomputed unnecessarily".

In a recent development, but is that not the part we need to compute and the white ones are recomputed unnecessarily,I might be taking the wording the wrong way I feel so needed to askThanks anyways! great read! 🤗.

You are absolutely right! Thanks for catching it. We have updated the blog and also credited you for the comment. 🤗 https://github.com/huggingface/blog/pull/3593.

→ Read original article