← All posts

AI paper reviews › Language models

DeepSeek-V4.1-Flash paper explained, shrinking the KV cache

How DeepSeek-V4.1-Flash shrinks its KV cache with cross-layer sharing, an FP4 cache, and SWA Bounded Replay, plus what it reports and where it stops.

If you’ve given a coding agent a long task, you’ve probably watched file contents and tool results fill its context surprisingly fast. The model stacks up a key and a value in its KV cache for every token it reads, so that store keeps growing as the session goes on. In September 2026, DeepSeek released a technical report about exactly that, asking how small the cache can get.

The report is “DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression,” posted to arXiv as v1 by DeepSeek-AI on September 17, 2026 (arXiv 2609.19969). In short, a 552B mixture-of-experts (MoE) model cuts the global KV cache it always keeps in GPU memory (HBM) to 890 bytes per token, roughly a quarter of DeepSeek-V4-Flash’s at the same length. Its persistent KV cache on SSD or host memory shrinks to roughly an eighth. Three changes get it there: CSA2, which lets layers share one cache; a 4-bit (FP4) cache; and SWA Bounded Replay, which recomputes a little instead of storing. The authors also report that it scores better than V4-Flash.

It drew attention fast. As of November 2, 2026, it had 214 upvotes on Hugging Face Daily Papers and 158 citations on Semantic Scholar.

Why long agent sessions run into the cache

A transformer leaves a key and a value for every token, in every layer, so the KV cache grows in step with the token count. Even Qwen2.5-0.5B, which I use in the experiments below, takes 12,288 bytes per token in bfloat16, so one million tokens would come to about 12 GB.

According to the report, agents make workloads input-heavy, because each tool call appends a little text to a long context, and when the cache misses, the whole prompt has to be prefilled again. Storage pressure shows up in two places, too. The KV of global attention, which looks across the whole context, is made of main KV and an indexer K that picks which entries to read, and it grows with length, bounded by HBM capacity. The KV of sliding-window attention (SWA), which only looks at recent tokens, never grows past its window. And the persistent KV cache, saved so that a later request starting with the same text can skip the work, takes up SSD, host memory, and transfer bandwidth.

A design that runs half its layers on the prompt

DeepSeek-V4.1-Flash is a 40-layer MoE model that reads images and text and handles up to one million tokens of context, with the first 20 layers forming a causal encoder and the last 20 a decoder. The whole architecture is drawn in Figure 3 of the paper. Pre-training used 45T tokens of text and images. Post-training follows supervised fine-tuning, reinforcement learning, and on-policy distillation as they are, and the report says what changed was the data and the environments.

This Causal Encoder-Decoder (CED) is inspired by YOCO, where the upper layers share a KV cache built by the lower ones. Each decoder layer projects its global KV from the hidden state of the last encoder layer, with weights of its own. So most of the prompt only passes through the 20 encoder layers, and the decoder handles just the last 128 tokens to build the SWA KV it needs to start generating. For a 100,000-token prompt, by my count, that comes to 50.1% of the layer passes a full model would make. The report explains that this design lets the model activate only 8B parameters per token during prefill, and 16B during decode.

How the global KV gets down to 890 bytes

The report treats KV cache cost as the product of three things: the size of one entry, the number of entries along the sequence, and the number of layers that keep their own copy. DeepSeek-V2 reported a KV cache 93.3% smaller than DeepSeek 67B’s by using MLA to compress keys and values together into a small latent vector, and the CSA of DeepSeek-V4 folded every m tokens into one entry. V4.1 goes after the third, the number of layers.

CSA2 fixes a mode for each layer. A Full layer computes and stores its own main KV and indexer K. A Reindex layer borrows those from an earlier layer and only re-picks which entries to read with its own query, and a Reuse layer borrows the picked entries too. Figure 4 of the paper shows what each mode computes itself and what it borrows. The encoder’s 18 CSA2 layers form three groups of one Full and five Reuse layers, at compression rate 2. The decoder’s 20 layers, at rate 1, form five groups of four, and only the first group starts with a Full layer. So of the 38 CSA2 layers, only 4 store main KV.

Precision went down as well. Where V4 kept main KV in FP8, V4.1 stores it in FP4, with one E4M3 scale for every 16 E2M1 values, and learns with the quantization in place during post-training (quantization-aware training, QAT). The SWA KV, which is sensitive to quantization, stays in FP8.

You can rebuild the 890 from the public config.json. By my count, one entry is a 512-value FP4 latent (256 bytes) with 32 bytes of scales. Next to it sits a 128-value indexer K in MXFP4 (64 bytes) with 4 bytes of scales, since MXFP4 puts one 8-bit scale on every 32 values. That’s 356 bytes. The three encoder Full layers leave an entry every 2 tokens and the decoder Full layer one per token, so each token leaves 2.5 entries, and 2.5 × 356 = 890. The breakdown is my own reconstruction and isn’t in the report, yet the number matches exactly. At one million tokens that’s about 890 MB, about a fourteenth of Qwen2.5-0.5B’s, with the SWA KV, which stops growing at the window size, on top.

Shrinking a real KV cache with FP4

Let’s see what 4 bits do to a cache, using the real cache of Qwen2.5-0.5B. This isn’t a reproduction of the paper. It’s a small example that borrows only the number format to show the idea. It reads the first 1,024 tokens of the pdb module’s docstring and rounds the cache for the first 768.

import pdb, torch
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.set_grad_enabled(False)
name = "Qwen/Qwen2.5-0.5B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32, attn_implementation="eager")
ids = tok(pdb.__doc__, return_tensors="pt").input_ids[:, :1024]  # a long docstring from Python 3.13
GRID = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6])  # every magnitude FP4 (E2M1) can hold

def fp4(x):  # 16 numbers share one FP8 (E4M3) scale that maps the largest one to 6
    b = x.reshape(-1, 16)
    s = (b.abs().amax(1, keepdim=True) / 6).to(torch.float8_e4m3fn).float().clamp(min=1e-12)
    y = (b / s).clamp(-6, 6)
    return (GRID[(y.abs().unsqueeze(-1) - GRID).abs().argmin(-1)] * y.sign() * s).reshape(x.shape)

cache = model(ids[:, :768]).past_key_values
K = torch.stack([layer.keys for layer in cache.layers])  # 24 layers x 2 heads x 768 tokens x 64
V = torch.stack([layer.values for layer in cache.layers])
print(f"relative error: keys {(fp4(K) - K).norm() / K.norm():.3f}, values {(fp4(V) - V).norm() / V.norm():.3f}")

def perplexity(k, v):  # on the rest of the text, read through k and v
    for i, layer in enumerate(cache.layers):
        layer.keys, layer.values = k[i], v[i]
    logits = model(ids[:, 768:], past_key_values=cache).logits[0, :-1]
    return torch.nn.functional.cross_entropy(logits, ids[0, 769:]).exp().item()
print(f"perplexity: original {perplexity(K, V):.2f}, fp4 {perplexity(fp4(K), fp4(V)):.2f}")
relative error: keys 0.076, values 0.093
perplexity: original 8.36, fp4 9.44

With the scales, each value costs 4.5 bits, so the cache is 3.56 times smaller than in FP16. The relative error was 7.6% for keys and 9.3% for values, and perplexity on the rest of the text, a measure of how unsure the model is about each next token, rose from 8.36 to 9.44. That’s the price for a model that never trained with FP4. DeepSeek-V4.1-Flash trains with the quantization in place, and the report only says that what’s left is marginal.

Do neighboring layers’ caches look alike?

If layers share caches, you start to wonder whether neighboring layers’ caches look alike. This one, too, is only an example of the idea.

cos = torch.nn.functional.cosine_similarity
out = model(ids, output_attentions=True, output_hidden_states=True)
keys = [layer.keys[0].transpose(0, 1).flatten(1) for layer in out.past_key_values.layers]
inputs = [h[0] for h in out.hidden_states[:24]]  # what each layer reads in

def top32(i):  # the 32 positions each query from 512 on attends to most
    return out.attentions[i][0].mean(0)[512:].topk(32, dim=-1).indices

def shared(i):  # fraction of layer i's top 32 that layer i + 1 also picked
    return (top32(i).unsqueeze(-1) == top32(i + 1).unsqueeze(-2)).any(-1).float().mean().item()

pairs = range(23)
print(f"keys, cosine:         {sum(cos(keys[i], keys[i + 1]).mean() for i in pairs) / 23:.2f}")
print(f"layer inputs, cosine: {sum(cos(inputs[i], inputs[i + 1]).mean() for i in pairs) / 23:.2f}")
print(f"top-32 shared:        {sum(shared(i) for i in pairs) / 23:.2f}")
print(f"shared by chance:     {(32 / torch.arange(513, 1025)).mean():.2f}")
keys, cosine:         -0.01
layer inputs, cosine: 0.88
top-32 shared:        0.63
shared by chance:     0.04

Since each layer projects with its own weights, the key vectors hardly resemble each other. The inputs those keys are made from are close, though, at a cosine of 0.88, and the 32 positions neighboring layers attend to most overlap by 63% (4% by chance). So handing a trained model its neighbor’s cache probably wouldn’t work well. That’s likely why CSA2 sets its modes before training, and why CED projects KV from one hidden state with different weights per layer.

Taking SWA KV out of the persistent cache, for an eighth

According to the report, SWA KV took nearly half of the persistent cache in the V4 deployment, yet it was reused only for minutes inside a session, and rebuilding it exactly means replaying L × n_win tokens, which for the 40 layers and 128-token window of V4.1-Flash is 5,120 tokens. V4.1 keeps SWA KV for only minutes, in a pool made from 10% of host DRAM, and on a miss it recomputes just the last 128 tokens of the cached prefix and uses the approximate state. If you draw V4-Flash’s persistent cache as roughly 4 cells of global KV and 4 of SWA KV, V4.1 removes the 4 SWA cells and shrinks the global part to 1, leaving 1 cell out of 8. The rebuilt state isn’t mathematically identical, though, so the KV that follows depends on where the cache hit, and the authors report that this barely affects quality.

DeepSeek-V4-Flash's persistent KV cache drawn as 4 cells of global KV and 4 of SWA KV, and DeepSeek-V4.1-Flash's as the 1 cell of global KV that remains
Our own drawing of the 8-cell count in the paragraph above, from two numbers in Section 3.2.1. In the V4 deployment, SWA KV took almost half of the persistent cache, and V4.1 shrank the remaining global KV to 1/4. The cell counts are approximate. The paper's own chart of global KV size per token across DeepSeek generations is Figure 1(b). Source: DeepSeek-AI (2026), Section 3.2.1.

What the report shows

The top four rows of the table compare instruct models at Max reasoning effort (Table 3), with the code agents run in the Minimal mode of DeepSeek Harness with a 1M-token context (mini-SWE for DeepSWE). The bottom two compare base models measured under the same setting in DeepSeek’s internal evaluation framework (Table 1).

Benchmark DeepSeek-V4-Flash DeepSeek-V4.1-Flash
Terminal-Bench 2.1, Pass@1 82.7 90.6
Terminal-Bench 4.0, Pass@1 7.0 31.2
DeepSWE v1.1, Resolved 54.4 74.2
GPQA Diamond, Pass@1 89.9 90.9
LongBench-V2, base model 44.7 45.2
MGSM, base model 85.7 80.2

Among these rows, agent coding improved the most, but the 31.2 on Terminal-Bench 4.0 falls far short of the 51.8 that Opus-5 scored in the same table. The long-context benchmark barely moves, and MGSM drops by 5.5 points. Even the same checkpoint scores anywhere from 65.5 to 74.2 on DeepSWE v1.1, depending on the scaffold (Table 4).

Bar chart of four agentic coding benchmarks. In the order V4-Flash, V4.1-Flash, Opus-5: Terminal-Bench 2.1 82.7, 90.6, 89.1; Terminal-Bench 3.0 7.6, 30.0, 43.3; Terminal-Bench 4.0 7.0, 31.2, 51.8; DeepSWE v1.1 54.4, 74.2, 74.0
Our own chart of four agentic coding benchmarks from Table 3, with scores for V4-Flash (gray), V4.1-Flash (orange), and Opus-5 (dark green). On these four, Opus-5 scores highest of the models in the table other than V4.1-Flash. V4.1-Flash is close to Opus-5 on Terminal-Bench 2.1 and DeepSWE v1.1 but falls well behind on 3.0 and 4.0. The paper's own chart, which compares it with four models from other companies, is Figure 1(a). Source: DeepSeek-AI (2026), Table 3.

How far to trust it

This is a technical report posted on arXiv, and I found no sign of peer review or a conference or journal listing on its arXiv page. Nor is there a table or figure that shows the accuracy cost of each compression step separately. CED is said to perform comparably to the baseline, FP4 to degrade only marginally, and bounded replay to have a negligible impact, all in words. Section 5.3.1 describes only how DeepSeek-V4.1-Flash was evaluated, and it doesn’t say how the other models’ numbers in Table 3 were obtained.

In Section 6, the authors themselves write that selection errors in CSA2 or the approximate states from SWA Bounded Replay may still degrade the model in cases they haven’t tested. Some of the gains also lean on the deployment environment. The 1/8 assumes DeepSeek’s serving setup with a persistent prefix cache on SSD, and the indexer’s MXFP4 was chosen to support many hardware platforms over formats that were more accurate in their experiments.

Weights, license, and where to start reading

The weights are on Hugging Face, and the model card says both the repository and the weights are under the MIT License. The files come to about 510 GB, and the inference folder holds reference inference code. I only read these files and didn’t run the model. In the report, you might start with Sections 2.2, 2.3.1, 2.4.4, and 3.2, which cover the cache design. I ran the two examples on November 2, 2026 with Python 3.13.12, PyTorch 2.15.0, and Transformers 5.22.1.

AI tools helped with the research for this post.