Models / Architectures

Attention

Read from context. Then decide what to store, what to retrieve, and how to execute the operation.

Published 2024-09-27 · Updated 2026-10-28
On this page

A token representation needs information from other positions. Attention chooses that information using the current representation. It then combines the retrieved values. The same basic operation creates several different costs: score computation, stored context, memory traffic and retrieval decisions.

Most variants change only some of these costs. GQA shares stored keys and values. MLA changes their representation. Linear attention compresses history into recurrent state. FlashAttention changes execution, not the mathematical attention rule. Understanding these separate axes prevents misleading comparisons.

Queries, keys and values

Let X contain one hidden-state row per token. Learned projection matrices produce three activation arrays: Q = XWQ, K = XWK, and V = XWV. The matrices W are parameters. Q, K and V depend on the current input.

A query describes what a position needs. A key describes how another position can be found. A value carries the content returned from that position. This retrieval interpretation is useful, but these roles are learned rather than predefined semantic labels.

One head, with queries on rows and keys on columns
ArrayShapeOperation
Qnq × dkOne query per output position
Knk × dkOne key per accessible source position
Vnk × dvContent to combine
QKTnq × nkQuery–key dot products
PVnq × dvWeighted values
P=softmax⁡keys(QK⊤dk+M),O=PVP=\operatorname{softmax}_{\mathrm{keys}}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right),\qquad O=PV
M is an additive visibility mask: 0 for allowed positions, −∞ otherwise. Normalize each query row across its key columns.

The dot product depends on vector norms as well as their angle. A high score does not establish a human-readable relationship. Softmax converts the allowed scores into nonnegative weights that sum to one. The output is therefore a weighted average of the values.

Multiple heads use separate query projections and can read different relations. Their outputs are concatenated and projected by WO. This output projection mixes head information; it is not another attention distribution.

Token embeddings are not identical across the vocabulary. Repeated instances of the same token ID initially share the lookup vector, but position and earlier contextual layers can distinguish their hidden states. Attention Is All You Need ↗

How heads write to the residual stream

Reading values is not the final update to the token state. Each head returns a vector of width dv. The output projection maps these vectors back to model width. The residual connection adds the result to the current state.

A projection can map a 768-wide token state to a 128-wide query. In a conventional 768-wide model with 12 equal-width heads, each head instead has width 64. The quotient is a layout choice, not a rule for every architecture.

headh=PhXWV,hΔX=concat⁡(head1,…,headH)WO=∑h=1HheadhWO,hX′=X+ΔX\begin{aligned}\mathrm{head}_h&=P_hXW_{V,h}\\\Delta X&=\operatorname{concat}(\mathrm{head}_1,\ldots,\mathrm{head}_H)W_O\\&=\sum_{h=1}^H\mathrm{head}_h W_{O,h}\\X'&=X+\Delta X\end{aligned}
Row-vector convention. WV,h: dmodel × dv. WO,h: dv × dmodel is one row block of WO. Normalization and dropout are omitted here.

Concatenation followed by a linear projection therefore equals a sum of projected head outputs. Heads need not write in the same direction. For one head, WV,hWO,h has rank at most dv. This factorization concerns the value-to-residual map. The entire block is not one fixed low-rank linear map: Ph depends nonlinearly on X.

Synthetic residual-write example, with model width two. Scroll horizontally on narrow screens.
OperationResult
Token statex=[1,−1]x=[1,-1]
First head returns 2; output row [1,0][1,0]Contribution [2,0][2,0]
Second head returns 3; output row [0,−1][0,-1]Contribution [0,−3][0,-3]
Sum writes, then add residualΔx=[2,−3]\Delta x=[2,-3]; x′=[3,−4]x\prime=[3,-4]

For a phrase such as “fluffy blue creature,” attention can transfer adjective information into the creature token's state. This is a conceptual interpretation, not proof that a particular head encodes adjectives. The updated state remains a learned vector, not a dictionary definition or necessarily a static word embedding.

Vector analogies can illustrate learned directions, but directions and semantic relations need not agree across models or contexts. Stacking layers allows information already contextualized at one position to influence another. Residual layout and normalization belong to Transformer Architecture.

Why divide by √d?

For independent, zero-mean, unit-variance query and key components, each product qikiq_i k_i has variance one. Summing dk independent products gives variance dk. Division by dk\sqrt{d_k} restores variance one.

Var⁡(q⊤k)=∑i=1dkVar⁡(qiki)=dkVar⁡(q⊤kdk)=1\begin{aligned}\operatorname{Var}(q^\top k)&=\sum_{i=1}^{d_k}\operatorname{Var}(q_i k_i)=d_k\\\operatorname{Var}\left(\frac{q^\top k}{\sqrt{d_k}}\right)&=1\end{aligned}
This argument requires its independence and scale assumptions. Learned, correlated representations need not satisfy them.

Without scale control, wider heads can create larger logits. Softmax can then concentrate almost entirely on one key. Its derivatives shrink near that saturated state, making some changes difficult to learn.

∂pi∂sj=pi(δij−pj)\frac{\partial p_i}{\partial s_j}=p_i(\delta_{ij}-p_j)
At a uniform distribution, entries are small for many keys but not identically zero. A uniform row is not automatically an optimization failure.

Head width is not the only variable. Increasing the number of visible keys changes the score distribution’s extremes and the attention entropy. A fixed variance scale does not guarantee fixed entropy across context lengths.

Su Jianlin studies entropy-oriented scales such as κlog⁡ndk\kappa\frac{\log n}{d_k} times QK⊤QK^\top. This is a different objective from the standard variance argument. For causal attention, n is the active row length. Treat these scales as hypotheses to evaluate, not universal replacements.

QueryNorm, KeyNorm and temperature

QueryNorm replaces q with q∥q∥2\frac{q}{\|q\|_2}. KeyNorm replaces k with k∥k∥2\frac{k}{\|k\|_2}. Normalizing both makes scores cosine similarities before any temperature multiplier. Query magnitude can no longer control sharpness when queries are normalized.

KeyNorm alone controls the stored key norms while queries retain magnitude-dependent confidence. Su reports useful length extrapolation in tested configurations. This intuition is not a theorem about all models. Normalization, temperature and precision must be evaluated together.

Softmax prevents a raw sum from growing solely because more values are added. It does not guarantee length generalization or eliminate positional-encoding failures.

Entropy and attention scaling ↗ · Gradient-based scale analysis ↗ · Key normalization ↗

Variance, temperature and normalization

The variance argument can be derived without assuming Gaussian components. For mutually independent zero-mean qiq_i, kik_i with variances σq2\sigma_q^2, σk2\sigma_k^2, E[qiki]=0\mathbb E[q_i k_i]=0 and E[qi2ki2]=σq2σk2\mathbb E[q_i^2 k_i^2]=\sigma_q^2\sigma_k^2.

Var⁡(q⊤k)=dkσq2σk2Var⁡(c q⊤k)=c2dkσq2σk2\begin{aligned}\operatorname{Var}(q^\top k)&=d_k\sigma_q^2\sigma_k^2\\\operatorname{Var}(c\,q^\top k)&=c^2d_k\sigma_q^2\sigma_k^2\end{aligned}
Independent products make covariance terms vanish. With unit component variances and c=1dkc=\frac{1}{\sqrt{d_k}}, the scaled variance is one. Correlations add covariance terms.

Numerical overflow and attention saturation are different problems. Subtracting the row maximum makes exponentiation numerically safer; it leaves softmax probabilities unchanged. Dividing by a scale changes relative logits and therefore changes the probabilities.

For temperature T>0, p=softmax⁡(s/T)p=\operatorname{softmax}(s/T). Smaller T increases concentration for unequal scores; larger T approaches uniform weights. Equal logits remain uniform at every positive temperature. No temperature can create a preference when every score is identical.

At uniform weights over n keys, the Jacobian diagonal is n−1n2\frac{n-1}{n^2} and each off-diagonal is −1n2-\frac{1}{n^2}. These entries are not zero. Whether an objective trains well also depends on upstream derivatives, values and the loss. There is no universal optimal scale obtained by maximizing one Jacobian entry.

Entropy uses H(p)=−∑jpjlog⁡pjH(p)=-\sum_j p_j\log p_j, in nats for natural logarithms. A uniform row has H=log⁡nH=\log n. Compare the number of allowed keys, not the padded batch length. A causal row near the start has fewer keys than a row near the end.

QueryNorm uses q∥q∥2\frac{q}{\|q\|_2}; KeyNorm uses k∥k∥2\frac{k}{\|k\|_2}. Only normalizing both produces a cosine score. QueryNorm alone still permits key norms to affect scores. KeyNorm alone still permits query norms to control scale. Zero-length vectors need an explicit epsilon or rejection policy.

q^t=qt∥qt∥2,k^j=kj∥kj∥2otQueryNorm=∑j≤texp⁡(q^t⊤kj)vj∑j≤texp⁡(q^t⊤kj)otKeyNorm=∑j≤texp⁡(qt⊤k^j)vj∑j≤texp⁡(qt⊤k^j)\begin{aligned}\hat q_t&=\frac{q_t}{\lVert q_t\rVert_2},\qquad\hat k_j=\frac{k_j}{\lVert k_j\rVert_2}\\o_t^{\mathrm{QueryNorm}}&=\frac{\sum_{j\le t}\exp(\hat q_t^\top k_j)v_j}{\sum_{j\le t}\exp(\hat q_t^\top k_j)}\\o_t^{\mathrm{KeyNorm}}&=\frac{\sum_{j\le t}\exp(q_t^\top\hat k_j)v_j}{\sum_{j\le t}\exp(q_t^\top\hat k_j)}\end{aligned}
Column vectors, causal visibility including t, nonzero norms, no additional temperature. Only the normalized side changes between these operators. Stable implementations subtract the row maximum before exponentiation.
Pt=softmax⁡allowed keys(κlog⁡ntdk qt⊤Kt)P_t=\operatorname{softmax}_{\mathrm{allowed\ keys}}\left(\kappa\frac{\log n_t}{d_k}\,q_t^\top K_t\right)
Here Kt has allowed column keys, nt counts those keys, and κ is a positive scale parameter. This source-proposed entropy-oriented rule is not the standard variance scale. At nt=1 the sole allowed key still gets weight one.

Variance control, entropy across lengths and retrieval quality are separate objectives. The inherited Su analyses propose length-dependent scales and KeyNorm experiments; their findings are not universal replacements for dk\sqrt{d_k}. Measure entropy, gradients and held-out task quality together.

One masked attention row

Consider the third position of a four-token sequence. Its raw query–key products are [4, 1, −1, 3]. With dk = 4, the scaled scores are [2, 0.5, −0.5, 1.5]. The fourth key is in the future, so causal attention excludes it before normalization.

One query · four keysSynthetic example

Scores choose. Values contribute.

01 / Compare

0k14.0k21.0k3-1.0k43.0future · not masked yetvalue coordinate 1value coordinate 2 First establish the retrieval weights.
q·k = [4, 1, −1, 3]

One query compares with four keys.

Original mathematical illustration, not measured model behavior. Values are two-dimensional for visibility. Playback time is not compute latency. Full numbers and the static derivation remain in the text.
p≈[0.7662,  0.1710,  0.0629,  0]o≈[0.8290,  0.2338]\begin{aligned}p&\approx[0.7662,\;0.1710,\;0.0629,\;0]\\o&\approx[0.8290,\;0.2338]\end{aligned}
Values are v1=[1,0]v_1=[1,0], v2=[0,1]v_2=[0,1], v3=[1,1]v_3=[1,1], v4=[−1,0]v_4=[-1,0]. Rounded displayed values can have a small sum discrepancy.

The future token has exactly zero weight. Zeroing its probability after an unmasked softmax would leave the other weights summing below one. Apply the mask to logits first, or explicitly renormalize a mathematically equivalent implementation.

Compact reference implementation
# q: [nq, dk], k: [nk, dk], v: [nk, dv]
# allowed: [nq, nk]; each query has at least one allowed key
scores = (q.float() @ k.float().T) / math.sqrt(q.shape[-1])
scores = scores.masked_fill(~allowed, -float("inf"))
weights = scores.softmax(dim=-1)
out = weights @ v.float()
# Teaching reference, not a fused production kernel.

All-masked rows require an explicit policy. Softmax of only −∞ can produce NaN. Exclude padded query rows or define a safe output convention. Also specify dropout, accumulation dtype and padding masks.

Prefill, decode and the cache

Prefill processes many prompt queries together. Ordinary dense attention computes a quadratic set of query–key interactions. During autoregressive decode, a new query reads the existing prefix. The model can reuse earlier projected keys and values because those causal states do not change.

At prefix length n, one new query still reads roughly n keys and values. Caching removes repeated prefix projections and hidden-state computation; it does not make full-context retrieval constant-time. Over a growing generation, the cumulative retrieval work remains quadratic in generated length.

NKV=B L n hKV(dk+dv)N_{\mathrm{KV}}=B\,L\,n\,h_{\mathrm{KV}}(d_k+d_v)
B: batch size. L: cached layers. n: cached positions. Multiply by bytes per element for unquantized storage, excluding allocator and other overhead.

For 32 layers, 32 query heads, dk = dv = 128 and 8,192 positions, MHA stores 4 GiB in BF16 for batch one. Eight KV heads reduce this to 1 GiB. One KV head reduces it to 128 MiB. This example holds width, length and layer count fixed; it is not a throughput benchmark.

Same queries. Different amounts of stored KV.
MHA · 32 KV heads4 GiB
GQA · 8 KV heads1 GiB
MQA · 1 KV head128 MiB

The cache design affects both capacity and decode bandwidth. A model that fits can still decode slowly if each step transfers too much cached state. Prefill and decode therefore need separate measurements. KV cache and serving →

MHA → MQA → GQA

Multi-head attention (MHA) gives each query head its own keys and values. This is flexible, but every position stores all KV heads. Multi-query attention (MQA, 2019) retains many query heads while sharing one KV head. The decode query still differs by head, but the retrieval database is shared.

Grouped-query attention (GQA, 2023) uses several KV groups. Each query head reads its assigned group. GQA sits between full independence and complete sharing; MQA is its one-group limit.

The cache/head-sharing branch
DesignQuery headsKV headsMain change
MHAhQhQIndependent per-head KV
MQAhQ1All query heads share KV
GQAhQg, between 1 and hQQuery heads share within groups

Head sharing can restrict representational freedom. The quality–cache tradeoff depends on training, tasks and head dimensions. Do not infer a guaranteed quality ranking from group count. Also do not explicitly replicate shared KV tensors in memory and then expect the intended savings.

MQA: Fast Transformer Decoding ↗ · GQA ↗

MLA: compress the cached representation

Head sharing changes how many KV groups exist. Multi-head latent attention (MLA, DeepSeek-V2, 2024) instead stores a shared compressed representation c. Learned maps recover richer per-head keys and values. The useful inference trick avoids materializing those expanded cached tensors.

ci=xiWc,ki=ciWk,vi=ciWvqtki⊤=xt(WqWk⊤)ci⊤\begin{aligned}c_i&=x_iW_c,\quad k_i=c_iW_k,\quad v_i=c_iW_v\\q_t k_i^\top&=x_t(W_qW_k^\top)c_i^\top\end{aligned}
Row-vector convention, one head, without position-dependent rotations. Wq: dmodel × dk; Wk: r × dk; Wc: dmodel × r.

Absorb WkT into the query projection. The query can now score cached c directly. Likewise, move the value expansion into the output projection after the weighted latent sum. This is an algebraic rearrangement under the stated conditions, not an approximation from dropping keys.

Expand once after reading, not once per cached token

Each head has its own weights and latent read. Its value expansion and output block are linear, so their product can follow the weighted sum.

at,i(h)=softmax⁡i(st,i(h))ot(h)WO,h=(∑iat,i(h)ciWV,h)WO,h=(∑iat,i(h)ci)(WV,hWO,h)Δxt=∑hot(h)WO,h\begin{aligned}a_{t,i}^{(h)}&=\operatorname{softmax}_{i}(s_{t,i}^{(h)})\\o_t^{(h)}W_{O,h}&=\left(\sum_i a_{t,i}^{(h)}c_iW_{V,h}\right)W_{O,h}\\&=\left(\sum_i a_{t,i}^{(h)}c_i\right)(W_{V,h}W_{O,h})\\\Delta x_t&=\sum_h o_t^{(h)}W_{O,h}\end{aligned}
Row-vector convention. c: width r; WV,h: r × dv; WO,h: dv × dmodel. The fused output map has shape r × dmodel. Head-specific weights do not become one shared distribution.

Use two cached row vectors and one head. Fix its attention weights at 0.25 and 0.75. The expanded path forms both values before averaging. The latent path averages the cached vectors first, then applies the fused value/output map.

Synthetic two-token value/output identity; weights fixed at 0.25 and 0.75
PathOperationResult
Expand cached vectorsc1=[1,0],c2=[0,2]c_1=[1,0],\quad c_2=[0,2]
WV=[1230]W_V=\begin{bmatrix}1&2\\3&0\end{bmatrix}
v1=[1,2],v2=[6,0]v_1=[1,2],\quad v_2=[6,0]
Read expanded values, then project0.25v1+0.75v2=[4.75,0.5]0.25v_1+0.75v_2=[4.75,0.5]
WO=[1002]W_O=\begin{bmatrix}1&0\\0&2\end{bmatrix}
[4.75,0.5]WO=[4.75,1][4.75,0.5]W_O=[4.75,1]
Read latent vectors, then project0.25c1+0.75c2=[0.25,1.5]0.25c_1+0.75c_2=[0.25,1.5]
WVWO=[1430]W_VW_O=\begin{bmatrix}1&4\\3&0\end{bmatrix}
[0.25,1.5](WVWO)=[4.75,1][0.25,1.5](W_VW_O)=[4.75,1]

Both paths return the same vector. Only the placement of the linear maps changes. In a long cache, the latent path avoids expanding every stored token for this read. Scroll the comparison horizontally on a narrow screen.

Keep the same masks, weights and parameters in both paths. The displayed identities omit biases and dropout. A nonlinear operation on expanded keys or values generally prevents this simple absorption. Finite-precision multiplication order can change rounding; compare numerical tolerances, not bitwise equality.

Latent caching saves expanded KV storage, but attention still retrieves previous latent entries. It is not constant-size recurrent memory. Fused projections and kernels determine achieved latency. DeepSeek-V2: full MLA formulas ↗

GQA already has a low-dimensional view

Concatenate the g groups’ keys and values into c = [k¹,…,kᵍ,v¹,…,vᵍ]. Then c = xWc, with dimension g(dk + dv). That dimension can already be below the model width.

Thus “MLA is low-rank” is not the complete distinction. GQA splits and repeats grouped KV projections. MLA learns latent-to-head maps and exploits their inference factorization. Effective head width under a fixed cache budget can matter as much as group count. This is a design observation, not a universal quality guarantee.

Why RoPE complicates the identity

Rotary positional encoding inserts position-dependent rotations into queries and keys. The score contains a relative-position matrix between Wq and WkT. It can no longer be absorbed into one fixed query projection.

qtki⊤=xtWqRt−iWk⊤ci⊤q_t k_i^\top=x_tW_qR_{t-i}W_k^\top c_i^\top
The rotation sign follows the selected row-vector/RoPE convention. The relevant point is dependence on the relative position.

A decoupled design splits content and rotary coordinates. The unrotated content path uses the latent factorization. A smaller positional key remains separately cached. Its storage is therefore roughly r + dRoPE elements per position, not just r. The actual layout can include additional normalization or quantization state.

GLM-5’s existing report note records a 512-dimensional KV latent and a shared 64-dimensional rotary key. Each query head has 192 unrotated and 64 rotary coordinates. A configuration’s “64 KV heads” does not by itself establish ordinary MHA storage.

DeepSeek-V2 ↗ · MLA analysis, part 1 ↗ · MLA analysis, part 2 ↗ · Positional encoding →

Local, global and cross-attention

The previous designs change stored representations. Connectivity is a separate choice: which positions can a query access? A causal sliding window of width w allows positions from max(0,t−w+1) through t. With fixed w, the attention work grows roughly as nw rather than n².

Stacked local layers expand the receptive field, but a distant token may require many propagation steps. Periodic full-context layers create direct long-range access. “Global” can mean a full attention layer or a designated token connected to every position, as in Longformer-style patterns. These are not the same layout.

MAI-Thinking-1 uses five local layers for each global layer. Its local window is 512 with RoPE base 10,000; global layers use no positional encoding. The recorded configuration has eight KV heads, head dimension 128, and RMSNorm on queries and keys. This is a tested recipe, not evidence that global RoPE always hurts.

Key-as-value is another independent storage choice

The Gemma 4 note records local/global interleaving and key-as-value attention in selected larger variants. Setting V=KV=K removes an independent value representation. Keys now serve both retrieval and returned content, which constrains the model.

Gemma 4 uses four local layers per global layer in E2B and five elsewhere. Global rotary fraction is p=0.25. The 12B, 26B-A4B and 31B global layers use key-as-value attention; do not apply this rule to every family member.

The specified unrotated-plus-positional cache representation reduces global KV entries by 37.5%. This is not total model memory. Gemma’s cache calculation and edge-model distinctions →

Cross-attention changes the source

Self-attention derives Q, K and V from the same sequence. Cross-attention derives queries from one sequence and keys/values from another. The score matrix has nq rows and nk columns. Translation, retrieval and multimodal models use this pattern. Different modalities are not required.

Longformer ↗ · MAI recipe → · Gemma 4 recipe →

Linear attention: a different memory

For an unmasked operation without softmax, associativity gives (QKT)V = Q(KTV). Computing KTV first avoids the n × n intermediate. This rearrangement does not hold for ordinary softmax because its nonlinear normalization sits between the products.

Kernelized linear attention uses feature maps φ(q), φ(k). Some maps approximate the exponential softmax kernel; others define a different operator. In causal form, the model accumulates a matrix S and a normalizer vector z.

St=St−1+ϕ(kt)vt⊤zt=zt−1+ϕ(kt)ot=ϕ(qt)⊤Stϕ(qt)⊤zt\begin{aligned}S_t&=S_{t-1}+\phi(k_t)v_t^\top\\z_t&=z_{t-1}+\phi(k_t)\\o_t&=\frac{\phi(q_t)^\top S_t}{\phi(q_t)^\top z_t}\end{aligned}
φ has r features. S is r × dv. Positive kernel features and an explicit small-denominator policy support normalized reads.

Here φ(k) and φ(q) are column feature vectors. The state is a matrix, not a list of original token values. For fixed feature and value dimensions, state size does not grow with context length. Computation instead scales with those feature dimensions. A large state can still be expensive; “linear in length” is not a claim that it wins at every sequence length.

The cost reduction changes the memory representation. All history must fit into a fixed-size state, so exact retrieval of individual old tokens can become difficult. Copying, induction-like retrieval and long code references need targeted evaluations, not just average language-model loss.

A global low-rank argument alone is insufficient: a causal mask can make a triangular attention matrix full rank. The important restriction is the recurrent state’s representational capacity and update rule. A short causal convolution captures local order and patterns before the recurrent update. It does not limit the state to that local window.

Transformers are RNNs, 2020 ↗ · Linear-attention derivation ↗

What linear complexity holds fixed

The reassociation (QKT)V = Q(KTV) changes multiplication order only for the unnormalized unmasked operator. With key width dk and value width dv, the two large contractions cost O(ndkdv) rather than O(n²(dk+dv)). Feature construction has additional cost.

A causal kernel recurrence with r features stores rdv matrix entries plus r normalization entries per head. Each step costs O(rdv) for update and read. The phrase “linear in sequence length” holds r and dv fixed. Increasing feature count to improve approximation can change practical cost substantially.

Keep the denominator when compressing history

Replacing softmax requires a declared similarity kernel. A finite feature map can define a new kernel; it does not automatically reproduce the exponential kernel. Put the standard scale inside the kernel when approximating softmax.

κ(q,k)=ϕ(q)⊤ϕ(k)orκ(q,k)≈exp⁡(q⊤kdk)ot=∑j≤tκ(qt,kj)vj⊤∑j≤tκ(qt,kj)=ϕ(qt)⊤(∑j≤tϕ(kj)vj⊤)ϕ(qt)⊤(∑j≤tϕ(kj))\begin{aligned}\kappa(q,k)&=\phi(q)^\top\phi(k)\quad\text{or}\quad\kappa(q,k)\approx\exp\left(\frac{q^\top k}{\sqrt{d_k}}\right)\\o_t&=\frac{\sum_{j\le t}\kappa(q_t,k_j)v_j^\top}{\sum_{j\le t}\kappa(q_t,k_j)}=\frac{\phi(q_t)^\top\left(\sum_{j\le t}\phi(k_j)v_j^\top\right)}{\phi(q_t)^\top\left(\sum_{j\le t}\phi(k_j)\right)}\end{aligned}
Column feature/value vectors; output shown as a row. Nonnegative similarities and a positive denominator give a normalized weighted average. The equality rearranges the chosen kernel, not arbitrary softmax.

Initialize S and z to zero. Add the current key–value write before reading when the causal mask includes the current token. For strict past-only attention, read before writing. Reset state at independent sequence boundaries. A zero denominator needs an explicit skip, rejection or fallback policy.

Synthetic kernel memory: keys and values both [1,0], [0,1], [1,1]
Visible prefixS: sum of outer productsz: sum of keysRead with feature query [2,1]
First token[[1,0],[0,0]][1,0][1,0]
First two[[1,0],[0,1]][1,1][23,13][\frac23,\frac13]
All three[[2,1],[1,2]][2,2][56,23][\frac56,\frac23]
[2,1]S=[5,4],[2,1]z=6o=[56,46]=26[1,0]+16[0,1]+36[1,1]\begin{aligned}[2,1]S&=[5,4],\qquad [2,1]z=6\\o&=\left[\frac56,\frac46\right]=\frac26[1,0]+\frac16[0,1]+\frac36[1,1]\end{aligned}
The state read and direct weighted sum agree exactly. Inputs are feature vectors already; this example defines a dot-product kernel, not a measured softmax approximation.

The denominator preserves normalized reads as the prefix grows. Omitting z produces the unnormalized operator and changes its behavior. Fixed inference state also does not imply constant total training memory: a naive backward pass can retain every intermediate state.

Linear Transformers: kernel reassociation and causal state ↗. Feature construction, denominator policy and the backward implementation belong to the complete method.

Explicit history: (x1,…,xt)⟶query-specific retrievalRecurrent memory: St−1+writet⟶St⟶readtShort convolution: x~t=∑τ=0w−1aτxt−τ\begin{aligned}\text{Explicit history: }&(x_1,\ldots,x_t)\longrightarrow\text{query-specific retrieval}\\\text{Recurrent memory: }&S_{t-1}+\mathrm{write}_t\longrightarrow S_t\longrightarrow\mathrm{read}_t\\\text{Short convolution: }&\tilde x_t=\sum_{\tau=0}^{w-1}a_\tau x_{t-\tau}\end{aligned}
Conceptual data paths, not a speed benchmark. Convolution uses a declared causal boundary policy; depthwise implementations learn coefficients per channel.

The short convolution provides local order-sensitive mixing before compressed memory. It can handle nearby patterns without requiring the global state to encode every local relation. It does not restore exact retrieval from all historical tokens or restrict the recurrent state to only w positions.

For a fixed set of allowed keys, one softmax weight approaches one as its score gap over the others grows. A finite feature map changes this concentration behavior. The resulting retrieval limits depend on the chosen kernel and update rule, not only on matrix rank.

Evaluate copying, induction, code dependencies and long-context retrieval separately. A compressed state can perform well on average loss yet miss a particular old token. Compare complete architectures at matched training and inference conditions rather than treating all recurrent operators as one quality class.

Delta updates and bounded decay

Simple additive memory keeps writing new key–value associations, even when they conflict with existing content. A delta update first predicts the value already stored for a key. It writes the prediction error instead of the full value.

v^t=St−1⊤ktSt=St−1+βtkt(vt−v^t)⊤\begin{aligned}\hat v_t&=S_{t-1}^\top k_t\\S_t&=S_{t-1}+\beta_t k_t(v_t-\hat v_t)^\top\end{aligned}
Simplified ungated delta rule. S: dk × dv. β is a write-step size; normalization and its bounds matter for stability.

For a unit-length key, β=1\beta=1 corrects that key’s current prediction exactly in this isolated ungated update. Other correlated keys can still interfere. L2-normalized keys control update magnitude; normalized queries control read magnitude. Normalization alone does not guarantee long-run stability.

Gated variants also decay parts of the state. The exact order of decay, prediction and write depends on the recurrence. Do not interchange these operations when reproducing a specific kernel.

Why a decay bound affects the kernel

gt=−5 sigmoid⁡(eAzt),αt=egtg_t=-5\,\operatorname{sigmoid}(e^A z_t),\qquad\alpha_t=e^{g_t}
Kimi K3’s recorded bounded log-decay parameterization. For finite inputs, −5 < gt < 0 and exp(−5) < αt < 1.

Very small decay factors can create large reciprocal rescaling values in chunked algorithms. K3 bounds each step’s log decay to make more tiles suitable for dense Tensor Core operations. A per-step bound does not bound the reciprocal of an arbitrarily long product; chunk size and accumulation remain important.

A bound closer to zero restricts rapid forgetting. A much more negative bound recreates numerical difficulties. This is a model–kernel co-design choice, not only an architectural hyperparameter.

K3 combines 69 KDA layers with 24 global Gated MLA layers. Its three-to-one pattern plus a final global layer separates economical recurrent accumulation from sharp token retrieval. Its NoPE global layers do not require RoPE interpolation. This does not by itself guarantee length extrapolation.

GLM-5.3-Flash uses 34 KDA and 11 sparse MLA blocks. Its KDA blocks include width-four causal depthwise convolution, 64 heads of width 128, L2-normalized Q/K, and gated normalized outputs. Its global MLA blocks have KV rank 512 and zero rotary dimensions.

K3 report details → · GLM-5.3 implementation details →

Qwen: decay, predict the stored value, then correct it

A fixed-size recurrent memory avoids a growing KV cache, but it cannot preserve every original token independently. Qwen3.8-Flash-Next uses three Gated DeltaNet (GDN) layers per retrieval layer. The retrieval layers use full attention initially, then Qwen Sparse Attention (QSA) after continued pretraining. This is a hybrid, not a claim that recurrent memory replaces exact retrieval.

S~t−1=αtSt−1et=vt−S~t−1TktSt=S~t−1+βtktetTyt=StTqt\begin{aligned}\widetilde S_{t-1}&=\alpha_tS_{t-1}\\e_t&=v_t-\widetilde S_{t-1}^{\mathsf T}k_t\\S_t&=\widetilde S_{t-1}+\beta_tk_te_t^{\mathsf T}\\y_t&=S_t^{\mathsf T}q_t\end{aligned}
Per head: S is dk × dv, q and k are dk-vectors, and v and e are dv-vectors. Decay precedes the prediction and correction. Both scalar gates lie between zero and one.

For a scalar illustration, let the old state be 2, the key be 1, decay be 0.5, value be 3 and write strength be 0.25. Decay gives 1; prediction error is 2; the new state is 1.5. Predicting before decay would give a different result. Correlated keys can still interfere in a matrix state.

qt=L2Norm⁡(SiLU⁡(ShortConv⁡(Wqxt)))kt=L2Norm⁡(SiLU⁡(ShortConv⁡(Wkxt)))vt=SiLU⁡(ShortConv⁡(Wvxt))βt=σ(Wβxt)αt=exp⁡[−exp⁡(A)softplus⁡(Wαxt+bα)]\begin{aligned}q_t&=\operatorname{L2Norm}(\operatorname{SiLU}(\operatorname{ShortConv}(W_qx_t)))\\k_t&=\operatorname{L2Norm}(\operatorname{SiLU}(\operatorname{ShortConv}(W_kx_t)))\\v_t&=\operatorname{SiLU}(\operatorname{ShortConv}(W_vx_t))\\\beta_t&=\sigma(W_\beta x_t)\\\alpha_t&=\exp[-\exp(A)\operatorname{softplus}(W_\alpha x_t+b_\alpha)]\end{aligned}
The short convolution is causal and depthwise. L2 normalization controls q/k magnitude before recurrence; it is not a softmax over history.

The output is RMS-normalized, multiplied by a sigmoid output gate, and projected. Qwen changes the original GDN SiLU output gate to a bounded sigmoid. The model uses zero-centered RMSNorm throughout. These are implementation choices with reported gains, not interchangeable activation names.

The hybrid ablation uses 28-layer 25B-A3B MoEs: 400B tokens at 4K, then 80B at 32K. Both hybrids retain one full-attention layer in four; the sliding-window alternative uses a window of 128. Across nine selected benchmarks, mean scores are 49.87 for full attention, 51.15 for the SWA hybrid and 53.81 for GDN. GDN wins eight comparisons against full attention and seven against SWA. The comparison supports this tested hybrid; it does not identify the cause of every individual score change.

RoPE and NoPE look similar during pretraining here. After post-training, NoPE produces substantially more endless generation, so Qwen retains RoPE in retrieval layers. This does not contradict successful NoPE recipes in other models. Positional encoding choices → · Late-stage checks →.

Qwen3.8-Next architecture report, §2.1.1, pp. 3–5 (26 August 2026) ↗.

QSA: select compressed blocks, attend to original tokens

Sparse attention needs a selector. A token-level selector can itself become expensive at long context. QSA reduces that cost by compressing only the keys used for selection. Core attention still reads original token representations from selected blocks.

  1. Project a query for each token and keys for the indexer.
  2. Average each complete group of four keys, then RMS-normalize the pooled key.
  3. Apply partial RoPE after pooling. A block uses its starting position; a query keeps its token position.
  4. Sum ReLU query–key similarities across four indexer query heads, with one shared key head.
  5. Select up to 512 complete blocks. Expand them into at most 2,048 original positions, then include the unfinished current block.
  6. Compute sparse core attention over those original tokens.
pb=br,r=4k^b=RMSNorm⁡(1r∑j=pbpb+r−1WKxj)Iib={∑h=1HReLU⁡(⟨qih,k‾b⟩),pb+r−1≤i−∞,otherwiseBi=TopK⁡512(Ii,:)\begin{aligned}p_b&=br,\quad r=4\\\widehat k_b&=\operatorname{RMSNorm}\left(\frac1r\sum_{j=p_b}^{p_b+r-1}W_Kx_j\right)\\I_{ib}&=\begin{cases}\sum_{h=1}^{H}\operatorname{ReLU}(\langle q_i^h,\overline k_b\rangle),&p_b+r-1\le i\\-\infty,&\text{otherwise}\end{cases}\\B_i&=\operatorname{TopK}_{512}(I_{i,:})\end{aligned}
H=4 indexer query heads. The indexer head width is 128; partial RoPE uses 64 dimensions. The block must be fully observed before selection; incomplete tail tokens use a separate always-included path.

Pooling before rotation avoids averaging vectors with different rotary phases. The final incomplete block has zero to three tokens, so the 2,048-token selection budget is not a strict bound on the complete core-attention set. At short prefixes fewer complete blocks exist. Any implementation must mask future tokens and handle an empty set of complete blocks.

Follow block selection without losing causality

Synthetic illustration: 12 keys, one query head, four-token blocks and one selected block. It omits projections, learned normalization gains and RoPE; it is not a quality or latency experiment. T marks tail tokens; × marks masked future tokens; ✓ marks selected complete-block tokens.

Step 1/4. Identify complete causal blocks. The unfinished current block remains directly accessible.

Scores are not computed yet. Tail: 8, 9, 10.

The production indexer has four query heads, selects up to 512 complete blocks, and uses partial RoPE. Its tail contains at most three tokens. The static procedure above defines the same causal boundary without requiring playback.

Teach the selector, then adapt the backbone

QSA is introduced at 256K continued-pretraining context, not used from the first token of the main run. The teacher sums dense softmax distributions across attention heads and L1-normalizes. It then max-pools token probabilities within each block and normalizes again. Key vectors use average pooling; teacher probabilities use max pooling. These are deliberately different operations.

a‾ib=max⁡j∈baij,a^ib=a‾ib∑b′a‾ib′,Lindex=1N∑iDKL ⁣(a^i ∥ softmax⁡(Ii))\overline a_{ib}=\max_{j\in b}a_{ij},\qquad \widehat a_{ib}=\frac{\overline a_{ib}}{\sum_{b'}\overline a_{ib'}},\qquad L_{\rm index}=\frac1N\sum_iD_{\rm KL}\!\left(\widehat a_i\,\|\,\operatorname{softmax}(I_i)\right)
N counts query tokens. Only complete causal blocks contribute. A query with no complete block needs an explicit empty-loss policy; the report does not specify that implementation detail.
QSA conversion stages; exposure is processed tokens, not unique corpus size
StageTrainable partsSteps / LR / batchExposure
Dense distillationIndexer only; backbone attention stays dense1,000; 10⁻³; 8 × 256K sequencesApproximately 2B
Sparse adaptationBackbone and indexer8,000; 2.5×10⁻⁵; 96 × 256K sequencesApproximately 200B

During sparse adaptation, compute the KL loss only over selected complete blocks. Renormalize the teacher on that selected support before comparing distributions. The indexer does not receive the dense objective over every unselected block in this stage. The report fuses sparse attention and the KL loss without materializing all intermediate tensors.

Directly using the initialized sparse selector loses RULER quality; joint adaptation recovers it. The final reported LM-loss gap is on the order of 10⁻⁴. In Table 2, short-task mean accuracy rises from 75.9 to 76.8; seven of eight scores improve, while MMMLU falls from 81.8 to 81.1. This is a measured result, not a proof that sparsity always improves quality.

Table 3: retrieval scores; full attention and QSA within the same hybrid backbone
SettingFull attentionQSA
RULER ≤128K99.8499.89
RULER 128–256K99.8199.62
RULER 256–512K97.6598.95
RULER 512K–1M90.0893.00
8-needle MRCR 128K97.1495.98
8-needle MRCR 256K94.2093.00
8-needle MRCR 512K30.6640.53
8-needle MRCR 1M20.7126.44

RULER remains strong at 1M while 8-needle MRCR is only 26.44. A supported context length does not mean reliable retrieval on every task. Compression-factor ablations at 35B-A3B favor four-token blocks; larger blocks lose fine detail. Four indexer heads balance quality and speed. Sharing selectors across global layers performs worse at comparable indexer savings in this hybrid, where three recurrent layers separate adjacent global layers.

With fixed compression ratio r, indexer prefill remains quadratic: O(n2/r)O(n^2/r). Sparse core attention is approximately O(nK)O(nK) at fixed K. Compression reduces the selector constant; it does not make the whole algorithm asymptotically linear. Kernel measurements and systems → · Reuse selection during MTP →.

Qwen3.8-Next architecture report, §2.1.2, Tables 2–4, Figures 3–6, pp. 5–9 (26 August 2026) ↗.

FlashAttention and online softmax

Linear attention changes the operator. FlashAttention keeps the dense softmax rule but changes where intermediate results live. A conventional implementation writes scores and probabilities to high-bandwidth memory (HBM). Those n × n arrays create expensive traffic.

FlashAttention tiles Q, K and V into smaller on-chip memory. It maintains compact row statistics and an output accumulator rather than storing the complete probability matrix. Dense arithmetic is still quadratic; avoiding intermediate traffic can nevertheless improve runtime substantially.

Combine blocks without losing normalization

For a score block b, keep its maximum mb, exponential sum ℓb, and weighted value sum ub. When a later block has a larger maximum, rescale the existing accumulators before combining them.

m′=max⁡(m,mb)ℓ′=em−m′ℓ+emb−m′ℓbu′=em−m′u+∑j∈besj−m′vjo=u′ℓ′\begin{aligned}m'&=\max(m,m_b)\\\ell'&=e^{m-m'}\ell+e^{m_b-m'}\ell_b\\u'&=e^{m-m'}u+\sum_{j\in b}e^{s_j-m'}v_j\\o&=\frac{u'}{\ell'}\end{aligned}
u is an unnormalized value-vector accumulator. Process only allowed keys; handle empty/all-masked tiles explicitly.

The final result equals the direct softmax operation in real arithmetic. Floating-point ordering can cause small differences. A low-precision approximation such as an FP8 path introduces additional numerical considerations; “exact attention” does not mean bitwise equality for every kernel.

Why backward recomputes instead of saving everything

The forward pass saves compact statistics needed by backward. Backward recomputes tiles instead of storing the complete score and probability arrays. Extra arithmetic can be cheaper than HBM traffic. Attention output and inputs still require linear storage, and the rest of the model has its own activations.

Kernel evolution is not a new attention architecture
VersionDesign focusSource
FlashAttention-1 · 2022IO-aware tiling and recomputationPaper ↗
FlashAttention-2 · 2023Better work partitioning and less non-matmul overheadPaper ↗
FlashAttention-3 · 2024Hopper asynchronous execution, overlap and low precisionPaper ↗

FlashAttention-4: when faster matmul exposes another bottleneck

The 2026 FlashAttention-4 design targets Blackwell’s uneven resource scaling. Tensor Core throughput grows faster than exponential throughput and shared-memory bandwidth. Faster matrix multiplication therefore exposes softmax in forward and memory movement in backward.

The forward pipeline alternates query tiles and separates correction work. It combines hardware exponentials with polynomial evaluation on FMA units. Conditional rescaling reduces repeated vector work while preserving the normalization bookkeeping. Approximate exponentials still require numerical validation.

Backward uses tensor memory and cooperating two-CTA matrix operations to reduce shared-memory traffic and atomic reductions. Causal and variable-length workloads also need balanced tile scheduling. The implementation uses CuTe-DSL. These changes target specific hardware resources, not a new attention distribution. FlashAttention-4 design ↗

Hardware support and kernel interfaces change. Select a kernel for the actual GPU, head width, mask, dtype and gradient requirements. Do not interpret the version number as a universal performance ranking. The next sections give a worked accumulator and the hardware/API contracts.

Watch the normalization reference change

The accumulator is easiest to inspect when the reference maximum changes. Use four scores [0,3,−1,4] and values [1,0], [0,1], [1,1], [−1,0]. Each tile contains one key. This is a numerical demonstration, not a GPU schedule or performance trace.

First two tiles, in real arithmetic
After tilemℓu
1: score0, value[1,0]01[1,0]
2: score3, value[0,1]3exp(−3)+1[exp(−3),1]

Tile2 changes the maximum from0 to3. Multiplying the old sums by exp(−3) expresses both tiles relative to the new maximum. Without that rescaling, the algorithm incorrectly treats the two scores as equally weighted.

Stopped online-softmax state
QuantityValueMeaning
Visible scoresnoneOne-key tiles in this synthetic example
Running maximum m−∞Reference for exponentials
Old-state rescale0.0000No previous state
Exponential sum ℓ0.0000Unnormalized probability mass
Weighted accumulator u[0.0000, 0.0000]Not yet divided by ℓ
Output u/ℓnot definedWeighted mean over the processed prefix

Scenario=rising; tiles=0; m=−∞; l=0.0000; u=[0.0000,0.0000]. No key has been processed.

Every stopped state remains readable. After all four keys, u/ℓ equals direct softmax followed by value aggregation. Reordering score/value pairs preserves the result in real arithmetic; this control changes only score order while values stay fixed, so its final answer can differ.

Hardware paths and kernel contracts

After avoiding quadratic intermediates, kernel performance still depends on how threads share work. FlashAttention-2 reduces non-matmul overhead and improves block/warp partitioning. More parallel work is useful only when register and shared-memory demand allow enough resident execution.

FlashAttention-3 uses Hopper's Warpgroup Matrix Multiply-Accumulate (WGMMA) and Tensor Memory Accelerator (TMA). Producer warps move tiles while consumer warps compute. Pingpong scheduling overlaps one warpgroup's softmax with another's matrix multiplication; further overlap within a warpgroup costs registers.

Its FP8 path uses a random-sign Hadamard transform to distribute activation outliers before quantization. An orthogonal transform applied consistently to Q and K preserves their dot products before rounding. Low-precision rounding still introduces error. These mechanisms do not imply an end-to-end speedup for every workload. FA3 design and scoped benchmarks ↗

Installation facts below were checked against the official repository on6 October2026. They are implementation requirements, not permanent properties of the algorithm.

Official NVIDIA implementation snapshot
PathRecorded scope
FA2Ampere/Ada/Hopper, CUDA12+, FP16/BF16; head dimensions up to256 with backward/dropout caveats
FA3Hopper H100/H800, CUDA12.3+; FP16/BF16 forward/backward and FP8 forward in the documented beta
FA4CuTeDSL line for Hopper/Blackwell; separate flash-attn-4 package
# Official FA4 interface; requires a supported installed GPU stack.
# q: [batch, nq, query_heads, head_dim]
# k, v: [batch, nk, kv_heads, head_dim]
from flash_attn.cute import flash_attn_func
out = flash_attn_func(q, k, v, causal=True)
# Interface illustration, not executed by this website.

Check the selected API's causal alignment when query and key lengths differ. Confirm packed-sequence boundaries, head grouping, dropout, backward determinism and cache updates. Passing fewer KV heads requires compatible grouping; do not silently expand the cache.

The official repository also documents ROCm paths; NVIDIA requirements above do not describe every backend. Pin the package and benchmark the actual supported path. Official installation and API reference ↗

A framework call can choose a different kernel or fall back. Inspect the trace in Profiling and Kernel Optimization. Compare against a higher-precision reference with the same mask and scale. Measure prefill, decode, memory and end-to-end latency separately. Kernel improvements cannot remove an unrelated bottleneck.

Source builds and packaging can fail outside supported GPU/software stacks. During single-token decode, reading the growing KV cache can dominate even when score intermediates are no longer stored. Memory and compute limits → · Low-precision attention errors → · Distributed context ownership →

Sparse retrieval and index sharing

A sparse attention layer retrieves only selected context positions. This reduces the main value aggregation, but selecting positions can remain expensive. Separate the indexer cost from the main attention cost.

GLM-5’s DSA selects 2,048 positions. Its lightweight indexer has 32 heads of dimension 128, ReLU scores, a learned head mixture and causal top-k. Main attention scales with the selected count; the indexer still scans the prefix. Sparse selection can omit relevant keys, so it is not mathematically equal to dense attention.

Dense-to-sparse conversion and RL behavior

The existing GLM-5 source records 1,000 indexer warm-up steps with the backbone frozen. Each step uses 14 sequences of length 202,752, with learning rate decreasing from 5e−3 to 2e−4. Joint sparse adaptation then uses 20B tokens at learning rate 1e−5.

The reported 1.5–2× lower long-sequence attention compute is source-specific, not a universal end-to-end speedup. During RL, nondeterministic top-k created train/inference mismatch and entropy collapse. The recorded recipe used deterministic top-k and froze the indexer.

Share decisions or compress candidates?

GLM-5.2 IndexShare reuses one selected-index list across a four-layer group. Each layer still computes its own queries, attention weights, values and outputs. The model was continued-trained with sharing; it is not an inference-only switch for an unchanged checkpoint.

GLM-5.3 IndexPool instead pools four neighboring indexer keys before scoring. Per-dimension softmax gates produce each pooled key. Selected pools expand back into original token indices, so main attention still reads raw values.

Different parts of sparse retrieval
MethodWhat is shared/compressed?What remains distinct?
IndexShareSelected positions across layersLayer queries, weights and aggregation
IndexPoolCandidates inside one indexerRaw KV entries used by main attention
CSA2 ReindexGlobal cache and indexer keysFresh selected positions
CSA2 ReuseCache and selected positionsMain queries and layer-local attention

With four-token pools and a target of 2,048 raw positions, IndexPool selects up to 512 pools. The incomplete current pool contributes up to three extra visible positions. Main attention can therefore see up to 2,051 indices. A fourfold reduction in indexer candidates does not give fourfold main-attention savings.

Share memory without sharing every computation

DeepSeek-V4.1-Flash’s CSA2 distinguishes Full, Reindex and Reuse modes. Full constructs global memory and selects entries. Reindex keeps memory but recomputes selection. Reuse keeps both. Every block retains its own local window and main queries.

The first decoder scan selects 512 entries and a candidate pool of up to 2,048 eight-position blocks. Later reindexers search that 16,384-position pool. A relevant position excluded from the pool cannot be recovered later. The first scan still grows with context length.

Prefill skipping is a further architectural change

V4.1 has 20 causal encoder and 20 decoder blocks. Decoder global memory comes from encoder outputs. Most prompt tokens can skip upper-block computation, while generated tokens use all 40 blocks. Local decoder state is reconstructed by bounded replay of 128 positions.

That replay is not exact full-depth reconstruction. Stacked local layers can depend on a longer history. The report records post-training adaptation and small measured quality impact, not equality for all inputs.

The reported 890 bytes per input token describe the global cache after sharing, compression and FP4 storage. At one million tokens this is 890 MB decimal, about 0.83 GiB, not total request memory. Local caches remain FP8, and model weights, workspaces and activations are additional.

GLM-5 and IndexShare → · IndexPool → · CSA2 and causal encoder–decoder →

Implementation and diagnostics

Start from the failure you need to solve. A cache-capacity failure, HBM-traffic failure and retrieval-quality failure require different interventions. A model can combine several methods, but each combination needs compatible masks, layouts and kernels.

Choose the axis before choosing the acronym
Observed problemTechniques to investigateWhat to verify
Growing decode cacheGQA/MQA, MLA, quantization, local layersCapacity, bandwidth and retrieval quality
Quadratic score/probability trafficFlashAttentionSupported masks, backward and numerical tolerance
Expensive full-context accessWindows, sparse retrieval, recurrent/hybrid attentionIndexer overhead, recall and exact-token tasks
Long-context attention entropy driftScale, Q/K normalization, position designEntropy by row length and held-out quality
  1. Shapes. Query heads, KV groups, key/value widths and latent dimensions.
  2. Visibility. Causal and padding masks, packed sequences, cache offsets and empty rows.
  3. Numerics. Stable exponentials, normalization denominators, accumulation dtype and recurrence ordering.
  4. Quality. Language-model loss plus retrieval, copying, code and context-length evaluations.
  5. Performance. Measure prefill and decode separately at actual batch sizes, lengths and hardware.
  6. Reproducibility. Top-k ties, deterministic paths, checkpointed state and train/inference agreement.

Do not compare FLOPs with throughput as if they were the same quantity. Sparse indexers, small matrix batches, memory movement and scheduling can dominate after the headline arithmetic decreases. Roofline reasoning →

Chronology: parallel research branches

These milestones explain distinct bottlenecks, not one sequence of replacements. Linear attention predates GQA and MLA. FlashAttention can execute a compatible head-sharing design without changing that design’s operator.

Selected first-publication years
YearBranchMechanism
2017BaselineTransformer multi-head scaled dot-product attention
2019Cache sharingMQA
2020Alternative operator / connectivityKernelized recurrent attention; Longformer
2022IO-aware executionFlashAttention
2023Cache sharing / executionGQA; FlashAttention-2
2024Latent cache / executionDeepSeek-V2 MLA; FlashAttention-3

Sources and connected notes

Primary method links appear beside their explanations. Connected recipe notes give contemporary configurations and their report-specific conditions.

Source reports: Transformer ↗ · MAI-Thinking-1 ↗ · Kimi K3 ↗.

Normalization and retrieval: Entropy-invariance derivation ↗ · Softmax and length generalization ↗ · Softmax alternatives ↗ · Attention concentration ↗.

Latent representations: Cache and quality: MHA to MLA ↗ · A second rotary-encoding construction ↗.

Recurrent attention: From Performer to linear attention ↗ · Infinite-dimensional linear attention ↗ · Linear-attention history ↗ · Why short convolution? ↗ · Why DeltaNet normalization? ↗.

Continue with Distributed Training and Parallelism to connect head sharding, context ownership and online attention normalization.