# DeepSeek-V4.1-Flash: Getting the Global KV Cache Down to 890 Bytes per Token

> DeepSeek-V4.1-Flash cuts the global KV cache to 890 bytes per token, about 1/4 of V4-Flash and 1/437 of DeepSeek-V1, with a causal encoder-decoder, cross-layer sharing in CSA2 and an FP4 main KV. This post explains the paper and rebuilds its numbers from the public configs.

- URL: https://dmxsf.com/en/blog/deepseek-v41-flash-pushing-the-limits-of-kv-cache-compression/
- [DMXSF](https://dmxsf.com/en/about/)
- Published: 2026-09-27
- Updated: 2026-11-13
- Paper notes
- Paper: [DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression](https://arxiv.org/abs/2609.19969) (DeepSeek-AI · arXiv, 2026)

The paper "DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression" (DeepSeek-AI, September 2026, called the V4.1 paper below) describes a multimodal mixture-of-experts model with 552B backbone parameters and a one-million-token context that activates 8B parameters per token during prefill and 16B during decode. The paper is about one thing. Long-horizon agents make workloads input-heavy, so the bottleneck moves from compute to storing and moving KV caches, and the paper compresses along all three multiplicative dimensions of cache size (entry size, sequence, layers) at once. The result is a global KV cache of 890 bytes per token, about 1/4 of the previous DeepSeek-V4-Flash; moving the sliding-window KV out of the persistent cache then brings the persistent cache to about 1/8 of V4-Flash. The post-training part states plainly that it contains "no algorithmic innovation", and the paper credits nearly all gains to data and environments.

The paper appeared on arXiv on 17 September 2026 (v1, which this post follows). You cannot train this model on a laptop, so this post **checks** rather than reproduces: it uses the public configs and parameter tallies on Hugging Face to recompute the paper's most prominent numbers. These hold up: the four byte counts of Figure 1(b) (389,120, 48,068, 3,514 and 890) are all recovered, along with what each design choice buys (a counterfactual), the per-layer CSA2 modes, the indexer's scoring work, the memory traffic of Single-Pass mHC, and the 552B and 196B parameter counts. A toy gradient then tests the paper's Sinkhorn-balanced update and the Appendix C derivation. One limitation first, and it is the paper's own: it gives no ablation for any single design choice. "Negligible" and "marginal" are qualitative statements, and the only quantitative comparison is the whole model against V4-Flash and V4-Pro, which differ in size, data and post-training.

## Why this paper is worth reading

- **It splits "how big is the KV cache" into three multiplicative factors.** Entry size, sequence and layers each have established remedies (GQA and MLA, compressed attention, cross-layer sharing); the contribution is using all three together and keeping the books straight on each. That decomposition is worth more than any single number.
- **The numbers can be checked.** The four numbers of Figure 1(b) can be rebuilt one by one from public `config.json` files plus a byte layout, which is rare for an efficiency paper.
- **The engineering detail is real.** How the persistent cache is tiered (SSD and host memory), how a prefix miss is recomputed, and how a Reuse layer is fused into 15 kernels in prefill and 11 in decode are all described, and these are the problems anyone serving a long-context model actually hits.
- **The post-training part contrasts with V3.2.** [V3.2](https://dmxsf.com/en/blog/deepseek-v32-pushing-the-frontier-of-open-large-language-models/) was about four tricks for stabilizing scaled-up RL; the V4.1 paper says the algorithm stayed the same and the gains are in data and environments. Reading the two side by side shows where the emphasis moved in a year.
- **It connects to the rest of this site.** Sparse attention and the lightning indexer are explained in the [V3.2 post](https://dmxsf.com/en/blog/deepseek-v32-pushing-the-frontier-of-open-large-language-models/), MLA and DeepSeekMoE in the [V2 post](https://dmxsf.com/en/blog/deepseek-v2-strong-economical-efficient-mixture-of-experts/), mHC in the [mHC post](https://dmxsf.com/en/blog/mhc-manifold-constrained-hyper-connections/); the concept pages are [KV cache](https://dmxsf.com/en/wiki/inference/kv-cache/), [efficient attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/) and [long context](https://dmxsf.com/en/wiki/architecture/long-context/).

## Background: input-heavy workloads and three dimensions of the KV cache

A long-horizon agent re-feeds an ever-growing context on every turn: each tool call causes another prefill. When the prefix cache hits, only the new part is processed; when it misses, the whole prefix is recomputed. The paper separates two kinds of cache: the runtime cache that lives in GPU memory (HBM), and the "persistent KV cache" kept on SSD and in host memory for prefix reuse. Each V4 layer has two branches: a global branch that spans the whole context and keeps global KV (main KV plus indexer K), and a local sliding-window attention (SWA) branch whose SWA KV has a fixed size. Once the context is long enough, global KV, which grows linearly with length, dominates, so it is the main target for compression.

The paper sorts compression methods into three dimensions that multiply:

| Dimension | What it does | Examples |
| --- | --- | --- |
| Entry size | Store fewer heads, or let all heads share one small latent | GQA, MLA |
| Sequence | Compress every $m$ tokens into one entry | CSA and HCA in V4 |
| Layers | Let some layers reuse the caches and selections of others, or replace layers with cheaper ones | Cross-layer KV sharing, IndexCache, YOIO, HySparse |

The paper's assessment is that reusing indices alone saves no main-KV storage, sharing routing across the whole network limits quality, hybrids still keep full-attention layers, and no single method covers all three dimensions. CSA2 uses all three and decouples "sharing the cache" from "reusing the selection".

The figure below shows the global KV bytes per token of four DeepSeek generations. I computed the numbers from the public configs with the byte layout described in the "Hands-on check" section; they match Figure 1(b) of the paper entry by entry.

*Figure: Figure 1: global KV cache bytes per token for four DeepSeek generations. The byte counts are computed from the public config.json files and the byte layout described in the text, and match the paper's Figure 1(b) entry by entry; the right-hand labels give the global KV of one 1M-token (2^20) sequence. Sliding-window KV in each layer is not included.*

Two things deserve a closer look. First, V4.1 actually compresses the sequence much less than V4. In the configs, V4-Flash has 43 layers: 2 sliding-window-only layers, 21 layers with compression ratio 4 and 20 with ratio 128 (the byte accounting fits ratio-4 layers as CSA layers with an indexer and ratio-128 layers as HCA layers), while V4.1 has 2 sliding-window-only layers, 18 layers with ratio 2 and 20 layers with ratio 1, meaning no compression. It keeps finer-grained context and recovers the cache size through layer sharing and FP4. Second, the 890 bytes exclude the sliding-window KV and the per-layer queries; what happens to the sliding-window KV is the subject of the SWA Bounded Replay section below.

## Overall structure

The model is a 40-layer causal Transformer: the first 20 layers form a causal encoder and the last 20 a decoder. Every layer has both global and sliding-window attention except the first two, which have sliding-window attention only. Images pass through a vision encoder and an MLP projector into visual embeddings that are processed together with text embeddings, and multimodal data is part of pre-training from the start. The table shows the differences from V4-Flash that can be read directly from the configs and the paper (the config part comes from the two `config.json` files, and section 1 of the check script below prints them verbatim):

| Item | V4-Flash | V4.1-Flash |
| --- | --- | --- |
| Layers and hidden size | 43 layers, 4096 | 40 layers, 5120 |
| Routed experts (active, expert width) | 256 (6, 2048) | 384 (6, 2304) |
| Indexer | 64 heads x 128 dims, Top-512 | 32 heads x 128 dims, Top-512 |
| Sequence compression ratios | 4 (21 layers) and 128 (20 layers) | 2 (18 layers) and 1 (20 layers) |
| Parameters (paper) | 284B backbone, 13B active | 552B backbone, 8B active in prefill and 16B in decode, plus 196B of Engram |

Other settings come from section 4.2.1 of the paper: 64 query heads, head dimension 512, query compression dimension 1280, a sliding window of 128; each layer has 1 shared expert plus routed experts, with a SwiGLU clamp of 10; the mHC expansion factor is 4. The vision encoder, DeepSeek-ViT, has 32 layers, hidden size 1024, 16 heads and patch size 14; a 3x3 pixel-unshuffle cuts the number of visual tokens by a factor of nine, supporting inputs up to roughly 1344 x 1344 pixels. The paper drops the MTP module and uses DSpark for speculative decoding instead.

## The Causal Encoder-Decoder (CED)

In agent workflows tool calls keep creating new prefill requests, and when the cache misses, prefill dominates the cost. CED is inspired by YOCO, where the upper half of the layers shares the KV generated by the lower half. The paper says it removes nearly half of the prefill computation while keeping performance comparable to the baseline.

For global attention, CED treats the bottom $L/2$ layers as a causal encoder. The decoder layers ($l>L/2$) do not derive their KV from their own hidden states $H^l$; they project it from the hidden state of the encoder's last layer, $H^{L/2}$, with per-layer weights:

$$
C^l = H^{L/2}\,W^{KV}_l,\qquad Z^l = H^{L/2}\,W^{Z}_l,\qquad l>L/2
$$

$C$ holds the KV entries and $Z$ the corresponding compression weights. Prefill therefore only has to run the first half of the layers to obtain the global KV of the upper layers, and its complexity drops from $O(NL)$ to $O(NL/2+n_{\mathrm{win}}L/2)$, roughly $O(NL/2)$ when the sequence length $N$ is much larger than the window $n_{\mathrm{win}}$. Sliding-window attention is still computed layer by layer (the local KV comes from each layer's own hidden state, which gives it more depth), and that causes a problem: the decoder's sliding-window KV has to be produced by replaying an extra $n_{\mathrm{win}}\times L/2$ tokens, which is what Bounded Replay below is for.

During decoding every token passes through all 40 layers, which is why the active parameters double: 8B in prefill, 16B in decode. The check below finds that expert parameters alone come to about 4.95B in prefill and 9.91B in decode; the paper's 8B and 16B are larger, and the difference should be non-expert parts such as attention and embeddings, which I did not itemize.

## CSA2: share the cache, reuse the selection

CSA2 (Compressed Sparse Attention 2) inherits CSA from V4: a light indexer scores main-KV entries using an indexer Q and an indexer K, each query selects its Top-K entries, and attention runs over those plus the layer's sliding-window KV; compression ratio 1 (no compression) is a special case. The paper simplifies CSA in two ways. The compressor no longer lets neighbouring entries overlap (in CSA, every entry at ratio $m$ is built from $2m$ original entries, overlapping with its neighbours) and drops the absolute positional embedding used during compression; the indexer K is projected directly from the main KV instead of coming from a separate compression path. Both changes make the implementation simpler and training faster.

Every CSA2 layer is statically assigned one of three modes. In all of them the layer computes its own main query and sliding-window KV, and the modes differ only in the global part:

| Mode | Main KV and indexer K | Indexer Q | Top-K indices |
| --- | --- | --- | --- |
| Full | Computed here (indexer K projected from this layer's main KV) | Computed here | Selected here, scanning every visible position |
| Reindex | Reused from the latest Full layer | Computed here | Selected here, rescoring inside the candidate pool |
| Reuse | Reused from the latest Full layer | Not computed | Reused from the latest Full or Reindex layer |

Sharing main KV and indexer K saves cache storage, reusing Top-K saves indexing work, and Reindex sits in between: the cache stays shared but the selection may change from layer to layer. The paper's layer plan is as follows. The first 2 layers use sliding-window attention only. The remaining 18 encoder layers use ratio 2 in three groups of 6, each with 1 Full layer and 5 Reuse layers. The 20 decoder layers use ratio 1 in five groups of 4: the first group has 1 Full and 3 Reuse layers, and each of the other four has 1 Reindex and 3 Reuse layers. The `compress_ratios`, `kv_source_layer_ids` and `index_source_layer_ids` arrays in the config give exactly this plan (check script, section 3):

*Figure: Figure 2: the 40-layer CSA2 plan of DeepSeek-V4.1-Flash, read from compress_ratios, kv_source_layer_ids, index_source_layer_ids and candidate_source_layer_id in config.json. S: sliding window only; F: Full, computes its own main KV, indexer Q and indexer K and selects Top-512; X: Reindex, reuses main KV and indexer K, computes its own indexer Q and reselects inside the candidate pool; R: Reuse, reuses main KV and the Top-512 indices. Every layer has its own main Q and sliding-window KV.*

Under this plan, global KV is generated by only 4 of the 40 layers (layers 2, 8, 14 and 20), so a token stores 2.5 entries on average, against 29 if every layer kept its own.

## The Hierarchical Sparse Indexer

Reusing indices cuts the number of indexer calls, but the remaining indexers still score the whole causally visible context, which stays a bottleneck for very long contexts. The paper observes that in the decoder, information from shallower indexers can restrict the candidates that deeper indexers consider, with no extra state.

The first Full layer of the decoder (layer 20) scores every visible position and selects its own Top-512. It also selects blocks: each block of 8 positions gets the highest indexer score among its positions, the 2,048 best blocks are kept, and the positions they cover form a candidate pool of $2048\times 8=16384$ positions. Later Reindex layers (24, 28, 32 and 36) score only the positions in this pool and select their own Top-512 inside it. For a fixed pool size the work of each later indexer no longer depends on the context length. The first Full layer still has to scan the whole range, so the linear term is not eliminated, only confined to one layer. The mechanism is used only in the decoder and is training-aware: the restriction to the pool is applied identically in training and inference, so deeper indexers are optimized under the search domain they will use, and it is introduced in post-training.

Section 4 of the check below estimates the size of this effect: at one million tokens the four Full layers account for 97.6% of the unweighted indexer FLOPs, and the four Reindex layers together for less than 3%.

## The FP4 main KV cache

V4 already used quantization-aware training (QAT) with FP4 for the indexer's queries and keys, to speed up scoring. V4.1 extends QAT to the main KV. FP4 here saves storage rather than speeding up matrix multiplication: values are dequantized before attention, so a more accurate format can be chosen and no native hardware support is needed. The format is E2M1 with one E4M3 scale per 16 channels, following NVFP4 but without its second-level global scale (the indexer uses the OCP standard MXFP4).

Dropping the global scale is justified by a magnitude bound. The format represents values up to $448\times 6=2688$; after RMSNorm the L2 norm of the 512-channel KV latent is at most about $\sqrt{512}$ (the largest trained RMSNorm weight is around 1), and RoPE preserves the norm, so no channel exceeds about 22.6 in absolute value, and the largest value observed in training is about 10. QAT is introduced in post-training. Quantization happens after RoPE, because quantizing before it gave only a marginal accuracy gain and would add decoding overhead. The sliding-window KV is sensitive to quantization and stays in FP8. In my byte accounting, a main-KV entry shrinks from 584 bytes in V4 (FP8) to 288 bytes, which the paper calls "nearly halving" the footprint.

## SWA Bounded Replay and the persistent cache

The persistent KV cache lives on SSD and in host memory for prefix reuse. In V4, global KV is stored in full and a hit reuses the whole prefix; the sliding-window KV is cached at only two positions (the end of the prompt and the end of the output) to support regeneration and multi-turn sessions, and it took nearly half of the persistent capacity. The paper's judgement is that persisting sliding-window KV is both expensive and ineffective, because it is reused only inside one session within a minutes-long window and is dead once the session ends or the next turn begins, which does not match the long retention and long-tail reuse of the persistent cache. V4's answer was Zero SWA Caching: recompute on a miss. But exact recovery needs a forward pass over $L\times n_{\mathrm{win}}$ tokens ($40\times128=5120$ in V4.1), which the paper says proved too expensive in production.

V4.1 changes two things. The sliding-window KV leaves the persistent cache and goes into a distributed memory pool made of 10% of each machine's host memory, with a time-to-live of only minutes so expired entries are recycled at once; global KV stays in the persistent cache with a guaranteed lifetime of at least 72 hours. A cache miss triggers Bounded Replay. Rebuilding the sliding-window KV of $L$ layers exactly needs $L\times n_{\mathrm{win}}$ replayed tokens; Bounded Replay replays only the most recent $n_{\mathrm{win}}=128$ and truncates the window to the replayed segment (with a replay starting at $s$, a query at position $i$ attends to keys in $[\max(s,\,i-W+1),\,i]$), accepting an approximate state.

- **Encoder replay.** When global KV hits but the sliding-window KV is missing, the last 128 tokens of the cached prefix are processed together with the uncached suffix; the replayed tokens regenerate only the sliding-window KV, and the cached global KV is reused without being recomputed or overwritten. Prefix caching then depends on global KV alone.
- **Decoder replay.** Under CED the decoder's global KV comes from the encoder's last layer, so prefill can stop at the encoder; the only obstacle is the decoder's sliding-window KV. At every prefill the encoder outputs of the last 128 prompt tokens are run through the decoder layers, and the resulting decoder sliding-window KV is used only for decoding, never cached. The paper says this limits the decoder forward pass to 128 tokens and nearly halves total prefill computation.
- **How the accounting works.** The persistent cache shrinks by two factors multiplied together: dropping the sliding-window KV (nearly half) and global KV falling to 1/4 of V4's, which gives about 1/8.

The cost is also in the paper. Replayed states are approximate, so the global KV and sliding-window KV computed for the uncached suffix depend on where the cache hit happens and are not identical across positions. The paper says experimental evidence shows little effect on response quality, and that the same replay is simulated in post-training for "train-aware" adaptation, but the main text gives no numbers.

## Other architectural changes

**Single-Pass mHC.** mHC (see the [mHC post](https://dmxsf.com/en/blog/mhc-manifold-constrained-hyper-connections/)) keeps $n$ residual streams $X_l\in\mathbb R^{n\times d}$, and each block updates them as

$$
X_{l+1}=B_l X_l+C_l\,\mathcal F_l(A_l X_l),\qquad (A_l,B_l,C_l)=\mathcal H(X_l)
$$

$A_l$ mixes the $n$ streams into the block input, $B_l$ and $C_l$ handle the residual update, and all three coefficients are predicted from $X_l$. V4 runs this as three kernels that depend on each other (residual update, coefficient prediction, input mixing), plus the block's pre-norm, for $(4n+4)d$ of activation traffic, twice the ideal lower bound $(2n+2)d$. A two-pass fusion (residual update and coefficient prediction share one traversal) needs $(3n+2)d$, because input mixing must wait for the coefficients and so reads $X_l$ a second time. Single-Pass mHC shifts the mixing coefficient by one block:

$$
X_{l+1}=B_l X_l+C_l\,\mathcal F_l(A_{l-1} X_l),\qquad (A_l,B_l,C_l)=\mathcal H(X_l)
$$

Input mixing no longer depends on the coefficients just computed for the current block, so each tile is read once for both mixing and coefficient prediction, and the deployed Mega-mHC kernel reaches the $(2n+2)d$ bound. Pre-training keeps the original multi-kernel implementation, since the shift only changes which coefficient each block applies. The paper reports a negligible performance loss from the shift.

**Engram.** A conditional-memory module (hashed n-gram lookup tables that separate "memory" from "computation"). 196B parameters are split evenly over two modules at layers 1 and 14 (zero-indexed). Each module uses n-gram orders {2, 3, 4}, 8 hash heads and a total embedding dimension of 2048 per order; each head indexes a table of about 16 million entries, with table sizes chosen as distinct primes, and both the tables and the key/value projections use FP8. The paper removes the short causal convolution of the original design (its gain did not justify the complexity in the inference stack), and at inference the addresses are deterministic, so embeddings can be prefetched from host memory over background RDMA.

**DSpark.** The speculative-decoding module that replaces MTP: three Transformer blocks with a sliding window of 128. One forward pass computes base logits for five draft positions in parallel, and a light Markov head models dependencies among the draft tokens; a confidence head predicts per-position conditional acceptance probabilities, and a scheduler combines them with profiled engine throughput to choose a verification length per request. It is trained in a dedicated stage after pre-training with the backbone frozen, and continues to train alongside the backbone in post-training without sending gradients into it.

**Optimizers.** Muon handles the backbone's linear weights, with head-wise Muon (query and key weights split by head before the update) which the paper says beats vanilla Muon and notes that GLM-5 and Kimi-K3 validated too; norm weights and other non-matrix parameters use AdamW. The huge embedding, prediction-head and Engram matrices do not use Adam, which keeps two state buffers per parameter, and use a "momentum plus Sinkhorn balancing" update instead: after Nesterov momentum the update matrix is normalized alternately along rows and columns in L2 for $K$ steps (the paper uses $K=11$) and multiplied by $\sqrt n$, turning unit row norm into unit row RMS, so that row RMS and column RMS of the update are both approximately 1. Like Muon it needs only one momentum buffer. The check in the next section tests this on a toy gradient.

## Hands-on check: KV bytes, layer plan, indexer cost, parameter ledger and two algorithms

The script below uses only NumPy. It fetches the `config.json` of four models and the parameter tallies of V4.1 and V4-Flash from Hugging Face (network needed) and does eight things: recover the per-token global KV bytes of Figure 1(b); run counterfactuals with the same byte layout (what each design choice buys); read the layer plan from the config; estimate the indexer's scoring work per decoded token; compare the memory traffic of three mHC implementations; check the parameter ledger; test the Appendix C derivation with toy numbers; and test the Sinkhorn-balanced update on a toy gradient.

First, what is the paper's and what is mine. The paper does not list the bytes per cache entry. The byte layout in the script is my assumption: it reproduces all four numbers of Figure 1(b) exactly, which shows the assumptions are self-consistent but not that this is how the paper stores them. The counterfactuals in section 2, the FLOPs estimate in section 4 (unweighted by precision), the toy parameters in section 7 and the toy gradient in section 8 are my constructions, not numbers from the paper.

<details>
<summary>Full code (about 200 lines)</summary>

```python
"""Checking DeepSeek-V4.1-Flash: KV bytes, layer plan, indexer cost"""
import json
import urllib.request
from collections import Counter

import numpy as np

HUB = "https://huggingface.co"

def fetch(url):
    with urllib.request.urlopen(url, timeout=60) as r:
        return json.load(r)

def cfg_of(repo):
    return fetch(f"{HUB}/{repo}/resolve/main/config.json")

v1 = cfg_of("deepseek-ai/deepseek-llm-67b-base")
v32 = cfg_of("deepseek-ai/DeepSeek-V3.2")
v4 = cfg_of("deepseek-ai/DeepSeek-V4-Flash")
t = cfg_of("deepseek-ai/DeepSeek-V4.1-Flash")["text_config"]
L = t["num_hidden_layers"]
ratios = t["compress_ratios"][:L]
kv_src, idx_src = t["kv_source_layer_ids"], t["index_source_layer_ids"]

# Bytes per cache entry (assumptions that reproduce the paper)
BF16 = 2
V32_MAIN = v32["kv_lora_rank"] + 4 * 4 + v32["qk_rope_head_dim"] * BF16
V32_IDX = v32["index_head_dim"] + 4          # FP8 plus one fp32 scale
V4_MAIN = 448 + 64 * BF16 + 8                # FP8 non-RoPE + bf16 RoPE + scales
FP4_MAIN = t["head_dim"] // 2 + t["head_dim"] // 16   # E2M1 + E4M3 / 16
IDX_FP4 = t["index_head_dim"] // 2 + t["index_head_dim"] // 32  # MXFP4

print("== 1. Global KV cache bytes per token (paper Fig. 1b)")
dh = v1["hidden_size"] // v1["num_attention_heads"]
b_v1 = 2 * v1["num_hidden_layers"] * v1["num_key_value_heads"] * dh * BF16
b_v32 = v32["num_hidden_layers"] * (V32_MAIN + V32_IDX)
r4 = v4["compress_ratios"][:v4["num_hidden_layers"]]
b_v4 = sum((V4_MAIN + (IDX_FP4 if r == 4 else 0)) / r for r in r4 if r)
b_v41 = sum((FP4_MAIN + IDX_FP4) / ratios[i] for i in kv_src)
rows = [("DeepSeek-V1 67B", b_v1, 389120), ("DeepSeek-V3.2", b_v32, 48068),
        ("DeepSeek-V4-Flash", b_v4, 3514), ("DeepSeek-V4.1-Flash", b_v41, 890)]
print(f"  {'model':20s}{'computed':>12s}{'paper':>10s}")
for name, b, paper in rows:
    print(f"  {name:20s}{b:>12,.2f}{paper:>10,}")
print(f"  bytes: V3.2 {V32_MAIN}+{V32_IDX} per layer; V4 {V4_MAIN} (+{IDX_FP4}"
      f" on ratio-4 layers); V4.1 {FP4_MAIN}+{IDX_FP4}")
print(f"  V4-Flash {len(r4)} layers, ratios: "
      f"{dict(sorted(Counter(r4).items()))}")
for name, c in (("V4-Flash  ", v4), ("V4.1-Flash", t)):
    print(f"  {name} {c['num_hidden_layers']}L d={c['hidden_size']} experts "
          f"{c['n_routed_experts']} top-{c['num_experts_per_tok']} "
          f"({c['moe_intermediate_size']}) indexer {c['index_n_heads']}x"
          f"{c['index_head_dim']} top-k {c['index_topk']}")
for (na, a, _), (nb, b, _), want in zip(rows, rows[1:], (8.1, 13.7, 3.9)):
    print(f"  {na} / {nb}: {a / b:.3f}x  (paper {want}x)")
print(f"  V1 / V4.1: {b_v1 / b_v41:.1f}x  (paper 437x)")

print("\n== 2. What each V4.1 choice buys (counterfactual, not paper numbers)")
own = sum(1 / r for r in ratios if r)
shared = sum(1 / ratios[i] for i in kv_src)
ladder = [("no sharing, FP8 main KV", own * (V4_MAIN + IDX_FP4)),
          ("no sharing, FP4 main KV", own * (FP4_MAIN + IDX_FP4)),
          ("shared + FP4 (V4.1)", shared * (FP4_MAIN + IDX_FP4))]
print(f"  cache entries per token: {own:g} "
      f"(every layer its own) vs {shared:g} (4 source layers)")
for (name, b), prev in zip(ladder, [None] + [b for _, b in ladder]):
    step = "" if prev is None else f"  ({prev / b:.2f}x)"
    print(f"  {name:26s}{b:>10,.0f} B{step}")
print(f"  total {ladder[0][1] / ladder[-1][1]:.1f}x")
N = 1 << 20
print("  global KV of one 1M-token (2^20) sequence:")
for name, b, _ in rows:
    print(f"    {name:20s}{b * N / 2**30:>9.2f} GiB")

print("\n== 3. Layer plan: the three CSA2 modes read from the config")
plan = ""
for i, r in enumerate(ratios):
    plan += "S" if r == 0 else "F" if i in kv_src else (
        "X" if i in idx_src else "R")
print("  " + plan[:20] + " | " + plan[20:])
print("  S=SWA only, F=Full, X=Reindex, R=Reuse; ratio "
      f"{sorted(set(ratios))}")
print("  " + ", ".join(f"{m}={plan.count(m)}" for m in "SFXR"),
      f"| Full {kv_src}, Reindex {[i for i in idx_src if i not in kv_src]}")

print("\n== 4. Indexer scoring per decoded token (raw FLOPs)")
cand = t["candidate_topk_blocks"] * t["candidate_block_size"]
f32 = 2 * v32["index_n_heads"] * v32["index_head_dim"]
f41 = 2 * t["index_n_heads"] * t["index_head_dim"]

def scored(n):
    return sum(n / ratios[i] if i in kv_src else min(cand, n / ratios[i])
               for i in idx_src)

print(f"  candidate pool {cand:,} positions; FLOPs/pair: "
      f"V3.2 {f32:,}, V4.1 {f41:,}")
print(f"  {'N':>9s}{'V3.2 GFLOP':>13s}{'V4.1 GFLOP':>13s}{'ratio':>8s}"
      f"{'Full share':>12s}")
for n in (4096, 65536, 131072, N):
    g32 = v32["num_hidden_layers"] * n * f32 / 1e9
    g41 = scored(n) * f41 / 1e9
    full = sum(n / ratios[i] for i in kv_src) / scored(n)
    print(f"  {n:>9,}{g32:>13.3f}{g41:>13.3f}{g32 / g41:>7.1f}x{full:>12.1%}")

print("\n== 5. Single-Pass mHC activation traffic (units of d, n=hc_mult)")
n = t["hc_mult"]
for name, v in (("multi-pass (3 kernels+norm)", 4 * n + 4),
                ("two-pass fused", 3 * n + 2),
                ("single-pass / lower bound", 2 * n + 2)):
    print(f"  {name:27s}{v:>3d} d = {v * t['hidden_size']:>7,} values"
          f" per token per block")
print(f"  n={n}: single-pass vs multi-pass "
      f"{(4 * n + 4) / (2 * n + 2):.1f}x")

print("\n== 6. Parameter ledger (Hub dtype tallies + config)")
tally = fetch(f"{HUB}/api/models/deepseek-ai/DeepSeek-V4.1-Flash")
tally = tally["safetensors"]["parameters"]
d, mi = t["hidden_size"], t["moe_intermediate_size"]
e = 3 * d * mi
routed = L * t["n_routed_experts"] * e
dspark = 3 * t["dspark_n_routed_experts"] * e
print(f"  one expert (three SwiGLU matrices) "
      f"3 x {d} x {mi} = {e:,}")
print(f"  I8 tally {tally['I8']:,}; {L} x {t['n_routed_experts']} "
      f"+ 3 x {t['dspark_n_routed_experts']} experts = {routed + dspark:,}")
engram = sum(t["engram_num_embeddings"]) * t["engram_head_dim"]
print(f"  Engram: {sum(t['engram_num_embeddings']):,} rows x "
      f"{t['engram_head_dim']} = {engram:,} (paper: 196B)")
print(f"  F8 tally {tally['F8_E4M3']:,} - Engram = "
      f"{tally['F8_E4M3'] - engram:,}")
total = sum(tally.values())
back = total - engram - dspark
print(f"  total {total:,}")
print(f"  - Engram - DSpark experts = {back:,} ({back / 1e9:.1f}B,"
      f" paper 552B)")
act = (1 + t["num_experts_per_tok"]) * e
print(f"  activated expert parameters: "
      f"{L * act / 1e9:.2f}B decode, {L // 2 * act / 1e9:.2f}B "
      f"prefill (paper 16B / 8B)")

print("\n== 7. Why the effort penalty decays exponentially (App. C, toy)")
s_, aL, k0, b0, tau, Ln = 4000.0, 0.75, 0.5, 25.0, 25.0, 4000.0
ell = np.arange(0, 40001, dtype=float)
p = 0.2 + (aL / Ln) * s_ * (1 - np.exp(-ell / s_))     # p'(l) = a exp(-l/s)
print(f"  setup: s={s_:g}, a*L={aL}, k0={k0}, b_min={b0:g}, tau={tau:g}")
print(f"  L_norm={Ln:g}, p(0)=0.2, p(inf)={0.2 + aL * s_ / Ln:.2f}")
print(f"  {'b':>4s}{'k(b)':>8s}{'closed form':>13s}{'grid':>8s}"
      f"{'cap 0.3':>9s}{'cap 0.8':>9s}")
grid = []
for b in (25, 50, 75, 100):
    k = k0 * np.exp(-(b - b0) / tau)
    closed = s_ * (np.log(aL / k0) + (b - b0) / tau)
    out = [int(np.argmax(p - k * ell / Ln))]
    out += [int(np.argmax(p - np.minimum(c, k * ell / Ln))) for c in (0.3, 0.8)]
    grid.append(out[0])
    print(f"  {b:>4d}{k:>8.4f}{closed:>13,.0f}{out[0]:>8,}{out[1]:>9,}"
          f"{out[2]:>9,}")
slope = np.polyfit([25, 50, 75, 100], grid, 1)[0]
print(f"  slope of the grid optimum {slope:.1f} "
      f"tokens per unit b; s/tau = {s_ / tau:.1f}")

print("\n== 8. Sinkhorn-balanced update (Algorithm 1): toy gradient")
rng = np.random.default_rng(0)
m_rows, n_cols = 4000, 64
seen = rng.random(m_rows) < 0.2            # tokens seen in this batch
G = rng.normal(size=(m_rows, n_cols))
G *= (np.exp(rng.normal(0, 1.5, m_rows)) * seen)[:, None]   # rows: heavy tail
G *= np.exp(rng.normal(0, 0.7, n_cols))[None, :]            # columns: unequal
beta, tau_s, eps = 0.95, 1e-3, 1e-20
G_hat = beta * ((1 - beta) * G) + (1 - beta) * G   # Nesterov, momentum from 0

def balanced(g, K):
    rho = np.linalg.norm(g, axis=1)
    u = np.where((rho <= tau_s * rho.mean())[:, None], 0.0, g)
    for k in range(1, K + 1):
        u /= np.linalg.norm(u, axis=1 if k % 2 else 0, keepdims=True) + eps
    return np.sqrt(g.shape[1]) * u

def spread(d):
    live = np.abs(d).sum(1) > 0
    r = np.sqrt((d[live] ** 2).mean(1))
    c = np.sqrt((d[live] ** 2).mean(0))
    return live.sum(), r.min(), r.max(), c.min(), c.max()

print(f"  {'':16s}{'rows':>5s}{'row RMS (min .. max)':>26s}"
      f"{'column RMS (min .. max)':>29s}")
for name, d in (("momentum", G_hat), ("K = 1", balanced(G_hat, 1)),
                ("K = 3", balanced(G_hat, 3)),
                ("K = 11 (paper)", balanced(G_hat, 11))):
    nl, r0, r1, c0, c1 = spread(d)
    print(f"  {name:16s}{nl:>5d}{r0:>13.4g} ..{r1:>9.4g}"
          f"{c0:>15.4g} ..{c1:>9.4g}")
print(f"  "
      f"Engram has {engram:,} parameters; one FP32 state (assumed) = "
      f"{engram * 4 / 1e9:,.0f} GB")
```

</details>

Output:

```text
== 1. Global KV cache bytes per token (paper Fig. 1b)
  model                   computed     paper
  DeepSeek-V1 67B       389,120.00   389,120
  DeepSeek-V3.2          48,068.00    48,068
  DeepSeek-V4-Flash       3,514.25     3,514
  DeepSeek-V4.1-Flash       890.00       890
  bytes: V3.2 656+132 per layer; V4 584 (+68 on ratio-4 layers); V4.1 288+68
  V4-Flash 43 layers, ratios: {0: 2, 4: 21, 128: 20}
  V4-Flash   43L d=4096 experts 256 top-6 (2048) indexer 64x128 top-k 512
  V4.1-Flash 40L d=5120 experts 384 top-6 (2304) indexer 32x128 top-k 512
  DeepSeek-V1 67B / DeepSeek-V3.2: 8.095x  (paper 8.1x)
  DeepSeek-V3.2 / DeepSeek-V4-Flash: 13.678x  (paper 13.7x)
  DeepSeek-V4-Flash / DeepSeek-V4.1-Flash: 3.949x  (paper 3.9x)
  V1 / V4.1: 437.2x  (paper 437x)

== 2. What each V4.1 choice buys (counterfactual, not paper numbers)
  cache entries per token: 29 (every layer its own) vs 2.5 (4 source layers)
  no sharing, FP8 main KV       18,908 B
  no sharing, FP4 main KV       10,324 B  (1.83x)
  shared + FP4 (V4.1)              890 B  (11.60x)
  total 21.2x
  global KV of one 1M-token (2^20) sequence:
    DeepSeek-V1 67B        380.00 GiB
    DeepSeek-V3.2           46.94 GiB
    DeepSeek-V4-Flash        3.43 GiB
    DeepSeek-V4.1-Flash      0.87 GiB

== 3. Layer plan: the three CSA2 modes read from the config
  SSFRRRRRFRRRRRFRRRRR | FRRRXRRRXRRRXRRRXRRR
  S=SWA only, F=Full, X=Reindex, R=Reuse; ratio [0, 1, 2]
  S=2, F=4, X=4, R=30 | Full [2, 8, 14, 20], Reindex [24, 28, 32, 36]

== 4. Indexer scoring per decoded token (raw FLOPs)
  candidate pool 16,384 positions; FLOPs/pair: V3.2 16,384, V4.1 8,192
          N   V3.2 GFLOP   V4.1 GFLOP   ratio  Full share
      4,096        4.094        0.218   18.8x       38.5%
     65,536       65.498        1.879   34.9x       71.4%
    131,072      130.997        3.221   40.7x       83.3%
  1,048,576     1047.972       22.012   47.6x       97.6%

== 5. Single-Pass mHC activation traffic (units of d, n=hc_mult)
  multi-pass (3 kernels+norm) 20 d = 102,400 values per token per block
  two-pass fused              14 d =  71,680 values per token per block
  single-pass / lower bound   10 d =  51,200 values per token per block
  n=4: single-pass vs multi-pass 2.0x

== 6. Parameter ledger (Hub dtype tallies + config)
  one expert (three SwiGLU matrices) 3 x 5120 x 2304 = 35,389,440
  I8 tally 557,171,343,360; 40 x 384 + 3 x 128 experts = 557,171,343,360
  Engram: 768,022,850 rows x 256 = 196,613,849,600 (paper: 196B)
  F8 tally 204,015,223,296 - Engram = 7,401,373,696
  total 763,205,315,794
  - Engram - DSpark experts = 553,001,921,234 (553.0B, paper 552B)
  activated expert parameters: 9.91B decode, 4.95B prefill (paper 16B / 8B)

== 7. Why the effort penalty decays exponentially (App. C, toy)
  setup: s=4000, a*L=0.75, k0=0.5, b_min=25, tau=25
  L_norm=4000, p(0)=0.2, p(inf)=0.95
     b    k(b)  closed form    grid  cap 0.3  cap 0.8
    25  0.5000        1,622   1,622   40,000    1,622
    50  0.1839        5,622   5,622   40,000    5,622
    75  0.0677        9,622   9,622    9,622    9,622
   100  0.0249       13,622  13,622   13,622   13,622
  slope of the grid optimum 160.0 tokens per unit b; s/tau = 160.0

== 8. Sinkhorn-balanced update (Algorithm 1): toy gradient
                   rows      row RMS (min .. max)      column RMS (min .. max)
  momentum          833     0.002021 ..    38.08         0.2766 ..    5.102
  K = 1             833            1 ..        1         0.2194 ..    3.137
  K = 3             833            1 ..        1         0.9721 ..    1.145
  K = 11 (paper)    833            1 ..        1              1 ..        1
  Engram has 196,613,849,600 parameters; one FP32 state (assumed) = 786 GB
```

Reading it item by item:

- **The four numbers of Figure 1(b) are recovered (section 1).** The layout is as follows. V1 67B uses GQA (95 layers, 8 KV heads, head dimension 128, bf16), which is 389,120 bytes per token. V3.2 stores 656 bytes of main KV per layer (a 512-dimensional FP8 latent, 16 bytes of scales and 64 bf16 position dimensions) plus 132 bytes of indexer K (128 FP8 dimensions plus a 4-byte scale), which makes 48,068 bytes over 61 layers. A V4-Flash main-KV entry is 584 bytes (448 FP8 dimensions, 64 bf16 position dimensions and 8 bytes of scales), and ratio-4 layers add a 68-byte FP4 indexer K; weighted by the compression ratio of each layer this gives 3,514.25 bytes (the paper's figure shows 3,514). Each V4.1 source layer stores 288 bytes of main KV (512 FP4 dimensions plus one FP8 scale per 16 channels) and 68 bytes of indexer K, and weighted by compression ratio this comes to exactly 890 bytes, the number in the paper's conclusion. Neighbouring generations shrink by 8.095, 13.678 and 3.949 times (the paper writes 8.1, 13.7 and 3.9), and V1 to V4.1 by 437.2 times (paper: 437).
- **Sharing is worth more than quantization (section 2, counterfactual).** If V4.1's layer structure (ratios 2 and 1) stored a copy per layer with an FP8 main KV, a token would take 18,908 bytes. Switching only to FP4 gives 10,324 bytes, a factor of just 1.83, because FP4 acts on the main KV only while the 68-byte indexer K is already 4-bit, so the entry goes from (584+68) to (288+68) bytes. Adding cross-layer sharing, which cuts the entries from 29 to 2.5, brings it to 890 bytes, another factor of 11.60, 21.2 in total. This is arithmetic inside V4.1's own layer structure, not an ablation: it says that within this structure most of the shrinkage comes from the layer dimension, but the paper's 1/4 is relative to V4-Flash, whose sequence compression is stronger, so the counterfactual cannot split that 3.949 into three parts. With these byte counts, one 1M-token ($2^{20}$) sequence needs 380.00 GiB of global KV on V1, 46.94 GiB on V3.2, 3.43 GiB on V4-Flash and 0.87 GiB on V4.1.
- **The layer plan matches the paper (section 3).** The config yields S=2, F=4, X=4, R=30: layers 2, 8 and 14 of the encoder are Full, layer 20 of the decoder is Full, layers 24, 28, 32 and 36 are Reindex, and the rest are Reuse, matching the paper's description in section 4.2.1 layer by layer.
- **The indexer's scoring work (section 4).** These are raw FLOPs, not weighted by precision: 16,384 per candidate position for V3.2 (64 heads x 128 dims x 2) and 8,192 for V4.1 (32 heads). At a sequence length of 4,096 the V4.1 indexer does 1/18.8 of V3.2's scoring, and at one million tokens 1/47.6: the four Reindex layers are capped by the candidate pool, leaving the four Full layers as the only part that grows linearly with length, and they account for 97.6% of the scoring at one million tokens. That explains why the paper says the first Full layer "still scans the entire causally visible range". The paper's Figure 2 claims that stretching the context 256-fold, from 4K to 1M, raises the decode FLOPs per token by only 1/4. I could not reproduce that number: the paper weights BF16, FP8 and FP4 operations by 1, 0.5 and 0.25 but does not say which part runs at which precision. My table only shows where the growth in the indexer comes from; it cannot verify that curve.
- **mHC memory traffic (section 5).** The multi-pass implementation (three kernels plus the pre-norm) moves $(4n+4)d$, the two-pass fusion $(3n+2)d$, and the single pass reaches the lower bound $(2n+2)d$. For $n=4$ and $d=5120$ that is 102,400, 71,680 and 51,200 values per token per block, so single-pass moves 2.0 times less than multi-pass, matching the paper's "halving". This is only the traffic arithmetic; whether the kernel is really twice as fast depends on the implementation, which I did not measure.
- **The parameter ledger (section 6).** One expert is three SwiGLU matrices, $3\times5120\times2304=35{,}389{,}440$ parameters. The I8 tally of V4.1 on the Hub is 557,171,343,360, exactly $(40\times384+3\times128)$ experts, that is 384 routed experts in each of 40 layers plus 128 experts in each of DSpark's three blocks, to the last digit. Engram is 768,022,850 rows times 256 dimensions, 196,613,849,600 in total (the paper says 196B); what remains of the FP8 tally after removing Engram is 7,401,373,696. The total is 763,205,315,794, and subtracting Engram and DSpark's experts gives 553,001,921,234, while the paper says 552B, a little lower than my count; I did not chase it tensor by tensor and it may be a difference in what is counted (for example, whether the vision encoder or DSpark's non-expert parts are included). Prefill runs only the 20 encoder layers, which activate 4.95B of expert parameters; decode runs all 40 and activates 9.91B. The paper's 8B and 16B should also include attention and embeddings, which I did not itemize.
- **The Appendix C derivation holds (section 7, toy numbers).** The appendix assumes that the benefit of one more reasoning token decays exponentially with length and derives an optimal length that is roughly linear in the effort $b$ with slope $s/\tau$. With toy parameters ($s=4000$, $\tau=25$), a direct grid search for the maximum gives optimal lengths of 1,622, 5,622, 9,622 and 13,622, identical to the closed form, and a slope of 160.0, exactly $s/\tau$. The appendix's caveat shows up as well: with the penalty capped at 0.3, the optimum at $b=25$ and $b=50$ jumps to the grid limit of 40,000, because beyond the cap another token costs nothing at the margin; capping at 0.8 changes nothing. The cap $C_{\max}$ must therefore not be set too low, or low effort ends up thinking the longest. The parameters are mine, chosen to illustrate the derivation, not the paper's.
- **The Sinkhorn-balanced update does what it claims (section 8, toy gradient).** The gradient matrix has 4,000 rows (tokens) and 64 columns; only about 20% of rows are non-zero (tokens present in the batch), the row sizes are heavy-tailed and the column scales are unequal. After momentum, the 833 live rows have an RMS from 0.002021 to 38.08, a spread of more than four orders of magnitude. With the paper's $K=11$ every live row has RMS 1 and so does every column (to four significant digits). At $K=1$ the rows are already exactly 1 but the column RMS still ranges from 0.2194 to 3.137, and $K=3$ narrows it to between 0.9721 and 1.145. The other 3,167 rows (tokens not seen, and rows below the mask threshold $\rho_i\le\tau\bar\rho$) get a zero update. This tests the algorithm's properties only; it does not test that it "beats Adam" (the paper says it does empirically, with no comparison table in the main text). Under an FP32 assumption, every extra optimizer state for Engram's 196,613,849,600 parameters is 786 GB, so dropping the second-moment buffer is not a small saving.

Environment: Apple M2 Max, Python 3.14.3, NumPy 2.4.2, CPU only, about 10 seconds. Configs and parameter tallies were fetched from Hugging Face on 13 November 2026 and may differ after the repositories are updated; the random numbers in section 8 use a fixed seed, and the two language versions of this page print identical numbers.

## Pre-training: sparse attention from scratch

V4.1-Flash is pre-trained on 45T tokens of multimodal data with a 7:1 ratio of text-only to multimodal tokens. One data decision worth remembering: content generated by weaker models and low-quality machine translation is filtered out as "implicit duplication", since it only rephrases existing information and may hurt over long training runs. The batch size is fixed at 100.6M tokens; the learning rate warms up linearly to $2.6\times10^{-4}$ over 2,000 steps, stays there until 28T tokens, decays on a cosine schedule to $2.6\times10^{-5}$ between 28T and 40T tokens, and stays flat for the last 5T.

A key change from [V3.2](https://dmxsf.com/en/blog/deepseek-v32-pushing-the-frontier-of-open-large-language-models/) is that the model is no longer "pre-trained dense, then retrofitted to sparse". The paper says sparse attention is trained from scratch at a sequence length of 64K with no dense warm-up stage, and the sequence length is extended to one million at 34T tokens. The optimizer settings are as follows. Muon uses momentum 0.95 and weight decay 0.1, and rescales the RMS of each update matrix to 0.18 so that the AdamW learning rate can be reused; AdamW uses $\beta_1=0.9$ and $\beta_2=0.95$; the Sinkhorn-balanced update uses the same momentum and learning-rate correction with $K=11$, $\tau=10^{-3}$ and $\epsilon=10^{-20}$; Engram's learning rate is scaled up by 5. The paper reports no instability during training.

The base-model comparison is against V4-Flash-Base and V4-Pro-Base (the latter with 49B active and 1.6T total parameters). The paper says V4.1-Flash-Base is on par with V4-Pro-Base in knowledge, reasoning and coding, with 5% to 10% gains on held-out evaluations, at 1/3 of the total and 1/4 of the active parameters. The detailed numbers are in the paper's Table 1 and are not repeated here.

## Post-training: data and environments, not algorithms

The paper is blunt about post-training: this release introduces no new algorithm. The recipe is standard supervised fine-tuning, reinforcement learning and on-policy distillation (OPD), and all substantive changes are in the data pipeline; "under a fixed and unremarkable optimization procedure", systematic gains in the scale, diversity and verifiability of synthesized data and environments "account for essentially all of the observed gains". That is the paper's claim; the main text shows no experiment that separates data from algorithm.

- **Task synthesis.** Each task is a (problem, environment, verification system) triplet scored on difficulty and correctness, and those two scores become rewards for iteratively training the model to build better tasks. General-agent environments come from interaction data that employees and partners volunteered, from which the pipeline builds many mock tools that reproduce the input formats, output structures and API constraints of real tools, and turns negative feedback and failure cases into replayable environments. Coding-agent environments come from two sources, coding sessions from employees and partners (keeping complex tasks and tasks where the model did poorly) and public GitHub repositories above a star threshold, and are built by several specialized agents: one judges whether the project can be built and verified automatically in a container, picks a starting commit and designs evaluation points (both fail-to-pass and pass-to-pass); another sets up the container, self-tests and removes traces that leak the solution; several solver agents attempt the task; an independent inspection agent reviews the environment and trajectories, and a repair agent fixes whatever fails.
- **Reinforcement learning.** Large-scale asynchronous RL, scaled along training compute and the number of scaffolds. Asynchrony brings a length-distribution bias and off-policy samples, which the paper handles by limiting concurrency per dataset, discarding early-returned short samples, bounding the off-policy ratio and masking the loss of stale tokens. It tried batch-level and prompt-level dispatch and settled on sample-level dispatch (a new prompt is dispatched as soon as enough finished samples have accumulated for the next GRPO group), and for samples that span several checkpoints it concatenates the expert routing of each rollout segment instead of recomputing it. The sandbox platform DSec scales to millions of containers and raised the density per physical node from about 1,000 to more than 2,500 concurrent containers. The paper also records agents cheating by exploiting sandbox vulnerabilities (a permission problem in the XFS driver, illegal memory access in AppArmor, answers leaking through package mirrors), countered with per-sandbox AppArmor profiles and eBPF network policies.
- **Reasoning-effort control.** During training a scalar $b\in\{1,\dots,100\}$ is written into the system prompt, each prompt is sampled at several values of $b$, and rewards are mean-centered only inside each (prompt, $b$) subgroup. Differences between effort levels come from a length penalty:

$$
r^{\mathrm{len}}_{b,j}=-\min\!\left(C_{\max},\ k(b)\,\frac{\ell_{b,j}}{L_{\mathrm{norm}}}\right),\qquad k(b)=k_0\exp\!\left(-\frac{b-b_{\min}}{\tau}\right)
$$

  $\ell_{b,j}$ is the number of reasoning tokens, and every increase of $b$ by $\tau$ multiplies the penalty coefficient by $e^{-1}$. The public API tiers max, high and low map to $b=100$, 75 and 50 (launched in September 2026). Section 7 of the check script above shows why Appendix C picks an exponential.
- **On-policy distillation.** The last post-training step is full-vocabulary OPD over data from all domains using more than 40 teacher models; teachers may differ in architecture from the student and from each other, and the infrastructure supports an unbounded number of heterogeneous teachers with cheap switching.

## Results in the paper

The table lists only numbers that the paper's main text states explicitly (Table 3 has more benchmarks and baselines, not repeated here). Model names are written as the paper writes them.

| Benchmark | V4.1-Flash | Comparisons named by the paper |
| --- | --- | --- |
| Codeforces (rating) | 3471 | V4-Pro 3348, V4-Flash 3289 |
| GPQA Diamond | 90.9 | V4-Flash 89.9 |
| MathArena Apex | 65.6 | Kimi-K3 65.6, V4-Pro 65.3 |
| DeepSWE v1.1 (resolved) | 74.2 | V4-Flash 54.4, Opus-5 74.0, GPT-5.6 Sol 73.0 |
| Terminal-Bench 2.1 | 90.6 | Opus-5 89.1, GLM-5.3 88.2 |
| AutomationBench | 54.8 | Paper says it leads open and closed baselines |
| Agents' Last Exam | 31.8 | Paper says it leads open and closed baselines |

The effect of reasoning effort is among the clearest curves in the paper:

| Metric | Effort 25 | Effort 100 |
| --- | --- | --- |
| Average Pass@1 on eight reasoning benchmarks | 67.1% | 76.3% |
| DeepSWE v1.1 | 66.0% | 74.2% |
| Terminal-Bench 2.1 | 82.4% | 90.6% |

The price is about 2.5 times the output tokens. The paper adds that the gains are front-loaded: the 60 to 80 range recovers most of the accuracy of the maximum setting at less than half of its token budget, while the final step to 100 lengthens agent trajectories by 1.6 to 1.8 times for only a marginal improvement, so the top tier is best kept for the hardest tasks. In a preliminary multi-agent experiment (the Agent Team mode of DeepSeek Harness), ProgramBench Almost@1 reaches 30.04% at 8 hours against 20.39% at best for a single agent, and FrontierSWE v2 Mean@5 reaches 32.90% at 20 hours against 28.20%; the paper says these results are preliminary and compare the strongest configuration observed on each side.

## Limitations and open questions

1. **No ablation for any single design choice.** For CED, CSA2, the hierarchical indexer, the FP4 main KV, SWA Bounded Replay and Single-Pass mHC, the paper uses only qualitative words such as "negligible", "marginal" and "barely". The only quantitative comparison is the whole model (base and post-trained) against V4-Flash and V4-Pro, and V4.1's backbone is 552B against 284B for V4-Flash, with different data and post-training too. "A smaller cache with better performance" is evidence that the two happened together, not that one caused the other.
2. **One key curve I could not reproduce.** Figure 2's decode FLOPs weight BF16, FP8 and FP4 by 1, 0.5 and 0.25 without giving the precision of each part or any breakdown; section 4 of the check can only show where the indexer's growth comes from.
3. **The cost of approximation is left to untested boundaries.** The conclusion itself says that selection errors in CSA2 and the approximate state reconstruction of SWA Bounded Replay may still degrade capability in untested boundary cases, and names sparse retrieval over long contexts and cache-resumption boundaries as the next areas for stress testing.
4. **Evaluation scope and saturation.** The comparison models and harnesses are the paper's own choice. The paper itself warns that standard benchmarks are saturating and that a narrow score margin "does not imply" parity with frontier systems on complex, high-difficulty reasoning and edge cases. The introduction's claim that it can complete "over 95% of real-world tasks" comes without a stated protocol. The paper also reports gaming behaviour during evaluation (for example, decompiling core Ubuntu packages to find vulnerabilities in CyberGym), and benchmark scores should be read together with that.
5. **Reproduction barrier.** The weights are released, but the training infrastructure (shadow indexers, pipeline payload extensions, micro-batch-level shared-state management) and the DSec sandbox are described only as designs, with no statement about whether they will be released; anyone who wants these numbers has to rebuild that layer.

## What to take away

1. **Think of the cache as multiplicative dimensions.** For any long-context cost problem, ask for each of the three factors whether it has room left: how big each entry is, how many entries each token keeps, and how many layers store their own copy. Inside V4.1's own layer structure, going from 29 entries to 2.5 saves a factor of 11.60 while FP4 saves 1.83, so the layer dimension has far more room than the bit width of an entry.
2. **Trade exactness for approximation only with boundary tests.** Bounded Replay swaps a 128-token approximate replay for half of the persistent cache, which is a good engineering deal but makes results depend on where the cache hits. Any approximation like this should ship with the boundaries where it breaks; the paper itself admits that testing is not finished.
3. **Leverage in data and environments.** The paper credits nearly all post-training gains to data and environments. Even taken as a hypothesis rather than a conclusion, its pipeline (task triplets, letting the model rate tasks for difficulty and correctness, multi-agent construction and inspection of environments) is worth studying piece by piece.
4. **With efficiency papers, first find the numbers you can recompute.** The 890 bytes can be rebuilt from the configs; "decode FLOPs grow by only 1/4" cannot. Both are equally prominent in the paper, but they are not equally checkable.

## Further reading

- Paper: [DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression](https://arxiv.org/abs/2609.19969) (DeepSeek-AI, 2026).
- Weights and configs on Hugging Face: [deepseek-ai/DeepSeek-V4.1-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash) and [deepseek-ai/DeepSeek-V4-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash).
- Related posts: [DeepSeek-V3.2](https://dmxsf.com/en/blog/deepseek-v32-pushing-the-frontier-of-open-large-language-models/) (sparse attention and the lightning indexer), [mHC](https://dmxsf.com/en/blog/mhc-manifold-constrained-hyper-connections/), [DeepSeek-V2](https://dmxsf.com/en/blog/deepseek-v2-strong-economical-efficient-mixture-of-experts/) (MLA and DeepSeekMoE), [DeepSeek-V3](https://dmxsf.com/en/blog/deepseek-v3-technical-report/), [GQA](https://dmxsf.com/en/blog/gqa-grouped-query-attention/), [StreamingLLM](https://dmxsf.com/en/blog/efficient-streaming-language-models-with-attention-sinks/) (sliding windows and attention sinks), [vLLM and PagedAttention](https://dmxsf.com/en/blog/vllm-pagedattention/), [speculative decoding](https://dmxsf.com/en/blog/speculative-decoding-fast-inference-from-transformers/).
- Concept pages: [KV cache](https://dmxsf.com/en/wiki/inference/kv-cache/), [efficient attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/), [long context](https://dmxsf.com/en/wiki/architecture/long-context/), [quantization](https://dmxsf.com/en/wiki/inference/quantization/), [speculative decoding](https://dmxsf.com/en/wiki/inference/speculative-decoding/), [mixture of experts](https://dmxsf.com/en/wiki/architecture/mixture-of-experts/), [optimizers and training stability](https://dmxsf.com/en/wiki/foundations/optimizers-and-training-stability/).

## FAQ

### How does DeepSeek-V4.1-Flash get its KV cache down to 890 bytes per token?

The global KV cache is a product of three factors: how big each entry is, how many entries each token keeps, and how many layers store their own copy. The paper squeezes all three: cross-layer sharing (only 4 of 40 layers are sources of global KV, so a token keeps 2.5 entries on average instead of 29), sequence compression (ratio 2 in the encoder, none in the decoder) and an FP4 main KV (288 bytes per entry against 584 bytes for V4's FP8). Using the public configs and this byte layout I get exactly 890 bytes, matching the paper. A counterfactual calculation shows that sharing accounts for a factor of 11.60 and FP4 only for 1.83.

### What is the difference between the Full, Reindex and Reuse modes of CSA2?

In all three modes a layer computes its own main query and sliding-window KV; the modes differ in the global part. Full computes its own main KV and indexer K and selects a fresh Top-512. Reindex reuses the main KV and indexer K of the latest Full layer but scores them with its own indexer Q and selects a new Top-512. Reuse reuses both the main KV and the latest Top-512 and runs no indexer at all. Of the 40 layers, 4 are Full, 4 are Reindex, 30 are Reuse and 2 use sliding-window attention only. Cache sharing and index reuse are decoupled: Reindex lets the selection change from layer to layer while the cache stays shared.

### What is SWA Bounded Replay and what does it give up?

Sliding-window dependencies accumulate across layers, so rebuilding the sliding-window KV of L layers exactly means replaying L x n_win tokens (40 x 128 = 5,120 here). Bounded Replay replays only the most recent n_win = 128 tokens and truncates the window to the replayed segment, which gives an approximate state; results therefore depend on where the cache hit happens and are not bit-identical across positions. In return the sliding-window KV no longer has to live in the persistent cache (where it took nearly half in V4), and the persistent footprint drops to about 1/8 of V4-Flash. The paper says the effect on response quality is negligible but gives no ablation numbers, and lists the approximation as a risk in untested boundary cases.

### How can an FP4 KV cache be almost lossless?

The paper uses E2M1 values with one E4M3 scale per 16 channels (following NVFP4 but without its second-level global scale), applies quantization-aware training in post-training, and quantizes after RoPE. Dropping the global scale is justified by a magnitude bound: after RMSNorm the 512-channel latent has an L2 norm of at most about the square root of 512, RoPE preserves the norm, so no channel exceeds about 22.6 in absolute value (the largest value seen in training is around 10), while the format can represent up to 448 x 6 = 2688. The sliding-window KV is more sensitive and stays in FP8. The paper only says the degradation is small and shows no ablation table.

### How is the reasoning effort b trained?

During training b in {1, ..., 100} is written into the system prompt, each prompt is sampled at several values of b, and rewards are mean-centered only inside each (prompt, b) subgroup. Behaviour differences between effort levels come from a length penalty whose coefficient k(b) = k0 * exp(-(b - b_min)/tau) decays exponentially with b. A local derivation in the paper's Appendix C shows that the optimal reasoning length is roughly linear in b with slope s/tau. The public API tiers max, high and low map to b = 100, 75 and 50. The paper reports that raising b from 25 to 100 lifts the average Pass@1 on eight reasoning benchmarks from 67.1% to 76.3% at about 2.5 times the output tokens.
