Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Illustrated Guide to KV Cache: The Secret Behind DeepSeek V4.1-Flash

DeepSeek V4.1-Flash dramatically compresses per-token global KV cache from 389KB down to just 890B using advanced KV Cache compression. This breakthrough solves critical memory and bandwidth bottlenecks for long-context AI agents. The article provides a visual breakdown of KV Cache evolution, hardware principles, and V4.1's core innovations, offering practical insights for Agent users, local deployers, and model developers alike.

KV CacheDeepSeek V4.1DeepSeek V4.1-FlashKV Cache compressionlong context LLM

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

🔗 Original link: https://x.com/wquguru/status/20991197602...

WquGuru · X · @wquguru · 2026-09-13 20:55

📌 This article is reposted. All copyrights belong to the original author. Please refer to the original link for the full text.

From DeepSeek V1 to V4.1-Flash, how was the per-token global KV cache compressed from 389,000 bytes down to just 890 bytes? This article offers valuable insights for AI agent users, local model deployers, and model developers alike.

Running a long-context agent today — for example, having a model read an entire million-token codebase before working on a task — reveals that the biggest consumer of VRAM is not the model weights, but the KV Cache. Model weights are fixed; a few hundred GB is just a few hundred GB. But the KV Cache grows linearly with context length — double the context, and it doubles in size.

At the beginning of September, DeepSeek released the V4.1-Flash technical report titled Pushing the Limits of KV Cache Compression. One sentence in the abstract cuts straight to the point: prefill remains expensive, and large KV caches continue to consume HBM and SSD capacity and bandwidth. Together, these three factors represent the most pressing bottlenecks in reducing deployment costs.

This article aims to map out the major breakthroughs in KV Cache compression over the past few years, with a deep dive into the innovations in V4.1-Flash. Along the way, it includes some essential hardware context — because without understanding what HBM is and why it’s so expensive, it’s hard to grasp why the community is so obsessed with squeezing every last byte.

Reading Guide:

  • AI Agent Users (people using tools like Claude Code or Cursor who want to understand why long conversations get slower and more expensive): Read Section 1 and the billing part of Section 5. Section 1 explains the difference between prefill and decode costs; Section 5 explains why cache-hit pricing can be set at just 2% of cache-miss pricing. You can safely skip the technical details in between and just look at the diagrams.

  • Local Model Deployers (running vLLM, SGLang, etc. on your own GPUs and struggling with VRAM): Focus on Section 2, Section 3, and the “If You Are Deploying Models” section at the end. Section 2 explains the VRAM hierarchy and why decode is bandwidth-bound. Section 3 clarifies which configurable switches actually matter. The four points at the end form a practical checklist.

  • Model Developers (working on architectures or training and wanting to know exactly what changed in V4.1): The three-dimensional framework in Section 3 and the entire Section 4 are the core of the article — especially the three modes of CSA2, the 40-layer layout, and the 890-byte cost breakdown. Section 5 lists four design rationales that you can cross-reference with the original technical report.

Readers with no machine learning background can comfortably finish the first two sections. Section 4 involves specific layer counts, dimensions, and byte calculations, so it reads more slowly — but every segment is accompanied by diagrams, which make the concepts much clearer when viewed directly.

1. What Is KV Cache?

This section explains three fundamental things: why KV Cache exists, how large it is, and the difference between prefill and decode. Everything that follows builds on these three points.

Transformer text generation produces tokens one by one. For each new token, the model must look back at all previous tokens — this “looking back” is attention.

The mechanism of attention is as follows: each token has three vectors — Q (Query: what I’m looking for), K (Key: what I am), and V (Value: the information I carry). The new token’s Q performs a dot product with the K of every previous token to compute attention weights, which are then used to compute a weighted sum of the corresponding V vectors.

A crucial observation here is that the K and V vectors of earlier tokens never change. The K and V used by the 100th token when attending to the 3rd token are exactly the same as those used by the 200th token when attending to the 3rd token.

Without caching, every time a new token is generated, the model would have to recompute the K and V for all previous tokens, resulting in O(N²) computation. With caching, only the new token’s K and V need to be computed at each step; the rest are read from memory, reducing the computation to O(N). The trade-off is increased memory usage: for every token and every layer, a copy of K and V must be stored.

This is the KV Cache. The name is straightforward — it simply caches the Keys and Values.

How Big Is the KV Cache, Really?

There’s a simple multiplication formula that makes it crystal clear:

Taking DeepSeek’s first-generation 67B model as an example: 95 layers, one copy each for K and V, 8 KV heads, 128 dimensions per head, and BF16 precision (2 bytes per value). Multiplying these together gives roughly 389 KB per token.

389 KB doesn’t sound like much. But with a 128K context, that becomes 48 GB. After storing the KV cache, an H100 (market price around 300,000 RMB as of September 12, 2026) with 80 GB of VRAM has very little space left for model weights. A 1M context would require 380 GB—even four H100s wouldn’t be enough if all their VRAM were dedicated to the KV cache.

This formula is crucial. Optimizing any single term in it can further reduce the size of the KV cache.

Prefill vs. Decode

  • Prefill: The stage where the model reads the prompt. All tokens pass through the network in a single forward pass, their K and V values are computed and stored. This phase is compute-intensive.

  • Decode: The stage where the model generates the response. It processes only one new token at a time, but must read the KV values of all previous tokens from VRAM. This phase is memory-bandwidth-intensive.

A distinctive characteristic of agent scenarios is the extremely frequent use of tools. Each tool call appends new results back into the context, requiring the model to read the entire context again. As a result, prefill performance is especially important in agent workloads. This consideration heavily influenced many of the design choices in V4.1 Flash.

Part Two: Hardware Layer — Why VRAM Is So Precious

To understand why engineers fight over every single byte, we first need to look at where those bytes actually live.

GPU memory forms a pyramid. At the very top is on-chip SRAM — only a few dozen MB, but with blazing speed reaching tens of TB/s. However, it’s so small that it can only hold the tiny slice of data currently being computed. Below that is HBM VRAM, offering tens to a couple hundred GB at 3–8 TB/s. Further down is host memory at the TB scale, but it must go through PCIe, dropping bandwidth to tens or hundreds of GB/s. At the very bottom are SSDs — tens of TB, but with only a few GB/s of bandwidth.

V4.1 divides the KV cache into two categories based on where it lives:

  • Runtime KV: The KV cache belonging to requests currently being served. It must stay in HBM and is constrained by HBM capacity.

  • Persistent KV: KV cache retained for prefix reuse. It is stored on SSD or host memory and is constrained by SSD capacity and I/O bandwidth.

What is prefix reuse? If you’ve already had 10 rounds of conversation with the model, and the 11th round starts with the exact same prompt as the previous 10 rounds — and the KV from round 10 is still available — then the model doesn’t need to recompute those earlier tokens. This kind of reuse happens extremely often in agent scenarios. Production systems therefore save the KV cache to SSD, where it can be kept for dozens of hours.

What Is HBM?

HBM stands for High Bandwidth Memory. It is fundamentally different from the memory sticks found in consumer PCs.

Ordinary memory modules plug into the motherboard and communicate with the CPU through a few dozen wires. HBM, by contrast, stacks DRAM chips vertically on top of each other, connecting them with TSVs (Through-Silicon Vias) that pierce through the silicon. The entire stack is then placed side-by-side with the GPU compute die on the same silicon interposer. The physical distance shrinks from centimeters to millimeters, and the number of connections jumps from dozens to thousands — which is why the bandwidth skyrockets.

The trade-offs are significant: it’s expensive, difficult to manufacture, and extremely hard to scale. Each HBM stack consists of 8 or 12 layers of chips; yield drops exponentially with each additional layer. The interposer has limited area, so the number of stacks that can be placed is fixed. This is why the H100 has 80 GB, the H200 has 141 GB, and the B200 has 192 GB. Adding a few dozen more gigabytes per generation is already pushing the limits of current packaging technology.

There’s another reason every byte of KV cache is so valuable. During decode, every new token generated requires reading the entire set of weights and the full KV cache from HBM. Compute units sit idle while the system is bottlenecked by HBM bandwidth. The longer the context, the more KV data must be read, and the longer each token takes to generate. Therefore, compressing the KV cache simultaneously saves money and improves speed.

III. Major Breakthroughs in KV Cache

This section begins with a clean analytical framework, followed by a detailed breakdown of the six major breakthroughs DeepSeek has achieved.

Here is a very clean framework: the total size of the KV Cache is the product of three numbers:

  • Size of each KV entry
  • Number of entries stored (sequence length)
  • Number of copies stored (number of layers)

The volume of the box represents the number of bytes resident in GPU memory. Before diving deeper, it’s important to understand two key distinctions:

First distinction: Saving storage vs. saving reads
As mentioned in Section II, during decoding, the KV must be read from HBM at every step. Therefore, “how much is read” and “how much is stored” are two different concerns. Some techniques reduce the amount read per step without shrinking the box itself. When the GPU is already fully occupied, a faster attention kernel cannot free up space for the next request—only shrinking the box can.

Second distinction: Baked in during training or applied at deployment
Techniques such as GQA, MLA, cross-layer sharing, and compressed attention change the model’s weight shapes and cache layout. They must be decided during training and cannot be patched onto an already-trained model. In contrast, quantization, paging, prefix caching, and hierarchical offloading are switches within the inference engine that leave the model untouched. This determines how quickly a technique can spread.

Breakthrough 1: GQA – Multiple Q heads share the same set of K and V

In the earliest Multi-Head Attention (MHA), 8 query heads were paired with 8 separate sets of K and V. In 2023, GQA (Grouped Query Attention) proposed that K and V do not need to be so numerous—4 query heads could share one set. This reduced the number of KV heads from 8 to 2, cutting the KV cache size to one-quarter. Both Llama 2 and DeepSeek-V1 adopted this approach, at the cost of a slight drop in precision.

Breakthrough 2: MLA – Low-Rank Compression

DeepSeek-V2 (2024) took a different path with MLA (Multi-head Latent Attention):

Instead of reducing the number of heads, it compresses the K and V of all heads into a single 512-dimensional latent vector for storage. During attention computation, two up-projection matrices decompress this latent vector back into the K and V for each head. Remarkably, these two matrices can be mathematically absorbed into the Q projection and output projection, allowing the decompression step to be completely eliminated. Additionally, 64 dimensions are reserved exclusively for RoPE positional encoding.

The result is striking: each layer stores only 576 values per token, compared to 2048 in standard MHA, while maintaining equivalent precision.

Breakthrough 3: Quantization – From 2 bytes to half a byte per value

A BF16 value takes 2 bytes, while an FP8 value takes 1 byte. Starting with DeepSeek-V3, KV cache is stored in FP8, immediately halving its size. V4.1 goes further by adopting FP4, halving it again. This is the only technique that can be used both as a deployment switch (quantizing at inference time) and incorporated during training (quantization-aware training).

Breakthrough 4: Sliding Window and Sparse Attention

On the sequence dimension, the first idea was Sliding Window Attention (SWA): each token only attends to the most recent 128 tokens. This makes the KV size fixed, independent of context length.

However, looking at only the most recent 128 tokens is clearly insufficient, so a global branch is needed. To make the global branch efficient, sparse attention is used: a lightweight indexer scores all historical tokens and selects only the top 512 highest-scoring ones for attention. DeepSeek-V3.2’s DSA follows this approach.

Note that sparse attention saves reads, not storage. All KV still needs to be kept in memory; only a subset is read each time. To actually reduce storage, there are two main paths. One is compression: DeepSeek-V4’s CSA compresses the KV of every two tokens into one, baked into training. The other is eviction: at runtime, tokens are discarded based on importance—for example, H2O keeps recent tokens plus those that have received the most attention historically. Eviction is a deployment-time switch; the downside is that discarded tokens are truly gone. A tool result that no one is looking at right now might become critical a few turns later.

There is also a more radical approach: hybrid models such as Qwen3-Next and Jamba replace most layers’ KV cache with a fixed-size recurrent state, keeping only a few full-attention layers. This is a fourth path outside the three dimensions. Although DeepSeek has not pursued this route, it is important to recognize it as another major school of thought in the field.

Breakthrough 5: Cross-Layer Reuse – Don’t Store So Many Copies

On the layer dimension, CLA (Cross-Layer Attention) proposed in 2024 allows adjacent layers to share the same KV. YoCo is even more aggressive: the lower half of the model computes KV, while the upper half directly reuses it.

This dimension actually holds the greatest potential. For a 40-layer model, storing only 4 copies of KV instead of 40 yields a 10× reduction. V4.1 has invested the most effort in this area.

Breakthrough 6: System-Level Optimizations – Changing Deployment Without Changing the Model

vLLM’s PagedAttention draws inspiration from operating system virtual memory by allocating KV in fixed-size pages, eliminating memory fragmentation. Prefix caching allows multiple requests to share the same prefix KV pages. Hierarchical offloading moves inactive KV to host memory and SSD.

All three are deployment-time switches. Their common trait is that they do not change how many bytes a single request’s KV occupies; instead, they reduce waste, eliminate duplication, and optimize where data is placed. System-level changes and model-level changes are multiplicative. This effect is especially evident in V4.1, which we will examine next.

Four, DS-V4.1-Flash: Joint Optimization Across Architecture, Cache Precision, and Deployment Strategy

All previous breakthroughs essentially optimized only one dimension at a time. The core philosophy of V4.1 is to jointly optimize across three layers — architecture, cache precision, and deployment strategy — while also applying system-level compression together. As a result, the global KV cache in HBM is reduced to 1/4 of the size used in V4-Flash, and the persistent KV stored on SSD is compressed to 1/8.

CED: Upper-half Model KV Computed by the Lower Half

V4.1 is a 40-layer model. The first 20 layers are called the Causal Encoder, and the latter 20 layers are the Decoder:

In a conventional Transformer, the KV of layer 30 is computed from its own hidden states. CED proposes a different approach: the global KV for layers 21–40 is entirely generated by taking the output of layer 20 and multiplying it by each layer’s independent projection matrices.

This means that during prefill, only the first 20 layers need to be executed; the KV for the remaining 20 layers can be obtained with a single matrix multiplication. The activation parameters during prefill are reduced from 16B to 8B, and the compute cost is halved. For agent workloads that are prefill-heavy, this directly saves half the cost.

The inspiration for CED comes from YoCo. However, each decoder layer retains its own projection matrix, so KV capacity is not compromised. The sliding window KV is still computed layer-by-layer, preserving the full depth of local information.

CSA2: Three Modes, Only 4 Out of 40 Layers Actually Store KV

CSA2 is the most significant architectural change in this release. Each layer is statically assigned one of three modes:

  • Full mode: Computes everything itself — main KV, projects the indexer’s K, computes the indexer’s Q, performs scoring, and selects the Top-512.

  • Reindex mode: Borrows the main KV and indexer K from the nearest preceding Full layer, but uses its own indexer Q to rescore. It does not store KV, yet each layer can still select a different set of 512 tokens to attend to.

  • Reuse mode: Directly borrows both the main KV and the Top-512 indices, then performs attention.

All three modes retain their own Q and SWA KV. The only difference lies in where the main KV, indexer K, and Top-K indices come from.

The report provides the actual 40-layer layout:

The 18 encoder layers are divided into 3 groups. Each group consists of 1 Full layer + 5 Reuse layers, with every 2 tokens compressed into 1. The 20 decoder layers are divided into 5 groups: the first group has 1 Full + 3 Reuse; the remaining four groups each have 1 Reindex + 3 Reuse.

In total, only 4 layers out of 40 operate in Full mode. Only these 4 layers incur actual storage overhead; the other 36 layers occupy no extra space.

Hierarchical Sparse Indexer: Later Layers Search Only Within a Candidate Pool

Cross-layer index reuse reduces the number of scoring operations, but the remaining Full and Reindex layers still need to score the entire context. For a context of one million tokens, this cost remains significant.

The hierarchical sparse indexer is used only in the decoder. After the first Full layer finishes scoring all positions, it groups every 8 positions together, takes the highest score in each group, and selects the top 2048 groups. This produces a candidate pool of 16,384 positions. Subsequent Reindex layers only perform scoring within this pool. As a result, the cost of later indexers changes from growing linearly with context length to a constant. Figure 2 in the report shows that when the context expands from 4K to 1M tokens, the per-token decode compute of V4.1 increases by only 25%.

Using the distinction made in Section 3, this optimization saves on reads. CSA2’s cross-layer reuse and FP4 are responsible for shrinking the box, while the hierarchical indexer ensures that each step only reads a small corner of the box. Only by doing both can the system simultaneously achieve 890 bytes of memory usage and decode compute that barely grows with context length.

P4 Main KV: One Token Occupies Only Half a Byte

In the dimension of precision, V4.1 compresses the main KV from V4’s FP8 down to FP4: specifically the E2M1 format, with every 16 channels sharing one FP8 scaling factor. The choice of the OCP-standard MXFP4 was made to ensure compatibility with as many hardware platforms as possible. It draws reference from NVIDIA’s NVFP4 but removes the second-level global scaling factor. The paper argues that after applying RMSNorm, the latent norm is bounded, making the global scaling factor entirely redundant.

There are two important details here. First, FP4 is used only for storage; before attention computation, the values are dequantized. Therefore, it does not rely on native hardware FP4 matrix multiplication. Second, SWA KV is sensitive to quantization, so it remains in FP8. Any precision loss in the main KV is mitigated to a marginal level through quantization-aware training in the later stages of post-training.

How the 890 Bytes Are Calculated

Although the DeepSeek official report does not provide a breakdown, we reverse-engineered the numbers based on the format parameters and layer configuration, arriving at the following estimate:

  • One FP4 main KV: 512 dimensions × 0.5 bytes + 32 scaling factors × 1 byte each = 288 bytes.
  • One FP4 indexer K: 128 dimensions × 0.5 bytes + 8 scaling factors = 72 bytes.

The encoder uses 3 copies. With a compression ratio of 2, each token occupies only half a copy: 3 × 360 ÷ 2 = 540 bytes. The decoder uses 1 copy: 360 bytes. The total is approximately 900 bytes, which closely matches the reported 890 bytes.

System Layer: Tiered by Lifetime, Not by Size

The model-layer changes end here, reducing the KV in HBM to 1/4 of the original size. The report shows that the other half of the effort lies in the deployment system, compressing the persistent KV on SSD down to 1/8. This half is most closely tied to hardware.

First, let’s look at the problem in V4. In V4’s persistent cache, SWA KV accounts for nearly half the storage. However, the access patterns of SWA KV and global KV are completely different: global KV exhibits long-tail reuse — a prefix may still be hit dozens of hours later — while SWA KV is only useful within a few minutes of an active session. Once the session ends, it becomes dead data. Using a 72-hour LRU policy to manage minute-level data is simply wasteful.

V4.1’s solution divides the cache into three tiers:

  • HBM: Runtime KV for requests currently being served. Millisecond-level lifetime.
  • Host DRAM Pool (new): 10% of each machine’s DRAM is allocated to form a distributed memory pool. It stores only the encoder’s SWA KV, with a TTL of a few minutes. Although its capacity is much smaller than SSD, its turnover is extremely fast.
  • SSD Persistent Cache: Stores only global KV, guaranteeing retention for over 72 hours.

What about the few requests that hit a global KV whose corresponding SWA KV has already expired? This is where SWA Bounded Replay comes in. The sliding windows of each layer are stacked sequentially. To accurately reconstruct the SWA state at layer 20, computation must start from 20 × 128 tokens earlier. Bounded Replay does not aim for perfect accuracy: it only replays the most recent 128 tokens and accepts an approximate state. Prior research has shown that the effective receptive field of SWA is much smaller than its theoretical value, and the experiments in the report confirm that this has almost no impact on answer quality.

This technique is applied in two places. On the encoder side, it allows the prefix cache to depend only on global KV, so SWA KV no longer needs to be written to SSD. On the decoder side, the approach is even more aggressive: the decoder’s SWA KV is never cached. During each prefill, only the last 128 tokens of the prompt are passed through the decoder, saving roughly half the prefill cost.

Thus, the 1/8 compression of persistent KV is the product of two factors: removing SWA KV saves about half, and compressing the global KV itself by 4× provides the other quarter.

Five, Summary: What These Bytes Ultimately Become

Compressing the KV Cache is not just about making the numbers in a paper look good. Ultimately, it translates into API pricing, while ensuring that model performance does not degrade — at least for base models.

DeepSeek API Price Reduction

On the same day V4.1-Flash was released, DeepSeek simultaneously adjusted its API pricing:

The single number that best illustrates the impact of KV compression is the cache hit price: it is only 2% of the cache miss price. When a user hits the prefix cache, all the service provider needs to do is move the persisted KV from SSD back to HBM. The smaller the KV per token, the faster it can be moved, the less SSD space it occupies, and the longer it can be retained — all of which allow the price to be set lower. V4.1 compresses the persisted KV to 1/8 the size of V4, directly enabling this price reduction. Four days later, all V4-Pro requests were automatically routed to V4.1-Flash and billed at the V4.1-Flash rate.

Compared with Claude Opus 5 and GPT-5.6 Sol, V4.1-Flash’s output price is 1/20 to 1/25 of theirs, and its cache hit price is 1/80 to 1/160. Moreover, DeepSeek retains prefixes on SSD for over 72 hours, while Claude and OpenAI’s cache defaults range from 5 minutes to 1 hour. For agent tasks that run for several days, these two differences compound and have a massive impact on cost.

With So Much Compression, Why Does Performance Increase Instead of Decrease?

First, let’s look at the comparisons in the report: V4.1-Flash-Base uses only 1/3 of V4-Pro’s total parameters and 1/4 of its active parameters, yet matches V4-Pro-Base on world knowledge, reasoning, and coding. After post-training, DeepSWE v1.1 scores 74.2, on par with Claude Opus 5 (74.0) and GPT-5.6 Sol (73.0).

KV size was compressed by 4× — why didn’t capability drop? The report doesn’t answer this directly, but by piecing together the design details, we can see the reasons:

  • What is compressed is redundancy, not the information itself. Cross-layer reuse is possible because KV representations in adjacent layers are highly similar. The Reindex mode still preserves the freedom to “select different 512 entries per layer”; only the KV values themselves are shared.

  • Every approximation was seen during training. FP4 relies on quantization-aware training; the hierarchical indexer uses the same candidate pool during both training and inference; and bounded replay is simulated during post-training.

  • Capacity was moved from KV to weights. V4.1 has 552B backbone parameters and 196B Engram conditional memory parameters — significantly larger than V4-Flash’s 284B. Storage pressure has shifted from “how much KV to store per token” to “how much the model itself can remember,” and the latter does not grow with context length.

  • Only the global branch was cut; the local branch was left untouched. All compression applies to the global branch. Each layer’s SWA KV is still computed independently and remains in FP8.

Of course, gaps still remain. On Terminal-Bench 3.0, V4.1-Flash scores 30.0 while Opus 5 scores 43.3; on HLE, it scores 36.8 versus 56.3. The official report itself acknowledges that there is still a gap compared with giant-parameter models on scientific agent tasks that require expert-level domain knowledge.

If You Are Deploying Models

Among those reading this, some are surely struggling with VRAM. Here’s a four-point summary of the above:

  • When choosing a model, look at four numbers: number of KV heads, ratio of local to global layers, whether latent compression is used, and whether there are recurrent layers.

  • When deploying existing models, first enable FP8 KV, then lock the prompt template to ensure prefix cache hits. These two steps lose no tokens. Leave eviction policy decisions for last, and only finalize them after testing against real workloads.

  • When VRAM usage appears unchanged, check how many tokens the KV pool can hold, not the total shown by nvidia-smi. The pool size is fixed — the space saved represents real extra capacity.

  • If you encounter latency bottlenecks, try measuring how many bytes the attention operation reads. Sparse reads can make each step significantly faster.