Shared KV Memory: From Transformers to DeepSeek

On this page

A language model stores earlier tokens' key and value vectors so it can reuse them when generating the next token. This stored information, called the KV cache, grows with context length and network depth. We derive its storage cost, then examine how DeepSeek-V4.1-Flash lets several layers share cached representations while computing different attention outputs.

The Two Minute Papers video motivates this question. We develop the attention, GPT, and cache-sharing calculations from primary papers rather than the video's benchmark comparisons.

Recap: A language model is a conditional token distribution

As in the alignment note, we factor the joint distribution of tokens XtX_t in a finite vocabulary V\mathcal V into conditional probabilities:

pθ(x1:N)=∏t=1Npθ(xt∣x<t).p_\theta(x_{1:N}) =\prod_{t=1}^N p_\theta(x_t\mid x_{<t}).

During generation, Xt∣X<t=x<t∼pθ(⋅∣x<t)X_t\mid X_{<t}=x_{<t}\sim p_\theta(\cdot\mid x_{<t}), with trained parameters θ\theta fixed; the empty prefix uses a start token. Although the token is sampled, its probabilities are deterministic given the prefix when dropout is disabled. We examine which intermediate computations can therefore be cached.

1. Attention reads a set of vectors

Attention combines information across token positions. Let H∈RN×dH\in\mathbb R^{N\times d} contain one row per token. For one head, we project these rows using learned matrices WQ,WK∈Rd×dkW_Q,W_K\in\mathbb R^{d\times d_k} and WV∈Rd×dvW_V\in\mathbb R^{d\times d_v}:

Q=HWQ,K=HWK,V=HWV.Q=HW_Q,\qquad K=HW_K,\qquad V=HW_V.

The query qtq_t scores key kjk_j at position jj; the resulting attention weight multiplies value vjv_j. Vaswani et al., Section 3.2 define this operation as scaled dot-product attention:

stj=qtkj⊤dk+Mtj,αtj=exp⁡(stj)∑uexp⁡(stu),ot=∑jαtjvj,O=softmax⁡row(QK⊤dk+M)V.\begin{aligned} s_{tj}&=\frac{q_t k_j^\top}{\sqrt{d_k}}+M_{tj},\\ \alpha_{tj}&=\frac{\exp(s_{tj})}{\sum_u\exp(s_{tu})},\\ o_t&=\sum_j\alpha_{tj}v_j,\\ O&=\operatorname{softmax}_{\rm row} \left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V. \end{aligned}

For causal attention, we set Mtj=0M_{tj}=0 if j≤tj\le t and −∞-\infty otherwise, giving αtj=0\alpha_{tj}=0 for future positions. The weights are computed from the query and keys, without an additional random draw.

Vaswani et al. Figure 2 shows query-key matrix multiplication, scaling, optional masking, softmax and value multiplication on the left. The right panel shows parallel projected attention heads, concatenation, and an output projection.
Figure 1. Attention weights and parallel attention heads. Original figure from Vaswani et al. (2017), Attention Is All You Need, Figure 2. The optional mask becomes a causal mask in an autoregressive language model. Attention weights are deterministic functions of the given query and keys. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.

Why divide by the square root?

To examine the score variance, let q,k∼independentN(0,Idk)q,k\overset{\rm independent}{\sim}N(0,I_{d_k}). Under this auxiliary law,

E[qk⊤]=0,Var⁡(qk⊤)=∑a=1dkE[qa2]E[ka2]=dk,Var⁡ ⁣(qk⊤dk)=1.\begin{aligned} \mathbb E[qk^\top]&=0,\\ \operatorname{Var}(qk^\top) &=\sum_{a=1}^{d_k}\mathbb E[q_a^2]\mathbb E[k_a^2] =d_k,\\ \operatorname{Var}\!\left(\frac{qk^\top}{\sqrt{d_k}}\right)&=1. \end{aligned}

Dividing by the square root keeps this variance constant as the head dimension grows. This calculation explains the scaling convention without assuming that trained queries and keys are independent Gaussians.

Multi-head attention combines hh heads' separate outputs OiO_i:

MHA⁡(H)=Concat⁡(O1,…,Oh)WO.\operatorname{MHA}(H) =\operatorname{Concat}(O_1,\ldots,O_h)W_O.

Different query projections allow these heads to weight the same positions differently.

2. From the Transformer decoder to GPT

The original Transformer encodes an input sequence and decodes an output sequence. Within the decoder, masked self-attention combines previous output positions, whereas cross-attention reads the encoder states.

Vaswani et al. Figure 1 shows a bidirectional encoder on the left and a decoder on the right. The decoder contains masked self-attention and a separate cross-attention sublayer that reads the encoder outputs, followed by a linear map and softmax.
Figure 2. The original encoder–decoder Transformer. Original figure from Vaswani et al. (2017), Attention Is All You Need, Figure 1. GPT-style decoder-only models remove the separate encoder and its cross-attention sublayer; they retain causal self-attention. DeepSeek's causal encoder later in this note is not the bidirectional translation encoder shown here. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.

Radford et al., Section 3.1 instead use a Transformer decoder for language modeling. GPT-style decoder-only models apply causal blocks to one token sequence, without a separate encoder or encoder–decoder cross-attention.

For embedding map e:V→Rde:\mathcal V\to\mathbb R^d and positional vectors ptp_t, set ht(0)=e(xt)+pth_t^{(0)}=e(x_t)+p_t. To describe the computations used in caching, we consider a schematic pre-normalized block:

U(ℓ)=H(ℓ−1)+MHA⁡ℓ{LN⁡(H(ℓ−1))},H(ℓ)=U(ℓ)+FFN⁡ℓ{LN⁡(U(ℓ))},ℓ=1,…,L,FFN⁡(u)=σ(uW1+b1)W2+b2,pθ(Xt+1=a∣x≤t)=exp⁡{(ht(L)Wvocab+b)a}∑v∈Vexp⁡{(ht(L)Wvocab+b)v}.\begin{aligned} U^{(\ell)} &=H^{(\ell-1)} +\operatorname{MHA}_{\ell}\{\operatorname{LN}(H^{(\ell-1)})\},\\ H^{(\ell)} &=U^{(\ell)} +\operatorname{FFN}_{\ell}\{\operatorname{LN}(U^{(\ell)})\}, \qquad \ell=1,\ldots,L,\\ \operatorname{FFN}(u)&=\sigma(uW_1+b_1)W_2+b_2,\\ p_\theta(X_{t+1}=a\mid x_{\le t}) &=\frac{\exp\{(h_t^{(L)}W_{\rm vocab}+b)_a\}} {\sum_{v\in\mathcal V}\exp\{(h_t^{(L)}W_{\rm vocab}+b)_v\}}. \end{aligned}

The feed-forward network uses W1∈Rd×dffW_1\in\mathbb R^{d\times d_{\rm ff}}, W2∈Rdff×dW_2\in\mathbb R^{d_{\rm ff}\times d} and an elementwise activation σ\sigma. The vocabulary map has Wvocab∈Rd×∣V∣W_{\rm vocab}\in\mathbb R^{d\times|\mathcal V|} and b∈R∣V∣b\in\mathbb R^{|\mathcal V|}. Layer normalization acts on one row u∈Rdu\in\mathbb R^d:

LN⁡(u)=g⊙u−uˉ1d−1∑a=1d(ua−uˉ)2+ε+β,uˉ=d−1∑a=1dua.\operatorname{LN}(u) =g\odot\frac{u-\bar u\mathbf1} {\sqrt{d^{-1}\sum_{a=1}^d(u_a-\bar u)^2+\varepsilon}}+\beta, \qquad \bar u=d^{-1}\sum_{a=1}^du_a.

Here g,β∈Rdg,\beta\in\mathbb R^d are learned, ε>0\varepsilon>0, and ⊙\odot denotes coordinatewise multiplication. Normalization and the feed-forward network act tokenwise, so causal masking restricts the block's output to prefix information. This pre-normalization convention need not match every GPT.

For a fixed-length data distribution PdataP_{\rm data}, training minimizes the expected negative log-likelihood over θ\theta:

L(θ)=EX1:N∼Pdata[−∑t=1Nlog⁡pθ(Xt∣X<t)].\mathcal L(\theta) =\mathbb E_{X_{1:N}\sim P_{\rm data}} \left[-\sum_{t=1}^N\log p_\theta(X_t\mid X_{<t})\right].

This expectation averages over data sequences, whose representations determine the attention weights. For inference, we hold the fitted parameters fixed and examine which computations generation can reuse.

3. Why a KV cache works, and why it grows

Prefill processes a prefix of NN tokens; decode then processes one new token at a time. At layer ℓ\ell, the new query uses eligible prefix keys and values together with the new token's entries:

K1:N+1(ℓ)=[K1:N(ℓ)kN+1(ℓ)],V1:N+1(ℓ)=[V1:N(ℓ)vN+1(ℓ)].\begin{aligned} K_{1:N+1}^{(\ell)} &=\begin{bmatrix}K_{1:N}^{(\ell)}\\k_{N+1}^{(\ell)}\end{bmatrix},\\ V_{1:N+1}^{(\ell)} &=\begin{bmatrix}V_{1:N}^{(\ell)}\\v_{N+1}^{(\ell)}\end{bmatrix}. \end{aligned}

Proposition: Appending a token does not change earlier causal states

Assume fixed parameters, prefix-invariant positional encodings, no dropout, causal attention, and tokenwise normalization and feed-forward operations. Reusing the prefix's keys and values gives the same mathematical attention output as recomputing that prefix.

We argue by induction. Appending xN+1x_{N+1} leaves earlier embeddings unchanged. If earlier states are unchanged at layer ℓ−1\ell-1, then, for t≤Nt\le N, attention uses the same positions j≤tj\le t with unchanged queries, keys and values. Therefore,

hj(ℓ−1)(x≤N+1)=hj(ℓ−1)(x≤N),j≤t,ot(ℓ)(x≤N+1)=∑j≤tαtj(ℓ)vj(ℓ)=ot(ℓ)(x≤N),ht(ℓ)(x≤N+1)=ht(ℓ)(x≤N).\begin{aligned} h_j^{(\ell-1)}(x_{\le N+1}) &=h_j^{(\ell-1)}(x_{\le N}),\quad j\le t,\\ o_t^{(\ell)}(x_{\le N+1}) &=\sum_{j\le t}\alpha_{tj}^{(\ell)}v_j^{(\ell)} =o_t^{(\ell)}(x_{\le N}),\\ h_t^{(\ell)}(x_{\le N+1}) &=h_t^{(\ell)}(x_{\le N}). \end{aligned}

Induction establishes equality at every layer in exact arithmetic; numerical kernels can still round differently. Causality is essential because later tokens can change earlier bidirectional representations, invalidating this reuse argument.

Cache size

Let hKVh_{\rm KV} be the number of stored key/value heads, dhd_h their common dimension, and bb bytes per scalar. Ignoring padding and metadata,

MKV=2LNhKVdhb.\boxed{M_{\rm KV}=2LNh_{\rm KV}d_hb.}

The factor two counts keys and values; the other factors count layers, positions, head coordinates, and bytes per scalar. With L=32L=32, N=32,768N=32{,}768, hKV=32h_{\rm KV}=32, dh=128d_h=128, and two-byte scalars,

MKV=17,179,869,184 bytes=16 GiBM_{\rm KV} =17{,}179{,}869{,}184\ {\rm bytes} =16\ {\rm GiB}

for one sequence, excluding weights and workspace. Thus caching avoids repeated prefix computation but retains linear storage growth and attention's cache-reading cost. We next examine how to reduce the width and number of stored representations.

4. Compressing the head dimension: MLA

Grouped-query attention (GQA) reduces cache width by sharing keys and values within groups of query heads; multi-query attention (MQA) uses one KV head. Multi-head latent attention (MLA) instead caches a low-dimensional representation of head-specific content keys and values.

DeepSeek-V2 Figure 3 compares MHA, grouped-query attention, multi-query attention, and multi-head latent attention. Hatched vectors are cached; MLA caches a compressed latent instead of expanded head-specific keys and values.
Figure 3. Reducing the cache across attention heads. Original figure from DeepSeek-AI (2024), DeepSeek-V2, Figure 3. This source diagram simplifies MLA. Its complete RoPE construction also caches a decoupled positional key; the article retains that extra term in the memory count. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.

Following DeepSeek-V2, Sections 2.1.2–2.1.3, we express this low-dimensional construction in row-vector notation for head ii:

cj=hjWD∈Rdc,kj,iC=cjUK,i,vj,iC=cjUV,i,qt,iC(kj,iC)⊤=(qt,iCUK,i⊤)⏟transformed querycj⊤,∑jαtj,ivj,iC=(∑jαtj,icj)UV,i.\begin{aligned} c_j&=h_jW_D\in\mathbb R^{d_c},\\ k^C_{j,i}&=c_jU_{K,i},\qquad v^C_{j,i}=c_jU_{V,i},\\ q^C_{t,i}(k^C_{j,i})^\top &=\underbrace{(q^C_{t,i}U_{K,i}^\top)}_{\text{transformed query}}c_j^\top,\\ \sum_j\alpha_{tj,i}v^C_{j,i} &=\left(\sum_j\alpha_{tj,i}c_j\right)U_{V,i}. \end{aligned}

Here WD∈Rd×dcW_D\in\mathbb R^{d\times d_c} and UK,i,UV,i∈Rdc×dhU_{K,i},U_{V,i}\in\mathbb R^{d_c\times d_h}. Associativity lets us regroup the matrix products. We apply the key projection to the query and apply the value projection after taking the weighted sum. Attention can then use cached cjc_j without storing the expanded content keys and values.

Rotary position embedding (RoPE) uses position-dependent rotations to encode token positions. These rotations complicate the preceding regrouping of projections. MLA therefore keeps a separate positional key kjR∈RdRk_j^R\in\mathbb R^{d_R}:

qt,ikj,i⊤=qt,iC(kj,iC)⊤+qt,iR(kjR)⊤.q_{t,i}k_{j,i}^\top =q^C_{t,i}(k^C_{j,i})^\top +q^R_{t,i}(k_j^R)^\top.

The cache therefore retains the pair (cj,kjR)(c_j,k_j^R), not only cjc_j, giving equal-precision storage

MMLA=LN(dc+dR)binstead of2LNhdhb.M_{\rm MLA}=LN(d_c+d_R)b \quad\text{instead of}\quad 2LNh d_hb.

MLA reduces width but retains the factor LL: different layers still store different latents. We next consider sharing these representations across layers.

5. Compressing the layer dimension: shared global memory

In You Only Cache Once (YOCO), Section 2, a lower causal stack produces representations MM for one global cache:

K^=Norm⁡(M)WK,V^=Norm⁡(M)WV.\widehat K=\operatorname{Norm}(M)W_K,\qquad \widehat V=\operatorname{Norm}(M)W_V.

Each upper layer computes its own query but attends to these same cached vectors:

Q(ℓ)=Norm⁡(H(ℓ−1))WQ(ℓ),O(ℓ)=Attention⁡(Q(ℓ),K^,V^;Mcausal).Q^{(\ell)}=\operatorname{Norm}(H^{(\ell-1)})W_Q^{(\ell)}, \qquad O^{(\ell)}=\operatorname{Attention} (Q^{(\ell)},\widehat K,\widehat V;M_{\rm causal}).
Sun et al. YOCO Figure 2 shows a lower self-decoder using efficient causal self-attention to create a global KV cache. An upper cross-decoder reads that same cache with its own queries. Input and output token sequences remain autoregressive.
Figure 4. One global cache read by multiple decoder layers. Original figure from Sun et al. (2024), You Only Cache Once: Decoder-Decoder Architectures for Language Models, Figure 2. Only the global KV cache is shared once. The lower efficient-attention layers can still keep bounded local or recurrent states. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.

If each global cache row occupies bgb_g bytes and each of LL layers retains at most ww local rows of blocb_{\rm loc} bytes, the storage count is

M(N)=Nbg+Lwbloc,M(N)=Nb_g+Lwb_{\rm loc},

rather than LNbgLNb_g for layer-specific global caches. Sharing removes the global depth factor, while the second term retains bounded local states.

Shared memory does not mean shared outputs

To see why sharing need not give identical outputs, take shared scalar keys k1=0,k2=1k_1=0,k_2=1 and values v1=0,v2=1v_1=0,v_2=1. For scalar query qq,

α2(q)=eq1+eq,o(0)=12,o(log⁡3)=34.\alpha_2(q)=\frac{e^q}{1+e^q},\qquad o(0)=\frac12,\qquad o(\log3)=\frac34.

The queries use identical memory but produce different attention outputs. Layer-specific output maps, residual connections, and feed-forward networks further distinguish their hidden states.

This sharing is built into the trained architecture; copying one layer's cache into arbitrary layers of an already trained decoder generally changes its function.

6. DeepSeek's causal encoder–decoder

DeepSeek-V4.1-Flash also separates an encoder from an upper decoder. Unlike the original translation encoder, its encoder is causal and cannot inspect future tokens. In Section 2.2, Equation (1), decoder global-cache projections use the final encoder states:

E=H(L/2),C(ℓ)=EWKV(ℓ),Z(ℓ)=EWZ(ℓ),ℓ>L/2.\begin{aligned} E&=H^{(L/2)},\\ C^{(\ell)}&=EW_{KV}^{(\ell)},\\ Z^{(\ell)}&=EW_Z^{(\ell)},\qquad \ell>L/2. \end{aligned}

Here C(ℓ)C^{(\ell)} supplies global-cache entries and Z(ℓ)Z^{(\ell)} their compression weights. These layer-dependent projections need not produce identical caches. Compressed Sparse Attention 2 (CSA2) specifies which layers create a cache and which reuse it.

DeepSeek-V4.1-Flash Figure 3 shows a twenty-layer causal encoder with three groups of compressed-attention layers and a twenty-layer decoder whose global KV comes from encoder hidden states. Full, Reindex and Reuse modes have different repeated positions; sliding-window states remain layer-local.
Figure 5. DeepSeek's causal encoder, decoder, and cache sources. Original figure from DeepSeek-AI (2026), DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression, Figure 3. The full source architecture also contains MoE, Engram, residual mixing, vision processing and speculative decoding. The note isolates global-cache construction and reuse rather than treating those other components as cache savings. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.

To distinguish stored caches from their readers, let gg identify a cache-producing layer with global state

Mg=(C‾g,Ig),C‾g∈Rng×dc,Ig∈Rng×dI.\mathcal M_g=(\overline C_g,I_g),\qquad \overline C_g\in\mathbb R^{n_g\times d_c}, \quad I_g\in\mathbb R^{n_g\times d_I}.

An indexer uses keys in IgI_g to select entries, which the main attention operation then reads from C‾g\overline C_g. Compressing nonoverlapping source blocks at ratio mgm_g gives roughly ng=N/mgn_g=N/m_g rows; mg=1m_g=1 leaves the sequence length unchanged. At any position, the model can select only entries constructed from tokens available by that point.

Alongside global memory, each layer retains sliding-window keys and values from its own hidden states. The window length ww bounds this layer-specific local cache independently of NN.

7. Full, Reindex, and Reuse

To distinguish cache reuse from selection, fix position tt. Let aℓ(t,j)a_\ell(t,j) denote layer ℓ\ell's score for eligible global entry jj, with at most kk entries selected. With a fixed tie rule,

Sℓ,t=TopK⁡j∈Ag,taℓ(t,j),∣Sℓ,t∣≤k,S_{\ell,t}= \operatorname{TopK}_{j\in\mathcal A_{g,t}}a_\ell(t,j), \qquad |S_{\ell,t}|\le k,

where Ag,t\mathcal A_{g,t} is the causally available index set for cache gg. This selected support specifies positions to retain; main attention then weights them using the layer's current query.

DeepSeek-V4.1-Flash Figure 4 compares three CSA2 paths. Full computes main KV, indexer keys and a selection. Reindex reads earlier main KV and indexer keys but selects again. Reuse reads earlier main KV and selection. All paths retain a new main query and local sliding-window KV.
Figure 6. Full, Reindex, and Reuse separate storage from selection. Original figure from DeepSeek-AI (2026), DeepSeek-V4.1-Flash, Figure 4. Green denotes newly computed quantities, yellow shared main KV and indexer keys, and red reused Top-K indices. Reused indices do not mean reused softmax weights or attention outputs. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.
ModeMain KV and indexer keysSelected positionsMain query and local KV
FullProduce a new cacheCompute new Top-KCompute in this layer
ReindexReuse the preceding cacheRescore its keys and compute new Top-KCompute in this layer
ReuseReuse the preceding cacheReuse the latest compatible Top-KCompute in this layer

The modes distinguish storing entries, selecting positions, and computing attention weights. Reusing the selection does not copy the softmax weights.

For an illustrative head, let (kjg,vjg)(k^g_j,v^g_j) denote keys and values represented by the shared cache. At layer ℓ\ell, attention combines selected global entries with the local window:

Rℓ,t={(kjg,vjg):j∈Sℓ,t} ∪ {(kℓ,uloc,vℓ,uloc):max⁡(1,t−w+1)≤u≤t},oℓ,t=Attention⁡(qℓ,t,Rℓ,t).\begin{aligned} \mathcal R_{\ell,t} &=\{(k^g_j,v^g_j):j\in S_{\ell,t}\} \ \cup\ \{(k^{\rm loc}_{\ell,u},v^{\rm loc}_{\ell,u}): \max(1,t-w+1)\le u\le t\},\\ o_{\ell,t} &=\operatorname{Attention}(q_{\ell,t},\mathcal R_{\ell,t}). \end{aligned}

We write separate global KK and VV to describe the computation, although the implementation retains a shared compact representation rather than these expanded arrays.

Algorithm 1 One-position cache and support reuse

Input: Fixed prefix, trained parameters, layer assignments to attention modes, causal entry masks, window length ww, and selection budget kk.

Output: The next-token distribution and updated caches.

  1. for each layer ℓ\ell in network order do
  2. Compute the current queries and update this layer's local sliding-window KV.
  3. if the layer uses only sliding-window attention (SWA) then apply local attention and the remaining block operations; continue to the next layer.
  4. if mode is Full then create or update Mg\mathcal M_g and select Sℓ,tS_{\ell,t} from eligible entries.
  5. else if mode is Reindex then retain Mg\mathcal M_g, compute new indexer queries, and select a new Sℓ,tS_{\ell,t}.
  6. else retain Mg\mathcal M_g and use the latest Sℓ′,tS_{\ell',t} selected from this same cache.
  7. end if
  8. Recompute attention weights using the current main query, selected global entries, and current local KV; apply the remaining block operations.
  9. end for
  10. return the vocabulary softmax and updated caches.

The pseudocode summarizes cache reuse, not the complete distributed inference implementation. Decoder Full layers construct their cache from EE; hierarchical indexing below further restricts decoder Reindex searches.

8. Counting the saved bytes

Because several layers read the same cache, we count each stored tensor once. Let G\mathcal G contain distinct global-cache owners, with bgb_g bytes per main-KV-plus-indexer row:

Mcontext(N)=∑g∈Gngbg+O(Lwbloc)+Mrouting.\boxed{ M_{\rm context}(N) =\sum_{g\in\mathcal G}n_gb_g +O(Lwb_{\rm loc})+M_{\rm routing}. }

Here MroutingM_{\rm routing} covers selection and candidate-pool workspace. With equal compression ratio mm and row size bg=b0b_g=b_0, sharing reduces the leading global term from approximately LNb0/mLN b_0/m to ∣G∣Nb0/m|\mathcal G|N b_0/m. The ratio ∣G∣/L|\mathcal G|/L compares global-cache storage, not total GPU memory or wall-clock speed.

The paper's cache layout

In Section 4.2.1, three encoder layers produce ratio-two caches and one decoder layer produces a ratio-one cache. Counting these four caches gives, apart from incomplete blocks,

∑g∈Gng≃3N2+N=52N.\sum_{g\in\mathcal G}n_g \simeq 3\frac N2+N=\frac52N.

Converting rows to bytes requires counting quantized values and scales. Section 2.4.4 stores the 512-channel main latent as four-bit values with an eight-bit scale per 16 channels, giving

bmain=512×48+51216=288 bytes.b_{\rm main} =\frac{512\times4}{8}+\frac{512}{16} =288\ {\rm bytes}.

The 128-channel indexer key uses MXFP4 with a standard block size of 32 and an eight-bit scale. Including its storage gives

bindex=128×48+12832=68 bytes,bg=288+68=356 bytes,Mglobal(N)N≃52(356)=890 bytes/token.\begin{aligned} b_{\rm index}&=\frac{128\times4}{8}+\frac{128}{32}=68\ {\rm bytes},\\ b_g&=288+68=356\ {\rm bytes},\\ \frac{M_{\rm global}(N)}N &\simeq \frac52(356)=890\ {\rm bytes/token}. \end{aligned}

This recovers the report's global-cache count: approximately 0.890.89 GB at one million tokens in decimal units, excluding local states, allocation padding, weights, and temporary workspace. Its approximately fourfold reduction relative to V4-Flash combines architectural and precision changes, not cross-layer sharing alone.

9. Avoiding repeated searches over the whole context

Although Reindex layers share keys, each could still score all nn available entries. The hierarchical sparse indexer reduces repeated searches by selecting a candidate pool for later indexers.

We partition positions into blocks BbB_b of size at most rr. From the first decoder Full layer's scores a0(t,j)a_0(t,j), we select blocks by their maximum scores, then entries within their union:

βb(t)=max⁡j∈Bba0(t,j),Bt=TopB⁡bβb(t),Pt=⋃b∈BtBb,∣Pt∣≤Br,Sℓ,t=TopK⁡j∈Ptaℓ(t,j)for later decoder Reindex layers.\begin{aligned} \beta_b(t)&=\max_{j\in B_b}a_0(t,j),\\ \mathcal B_t&=\operatorname{TopB}_b\beta_b(t),\\ \mathcal P_t&=\bigcup_{b\in\mathcal B_t}B_b,\qquad |\mathcal P_t|\le Br,\\ S_{\ell,t}&=\operatorname{TopK}_{j\in\mathcal P_t}a_\ell(t,j) \quad\text{for later decoder Reindex layers}. \end{aligned}
DeepSeek-V4.1-Flash Figure 5 shows the first Full-mode indexer scoring all available positions and selecting blocks for a shared candidate pool. Subsequent Reindex layers score only that pool and choose their own Top-512 positions, which need not agree.
Figure 7. A full-range indexer builds a smaller search pool. Original figure from DeepSeek-AI (2026), DeepSeek-V4.1-Flash, Figure 5. The first decoder indexer still scans the causally visible context. Only the subsequent candidate-restricted scoring cost is bounded independently of context length. Full resolution ↗Figure excerpt for discussion; copyright remains with the authors/rightsholder.

With RR later indexers and fixed score-evaluation cost, the number of positions scored decreases from

(R+1)nto at mostn+RBr.(R+1)n \quad\text{to at most}\quad n+RBr.

The first pass still depends on context length. With the paper's B=2048B=2048, r=8r=8, and k=512k=512, later queries select subsets from at most 16,38416{,}384 positions rather than the entire million-token history. This score-evaluation count excludes Top-K selection, attention, projections, and other block operations.

What is lost by restricting the support?

Restricting the pool can exclude useful entries. To bound one attention output's error, fix the query, keys, and values. Let αj\alpha_j be full-attention weights, o=∑jαjvjo=\sum_j\alpha_jv_j, and SS a nonempty retained set. Suppose ∥vj∥≤V\|v_j\|\le V and define omitted mass

δ=∑j∉Sαj<1.\delta=\sum_{j\notin S}\alpha_j<1.

Since the retained scores are unchanged, their softmax weights renormalize to give

oS=∑j∈Sαj1−δvj.o_S=\sum_{j\in S}\frac{\alpha_j}{1-\delta}v_j.

For 0<δ<10<\delta<1, let oSˉ=δ−1∑j∉Sαjvjo_{\bar S}=\delta^{-1}\sum_{j\notin S}\alpha_jv_j average the omitted values. We split the output into retained and omitted contributions and apply the triangle inequality:

o=(1−δ)oS+δoSˉ,∥o−oS∥=δ∥oSˉ−oS∥≤2Vδ.\begin{aligned} o&=(1-\delta)o_S+\delta o_{\bar S},\\ \|o-o_S\| &=\delta\|o_{\bar S}-o_S\| \le 2V\delta. \end{aligned}

For δ=0\delta=0, the outputs agree. This bound concerns one attention output, not the complete model, and is not a theorem from the DeepSeek report. The indexer's scores can differ from the main attention scores. Its selected pool therefore need not retain most of the main attention weight, so δ\delta need not be small.

10. Prefill savings and approximate local replay

Prefill also benefits from computing global decoder memory directly from EE, without processing every prompt position through the decoder. However, local decoder KV still requires decoder states. For prompt length NN and window ww, the report reconstructs these through bounded replay over the last ww prompt tokens.

We measure processed positions through layer-token evaluations at fixed width:

full-stack work∼NL,encoder plus bounded decoder replay∼NL2+wL2,second countfirst count=12+w2N⟶12(N/w→∞).\begin{aligned} \text{full-stack work}&\sim NL,\\ \text{encoder plus bounded decoder replay} &\sim N\frac L2+w\frac L2,\\ \frac{\text{second count}}{\text{first count}} &=\frac12+\frac{w}{2N}\longrightarrow\frac12 \quad(N/w\to\infty). \end{aligned}

The encoder processes the full prompt, whereas the decoder processes the replay segment. This count excludes projection and serving overheads; it does not establish half the total FLOPs for an arbitrary dense-attention Transformer.

A short window is not an exact deep receptive field

Although each layer uses a bounded window, dependencies extend across layers. For example, two layers with a two-position window and uniform scalar attention give

hi(1)=xi−1+xi2,hi(2)=hi−1(1)+hi(1)2=xi−2+2xi−1+xi4.h_i^{(1)}=\frac{x_{i-1}+x_i}{2}, \qquad h_i^{(2)} =\frac{h_{i-1}^{(1)}+h_i^{(1)}}2 =\frac{x_{i-2}+2x_{i-1}+x_i}{4}.

Because the output depends on xi−2x_{i-2}, replaying only (xi−1,xi)(x_{i-1},x_i) cannot always recover it. In Section 3.2.2, bounded replay instead approximates local states by restricting attention to

j∈[max⁡(s,i−w+1),i],j\in[\max(s,i-w+1),i],

where ss is the replay start. During replay, prefix tokens read the cached global entries without overwriting them and rebuild approximate local states. The report acknowledges this approximation and evaluates it empirically. The earlier proof that an exact causal cache remains valid does not show that these reconstructed local states are exact.

11. Which problem does sharing solve?

We can now separate the reductions by the terms they change:

head-width compression:2hdh ⟶ dc+dR,sequence compression:N ⟶ N/m,cross-layer cache reuse:L ⟶ ∣G∣,lower cache precision:fewer bytes per stored coordinate,hierarchical indexing:(R+1)n ⟶ n+RBr.\begin{array}{rcl} \text{head-width compression} &:& 2h d_h\ \longrightarrow\ d_c+d_R,\\ \text{sequence compression} &:& N\ \longrightarrow\ N/m,\\ \text{cross-layer cache reuse} &:& L\ \longrightarrow\ |\mathcal G|,\\ \text{lower cache precision} &:& \text{fewer bytes per stored coordinate},\\ \text{hierarchical indexing} &:& (R+1)n\ \longrightarrow\ n+RBr. \end{array}

Cross-layer sharing separates cached representations from the queries used to read them, reducing storage without forcing identical outputs. Sparse selection, quantization, and bounded replay introduce separate approximations; their quality effects do not follow from the storage calculation.

This note concerns how the token policy is computed; the PPO/DPO and GRPO notes concern its training. A smaller context cache does not itself define a new policy-gradient estimator or make model parameters fit on a small device.

References

The cache-invariance proof, illustrative arithmetic and readout examples, and truncation bound are worked explanations, not new model evaluations. Source figures retain their original artwork and attribution.