bobofamilyNIU CHUN
44/44

Where History Lives: Sliding Windows, Linear States, Gates and MLA

21 MIN—READS

In global causal attention, the current Q matches each visible historical K and mixes V using the resulting weights. KV caching avoids recomputing old K/V, but the cache keeps growing and each new Q reads more history. The designs below change different parts of that process.

DesignMain changeHistorical representation
Sliding windowPositions directly visible to the current QK/V for the most recent W positions
Basic linear attentionMatching rule and summation orderFixed-shape S/z aggregating the prefix
Gated DeltaNetFixed-state update ruleRetain old state, then correct along the current key
Attention output gatingHow much of each retrieved feature passes onwardDoes not itself replace the history cache
GQAHow Q heads share K/VFewer K/V groups per position
MLAWhat each position storesA content latent vector and a separate positional key

We use row vectors multiplying weights on the right. The seven diagrams contain teaching examples at different scales: the small window example uses W=3, the three-column comparison uses W=2, and the full block has its own weights. Comparisons within each diagram use shared inputs; numbers from different diagrams are not successive steps of one model. Script names and step labels locate computations. Model quality and performance require separate evaluation.

A window changes visibility and renormalizes the remaining weights

Global and sliding-window attention: D's mask, weights and output, followed by E's KV cache
Figure 1 · Steps 03–05 follow D; step 06 slides to E. W=3 includes the current position.Full size ↗

For query position i and key position j, global causality requires j ≤ i. When W includes the current position, the window requires 0 ≤ i−j < W. Before softmax, masked scores become −∞, whose exponential is zero.

Figure 1 uses A, B, C, D, E and a one-dimensional head: q_D=1, keys for A–D are [0,0,0,ln 2], values are [10,2,4,6], and the scale is √d=1. Both paths mask future position E when processing D.

D’s computationGlobal causalWindow W=3
Visible positionsA, B, C, DB, C, D
Exponentials, in A–D order[1,1,1,2][0,1,1,2]
Normalized weights[1/5,1/5,1/5,2/5][0,1/4,1/4,1/2]
Weighted V sum(10+2+4+2×6)/5 = 5.6(2+4+2×6)/4 = 4.5

D’s raw self-score stays the same, but its self-weight rises from 40% to 50%. The remaining positions must be renormalized. Removing A’s old 20% contribution without changing the other weights gives the wrong result.

After D, a window cache can retain [B,C,D]. When E arrives, reuse C/D, add E’s K/V and evict B, leaving [C,D,E]. The global cache retains [A,B,C,D,E]. E computes its own weights with its own Q; D’s outputs 5.6 and 4.5 are not reused as E’s output.

The window decides visibility; caching reuses computed results. Training can process a whole sequence in parallel with a separate window for each query row. Inference can update a rolling cache token by token. After evicting old positions, absolute RoPE positions must still advance: the current cache length is no longer the next position index. See KV Cache: masks and RoPE offsets.

Put the mask back into a full block: from predicting E to parameter gradients

Nineteen-step Transformer block comparison from projections through global/window attention to loss and parameter updates
Figure 2 · One layer, hidden width 4, two Q heads and one shared KV head. Steps 01–06 agree; step 07 introduces the difference. These values belong to this diagram's teaching weights.Full size ↗

The inputs are A–E and the shifted targets are B–F. D’s output predicts E; D is not given E’s input features first. This diagram names the score matrix S. Later, linear attention also uses S for a state matrix, but the axes mean different things.

Steps 01–06: identical inputs and raw scores

Embedding lookup produces X:[5,4]. The first RMSNorm operates over the four features at each position, followed by three projections:

U = RMSNorm(X)
Q = U W_Q [5,4]
K = U W_K [5,2]
V = U W_V [5,2]

Q splits into two 2D heads; K/V have one shared head. Each Q head computes its own scores. Sharing K/V does not require identical attention weights. After per-head RMSNorm and RoPE on Q/K, head 0’s raw D-to-A score is approximately 0.63.

Both paths share inputs and weights up to this point. “The first difference is the mask” applies to the same sublayer receiving the same input. In a multi-layer comparison, earlier outputs can already differ, so later layers may have different inputs and Q/K/V despite identical weights.

Steps 07–10: mask, position softmax, read V, output projection

With W=3, the window replaces D→A’s score with −∞. In head 0, D’s weight on A changes from about 0.140 to 0, and B/C/D are renormalized. Mixing the same V gives:

Global: H_D ≈ [1.006, 0.536]
Window: H_D ≈ [1.037, 0.224]

Concatenate head 1’s result and multiply by W_O to obtain attention-branch output O. This softmax runs across token positions: it controls which V rows are read.

Steps 11–16: two residuals and SwiGLU

R = X + O
Z = RMSNorm(R)
F = [SiLU(Z W_g) ⊙ (Z W_u)] W_d
Y = R + F

The first residual adds the original X; the second adds R. Y is the whole block’s output and the next layer’s input. Window attention does not remove the rest of the block from training: norms, projections, MLP and residuals all remain in the forward and backward paths. See the SwiGLU supplement for its two projections.

Steps 17–19: vocabulary softmax and parameter updates

This single-layer model applies final RMSNorm to Y and projects with the tied vocabulary matrix, yielding [5,6] logits. This softmax runs across vocabulary IDs, unlike the earlier normalization across positions.

Teaching forward-pass resultGlobalWindow
Probability of E at D5.385%3.479%
Cross-entropy at D2.92163.3584
Mean cross-entropy over five positions3.35053.4899

The window gives D→A a zero direct score gradient. This does not imply that A or W_Q/W_K/W_V receive no gradient. A can contribute to predictions at other positions, and shared parameters can receive contributions through other paths.

The bottom of the diagram independently applies gradient clipping and one AdamW step from the same initialization, using learning rate 0.001 and matrix weight decay 0.1. For example, Wq[0,0] becomes 0.998900 on one path and 1.000900 on the other. Changing the mask changes both the forward pass and gradient direction; one teaching input’s loss does not establish an architecture’s quality.

A can influence D indirectly across layers

If the input contains only B, C, D and no inherited state, A’s specific content cannot affect this computation. If A is present and every layer uses W=3, C in layer 1 can read A, and D in layer 2 can read layer 1’s C:

A's input → C's representation in layer 1 → D's representation in layer 2

Across L consecutive pure window layers, the maximum reachable input span is 1+L(W−1) positions when W includes self, further truncated by the sequence boundary. This describes possible information dependencies, not guaranteed retention of every detail. There is no universal fixed decay factor per layer or unit of distance.

If a question at the end asks for an order number from the beginning, a global layer can query its historical key/value directly. A pure window model depends on intermediate representations having preserved the relevant information. Window and global layers can be interleaved. Mistral 7B §2 describes sliding-window attention and rolling caches.

Same X and W: where three mechanisms diverge

Nine-step, three-column comparison of global, window and basic linear attention: inputs, projections, states, outputs and training paths
Figure 3 · Read across to compare a step, down to follow a mechanism. One head, B=1, T=3, D=2; the window here is W=2. Only the attention sublayer is shown.Full size ↗

To isolate matching rules, Figure 3 omits Embedding, Norm, RoPE, residuals, MLP and vocabulary output. X is already the sublayer’s input features. Four matrices contain 16 trainable scalars; values of 0 or 1 do not mean those parameters are frozen.

X = [[1,0], [0,1], [1,1]] # Rows: A, B, C
W_Q = [[1,0], [1,1]]
W_K = [[1,0], [0,1]]
W_V = [[10,2], [4,8]]
W_O = [[1,1], [0,1]]
Q = X W_Q = [[1,0], [1,1], [2,1]]
K = X W_K = [[1,0], [0,1], [1,1]]
V = X W_V = [[10,2], [4,8], [14,10]]

PyTorch stores Linear.weight as [out,in] and computes X @ weight.T; it stores the transpose of W as written here.

C’s dot products are [2,1,3]. Dividing by √2 gives [1.414214,0.707107,2.121320]. Global attention applies softmax over A/B/C; W=2 masks A and normalizes over B/C.

C’s computationGlobalWindow W=2
Weights[0.283995,0.140029,0.575975][0,0.195570,0.804430]
H[11.463726,7.447978][12.044297,9.608859]

Basic linear attention chooses a different, separable matching rule. Before expanding the third column, distinguish parameters, features and state.

A linear state stores feature coefficients, not token rows

ObjectMeaningDirectly updated by the optimizer?
W_Q, W_K, W_V, W_OProjection parameters shared across positionsYes
X, Q, K, V, H, OInput and computed featuresNo, but gradients can pass through them
Scores and attention weightsInput-dependent matching resultsNo
S, zHistorical state per layer, head and sequenceNo; updated by forward recurrence

Use the fixed feature map φ(x)=ELU(x)+1: x+1 for nonnegative x and exp(x) otherwise. Write q̄=φ(q) and k̄=φ(k), whose entries are positive. Here φ has no trainable parameters, and V is unchanged.

For key-feature width d_k and value width d_v:

S_0 = zeros[d_k,d_v]
z_0 = zeros[1,d_k]
ΔS_t = k̄_tᵀ v_t # Outer product: [d_k,1] × [1,d_v]
S_t = S_(t−1) + ΔS_t
z_t = z_(t−1) + k̄_t
h_t = (q̄_t S_t) / (q̄_t z_tᵀ) # Vector divided by scalar

Write the current position before reading, so it can attend to itself and the past. S rows index key features, columns index value features; neither indexes token positions. Ordinary multi-head S has shape [B,H,d_k,d_v], and z has shape [B,H,d_k]. New tokens change existing entries without adding rows.

Continue the state within a sequence; reset for an independent sequence. Each layer, head and batch item maintains its own state. This additive rule does not evict the oldest token as a window does. Historical contributions merge, and a particular position’s original value generally cannot be extracted losslessly.

Why history can be aggregated before the current query reads it

Define the match with historical position j as q̄_t k̄_jᵀ, then normalize and mix V:

h_t = Σ(j≤t) [(q̄_t k̄_jᵀ) v_j] / Σ(j≤t) (q̄_t k̄_jᵀ)
= q̄_t [Σ(j≤t) k̄_jᵀv_j] / [q̄_t (Σ(j≤t) k̄_j)ᵀ]
= q̄_t S_t / (q̄_t z_tᵀ)

Associativity and distributivity separate the query from the historical sum. z accumulates keys; the denominator is the current query’s total matching score, not simply a token count.

These orders are equivalent within the same kernel rule. Ordinary softmax puts the query inside each exponential exp(qkᵀ/√d), preventing the same factoring step. ELU+1 linear attention is not an equivalent acceleration of ordinary softmax attention. See Transformers are RNNs §3.2–3.3 for the original formulation.

A→B→C: how four fixed state entries change

Explicit kernel matching and recurrent causal linear attention, comparing numerators, denominators and outputs at A, B and C
Figure 4 · Same X/W as Figure 3. Left sums over tokens; right accumulates by features. The two paths agree on H and O at every position.Full size ↗

Q/K are nonnegative in this example, so φ adds one elementwise:

Q̄ = [[2,1], [2,2], [3,2]]
K̄ = [[2,1], [1,2], [2,2]]
Position writtenOuter-product increment ΔSUpdated SUpdated z
A[[20,4],[10,2]][[20,4],[10,2]][2,1]
B[[4,8],[8,16]][[24,12],[18,18]][3,3]
C[[28,20],[28,20]][[52,32],[46,38]][5,5]

For C, q̄=[3,2]. Explicit matches with A/B/C are 8, 7, 10, with denominator 25. For H’s first component, sum by token:

(3×2+2×1)×10 + (3×1+2×2)×4 + (3×2+2×2)×14
= 8×10 + 7×4 + 10×14 = 248

Collect terms multiplying 3, then those multiplying 2:

3×(2×10+1×4+2×14) + 2×(1×10+2×4+2×14)
= 3×52 + 2×46 = 248

52 and 46 are S’s first column. Its second column is [32,38] by the same calculation:

q̄_C S_C = [248,172]
q̄_C z_Cᵀ = 3×5+2×5 = 25
H_C = [9.92,6.88]

A and B produce [10,2] and [7,5]. All three mechanisms finally multiply by the same W_O, where [a,b]W_O=[a,a+b]:

MechanismH_CO_C
Global[11.463726,7.447978][11.463726,18.911704]
Window W=2[12.044297,9.608859][12.044297,21.653156]
Basic linear[9.92,6.88][9.92,16.8]

Different matching rules produce these different values. There are no labels or loss in this example, so the table says nothing about training quality. During training, gradients pass through state reads, accumulation and φ back to W. “S/z are not parameters” does not exclude them from backpropagation. During inference, S/z still change, without optimizer updates to parameters.

Gated DeltaNet: retain, then correct along the current key

Basic accumulation adds a new outer product to the old state. Gated DeltaNet introduces α to scale the old state and β to scale the correction along the current key. Keeping key features as rows and value features as columns:

S_retained = α S_old
prediction = k S_retained
δ = v − prediction
S_new = S_retained + β kᵀ δ
h = q S_new

First read with k to predict the value; later read with q to produce the output. This does not use the z denominator of basic normalized linear attention. These equations describe the core recurrence; a complete model can also include short convolutions, normalization, scaling and output gates. The Gated Delta Networks paper gives the corresponding state update.

Basic linear attention and Gated DeltaNet: accumulation, retention and correction, gate gradients and one SGD update
Figure 5 · State updates above; a supplied output gradient backpropagates to two gate projections below. The right-hand q/k are already normalized.Full size ↗

Gates depend on the input; gate weights are shared across positions

Using Qwen3-Next’s parameterization, projections of the current hidden vector produce a and b:

a = x · w_a b = x · w_b
Δt = softplus(a + dt_bias)
α = exp(−exp(A_log) × Δt) β = sigmoid(b)

w_a/w_b, A_log and dt_bias are trainable parameters; α/β are current-input results. The implementation computes gates for V heads in parallel. Compare the Transformers Qwen3-Next implementation.

Choose x=[1,2], w_a=[ln 3,0], w_b=[0,ln 2] and A_log=dt_bias=0:

a = ln 3 → softplus(a)=ln 4 → α=exp(−ln 4)=0.25
b = 2 ln 2 = ln 4 → β=4/(1+4)=0.8

The gates are independent, not complementary, and need not sum to one.

k selects the correction direction; q selects the read direction

Take S_old=[[10,2],[4,8]], k=[1,0], v=[1,9] and q=[0.6,0.8]. Here q/k are unit vectors:

StepResult
0.25×old stateS_retained=[[2.5,0.5],[1,2]]
Trial read with k[2.5,0.5]
v−trial readδ=[−1.5,8.5]
βδ[−1.2,6.8]
Outer-product write along kΔS=[[−1.2,6.8],[0,0]]
Updated stateS_new=[[1.3,7.3],[1,2]]
Query read of new stateh=[1.58,5.98]

Only k’s first component is nonzero, so only row 1 receives the correction. Reading along k again yields [1.3,7.3], 80% of the way from [2.5,0.5] toward v. This interpolation interpretation requires ||k||²=1; otherwise the read change also includes a factor of ||k||². q mixes the two rows with 0.6 and 0.8 to produce h for the subsequent network.

α has two gradient paths, not only direct retention

Supply the teaching upstream gradient ∂L/∂h=[0,−1]. Only the second component contributes:

h₂ = 0.6[2α + β(9−2α)] + 0.8(8α)
∂h₂/∂α = 0.6×2 + 0.8×8 − 0.6×β×2 = 6.64
∂h₂/∂β = 0.6(9−2α) = 5.1
∂L/∂α = −6.64 ∂L/∂β = −5.1

α directly retains more of the old state, but also changes k’s trial read and reduces the correction. Omitting this second path incorrectly gives a derivative of 7.6.

For the special case A_log=dt_bias=0, α=1/(1+exp(a)), so dα/da=−α(1−α)=−0.1875; meanwhile dβ/db=β(1−β)=0.16. Demonstrate ordinary SGD with learning rate 0.1, updating only the two gate projections:

Quantityα branchβ branch
Score gradient1.245−0.816
Weight gradient: score gradient×x[1.245,2.49][−0.816,−1.632]
Updated weights[0.974112,−0.249000][0.081600,0.856347]

Recompute with the same x and old S: α≈0.383171, β≈0.857453 and h≈[2.068337,7.148081]. This is one step under a supplied upstream gradient, not a language-model training result. Real training aggregates gradients across positions and later state dependencies. A single gate value does not establish that the model has detected a particular semantic change.

Attention output gates scale retrieved H feature by feature

Standard and output-gated attention: mix V by position, generate feature gates from the current input, then project
Figure 6 · A weights token positions; g scales output features. This gate acts after H is read, unlike α/β updating S in Figure 5.Full size ↗

Let the current attention weights be A=[0.75,0.25] and the two V rows be [4,0] and [0,8]. Both paths first compute:

H = 0.75[4,0] + 0.25[0,8] = [3,2]

A separate branch reads current x=[1,2], with trainable W_g=[[ln 4,0],[0,−ln 2]]:

x W_g = [ln 4,−ln 4]
g = sigmoid(x W_g) = [0.8,0.2]
H ⊙ g = [2.4,0.4]

g’s entries index features, not historical positions. They pass through independent sigmoids; summing to one is incidental here. Multiplying by W_O=[[1,1],[0,1]] gives [3,5] on the standard path and [2.4,2.8] on the gated path. With multiple heads, concatenate gated results before output projection and residual addition.

During inference, W_g is fixed while g varies with x. Training backpropagates along O → H⊙g → g → xW_g and updates the shared W_g. The Gated Attention paper studies this gate after SDPA output.

Why a gate generally cannot be folded into a fixed matrix

Two fixed linear maps satisfy (HW)W_O=H(WW_O). Input-dependent gating gives (H⊙sigmoid(xW_g))W_O, which generally cannot be merged ahead of time.

Take one dimension, one visible token and W_v=W_g=1, so H=x. At x=1, x sigmoid(x)≈0.7311; at x=2, it is approximately 1.7616. A fixed multiplier w would need to be about 0.7311 for the first input, but then produces only 1.4622 for the second. If gate values were constant across all inputs, their fixed scaling could be absorbed into W_O.

GQA and MLA keep per-position records, but store different data

GQA and MLA cache flow: B writes, D scores each position, mixes values or latent vectors, concatenates heads and projects
Figure 7 · Four Q heads and four positions. Inputs agree but content projections differ; GQA and MLA outputs are not expected to match.Full size ↗

Both GQA and MLA let D score A/B/C/D separately. Both retain position-specific records, unlike aggregating the prefix into a fixed S.

When B arrives: 16 scalars versus 6

B’s hidden vector is [0,1,1,0,1,0]. For easy arithmetic, the MLA content down-projection selects the first four features as c; the positional branch selects the last two and applies a teaching rotation to obtain r. Real models learn projections; “select the first four features” is not the definition of MLA.

One layer, one sequenceGQA: 2 KV headsMLA: compressed cache
B’s recordK₀=[0,1,0,1], V₀=[1,1,1,0]; K₁=[1,0,0,1], V₁=[1,0,0,1]c=[0,1,1,0]; r=[0,1]
ReadersQ₀/Q₁ read group 0; Q₂/Q₃ read group 1All heads read c/r with their own queries and projections
Scalars per position2×(4+4)=164+2=6
Four positions A–D6424

MLA stores one c per position, not one c for the whole prefix. The positional key is retained separately for relative-position scoring. DeepSeek’s implementation separately caches compressed content and positional keys; see DeepSeek-V2 §2.1.

How D queries compressed records

Follow only D’s head 0: content query [1,1], positional query [0,−1], scale √4=2. MLA’s content key projection for this head is [u+w,v], giving:

[1,1] · [u+w,v] = u+v+w = [1,1,1,0] · c

Absorbing the key’s content projection into the query transformation allows scoring directly against cached c. B’s content dot product is 2 and positional dot product −1, giving (2−1)/2=0.5. GQA’s content dot product for B is 1, giving score 0.

D, head 0GQAMLA
Scores for A–D[0.5,0,1,1.5][0.5,0.5,1,2]
Softmax weights[0.1674,0.1015,0.2760,0.4551][0.1230,0.1230,0.2028,0.5512]
What is mixed first?V₀ at each positionc at each position
Mixed result[1.7311,0.3775,0.5566,0.4434][1.4282,0.3258,0.6742,0.3258]

MLA then applies this head’s value projection F(c)=[u+w,v+l,u−v,w+l], obtaining H≈[2.1025,0.6516,1.1025,1.0000]. F can be applied after the sum because all positions share the same linear map:

Σ a_j F(c_j) = F(Σ a_j c_j)

This compares two computation orders for the same MLA head, not MLA with the neighboring GQA path. After concatenating four heads and applying the shared output matrix, the diagram gives:

GQA: [1.0090,0.8872,0.4775,0.5225,−0.0566,0.1468]
MLA: [1.2193,0.9107,1.2160,1.0433,0,−0.1391]

Smaller caches, higher throughput and better quality are separate claims

DeepSeek-V2 reports 93.3% less KV cache and 5.76× maximum generation throughput relative to DeepSeek 67B. The latter compares peak throughput of complete systems; it is not a 5.76× reduction in single-request latency or an isolated attention replacement’s speedup. Under the V2 paper’s dimensions, MLA cache equals 2.25 GQA KV heads: smaller than eight-head GQA, slightly larger than two-head GQA. Cache comparison and inference evaluation

The 2.9B comparison in “Multi-Head Low-Rank Attention” also shows that metrics need not move together:

MetricGQAMLA
Mean validation perplexity over six text datasets (lower is better)13.39913.115
HellaSwag accuracy61.83%62.20%
Mean accuracy over six downstream tasks55.68%55.46%

These results belong to that paper’s training configuration, not the teaching matrices here. They do not establish that every MLA model outperforms every GQA model. Original paper, Tables 3 and 4

Combine mechanisms by layer, and count computation separately from cache

Let T be context length and W the window including self. Ignore batch, head counts and projection costs. Ordinary attention uses equal key/value width d; basic linear attention uses mapped key width d_k and value width d_v:

Core mechanismWhole-sequence matching/state-update workOne-step historical read/updateInference history storage
Global softmaxO(T²d)O(Td)O(Td)
Optimized window softmaxO(TWd)O(Wd)O(Wd)
Basic linear recurrenceO(T d_k d_v)O(d_k d_v)O(d_k d_v+d_k)

For fixed W, window attention also scales linearly with T, but it remains softmax inside a window, not kernel-based linear attention. A teaching program that constructs the full T×T score matrix before masking does not obtain the sparse-computation benefit in the table. Fixed inference state does not make all training memory constant: backpropagation may save intermediate states or reduce storage through chunking and recomputation. A positive kernel gives a positive denominator in exact arithmetic; implementations still need to handle underflow and numerical stability.

GQA mainly reduces KV group count; MLA mainly compresses each position’s record. As long as positions are retained and queried individually, cache and per-step historical reads still grow with T. Fixed-state methods remove the historical-position axis, at the cost of merged, potentially interfering contributions rather than guaranteed lossless recall.

Mechanisms can be mixed by layer, with each layer owning its parameters and history representation. Specific examples include:

  • Gemma 3: five local-window layers followed by one global layer. Official architecture description
  • Qwen3-Next-80B-A3B-Instruct: 12 groups of “3 Gated DeltaNet layers + 1 Gated Attention layer,” with MoE in each layer. Official model card
  • Qwen3.5-35B-A3B-Base: 10 groups of the same 3:1 attention layout; this is the configuration of this particular model. Official model card

“Window + global” and “state recurrence + global” are different combinations. If a hybrid retains global layers, their KV caches can still grow with context. For a new architecture, inspect each layer: is history indexed by position or feature, what does the current query read, does a gate affect state or output, and which shared parameters does training update? Those relationships identify which computation and storage costs the design changes.