Architecture explainer

DeepSeek-V4.1-Flash

A model is a learned program that transforms tokens, small pieces of text or image input, through successive layers. Its learned numbers are parameters. During generation, a KV cache keeps reusable representations of earlier tokens so the model does not rebuild all prior context state for every new token.

ReportPushing the Limits of KV Cache Compression
AuthorsDeepSeek-AI
ReleasedSeptember 10, 2026
Scale40 layers, up to 1M tokens
01 / Begin with the workload

One long request, then one small answer

An agent is software that repeatedly asks a model to inspect information and choose the next step. Its existing input is the prompt. Prefill processes that prompt; decode produces the answer one token at a time. Producing each next token from earlier tokens is autoregressive generation.

Repository
files and symbols
Prior turns
plans and decisions
Tool output
tests, logs, screenshots
New result
the latest 128 tokens
Next token
the answer begins

Teaching example: a sampled 100,000-token coding-agent session. It is illustrative, not a workload measurement from the report.

The backbone

Stages with memory

A Transformer is a model built from repeated blocks. Its depth is the number of layers traversed. Causal means a position can use only earlier or current positions. A hidden state is its internal vector for a token. To encode is to turn input into those internal representations.

Finding information

Attention

Attention compares a current query with stored keys, then mixes their associated values. A useful key receives more influence on the output.

Three scopes

Far, near, and selected

Global attention can reach the whole earlier context. Sliding-window attention (SWA) reaches only a recent fixed window. Sparse attention reads a selected subset instead of every old position.

The report's answer

Split work, share memory

Causal Encoder-Decoder (CED) keeps most prompt work in the lower half. Compressed Sparse Attention 2 (CSA2) compresses and shares the far-reaching memory and can reuse its selection decisions.

The central idea: keep rich local processing in every layer, but stop duplicating the expensive global path. CED reduces prompt computation; CSA2 reduces global cache and indexing duplication.

Sources: report Abstract, Introduction, and Sections 2.1-2.3.

02 / Ordinary decoder-only baseline

Every prompt token climbs every layer

In the qualitative baseline, each layer derives its own global key-value entries from its own hidden states. A longer prompt therefore multiplies both prompt computation and cache storage across layers.

100K prompt
all tokens

Each bar is one layer; height variation is only visual grouping.

Layer-local cachemany copies

Interpretive baseline based on report Sections 2.2-2.3. This does not assign a generic Transformer a made-up byte count.

Prefill bill

Depth times prompt length

Every prompt token runs through every layer even when most of the context is old tool history.

Memory bill

Context times cache-owning layers

Independent global caches repeat long-context state and must be stored, moved, and sometimes persisted for later reuse.

03 / Causal Encoder-Decoder

CED changes how the prompt and new tokens travel

The 40-layer language backbone is split into a 20-layer causal encoder and a 20-layer decoder. The key is phase-dependent: most prompt tokens stop after the encoder, but every newly generated token still traverses both halves.

Phase explorer

Where does one token travel?

oldest context100K prompt positionslast 128
100K prompt tokensexisting context
20-layer encoderall prompt tokens
20-layer decoderonly the last 128-token SWA replay

Prefill: all prompt tokens build final encoder states. The first decoder layer, paper layer 21 and zero-indexed config layer 20, projects the shared global cache from those states; only the recent window is replayed through decoder layers for their local SWA state.

Generic source

HL/2

Final causal-encoder hidden states for the prompt.

Generic projections

WlKV and WlZ

Layer-dependent maps in the report's general CED rule.

Generic outputs

Cl and Zl

Global KV entries and compression weights for l > L/2.

Released decoder source: paper layer 21 is zero-indexed config layer 20. It stores one main-KV entry per position, so the reference compressor has no learned compression gate. That main KV is shared by config layers 21-39.

Source: report Sections 2.2 and 4.2.1, Equation (1), plus official `kv_source_layer_ids`, `compress_ratios`, and reference `Compressor`. The equation's general Z branch is not materialized by the released ratio-1 decoder source.

Report Equation 1

Decoder global cache comes from the encoder boundary

The equation extends horizontally.

Cl=HL/2WlKV,Zl=HL/2WlZ,l>L2,C_l = H_{L/2}W_l^{KV},\quad Z_l = H_{L/2}W_l^Z,\quad l > \frac{L}{2},
Read it as: a decoder cache-producing layer does not derive its global entries from its own hidden state. It applies its learned projections to the final encoder state.
Cl
Global KV entries for cache-producing layer l
Zl
Compression weights paired with those entries
HL/2
Hidden states at the encoder-decoder boundary
WlKV, WlZ
Learned layer-dependent projection weights
L, l
Total layer count and current layer index
L/2
The halfway boundary; 20 when L is 40
=, >
Equality and the decoder-side condition
three commas
Two separators; Equation 1 ends with a comma

Coding-agent example: the 100K-token prompt reaches H20. Equation (1) gives the general Cl/Zl rule; the released ratio-1 decoder source uses only the unpooled main-KV projection because no multi-token compression gate is needed.

Visual mapping: the three generic boxes above map HL/2 through WlKV and WlZ into Cl and Zl; the green callout then narrows that rule to the released implementation.

Source: report Section 2.2, Equation (1).

Cost interpretation from the report: for prompt length N much larger than the 128-token window, prefill changes from order NL to order NL/2 plus nwinL/2, approximately order NL/2. This is a complexity explanation, not an additional numbered source equation.
04 / Compressed Sparse Attention 2

Three different levers shrink the global cache

A compression ratio says how many source positions become one stored entry. That compact internal vector is a latent. An indexer is a lightweight scorer that chooses the Top-K most relevant positions. Quantization stores numbers at lower precision: FP4 uses roughly four bits per value, while FP8 uses roughly eight.

Sequence axisGroup positions

Encoder ratio 2 turns each non-overlapping token pair into one main-KV entry. Decoder ratio 1 keeps one entry per position.

Layer axisShare cache and selections

Many layers borrow main KV and indexer K; some also reuse the latest Top-K indices.

Precision axisStore main KV in FP4

This is complementary to CSA2. Sliding-window KV stays FP8 because the authors found it more sensitive.

Encoder, ratio 2

Two positions become one latent entry

t0t1c0t2t3c1
Decoder, ratio 1

Each position keeps one latent entry

t0c0t1c1

Source: report Sections 2.3 and 4.2.1. Unlike the earlier CSA, CSA2 removes overlap between neighboring compression groups, removes absolute positional embeddings from compression, and projects indexer K from main KV.

Layer-mode explorer

What does the current layer compute or borrow?

A candidate pool is a bounded shortlist of positions that later indexers may rescore. Every CSA2 mode still computes a current-layer main query and local SWA KV.

Main QCompute here
SWA KVCompute here
Main KVCompute here
Indexer KProject here
Indexer QCompute here
Top-K indicesSelect here
current indexer Q current indexer K
score positions with the indexer
fresh Top-K indices
select entries from current main KV
selected current main KVcurrent-layer local SWA KV
Core sparse attention with current-layer main Q

Full mode publishes main KV and indexer K, computes an indexer query, and selects fresh Top-K positions.

Source: report Section 2.3.1 and Figure 4. Green means current computation, amber means shared cache, and coral means reused indices; the diagram is redrawn rather than copied.

05 / Hierarchical sparse indexer

Scan broadly once, then search a bounded shortlist

Cross-layer index reuse removes many indexer calls, but the remaining Reindex layers would still score the whole context. The decoder's first Full layer therefore creates one shared candidate pool for deeper indexers.

For each decoder query separately, zero-indexed config layer 20 scores the full causally visible context. Its score output then splits into two paths.

The sampled context strip extends horizontally.

1. Full scores
scores full visible range
Own-attention pathAll position scores → Full layer's Top-512
Candidate pathGroups of 8 → maximum score per block → up to 2,048 blocks

Expose every position in the winning blocks: at most 16,384 candidates.

2a. Full Top-512
used by Full attention
2b. Shared pool
up to 16,384 positions
3. Reindex scores pool
own query → fresh Top-512
Important boundary: the first Full layer still scores the entire causally visible range. Only later Reindex layers have a score count bounded independently of context length when the candidate-pool size is fixed.

Source: report Section 2.3.2 and Figure 5. Candidate restriction is applied per query, was introduced during post-training, and is used identically in training and inference. The 48 marks are a sampled visual, not one mark per context position.

Released configuration

The exact 40-layer attention schedule

The layer schedule extends horizontally.

Encoder 0-19zero-based; CSA2 m=2 after SWA-only layers 0-1

Layer strip continues to the right.

Decoder 20-39zero-based; CSA2 m=1

Layer strip continues to the right.

SWA = local only F = Full I = Reindex R = Reuse

Source: report Section 4.2.1 and official `config.json`. All tile numbers are zero-based config indices: KV sources 2, 8, 14, 20; index sources 2, 8, 14, 20, 24, 28, 32, 36; Top-K 512; SWA window 128.

06 / SWA bounded replay

Long-lived global memory, short-lived local state

A persistent cache stores reusable prefix state beyond one active request, typically in host memory or on solid-state drives. The report separates long-tail global reuse from minutes-scale SWA reuse.

Encoder lane: only on an SWA miss

Reuse global KV; rebuild the recent window

Global cache hit
Load the cached long prefix; the described deployment retains it for at least 72 hours.
Encoder SWA miss
The short-lived host-memory entry has expired or was evicted.
Replay the cached-prefix tail
The last 128 cached tokens regenerate only encoder SWA KV; cached global KV is reused without overwrite.
Join the uncached suffix
Process new suffix tokens alongside the replay segment; the suffix generates both global KV and SWA KV.

Approximate: exact recovery would replay the most recent L x 128 prompt tokens. Suffix state can therefore depend on the cache-hit position.

Decoder lane: every prefill

Decoder SWA KV is never persisted

Take final encoder outputs
Use only the last 128 prompt positions.
Replay through 20 decoder layers
Apply the same local-window truncation at each layer.
Seed generation
Use the resulting decoder SWA KV for decode, not prefix caching.

Approximate: it is not mathematically identical to a full decoder pass over the prompt.

Do not merge the ratios: CSA2 plus FP4 gives the author-reported 890 bytes per token global KV footprint, about one quarter of V4-Flash. Removing SWA KV from persistent storage plus bounded replay gives about one eighth of V4-Flash's persistent KV footprint.

Source: report Sections 3.2.1-3.2.2. The quality impact is author-reported as negligible; Section 6 still names replay reconstruction as an incompletely characterized robustness boundary.

07 / Supporting architecture

The main idea sits inside a larger co-designed system

A mixture of experts (MoE) stores many feed-forward subnetworks but routes each token through only a few; the weights used for that token are its active parameters. Engram is hashed conditional memory. DSpark is a speculative draft-and-verify module. mHC, or multi-head hyper-connections, mixes several residual streams between blocks.

Multimodal input

Images join the token stream

A 32-layer vision encoder uses 2D rotary positions. A 3 x 3 pixel-unshuffle reduces visual-token count ninefold before a two-layer projector maps features into the language width.

Joint image-text processing from language pretraining start
DeepSeekMoE

Large stored, small active

Every Transformer block has one shared expert and 384 routed experts; six routed experts are selected per token.

552B backbone; 8B active in prefill, 16B in decode
Engram memory

Lookup instead of compute

Two modules at zero-indexed layers 1 and 14 retrieve hashed 2-, 3-, and 4-token patterns using eight hash heads.

196B additional stored parameters
Main KV precision

E2M1 values, E4M3 scales

Main KV uses one E4M3 scale per 16 FP4 channels after rotary position encoding. Local SWA KV remains FP8.

Enabled by quantization-aware post-training
DSpark

Draft five positions together

Three small Transformer blocks produce five base draft positions in parallel; a Markov head models draft dependencies and a confidence head helps schedule verification length.

Trained after backbone pretraining
Single-Pass mHC

Shift one dependency

Each block consumes the preceding block's input-mixing coefficients, letting deployment fuse residual update, input mixing, coefficient prediction, normalization, and conversion.

Author-reported 2x lower activation traffic than the original implementation

Sources: report Sections 2.1.1 and 2.4. Components are shown separately because none is another name for CED or CSA2.

Original mHC, Equation 2

Current coefficients control current input mixing

compute Xlpredict Al, then mix AlXl

The input-mixing pass must wait until Al has been predicted from all of Xl.

Single-Pass mHC, Equation 6

Previous coefficients remove the wait

read one tile of Xlmix with ready Al-1 and predict next coefficients

Input mixing can proceed while the same residual traversal accumulates the coefficients for the next block.

Report Equation 2

Original mHC update

The equation extends horizontally.

Xl+1=BlXl+ClFl(AlXl),(Al,Bl,Cl)=H(Xl),X_{l+1} = B_lX_l + C_l\mathcal{F}_l(A_lX_l),\quad (A_l,B_l,C_l) = \mathcal{H}(X_l),
Read it as: predict Al, Bl, and Cl from the current residual streams Xl; Al mixes the current block input, Bl carries residuals, and Cl injects the transformed result.
Xl, Xl+1
n residual streams before and after block l
Al
Current input-mixing coefficients
Bl, Cl
Residual-carry and transformed-output mixing coefficients
l
Calligraphic ℱ: Transformer block l

Calligraphic ℋ: coefficient predictor applied to Xl
l, l+1
Current and next block indices
=, +, ( )
Equality, addition, and three grouping pairs
four commas
Formula separator and two tuple separators; Equation 2 ends with a comma

Agent example: at one token position, the current four residual streams must be fully reduced before Al is ready to mix the block input.

Visual mapping: the left comparison branch places coefficient prediction before current input mixing.

Source: report Section 2.4.1, Equation (2).

Report Equation 6

Single-Pass mHC shifts only the input-mixing index

The equation extends horizontally.

Xl+1=BlXl+ClFl(Al1Xl),(Al,Bl,Cl)=H(Xl).X_{l+1} = B_lX_l + C_l\mathcal{F}_l(A_{l-1}X_l),\quad (A_l,B_l,C_l) = \mathcal{H}(X_l).
Read it as: Bl and Cl are still predicted from Xl, but the block input uses already-available Al-1. That dependency shift enables one residual traversal in the deployment kernel.
Xl, Xl+1
n residual streams before and after block l
Al-1
Previous block's ready input-mixing coefficients
Al, Bl, Cl
Al is saved for the next block; Bl carries residuals; Cl injects transformed output
l
Calligraphic ℱ: Transformer block l

Calligraphic ℋ: coefficient predictor applied to Xl
l-1, l, l+1
Previous, current, and next block indices
=, +, ( )
Equality, addition, and three grouping pairs
three commas and period
One formula separator and two tuple separators; Equation 6 ends with a period

Agent example: the current token's residual tile can immediately use Al-1 while the kernel predicts Al for the following block.

Visual mapping: the right comparison branch shows ready Al-1 entering the same pass that predicts the next coefficients.

Source: report Section 2.4.1, Equation (6).

08 / What is actually reported

Architecture facts and first-party systems claims

The report's weighted single-token decode FLOPs count one BF16 operation as 1, one FP8 operation as 0.5, and one FP4 operation as 0.25. This is an author-defined compute proxy, not measured wall-clock latency.

Active backbone8B / 16B

Parameters active per token during prefill / decode. Stored backbone size is 552B, plus 196B Engram parameters.

Architecture setup
Global KV in HBM890 B/token

About one quarter of V4-Flash at equal sequence length, attributed jointly to cross-layer reuse and FP4 caching.

Author-reported
Persistent KVabout 1/8

V4-Flash's footprint under identical workloads after removing SWA KV from persistent storage and compressing global KV.

Author-reported
Context scaling256x context, +25%

From 4K to 1M context, Figure 2 reports only about one-quarter more weighted single-token decode FLOPs.

Author-reported proxy
Reuse-mode execution15 / 11

Inference kernels per layer during prefill / decode after the authors' kernel fusion.

Implementation claim
Training scale45T tokens

Multimodal pretraining from 64K sparse context, extended to 1M at 34T tokens. Text-only to multimodal token ratio is 7:1.

Training setup
Interpretation boundary: these numbers describe one co-designed model, precision format, cache policy, and kernel stack. They do not show that transplanting CED or CSA2 into an arbitrary model produces the same savings.

Sources: report Abstract, Figures 1-2, Sections 3.2 and 4.2. As of September 10, 2026, these are first-party release results rather than independent replication.

09 / Limits

Compression buys efficiency by accepting new failure surfaces

Sparse selection can miss.
Top-K routing may omit a distant position that later layers need; the report calls selection errors an incompletely characterized boundary.
Replay state is approximate.
Encoder suffix state can depend on where the cache hit occurs, and decoder SWA reconstruction is not mathematically identical to a full pass.
One million is capacity, not comprehension.
Supporting a 1M-token input does not guarantee perfect retrieval, integration, or reasoning at that length.
FP4 needs training and kernels.
The main-cache format uses quantization-aware post-training and a compatible dequantization path; it is not a free storage conversion.
The evidence is first-party.
The report and reference code were released on September 10, 2026. Broad hardware portability and boundary behavior still need independent testing.
This is not a new reasoning objective.
The architecture changes how context is processed and cached. The report says post-training follows SFT, RL, and on-policy distillation without algorithmic innovation.
One-sentence model: CED avoids deep prompt processing, CSA2 avoids duplicating global memory and routing work, and bounded replay avoids persisting short-lived local state.
10 / Primary sources

Read the release materials

Visuals on this page are original explanatory redrawings. No report figure is embedded or copied.