← Back to Technical Library
Attention Mechanisms: From Bahdanau to Flash Attention
A Technical Deep-Dive into the Mechanism That Powers Modern AI
Category: Core AI Concepts
Read time: ~25 min
Updated: June 2026
Level: Intermediate-Advanced
Attention mechanisms are the computational heart of every modern transformer-based language model. This reference traces attention from its origin as a solution to the fixed-length encoding bottleneck in recurrent neural networks, through the landmark Bahdanau (additive) and Luong (multiplicative) formulations, to the self-attention that defined the Transformer architecture. We cover scaled dot-product attention with full mathematical derivation, multi-head attention and what individual heads learn, causal masking for autoregressive generation, cross-attention in encoder-decoder designs, and the efficiency frontier: grouped-query attention (GQA), multi-query attention (MQA), sliding window attention (Mistral, Longformer), Flash Attention, and sparse and linear attention variants. A complexity analysis explains why O(n²) attention is the central challenge for long-context models, and a comprehensive comparison table catalogs every major attention variant by compute cost, memory footprint, context length capability, and deployment readiness.
Attention
Self-Attention
Multi-Head
GQA
Flash Attention
Transformers
1. The Problem Attention Solves: The RNN Encoding Bottleneck
Before 2014, sequence-to-sequence models for machine translation used an encoder-decoder architecture built on recurrent neural networks (RNNs, typically LSTMs or GRUs). The encoder read the entire source sentence one token at a time and compressed all of its meaning into a single fixed-length vector -- the final hidden state. The decoder then generated the target sentence conditioned on that one vector.
This design has a fundamental flaw: no matter how long the input sentence is, the decoder must extract everything from the same fixed-size bottleneck. A 5-word sentence and a 50-word sentence are both squeezed into the same vector. For short inputs this works reasonably well. For long inputs, the encoder is forced to discard information, and translation quality degrades sharply.
+--------------------------------------------------+
| RNN Encoder-Decoder (pre-attention) |
+--------------------------------------------------+
Source: "The cat sat on the mat"
Encoder: h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> h7
|
v
+-------------+
| FIXED |
| VECTOR c | <-- BOTTLENECK
| (1 vector |
| for all) |
+-------------+
|
v
Decoder: s1 -> s2 -> s3 -> s4 -> s5 -> s6 -> s7
| | | | | | |
"Le" "chat" "s..." ... ... ... ...
Problem: ALL source info must flow through ONE vector.
Long sentences -> information loss -> bad translation.
The bottleneck is not merely a theoretical inconvenience. Experiments by Cho et al. (2014) and Sutskever et al. (2014) showed that BLEU scores on translation tasks dropped precipitously once source sentences exceeded roughly 30-40 tokens. The encoder simply could not remember everything.
What Attention Does Instead
Attention solves this by giving the decoder direct access to every encoder hidden state, not just the final one. At each decoding step, the decoder computes a set of alignment scores -- one per source position -- indicating how relevant each source token is to the current target token. These scores are normalized into weights, and a weighted sum (a context vector) is formed. The decoder consults the context vector at every step, dynamically selecting the information it needs.
This means that instead of a single static vector, the decoder draws from the entire sequence of encoder states, dynamically re-weighted at each output step. The bottleneck is eliminated because no single vector must carry everything; information is distributed across the full sequence and retrieved on demand.
Core Idea: Attention replaces a fixed information bottleneck with a dynamic, learned retrieval mechanism. The decoder "looks back" at all source positions at every step, weighting them by relevance. This is the seed from which all modern attention mechanisms grew.
The Three Roles in Any Attention Mechanism
Every attention variant, from Bahdanau to Flash Attention, can be understood in terms of three roles played by vectors:
- Query (Q): What the current position is "looking for." In a decoder, this is the current decoder hidden state asking "which source tokens are relevant to me right now?"
- Key (K): What each candidate position "offers" or "is about." In an encoder, these are the source hidden states -- each advertises its content for matching against queries.
- Value (V): The actual information content that gets retrieved if a key is selected. This is also typically the source hidden state (or a transform of it).
The Q-K-V framework, formalized explicitly in the Transformer paper, retroactively clarifies all earlier attention mechanisms. Bahdanau attention computes Q from the decoder, K from the encoder, and V from the encoder -- it just did not use those names.
2. Bahdanau Attention (Additive Attention)
In 2014, Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio published "Neural Machine Translation by Jointly Learning to Align and Translate," introducing the first attention mechanism for neural machine translation. The paper addressed the exact bottleneck described above and demonstrated near-state-of-the-art performance on English-to-French translation with sentences far longer than prior RNN systems could handle.
The Alignment Score: Additive Formulation
Bahdanau attention computes the relevance (alignment score) between a decoder state sₒ₁ and an encoder state hᵢ using a small feed-forward network with a single hidden layer:
score(sₒ₁, hᵩ) = vᵖᵀ · tanh(Wₐ sₒ₁ + Wᵢ hᵩ + b)
where:
sₒ₁ = decoder hidden state at step t-1 (the Query)
hᵩ = encoder hidden state at position i (the Key)
Wₐ, Wᵢ = learned weight matrices
vᵖᵀ, b = learned scoring vector and bias
tanh = hyperbolic tangent activation
The score is computed for EVERY encoder position i,
producing a vector of alignment scores: eₒ = [eₒ,₁, eₒ,₂, ..., eₒ,ₙ]
This is called additive attention because the two vectors (decoder state and encoder state) are first projected into a shared space and added together before passing through a nonlinearity and a scoring layer. The additive combination inside the tanh is what distinguishes it from the later Luong (multiplicative) formulation.
From Scores to Weights to Context
The alignment scores are converted to a probability distribution via softmax, then used to form a weighted sum of encoder states:
αₒ,ᵩ = softmax(eₒ,ᵩ) = exp(eₒ,ᵩ) / Σᵢ₁ exp(eₒ,ᵡ)
cₒ = Σᵩ αₒ,ᵩ · hᵩ
where:
αₒ,ᵩ = attention weight for source position i at decode step t
cₒ = context vector: weighted sum of ALL encoder hidden states
hᵩ = encoder hidden state (also the Value)
The context vector cₒ is then concatenated with the decoder input and fed into the RNN cell to produce the next decoder state. At every generation step, the decoder re-computes attention weights from scratch, allowing it to focus on different parts of the source sentence as it produces each target word.
+-------------------------------------------------+
| Bahdanau Attention Flow |
+-------------------------------------------------+
Encoder: h1 h2 h3 h4 h5 h6
| | | | | |
| | | | | |
+--+------+--+---+------+--+---+------+--+
| Alignment | | Alignment | | |
| Score e1 | | Score e3 | | |
| (additive) | | (additive)| | |
+-------------+ +------------+ +-----+
| | |
v v v
+----+----+-------+----+----+--------+----+
| softmax --> alpha_1, alpha_2, ... alpha_6 |
+-----------------------------------------+
|
v
c_t = sum(alpha_i * h_i) (context vector)
|
v
decoder uses c_t + s_{t-1} -> s_t -> output
Why "Additive": The name refers to the score function. In Bahdanau, the query and key vectors are projected by separate weight matrices and then summed before a nonlinearity: score = vᵀ tanh(Wᵖ q + Wᵬ k). The addition inside the tanh is the defining operation. In contrast, Luong attention multiplies the vectors directly.
Properties and Limitations
- Learned alignment: The attention weights form an explicit alignment matrix between source and target tokens, which is interpretable and can be visualized.
- Cost: The additive scorer (a feed-forward network) has its own parameters and must be applied at every (decoder-step, encoder-position) pair, making it more expensive per pair than a simple dot product.
- Sequential: Because it is coupled with an RNN decoder, the mechanism remains sequential in the target dimension -- each decoder step depends on the previous. This limits parallelism even though the attention over source positions can be computed in one matrix operation per step.
- Foundation: Despite these limitations, Bahdanau attention established the Q-K-V retrieval paradigm that all subsequent work, including the Transformer, builds upon.
3. Luong Attention (Multiplicative Attention)
In 2015, Thang Luong, Hieu Pham, and Christopher Manning at Stanford published "Effective Approaches to Attention-based Neural Machine Translation," simplifying and improving the Bahdanau formulation. Their key change was the score function: instead of a learned feed-forward network, they used a direct multiplicative (dot-product or general-product) comparison between the decoder state and encoder state.
The Three Luong Scoring Functions
Luong et al. proposed and compared three scoring functions:
1. Dot: score(hₒ, hᵩ) = hₒᵖᵀ hᵩ
(decoder and encoder must have same dimension)
2. General: score(hₒ, hᵩ) = hₒᵖᵀ Wₐ hᵩ
(Wₐ is a learned d_decoder x d_encoder matrix;
allows different dimensions for decoder and encoder)
3. Concat: score(hₒ, hᵩ) = vᵖᵀ tanh(Wₐ [hₒ ; hᵩ])
(equivalent to Bahdanau's additive scorer)
The "General" form is the most commonly cited as "Luong attention."
The "Dot" form is the direct precursor to Transformer scaled dot-product.
The dot and general forms are called multiplicative attention because the score is computed by multiplying (dot-producting) the query and key vectors, optionally through a learned projection matrix. This is simpler and faster than the additive form: it requires no intermediate nonlinearity and can be expressed as a single matrix multiplication when processing all source positions at once.
Differences from Bahdanau
| Aspect |
Bahdanau (Additive) |
Luong (Multiplicative) |
| Score function |
vᵀ tanh(Wᵖ q + Wᵬ k) |
qᵀ k or qᵀ W k |
| Nonlinearity in scorer |
Yes (tanh) |
No |
| Extra parameters |
Wᵖ, Wᵬ, v, b |
None (dot) or W (general) |
| Query source |
Previous decoder state sₒ₁ |
Current decoder state hₒ |
| Context usage |
Concatenated with decoder input |
Combined after decoder RNN step |
| Compute per pair |
Matrix-vector + tanh + dot |
Single dot product |
The choice of query timing is a subtle but important difference. Bahdanau computes attention using the previous decoder state (before consuming the current input), so the attention is used to help select the next input. Luong computes attention from the current decoder state (after the RNN step), so attention refines an already-updated representation. Empirically, Luong's approach was slightly simpler to train and performed comparably or better on standard benchmarks.
Legacy: The Luong "general" scorer (qᵀ W k) is, after adding a scaling factor, exactly the scaled dot-product attention used in Transformers. The line from Luong 2015 to Vaswani 2017 is direct: remove the RNN, apply the multiplicative scorer to all positions in the sequence simultaneously, and you have self-attention.
4. Self-Attention: The Core Transformer Innovation
The Transformer architecture (Vaswani et al., 2017) made a single, radical change: instead of attention flowing from a decoder to an encoder (cross-attention), attention flows within a single sequence. Every token attends to every other token in the same sequence -- including itself. This is self-attention, and it is the mechanism that replaced recurrence entirely.
Why Self-Attention Replaces Recurrence
In an RNN, token representations are built sequentially: token i's representation depends on token i-1's, which depends on i-2's, and so on. To let token i "know about" token 1, information must pass through i-1 intermediate hidden states, each of which is a potential point of information loss.
Self-attention gives every token direct, O(1)-length access to every other token. Token i computes a query, every token j (including i itself) provides a key and a value, and token i's new representation is a weighted sum of all values. The path length between any two tokens is exactly 1, no matter how far apart they are in the sequence. This is the structural reason transformers handle long-range dependencies far better than RNNs.
+-------------------------------------------------+
| Self-Attention: every token sees every token |
+-------------------------------------------------+
Sequence: [The] [cat] [sat] [on] [the] [mat]
Positions: 1 2 3 4 5 6
For position 3 ("sat"), compute attention to ALL positions:
Position 3 Query --> scores against Keys at positions 1..6
1 2 3 4 5 6
+-----+-----+-----+-----+-----+-----+
| 0.1 | 0.4 | 0.2 | 0.1 | 0.05| 0.15| = softmax scores
+-----+-----+-----+-----+-----+-----+
"The" "cat" "sat" "on" "the" "mat"
^^^ ^^^^ ^^^^
low HIGH medium
(subject) (object)
New rep for "sat" = 0.1*V1 + 0.4*V2 + 0.2*V3 + 0.1*V4 + ...
= mostly "cat" (subject) + some "mat" (object)
Every token does this simultaneously -> fully parallel.
What Makes It "Self"
In self-attention, the queries, keys, and values all come from the same input sequence. They are produced by three different learned linear projections of the input:
Q = X · Wᵖ (queries: "what am I looking for?")
K = X · Wᵬ (keys: "what do I contain?")
V = X · Wᵟ (values: "what information do I pass along?")
where X is the input matrix (n_tokens x d_model)
and Wᵖ, Wᵬ, Wᵟ are learned projection matrices of size d_model x d_k (or d_v)
Because Q, K, and V all derive from the same X, the mechanism lets tokens within the same sequence compare and combine their representations. This is fundamentally different from cross-attention (where Q comes from one sequence and K, V from another) and is what makes a single transformer block able to refine contextual representations without any recurrence.
Parallelism: Because self-attention computes all token interactions simultaneously via matrix multiplication (Q · Kᵀ), a transformer layer processes the entire sequence in one shot. There is no sequential dependency between tokens within a layer. This is why transformers train dramatically faster than RNNs on modern hardware -- the entire computation is a small number of large matrix multiplies, which GPUs and TPUs execute with near-peak utilization.
The Three Attention Types in a Transformer
The Transformer paper defines three ways attention is used, distinguished by where Q, K, and V come from:
- Self-attention: Q, K, V all from the same sequence. Used in encoder layers (bidirectional) and in decoder layers (masked, autoregressive). This is the default mechanism in decoder-only LLMs like GPT.
- Cross-attention (encoder-decoder attention): Q from the decoder, K and V from the encoder. Used in encoder-decoder models like T5 and the original Transformer for translation. Allows the decoder to retrieve relevant source information at each generation step.
- Masked self-attention (causal self-attention): Self-attention with a mask that prevents positions from attending to future positions. Used in decoder layers so that the prediction at position i can only depend on positions ≤ i.
5. Scaled Dot-Product Attention: Formula and Intuition
The specific self-attention function used in Transformers is called scaled dot-product attention. It is remarkably simple -- a single formula -- yet it is the computational atom from which all modern LLMs are built.
The Formula
Q · Kᵀ
Attention(Q, K, V) = softmax( -------- ) · V
√dᵭ
where:
Q = query matrix (n x d_k)
K = key matrix (m x d_k)
V = value matrix (m x d_v)
Kᵀ = transpose of K (d_k x m)
dᵭ = dimension of keys (= dimension of queries)
softmax is applied row-wise (over the m key positions)
Output: (n x d_v) matrix -- one new representation per query position
The computation proceeds in four steps, all of which are matrix operations:
- Dot products: Compute Q · Kᵀ, producing an n × m matrix of raw similarity scores. Each entry [i, j] measures how much query i aligns with key j.
- Scaling: Divide every score by √dᵭ. This is the "scaled" in "scaled dot-product."
- Softmax: Apply softmax along each row (over the m key positions), converting raw scores into a probability distribution that sums to 1. These are the attention weights.
- Weighted sum: Multiply the weight matrix by V, producing a weighted combination of value vectors for each query.
Why the Scaling Factor √dᵭ?
The division by √dᵭ is not cosmetic -- it is essential for training stability. The dot product of two vectors of dimension dᵭ, each with mean 0 and unit variance, has variance dᵭ. As dᵭ grows (modern models use 64, 128, or 256 per head), the raw dot products become large in magnitude.
When the inputs to softmax are large, the softmax function saturates: it outputs values very close to 0 or 1, producing gradients that vanish. This makes training unstable or impossible. Dividing by √dᵭ keeps the variance of the dot products at approximately 1 regardless of dimension, ensuring softmax operates in a well-behaved range.
Without scaling, training diverges. The original Transformer paper explicitly notes that additive (Bahdanau) attention works without scaling because the learned projections can implicitly control the magnitude, but dot-product attention grows with dimension and must be scaled. Omitting the √dᵭ factor is a common implementation bug that causes silent training instability at large model dimensions.
Step-by-Step Numerical Example
Consider a tiny example with n=3 query positions, m=3 key positions, and dᵭ = 4 (so √dᵭ = 2):
Q · Kᵀ (raw scores, d_k = 4, sqrt(4) = 2):
Key1 Key2 Key3
Query1 [ 8.0, 2.0, 0.0 ]
Query2 [ 1.0, 6.0, 1.0 ]
Query3 [ 0.0, 1.0, 4.0 ]
After scaling (divide by 2):
Key1 Key2 Key3
Query1 [ 4.0, 1.0, 0.0 ]
Query2 [ 0.5, 3.0, 0.5 ]
Query3 [ 0.0, 0.5, 2.0 ]
After softmax (row-wise):
Key1 Key2 Key3
Query1 [ 0.950, 0.047, 0.002 ] -> mostly Key1
Query2 [ 0.018, 0.964, 0.018 ] -> mostly Key2
Query3 [ 0.057, 0.094, 0.849 ] -> mostly Key3
Output = weights · V (weighted sum of value vectors)
In this example, Query1 is strongly aligned with Key1 (weight 0.95), so its output is approximately V1. Query2 attends almost entirely to Key2, and Query3 mostly to Key3. In a real model with hundreds of dimensions and learned projections, the attention patterns are far more diffuse and capture semantic relationships.
Intuition: A Differentiable Dictionary Lookup
A useful mental model is that scaled dot-product attention is a soft, differentiable dictionary lookup. In a standard dictionary, you provide a key and retrieve the exact matching value. In attention, you provide a query, compare it softly against all keys, and retrieve a weighted average of all values. The weights are determined by similarity (dot product) and normalized by softmax. Everything is differentiable, so the projections Wᵖ, Wᵬ, Wᵟ can be learned by gradient descent to route information where it is needed.
6. Multi-Head Attention
A single attention function produces one set of attention weights per position -- one "perspective" on which other tokens are relevant. But language involves many simultaneous relationships: syntax, coreference, semantics, discourse structure, and more. A single attention head cannot easily capture all of these at once. The solution is multi-head attention.
The Mechanism
Instead of performing attention once on the full d_model-dimensional vectors, the model projects Q, K, and V into h separate lower-dimensional subspaces (one per "head"), runs scaled dot-product attention independently in each subspace, concatenates the results, and projects back to d_model:
For each head i = 1, 2, ..., h:
Qᵨ = Q · Wᵖₐ (d_model -> d_k)
Kᵨ = K · Wᵬₐ (d_model -> d_k)
Vᵨ = V · Wᵟₐ (d_model -> d_v)
headᵨ = Attention(Qᵨ, Kᵨ, Vᵨ) (scaled dot-product)
Concatenate all heads:
MultiHead(Q, K, V) = Concat(head₁, head₂, ..., head₋) · Wᵾ
where:
h = number of heads (typically 8, 16, 32, or 64)
d_k = d_model / h (per-head key/value dimension)
Wᵾ = output projection matrix (h·d_v x d_model)
Constraint: h · d_k = d_model (total dimension is preserved)
Cost: approximately the same as single-head attention at full dimension,
because each head operates on d_model/h dimensions.
The dimensionality split means that the total computation is roughly the same as a single full-dimensional attention operation, but the model gains the ability to learn h different attention patterns simultaneously. Each head has its own Wᵖₐ, Wᵬₐ, Wᵟₐ parameters, so each head can specialize in detecting a different type of relationship.
+---------------------------------------------------+
| Multi-Head Attention |
+---------------------------------------------------+
Input (d_model)
|
+-------+-------+-------+-------+
| | | | |
W_Q1 W_Q2 W_Q3 ... W_Qh
W_K1 W_K2 W_K3 ... W_Kh
W_V1 W_V2 W_V3 ... W_Vh
| | | | |
+-----+ +-----+ +-----+ +-----+
| Att | | Att | | Att | ... | Att |
| 1 | | 2 | | 3 | | h |
+-----+ +-----+ +-----+ +-----+
| | | | |
v v v v v
head1 head2 head3 ... headh
| | | | |
+-------+-------+-------+-------+
|
Concatenate
|
W_O (output projection)
|
v
Output (d_model)
What Individual Heads Learn
Interpretability research (Voita et al., 2019; Clark et al., 2019; Olah et al., 2020) has probed what individual attention heads actually attend to. Findings include:
- Syntactic heads: Some heads consistently attend from a word to its syntactic parent -- e.g., from a verb to its subject or object, from a noun to its determiner, from a pronoun to its antecedent.
- Positional heads: Some heads attend to fixed relative positions (e.g., "always look at the previous token" or "always look at the next token"). These serve a function similar to n-gram features.
- Coreference heads: Some heads specialize in tracking entity references across long distances, attending from a pronoun ("it", "they") to the noun it refers to.
- Rare-word heads: Some heads attend strongly to rare or content-rich tokens, effectively acting as a content-addressable lookup.
- "No-op" heads: Many heads, especially in later layers, attend almost entirely to the current position (identity-like) or to a single fixed token (like a [CLS] or BOS token). These can often be pruned with minimal performance impact.
Practical finding: Not all heads are equal. Studies show that 20-40% of heads in a trained transformer can be removed (set to attention to self only) with negligible impact on perplexity or downstream task performance. The important heads are concentrated in lower layers (syntactic) and specific upper layers (task-specific). This insight motivated head pruning and the development of more parameter-efficient attention variants.
Why Not Just One Big Head?
A single attention head with the full d_model dimension would have the same total parameter count and compute, but it would be forced to learn a single attention distribution per position. This is a severe bottleneck: if position i needs to attend to both its syntactic parent and a coreferent entity, a single head must compromise. Multi-head attention lets the model learn multiple, partially independent attention patterns and combine them, which empirically improves both training speed and final quality.
Typical Head Counts by Model Scale
| Model |
Parameters |
d_model |
Heads (h) |
d_k per head |
| GPT-2 Small |
117M |
768 |
12 |
64 |
| GPT-2 XL |
1.5B |
1600 |
25 |
64 |
| GPT-3 |
175B |
12288 |
96 |
128 |
| Llama 2 7B |
7B |
4096 |
32 |
128 |
| Llama 3 70B |
70B |
8192 |
64 |
128 |
| Mistral 7B |
7B |
4096 |
32 |
128 |
A common pattern is d_k = 64 or 128 per head, with the number of heads scaling proportionally to d_model. The per-head dimension is kept small to ensure the dot products remain well-conditioned after scaling by √dᵭ.
7. Causal / Autoregressive Masking
In a decoder-only language model (GPT family, Llama, Mistral, Claude, Gemini), the model is trained to predict the next token given all previous tokens. The training signal at position i is "predict token i+1 from tokens 1 through i." For this to work, position i must not be allowed to see positions > i -- otherwise the model could "cheat" by copying the answer from the future, and the training objective would be trivially satisfied without learning anything useful.
Causal masking (also called autoregressive masking or lower-triangular masking) enforces this constraint by setting the attention weights for all future positions to negative infinity before softmax. After softmax, these positions receive weight exactly zero.
The Mask
Causal (lower-triangular) mask for n=6 positions:
Pos1 Pos2 Pos3 Pos4 Pos5 Pos6
Pos1 [ 0, -∞, -∞, -∞, -∞, -∞ ]
Pos2 [ 0, 0, -∞, -∞, -∞, -∞ ]
Pos3 [ 0, 0, 0, -∞, -∞, -∞ ]
Pos4 [ 0, 0, 0, 0, -∞, -∞ ]
Pos5 [ 0, 0, 0, 0, 0, -∞ ]
Pos6 [ 0, 0, 0, 0, 0, 0 ]
Applied as: scores = scores + mask
then softmax
After softmax, all -∞ entries become 0.0:
Each row attends ONLY to itself and previous positions.
Pos1 Pos2 Pos3 Pos4 Pos5 Pos6
Pos1 [ 1.0, 0, 0, 0, 0, 0 ]
Pos2 [ 0.3, 0.7, 0, 0, 0, 0 ]
Pos3 [ 0.1, 0.2, 0.7, 0, 0, 0 ]
Pos4 [ 0.1, 0.1, 0.2, 0.6, 0, 0 ]
Pos5 [ 0.05, 0.1, 0.1, 0.15, 0.6, 0 ]
Pos6 [ 0.05, 0.05, 0.1, 0.1, 0.2, 0.5]
The mask is added to the raw Q·Kᵀ scores before the softmax step. Because softmax converts exp(-∞) = 0, the future positions contribute nothing to the weighted sum. The result is that each position's representation depends only on itself and all preceding positions -- exactly the autoregressive property.
Why Decoder Attention Must Be Masked
The masking is not optional in autoregressive models; it is a structural requirement for the training objective to be meaningful:
- Training (teacher forcing): The model is given the entire sequence at once and must predict token i+1 at every position i. Without masking, position i could attend to position i+1, which contains the target token. The loss would collapse to near-zero without the model learning anything about language -- it would simply learn to copy the adjacent token.
- Inference (generation): During generation, future tokens do not exist yet (the model is generating them one at a time). The mask ensures that the computation at inference matches the computation during training, so the model's learned behavior transfers correctly.
- Prefix / fill-in-the-middle: Some training setups (FIM, code infilling) use a more complex mask that allows a prefix and suffix to be visible while a middle section is predicted. This is still a form of masking, just with a non-strictly-lower-triangular pattern.
Encoder vs Decoder masking: Encoder models (BERT) use bidirectional attention -- no causal mask -- because they are trained with masked-language-modeling (predict a few randomly chosen tokens from all the others). Decoder-only models (GPT, Llama) must use causal masking. Mixing these up is a classic implementation error: an unmasked decoder learns nothing useful, and a masked encoder cannot do bidirectional understanding.
The Efficiency Cost of Causal Masking
A subtle consequence of causal masking is that position i attends to i positions (itself plus all previous), so the total number of nonzero attention entries is n(n+1)/2 rather than n². This is still O(n²), but it means that on average, half the attention matrix is zero. Some implementations exploit this sparsity to reduce computation, though the savings are modest because the dense matrix multiply is already highly optimized on modern hardware.
8. Cross-Attention (Encoder-Decoder Attention)
Cross-attention is the attention mechanism that connects an encoder to a decoder. It is the direct descendant of Bahdanau attention: the decoder queries the encoder's outputs to retrieve relevant source information at each generation step. In the original Transformer and in encoder-decoder models like T5, BART, and Whisper, cross-attention is the bridge between understanding the input and generating the output.
The Setup
In cross-attention, the three roles come from different sources:
Q = decoder_hidden_states · Wᵖ (from the decoder)
K = encoder_hidden_states · Wᵬ (from the encoder)
V = encoder_hidden_states · Wᵟ (from the encoder)
Attention(Q, K, V) = softmax(Q·Kᵀ / √dᵭ) · V
- Q has n_decoder rows (n = target sequence length)
- K has m_encoder rows (m = source sequence length)
- V has m_encoder rows
- Output has n_decoder rows, each a weighted sum of encoder values
The decoder produces a query at each position asking "what part of the source is relevant to what I'm generating now?" The encoder's keys and values represent the source content. The attention weights form an alignment matrix between target and source positions.
+---------------------------------------------------+
| Cross-Attention in Encoder-Decoder |
+---------------------------------------------------+
Encoder output (m=5 source positions):
E1 E2 E3 E4 E5
| | | | |
v v v v v
K1 K2 K3 K4 K5 (Keys from encoder)
V1 V2 V3 V4 V5 (Values from encoder)
Decoder states (n=4 target positions, being generated):
D1 D2 D3 D4
| | | |
v v v v
Q1 Q2 Q3 Q4 (Queries from decoder)
Cross-attention scores: Q · Kᵀ -> n x m matrix
K1 K2 K3 K4 K5
Q1 [ 0.7, 0.1, 0.1, 0.05, 0.05 ] -> "Le" attends to "The"
Q2 [ 0.1, 0.8, 0.05, 0.02, 0.03 ] -> "chat" attends to "cat"
Q3 [ 0.05, 0.1, 0.7, 0.1, 0.05 ] -> "est" attends to "sat"
Q4 [ 0.05, 0.05, 0.1, 0.7, 0.1 ] -> "sur" attends to "on"
Each decoder position retrieves a weighted blend of source info.
Where Cross-Attention Appears
| Model |
Architecture |
Cross-Attention Role |
| Original Transformer |
Encoder-Decoder |
Decoder attends to encoder outputs at every layer |
| T5 |
Encoder-Decoder |
Each decoder block has one cross-attention sublayer |
| BART |
Encoder-Decoder |
Cross-attention for summarization and translation |
| Whisper |
Encoder-Decoder |
Decoder (text) attends to encoder (audio features) |
| Stable Diffusion |
U-Net + Cross-Attn |
Image features attend to text embeddings (CLIP) |
| GPT / Llama / Mistral |
Decoder-only |
No cross-attention (self-attention only) |
Modern general-purpose LLMs (GPT-4, Claude, Gemini, Llama) are almost universally decoder-only and therefore have no cross-attention. The encoder-decoder design with cross-attention persists in specialized domains: speech-to-text (Whisper), translation (some production systems), and multimodal generation (diffusion models, where cross-attention lets image patches attend to text prompts).
KV Cache Note: In cross-attention, the encoder's K and V matrices are computed once and reused across all decoder steps and all decoder layers (if the encoder outputs are shared). This is the original "KV cache" pattern. In decoder-only self-attention, the KV cache stores previously computed keys and values so that each new token only needs to compute its own Q, K, V rather than recomputing the full sequence.
9. Grouped-Query Attention (GQA) and Multi-Query Attention (MQA)
In standard multi-head attention, every head has its own set of Q, K, and V projections. During autoregressive inference, the KV cache (stored keys and values for all past tokens) must hold h keys and h values per token per layer. For a model with 32 heads, d_k=128, 32 layers, and a 32K-token context, the KV cache alone can consume multiple gigabytes of memory -- often more than the model weights themselves.
Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) reduce this memory cost by sharing K and V projections across multiple query heads.
Multi-Query Attention (MQA)
Introduced by Noam Shazeer in 2019, MQA uses one shared K and V head across all query heads. Every query head computes attention against the same set of keys and retrieves from the same set of values:
Standard MHA: h query heads, h key heads, h value heads
-> KV cache size proportional to h
MQA: h query heads, 1 key head, 1 value head
-> KV cache size proportional to 1 (reduced by factor h)
Memory savings (KV cache): ~h times smaller
Compute savings (inference): significant due to smaller memory bandwidth
Quality impact: small degradation vs MHA
MQA dramatically reduces the KV cache size and, more importantly, the memory bandwidth needed to load keys and values at each decoding step. Since autoregressive inference is often memory-bandwidth-bound rather than compute-bound, this translates to substantial real-world speedups. The cost is a modest quality degradation compared to full multi-head attention, because all heads share the same key/value subspace.
Grouped-Query Attention (GQA)
Introduced by Ainslie et al. (2023) in "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints," GQA is the middle ground between MHA and MQA. Instead of a single shared KV head (MQA) or fully separate KV heads (MHA), GQA uses g groups of KV heads, where g is between 1 and h:
MHA: h query heads, h KV heads (g = h, no sharing)
GQA: h query heads, g KV heads (1 < g < h, partial sharing)
MQA: h query heads, 1 KV head (g = 1, full sharing)
Each group of (h/g) query heads shares one KV head.
Example: h=32, g=8
- 32 query heads, 8 KV heads
- Each KV head serves 4 query heads
- KV cache reduced by 4x vs MHA
- Quality closer to MHA than MQA
GQA was designed to be upgradable from existing MHA checkpoints: a model originally trained with h KV heads can be converted to g groups by averaging the weights of (h/g) heads per group, then fine-tuned briefly to recover quality. This made GQA immediately practical for large models that had already been trained with standard MHA.
Comparison: MHA vs GQA vs MQA
| Property |
MHA (standard) |
GQA (grouped) |
MQA (multi-query) |
| Query heads |
h |
h |
h |
| KV heads |
h |
g (1 < g < h) |
1 |
| KV cache size |
1 × (baseline) |
g/h × baseline |
1/h × baseline |
| Inference speed |
Baseline |
1.5x - 3x faster |
3x - 8x faster |
| Quality (vs MHA) |
Baseline |
Nearly identical |
Small degradation |
| Training cost |
Baseline |
~Same as MHA |
~Same as MHA |
| Used in |
GPT-3, BERT, T5 |
Llama 2/3 70B, Mistral, Gemma |
PaLM, Falcon, Gemini |
Industry consensus (2024-2026): GQA with g = h/8 or g = h/4 has become the default for new large models. It captures most of MQA's inference speedup while preserving MHA-level quality. Llama 2 70B, Llama 3, Mistral, Mixtral, and Gemma all use GQA. MQA remains relevant for extreme inference efficiency scenarios where a small quality trade-off is acceptable.
10. Sliding Window Attention (Mistral, Longformer)
Standard self-attention lets every token attend to every other token -- the full O(n²) computation. For long sequences, this becomes prohibitive. Sliding window attention restricts each token to attend only to a fixed-size window of nearby positions, reducing the per-token cost from O(n) to O(w) where w is the window size.
The Mechanism
Each token at position i attends only to positions in the range [i - w + 1, i] (for causal / autoregressive models) or [i - w/2, i + w/2] (for bidirectional models). The window slides across the sequence, and each token sees only a local neighborhood:
Sliding Window Attention (w=4, causal):
Token 1: [1] attends to: {1}
Token 2: [1, 2] attends to: {1, 2}
Token 3: [1, 2, 3] attends to: {1, 2, 3}
Token 4: [1, 2, 3, 4] attends to: {1, 2, 3, 4}
Token 5: [2, 3, 4, 5] attends to: {2, 3, 4, 5}
Token 6: [3, 4, 5, 6] attends to: {3, 4, 5, 6}
Token 7: [4, 5, 6, 7] attends to: {4, 5, 6, 7}
Token 8: [5, 6, 7, 8] attends to: {5, 6, 7, 8}
Each token sees at most w=4 positions.
Per-token attention cost: O(w) instead of O(n).
Total attention cost: O(n · w) instead of O(n²).
With w = 4096 and n = 128K:
Full attention: 128K ² = 16.4 billion entries
Sliding window: 128K · 4K = 524 million entries (31x fewer)
Receptive Field Across Layers
A single sliding-window layer has a limited receptive field of w tokens. But when stacked across L layers, the effective receptive field grows to L · w tokens. A token in layer L can indirectly attend to tokens L · w positions away, because each layer extends the reach by w. With 32 layers and w=4096, the effective receptive field is 131,072 tokens -- covering a 128K context window.
Receptive field growth across layers (w=4):
Layer 0 (input): Token 8 sees tokens {5, 6, 7, 8}
Layer 1: Token 8's representation includes info from
tokens {2, 3, 4, 5, 6, 7, 8} (via layer 0)
Layer 2: Token 8 includes info from
tokens {-2, ..., 8} (via layers 0, 1)
...but bounded by sequence start
Effective receptive field after L layers = L · w tokens
L=32, w=4096 -> effective RF = 131,072 tokens
This is why Mistral 7B supports 32K context with w=4096.
Models Using Sliding Window Attention
| Model |
Window Size |
Context Length |
Notes |
| Longformer |
512 (local) + global tokens |
4,096 - 16,384 |
Bidirectional; designated "global attention" tokens |
| Longformer-Encoder-Decoder |
512 |
Up to 16K |
Local + global attention for document tasks |
| Mistral 7B |
4,096 |
8K (32K with sliding) |
Causal sliding window; GQA; 32 layers |
| Mixtral 8x7B |
4,096 |
32K |
Sliding window + MoE |
| Mistral Large |
4,096 |
32K - 128K |
Sliding window with extended context |
Limitations
Sliding window attention trades long-range direct access for efficiency. A token at position 100,000 cannot directly attend to a token at position 10 -- it must rely on information being propagated through many intermediate layers. In practice, this works well for most language tasks because relevant context is usually local (within a few thousand tokens). But tasks requiring precise long-range retrieval (e.g., "find the exact sentence from page 1") can suffer, because the information may be blurred or lost as it passes through dozens of layers.
Some models address this by combining sliding window with a small number of global attention tokens (Longformer) or by alternating local and global attention layers. Others use sliding window for most layers and full attention for a few "bridge" layers.
Mistral's design choice: Mistral 7B uses sliding window attention with w=4096 across all 32 layers, combined with GQA (g=8) and rolling buffer KV cache. The effective receptive field of 32 × 4096 = 131K covers the full 32K context. This design achieves near-full-attention quality at a fraction of the compute for sequences in the 8K-32K range.
11. Flash Attention and Memory-Efficient Attention
Flash Attention (Dao et al., 2022; Dao, 2023) is not a new attention variant -- it computes exactly the same mathematical result as standard scaled dot-product attention. What it changes is the algorithm and memory access pattern, reducing memory usage from O(n²) to O(n) and accelerating wall-clock time by 2-4x on modern GPUs. It is the single most impactful efficiency improvement for transformer inference and training in recent years.
The Problem: The Attention Matrix Is Huge
Standard attention materializes the full n × n attention matrix (Q · Kᵀ, then softmax, then · V) in GPU SRAM or HBM. For n = 16,384 and d_k = 128, the Q · Kᵀ matrix is 16,384 × 16,384 × 2 bytes = 512 MB per head. With 32 heads and 32 layers, the total intermediate memory for attention alone exceeds 500 GB -- far more than any GPU's HBM. This forces implementations to either use smaller batch sizes or fall back to naive sequential computation that is slow due to memory bandwidth.
The root issue is that the n² attention matrix is written to and read from GPU HBM (high-bandwidth memory), which is ~10x slower than on-chip SRAM. The actual FLOPs of attention are modest; the bottleneck is memory movement.
Flash Attention's Solution: Tiling and Kernel Fusion
Flash Attention restructures the computation to avoid ever materializing the full n² matrix in HBM. It uses two key techniques:
Flash Attention Algorithm (simplified):
1. TILING: Divide Q, K, V into blocks of size B_rows x d_k.
Process one block of Q at a time, against all blocks of K and V.
2. ONLINE SOFTMAX: Compute softmax incrementally as K blocks arrive.
Standard softmax needs all scores at once: softmax(x)_i = exp(x_i) / sum(exp(x_j))
Flash Attention uses a numerically stable online softmax that
maintains running max and running sum, updating as new K blocks arrive.
3. KERNEL FUSION: Fuse Q·Kᵀ, softmax, and ·V into a single GPU kernel.
Intermediate results stay in on-chip SRAM (registers / L1 cache).
Only the final output (n x d_v) is written to HBM.
Result:
- HBM reads/writes: O(n · d) instead of O(n²)
- Memory for attention matrix: O(n) instead of O(n²)
- Wall-clock speedup: 2-4x (memory-bound -> compute-bound)
- Mathematical output: IDENTICAL to standard attention
Standard Attention (memory-bound):
HBM: Q(n,d) --read--> SRAM: Q·Kᵀ = (n,n) --write--> HBM
HBM: (n,n) --read--> SRAM: softmax --write--> HBM
HBM: (n,n) --read--> SRAM: ·V = (n,d) --write--> HBM
3 reads + 3 writes of the n×n matrix to slow HBM.
For n=16K: 512MB matrix moved 6 times = 3GB of transfers PER HEAD.
Flash Attention (fused, tiled):
HBM: Q block --read--> SRAM
HBM: K block --read--> SRAM -> Q·Kᵀ in SRAM
HBM: V block --read--> SRAM -> softmax(·) in SRAM
-> accumulate output in SRAM
SRAM: output block --write--> HBM (only final result!)
n×n matrix NEVER written to HBM.
Stays entirely in fast on-chip SRAM.
Total HBM traffic: O(n·d) instead of O(n²).
Flash Attention 2 and 3
- Flash Attention 1 (2022): Introduced tiling and online softmax. 2-4x speedup over PyTorch standard attention. Reduced memory from O(n²) to O(n).
- Flash Attention 2 (2023): Improved work partitioning across GPU thread blocks and warps. Better GPU occupancy, ~2x over FA1. Reduced non-matmul FLOPs. Supports larger sequence lengths (up to 256K on A100/H100).
- Flash Attention 3 (2024): Optimized for H100/H200 GPUs. Uses asynchronous data movement (TMA), FP8 support, and overlaps matmul with softmax. Up to 1.5-2x over FA2 on Hopper architecture. Achieves near-peak hardware utilization.
What Flash Attention Enables
| Capability |
Without Flash Attention |
With Flash Attention |
| Max sequence length (A100 80GB) |
~16K - 32K |
128K - 256K |
| Attention memory (n=16K) |
O(n²) ~ 512MB/head |
O(n) ~ negligible |
| Training throughput (long ctx) |
Baseline |
2-4x faster |
| Inference latency (long ctx) |
Baseline |
2-3x lower |
| Numerical accuracy |
Baseline |
Identical (exact computation) |
Near-universal adoption: Flash Attention is now the default attention implementation in PyTorch 2.x (F.scaled_dot_product_attention), Hugging Face Transformers, vLLM, TensorRT-LLM, and all major training frameworks. If you are training or running a transformer in 2026, you are almost certainly using Flash Attention (or a derivative) whether you know it or not. It requires no model architecture changes -- it is a drop-in replacement for the attention kernel.
Other Memory-Efficient Attention Techniques
- PagedAttention (vLLM): Manages the KV cache in non-contiguous memory pages (like virtual memory in OS design), eliminating fragmentation and enabling efficient batching of sequences with different lengths. Combined with Flash Attention for the compute kernel.
- Memory-Efficient Attention (Rabe & Staadt, 2021): An earlier approach that computes attention in blocks without Flash Attention's kernel fusion. Less efficient but does not require custom CUDA kernels.
- xFormers memory_efficient_attention: Meta's implementation of blockwise attention with custom kernels. Predates Flash Attention; largely superseded by it but still used in some contexts.
- Ring Attention (Liu et al., 2023): Distributes attention computation across multiple GPUs, each holding a shard of the sequence. Enables context lengths of millions of tokens by overlapping communication with computation. Combined with Flash Attention within each GPU.
12. Attention Patterns Visualization
Attention weights form an n × n (or n × m for cross-attention) matrix that can be visualized as a heatmap. Different attention variants produce characteristic patterns. Understanding these patterns helps in debugging models, interpreting behavior, and choosing the right attention variant for a task.
Standard (Full) Self-Attention Pattern
Every token attends to every other token. The attention matrix is fully dense. Bright cells indicate high attention weights.
Full Self-Attention (n=10, bidirectional / encoder):
T1 T2 T3 T4 T5 T6 T7 T8 T9 T10
T1 [ ## ## . . . . . . ## . ]
T2 [ ## ## ## . . . . . . . ]
T3 [ . ## ## ## . . . . . . ]
T4 [ . . ## ## . . . ## . . ]
T5 [ . . . . ## ## . . . . ]
T6 [ . . . . ## ## ## . . . ]
T7 [ . . . . . ## ## . . . ]
T8 [ . . . ## . . . ## ## . ]
T9 [ ## . . . . . . ## ## ## ]
T10 [ . . . . . . . . ## ## ]
Legend: ## = high attention . = low attention
Fully dense: every cell can be nonzero.
Cost: O(n²) = 100 entries for n=10.
Causal (Masked) Self-Attention Pattern
Lower-triangular. Each token attends only to itself and previous tokens. The upper triangle is strictly zero.
Causal Self-Attention (n=10, decoder):
T1 T2 T3 T4 T5 T6 T7 T8 T9 T10
T1 [ ## -- -- -- -- -- -- -- -- -- ]
T2 [ ## ## -- -- -- -- -- -- -- -- ]
T3 [ . ## ## -- -- -- -- -- -- -- ]
T4 [ . . ## ## -- -- -- -- -- -- ]
T5 [ . . . ## ## -- -- -- -- -- ]
T6 [ . . . . ## ## -- -- -- -- ]
T7 [ . . . . . ## ## -- -- -- ]
T8 [ . . . . . . ## ## -- -- ]
T9 [ . . . . . . . ## ## -- ]
T10 [ . . . . . . . . ## ## ]
Legend: ## = high attention . = low (allowed) -- = masked (zero)
Lower triangle only. n(n+1)/2 = 55 potentially nonzero entries.
Sliding Window Attention Pattern
A band around the diagonal. Each token attends only to a local window of w positions. Combined with causal masking, this is a lower-triangular band.
Sliding Window + Causal (n=10, w=4):
T1 T2 T3 T4 T5 T6 T7 T8 T9 T10
T1 [ ## -- -- -- -- -- -- -- -- -- ]
T2 [ ## ## -- -- -- -- -- -- -- -- ]
T3 [ ## ## ## -- -- -- -- -- -- -- ]
T4 [ ## ## ## ## -- -- -- -- -- -- ]
T5 [ -- ## ## ## ## -- -- -- -- -- ]
T6 [ -- -- ## ## ## ## -- -- -- -- ]
T7 [ -- -- -- ## ## ## ## -- -- -- ]
T8 [ -- -- -- -- ## ## ## ## -- -- ]
T9 [ -- -- -- -- -- ## ## ## ## -- ]
T10 [ -- -- -- -- -- -- ## ## ## ## ]
Band of width w=4 along the diagonal.
Nonzero entries: n · w = 40 (vs 55 for full causal, vs 100 for full bidirectional).
Sparse Attention Pattern (BigBird-style)
Combines local windows with a few random and global connections. This allows some long-range attention without the full O(n²) cost.
Sparse Attention (n=10, window=3 + random + global):
T1 T2 T3 T4 T5 T6 T7 T8 T9 T10
T1 [ ## ## ## . . . . . . ## ] <- global
T2 [ ## ## ## . . . . . . . ]
T3 [ ## ## ## ## . . ## . . . ] <- random
T4 [ . ## ## ## ## . . . . . ]
T5 [ . . ## ## ## ## . . . . ]
T6 [ . . . ## ## ## ## . . . ]
T7 [ . . ## . ## ## ## ## . . ] <- random
T8 [ . . . . . ## ## ## ## . ]
T9 [ . . . . . . . ## ## ## ]
T10 [ ## . . . . . . . ## ## ] <- global
Local window (w=3) + random connections + global tokens (T1, T10).
Nonzero: ~n·w + n·r + n·g (r=random, g=global)
Much sparser than full attention but retains some long-range links.
Real Attention Head Patterns in Trained Models
When visualizing attention in a trained transformer, heads often specialize into recognizable patterns:
- Diagonal-dominant: The head mostly attends to the current token (identity). Common in later layers; often prunable.
- Previous-token: Strong attention to position i-1. Acts like a bigram feature. Common in early layers.
- Syntactic: Attention from verbs to their subjects/objects, from pronouns to antecedents. Appears as sparse off-diagonal patterns.
- Diffuse: Relatively uniform attention across many positions. Captures broad context rather than specific tokens.
- End-of-sentence / BOS: Many positions attend to a single special token (BOS, EOS, or [CLS]). Acts as a global aggregation point.
13. Complexity Analysis: O(n²) and Why It Matters for Long Context
The central limitation of standard attention is its quadratic complexity in sequence length. Both the compute (FLOPs) and the memory (if the attention matrix is materialized) scale as O(n²) where n is the sequence length. This is the single most important scaling challenge for long-context models.
Where the n² Comes From
The Q · Kᵀ step multiplies an (n × d_k) matrix by a (d_k × n) matrix, producing an (n × n) result. This requires n · n · d_k = n²dᵭ multiply-adds. The softmax operates on n² elements. The final · V is (n × n) · (n × d_v) = n²dᵟ operations. The dominant term is O(n²d), and since d is fixed for a given model, the scaling with sequence length is O(n²).
Attention FLOPs breakdown (per head, per layer):
Step 1: Q·Kᵀ -> n · n · d_k = O(n² d)
Step 2: scale + mask -> n · n = O(n²)
Step 3: softmax -> n · n = O(n²)
Step 4: weights·V -> n · n · d_v = O(n² d)
Total: O(n² d) per head per layer
Full layer (h heads): O(n² d h) = O(n² d_model) [since h·d_k = d_model]
Full model (L layers): O(L · n² d_model)
Memory (if materialized): O(n²) for the attention matrix per head per layer
Concrete Numbers: Why n² Hurts
The quadratic scaling means that doubling the context length quadruples the attention cost. This has dramatic consequences as models push toward longer contexts:
| Context Length (n) |
Attention Entries (n²) |
Relative Cost (vs 4K) |
Attention Matrix Size (FP16, 32 heads) |
| 4,096 |
16.7M |
1× |
~1 GB |
| 8,192 |
67.1M |
4× |
~4 GB |
| 16,384 |
268M |
16× |
~16 GB |
| 32,768 |
1.07B |
64× |
~64 GB |
| 65,536 |
4.29B |
256× |
~256 GB |
| 131,072 (128K) |
17.2B |
1,024× |
~1,024 GB (1 TB) |
| 1,048,576 (1M) |
1.1T |
65,536× |
~64 TB |
The last column shows the memory required to materialize the full attention matrix for a single layer, in FP16, across 32 heads. At 128K context, this exceeds 1 TB -- obviously impossible on any single GPU. This is why Flash Attention (which avoids materializing the matrix) and approximate attention methods are not optional for long-context models; they are prerequisites.
The 4K-to-128K gap: Going from 4K to 128K context is a 1,024x increase in attention cost. Without Flash Attention, sliding window, or other techniques, 128K context is simply infeasible on current hardware. Every long-context model (Gemini 1.5 Pro at 2M, Claude at 200K, GPT-4 Turbo at 128K) uses some combination of efficiency techniques to make this work. There is no "free lunch" -- the quadratic wall is real.
FLOPs vs Memory Bandwidth: Two Different Bottlenecks
The n² cost manifests differently in training and inference:
- Training (batched, large batches): The bottleneck is FLOPs. The Q·Kᵀ and weights·V matmuls dominate, and GPUs have enough FLOP throughput that attention is a significant fraction of total compute. Flash Attention helps by reducing memory traffic and enabling larger batches.
- Inference (autoregressive, batch=1): The bottleneck is memory bandwidth. Each decoding step processes one new token but must load the entire KV cache (all past keys and values) from HBM. The Q·Kᵀ is a vector-matrix product (1 × n), which is tiny in FLOPs but requires reading n · d · h entries from memory. This is why GQA/MQA (which shrink the KV cache) and Flash Attention (which reduces HBM traffic) are so impactful for inference latency.
Why This Drives the Search for Alternatives
The quadratic wall has motivated an enormous research effort into sub-quadratic attention alternatives:
- Sliding window: O(n · w) -- linear in n for fixed w.
- Sparse attention: O(n · (w + r + g)) -- linear in n with fixed sparsity pattern.
- Linear attention: O(n · d²) -- replaces softmax with a kernel feature map, enabling associativity tricks that avoid the n² matrix.
- State space models (Mamba, S4): O(n · d) -- not attention at all, but recurrent architectures with linear complexity.
- RING / blockwise / distributed: Still O(n²) total but distributed across multiple devices.
Each of these trades some expressivity or quality for efficiency. The open question is whether a sub-quadratic method can match full attention's quality at the longest context lengths. As of 2026, the dominant strategy remains full attention + Flash Attention + GQA for contexts up to ~128K, with sliding window and hybrid approaches extending further.
14. Sparse Attention and Linear Attention Variants
Beyond sliding window and Flash Attention, a family of methods attempts to break the O(n²) barrier more fundamentally. These fall into two broad categories: sparse attention (compute attention on a subset of position pairs) and linear attention (replace the softmax with a decomposable function that enables an O(n) algorithm).
Sparse Attention
Sparse attention methods keep the standard attention formula but restrict which position pairs are computed. The attention matrix becomes sparse -- most entries are never evaluated. The key challenge is choosing which entries to compute: too few and the model loses important long-range connections; too many and the sparsity savings vanish.
Major Sparse Attention Methods
- Longformer (Beltagy et al., 2020): Sliding window + a few "global attention" tokens (e.g., [CLS], question tokens) that attend to and are attended by all positions. Complexity: O(n · (w + g)) where g is the number of global tokens. Designed for document-level NLP tasks.
- BigBird (Zaheer et al., 2020): Sliding window + random attention + global tokens. The random connections provably allow the model to approximate full attention's expressivity. Complexity: O(n). Theoretical result: BigBird is Turing-complete and universal approximator, like full attention.
- Sparse Transformer (Child et al., 2019): Uses a fixed sparse pattern (e.g., attend to every k-th position plus a local window). Designed for images and long sequences. Complexity: O(n · √n).
- Axial / factorized attention: For multi-dimensional inputs (images, video), attends along one axis at a time. Reduces 2D or 3D attention from O((HW)²) to O(HW · (H+W)).
- Dilated sliding window: Like sliding window but with gaps (dilation), so the window covers a wider span with the same number of entries. Inspired by dilated convolutions.
Sparse Attention Patterns Compared (n=12):
(a) Full Attention: (b) Sliding Window (w=4):
################ ----####-------- row 1
################ #----####------ row 2
################ ##---####------ row 3
################ ###--####------ row 4
################ -###-####------ row 5
################ --###-####----- row 6
################ ---###-####---- row 7
################ ----###-####--- row 8
################ -----###-####-- row 9
################ ------###-####- row 10
################ -------###-#### row 11
################ --------###-### row 12
(144 entries) (48 entries: 3x fewer)
(c) BigBird (window+random+global):
G###############G G = global row/col
#-###--#-###---#G # = window or random
##-###--#-###--#G
###-###--#-###-#G
-###-###--#-####G
--###-###--#-###G
#--###-###--#-##G
##--###-###--#-#G
-##--###-###--#-G
#-##--###-###--#G
##-##--###-###-#G
GGGGGGGGGGGGGGGGG (global column too)
(~60-80 entries, some long-range)
Linear Attention
Linear attention takes a fundamentally different approach. Instead of sparsifying the attention matrix, it replaces the softmax with a kernel function that can be decomposed, allowing the associative property of matrix multiplication to reorder the computation and avoid the n² matrix entirely.
The Key Insight
Standard attention computes: softmax(Q·Kᵀ) · V, which requires the n×n intermediate matrix. But softmax can be written as exp(Q·Kᵀ), and if exp(q·k) can be factored as φ(q)·φ(k) for some feature function φ, then:
Standard: softmax(Q·Kᵀ) · V = [exp(Q·Kᵀ) / Z] · V
Requires n×n matrix. Cost: O(n²d)
Linear: Φ(Q) · (Φ(K)ᵀ V) / (Φ(Q) · sum(Φ(K)))
where Φ(X) = φ(X) (kernel feature map, e.g., ELU+1, ReLU, random features)
Key: compute (Φ(K)ᵀ V) FIRST -> (d × d) matrix, independent of n!
Then: Φ(Q) · (d × d) -> (n × d) per position, O(d²) per token
Total cost: O(n · d²) -- LINEAR in n!
Memory: O(d²) for the KᵀV matrix, independent of n
The catch is that the factorization exp(q·k) = φ(q)·φ(k) is not exact for the true softmax (the exponential of a dot product cannot be exactly decomposed into a finite-dimensional feature map). Linear attention methods use approximations: ELU+1, ReLU, random Fourier features, or polynomial kernels. The quality of the approximation determines how much accuracy is lost compared to standard attention.
Linear Attention Methods
| Method |
Kernel φ(x) |
Complexity |
Quality vs Softmax |
| Linear Transformer (Katharopoulos et al., 2020) |
ELU(x) + 1 |
O(n · d²) |
Lower; struggles on language modeling |
| Performer (Choromanski et al., 2020) |
Random Fourier features |
O(n · d²) |
Approximates softmax; moderate quality loss |
| Linear Attention (Shen et al., 2021) |
ReLU or ReLU² |
O(n · d²) |
Similar to ELU+1; task-dependent |
| RWKV (Blink, 2023) |
Custom (recurrent form) |
O(n · d) |
Competitive for LM; not pure attention |
| RetNet (Microsoft, 2023) |
Exponential decay + retention |
O(n · d) inference |
Claims GPT-level quality; hybrid design |
| Mamba / SSMs (Gu & Dao, 2023) |
State space (not kernelized attention) |
O(n · d) |
Strong on some tasks; still maturing |
Linear attention trade-off: Linear attention is O(n · d²) instead of O(n² · d). For short sequences where n < d, linear attention is actually slower than standard attention. The crossover point is around n ≈ d (typically 1024-4096). Linear attention wins decisively only for very long sequences (n >> d), but the quality gap from the softmax approximation has limited adoption in production LLMs. Most production models in 2026 still use standard (Flash) attention with GQA and sliding window rather than linear attention.
The Hybrid Frontier (2024-2026)
The most promising recent direction is hybrid architectures that mix full attention layers with sub-quadratic layers (linear attention or SSM blocks). The idea is to use expensive full attention at a few critical layers for global routing, and cheap linear/SSM layers everywhere else. Examples include Jamba (AI21, 2024), which interleaves Mamba SSM blocks with attention layers, and Samba (Microsoft, 2024), which combines Mamba with sliding window attention. These aim to capture the best of both worlds: long-context efficiency from SSMs and precise retrieval from attention.
State of the art (2026): No sub-quadratic or linear attention method has definitively replaced standard attention for frontier LLMs. The combination of Flash Attention + GQA + sliding window + ring/distributed attention has extended standard attention to million-token contexts. Linear and sparse methods remain active research, with hybrids (Jamba, Samba) showing the most promise. The quadratic wall is being climbed with engineering, not breached with new math -- at least not yet.
15. Comparison Table of Attention Variants
The following table summarizes all attention variants covered in this reference, their key properties, and their deployment status as of 2026.
| Variant |
Year |
Complexity |
Memory (attn matrix) |
Key Feature |
Production Use |
| Bahdanau (Additive) |
2014 |
O(n·m·d) per step |
O(m) per decode step |
Learned alignment; RNN-based |
Legacy / historical |
| Luong (Multiplicative) |
2015 |
O(n·m·d) per step |
O(m) per decode step |
Dot-product scorer; simpler |
Legacy / historical |
| Scaled Dot-Product Self-Attn |
2017 |
O(n²d) |
O(n²) |
Parallel; √d_k scaling |
Universal (every transformer) |
| Multi-Head Attention |
2017 |
O(n²d) |
O(n²) total |
h parallel attention subspaces |
Universal (every transformer) |
| Causal / Masked Attention |
2017 |
O(n²d) |
O(n²/2) |
Lower-triangular mask |
All decoder-only LLMs |
| Cross-Attention |
2017 |
O(n·m·d) |
O(n·m) |
Q from decoder, KV from encoder |
T5, BART, Whisper, diffusion |
| Multi-Query (MQA) |
2019 |
O(n²d) train; O(nd) infer |
O(n) KV cache (1 head) |
1 KV head shared by all Q heads |
PaLM, Falcon, Gemini |
| Sparse Transformer |
2019 |
O(n·√n) |
O(n·√n) |
Fixed strided + local pattern |
Image/video generation |
| Longformer |
2020 |
O(n·(w+g)) |
O(n·(w+g)) |
Sliding window + global tokens |
Document NLP tasks |
| BigBird |
2020 |
O(n) |
O(n) |
Window + random + global |
Long-document; theoretical work |
| Linear Transformer |
2020 |
O(n·d²) |
O(d²) |
ELU+1 kernel; no softmax |
Research; limited production |
| Performer (FAVOR+) |
2020 |
O(n·d²) |
O(d²) |
Random features approximate softmax |
Research; limited production |
| Grouped-Query (GQA) |
2023 |
O(n²d) train; O(ngd/h) infer |
O(ng/h) KV cache |
g KV head groups; 1<g<h |
Llama 2/3, Mistral, Gemma (default) |
| Sliding Window |
2020+ |
O(n·w) |
O(n·w) |
Local window of size w |
Mistral, Mixtral, Longformer |
| Flash Attention 1 |
2022 |
O(n²d) (same FLOPs) |
O(n) (no n² matrix) |
Tiling + online softmax + kernel fusion |
Universal default (PyTorch SDPA) |
| Flash Attention 2 |
2023 |
O(n²d) (same FLOPs) |
O(n) |
Better GPU work partitioning |
Universal default |
| Flash Attention 3 |
2024 |
O(n²d) (same FLOPs) |
O(n) |
Hopper-optimized; FP8; async |
H100/H200 training and inference |
| PagedAttention |
2023 |
O(n²d) (same FLOPs) |
O(n) paged KV cache |
Non-contiguous KV cache pages |
vLLM and serving frameworks |
| Ring Attention |
2023 |
O(n²d) total (distributed) |
O(n²/p) per GPU |
Distributes sequence across p GPUs |
Million-token context experiments |
| Mamba / SSMs |
2023 |
O(n·d) |
O(d) state |
Not attention; selective state spaces |
Research; hybrid models (Jamba) |
| RetNet |
2023 |
O(n·d) inference |
O(d) state |
Multiscale exponential retention |
Research; claims GPT-level quality |
| RWKV |
2023 |
O(n·d) |
O(d) state |
Linear attention as RNN |
Open-source community models |
Quick Selection Guide
| If you need... |
Use... |
| Best quality, moderate context (up to ~128K) |
MHA or GQA + Flash Attention 2/3 |
| Fast autoregressive inference |
GQA (g=h/8) + Flash Attention + PagedAttention |
| Lowest inference memory (KV cache) |
MQA (1 KV head) + Flash Attention |
| Long context (128K - 1M) |
GQA + Flash Attention 3 + Ring Attention (distributed) |
| Very long context, local suffices |
Sliding window + GQA + Flash Attention |
| Document tasks with global tokens |
Longformer / BigBird (window + global) |
| Sub-quadratic, willing to trade quality |
Linear attention or Mamba/SSM hybrid |
| Encoder-decoder (translation, speech) |
MHA + Cross-attention + Flash Attention |
Summary & Key Takeaways
Attention mechanisms have evolved from a targeted fix for the RNN encoding bottleneck into the foundational computational primitive of all modern AI. The key points:
- The bottleneck problem: Pre-attention RNN encoder-decoders compressed entire source sentences into one fixed-length vector, losing information on long inputs. Attention gave the decoder dynamic access to all encoder states.
- Bahdanau (additive): The first attention mechanism. Uses a learned feed-forward scorer (vᵀtanh(Wq+Wk)). Established the Q-K-V retrieval paradigm.
- Luong (multiplicative): Simplified the scorer to a dot product (qᵀk or qᵀWk). The direct precursor to Transformer attention.
- Self-attention: The Transformer's core innovation. Every token in a sequence attends to every other token (including itself), enabling O(1)-length paths between any two positions and full parallelism.
- Scaled dot-product: Attention(Q,K,V) = softmax(Q·Kᵀ/√dᵭ)·V. The √dᵭ scaling is essential to prevent softmax saturation at large dimensions.
- Multi-head attention: Runs h parallel attention computations in subspaces, letting the model learn multiple relationship types (syntactic, coreference, positional) simultaneously at the same total cost.
- Causal masking: Lower-triangular mask prevents attending to future positions, enabling autoregressive training and generation. Mandatory for decoder-only models.
- Cross-attention: Q from decoder, KV from encoder. The bridge in encoder-decoder models (T5, Whisper, diffusion). Absent in decoder-only LLMs.
- GQA / MQA: Share KV heads across query heads to shrink the KV cache and reduce memory bandwidth at inference. GQA (g=h/8) is the 2026 default for new large models.
- Sliding window: O(n·w) local attention. Effective receptive field grows as L·w across layers. Used by Mistral and Longformer for efficient long-context.
- Flash Attention: Exact same math as standard attention, but computed with tiling, online softmax, and kernel fusion to avoid materializing the n² matrix. Reduces memory to O(n) and accelerates 2-4x. Universal default in 2026.
- O(n²) complexity: The quadratic wall is the central challenge for long context. Going from 4K to 128K is a 1,024x cost increase. Every long-context model uses efficiency techniques to address this.
- Sparse & linear attention: Sub-quadratic alternatives (BigBird, Performer, linear transformers, Mamba/SSMs) trade quality for efficiency. Hybrids (Jamba, Samba) are the most promising current direction but have not replaced standard attention at the frontier.
Understanding these mechanisms is essential for anyone working with modern language models -- whether optimizing inference, extending context length, interpreting model behavior, or developing new architectures. Attention is not merely a component of transformers; it is the computational primitive around which the entire modern AI stack is organized.
Further Reading
- Bahdanau, Cho, & Bengio (2014) -- "Neural Machine Translation by Jointly Learning to Align and Translate"
- Luong, Pham, & Manning (2015) -- "Effective Approaches to Attention-based Neural Machine Translation"
- Vaswani et al. (2017) -- "Attention Is All You Need"
- Shazeer (2019) -- "Fast Transformer Decoding: One Write-Head is All You Need" (MQA)
- Child et al. (2019) -- "Generating Long Sequences with Sparse Transformers"
- Beltagy, Peters, & Cohan (2020) -- "Longformer: The Long-Document Transformer"
- Zaheer et al. (2020) -- "Big Bird: Transformers for Longer Sequences"
- Katharopoulos et al. (2020) -- "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention"
- Choromanski et al. (2020) -- "Rethinking Attention with Performers" (FAVOR+)
- Dao et al. (2022) -- "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness"
- Ainslie et al. (2023) -- "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints"
- Dao (2023) -- "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning"
- Shah et al. (2023) -- "FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-Precision"
- Kwon et al. (2023) -- "Efficient Memory Management for Large Language Model Serving with PagedAttention" (vLLM)
- Liu et al. (2023) -- "Ring Attention with Blockwise Transformers for Near-Infinite Context"
- Gu & Dao (2023) -- "Mamba: Linear-Time Sequence Modeling with Selective State Spaces"
- Voita et al. (2019) -- "Analyzing Multi-Head Self-Attention: Specialized Heads Do the Heavy Lifting, the Rest Can Be Pruned"
- Clark et al. (2019) -- "What Does BERT Look at? An Analysis of BERT's Attention"