Introduction
Many tasks take a sequence as input and produce a sequence as output. The classical way to do this is the sequence-to-sequence structure. An encoder ingests the input sequence and compresses it into a single vector, the context vector. A decoder then produces the output sequence one timestep at a time from that vector.
The structure works well, but it has a flaw. Everything the model knows about the input must fit into one context vector, and that vector never changes during generation. The encoder squeezes a sentence, a paragraph, or a book into a fixed-size representation. The decoder reads that same vector at every step. So long inputs lose information.
Attention removes that constraint. At each decoder timestep, we score how relevant every input token is to the token we are about to generate. Then we normalize those scores into a probability distribution over the input positions. We call these distributions the attention weights. For that timestep, the context vector is a sum of the encoder hidden states, each weighted by its attention weight. Every decoder step therefore gets its own context vector, built for the token it is about to produce. It no longer reuses one fixed summary of the whole input.
In this post we reduce attention to its essential operation and write it as a general layer, the attention layer. Then we specialize it to the case where the queries, the keys, and the values all come from the same sequence. Each token looks at every other token in that sequence. This is the self-attention layer.
The generalised attention layer
Attention has three parts. The decoder’s hidden state supplies the query. The encoder’s hidden states are the input vectors the query is compared against. The similarity function scores how much each encoder state matters to the decoder’s current state.
The input fixes the encoder states, while the decoder state changes at every timestep and determines which encoder states to emphasize. We compare every decoder state against every input-side encoder state. So the decoder state is the query, and the encoder states are the inputs it queries.
None of these choices is intrinsic to the mechanism. A query need not come from a decoder, the inputs need not be encoder states, and the similarity function need not be a learned network. The operation is more general than this one application, so we define it as a self-contained layer.
The layer takes two arguments. The query vector $q$ is what we are looking for. The inputs $X = \left[ x_1, \dots, x_N \right]$ are the vectors we attend over. A similarity function $f_{\mathrm{att}}$ scores how relevant each input vector is to the query. The scores become attention weights, and the output is a weighted sum of the inputs. For a single query the layer computes one score per input,
$$ e_i = f_{\mathrm{att}}(q, x_i) $$Stacking the scores into the vector $e = (e_1, \dots, e_N)$, the layer normalizes them into attention weights and combines the inputs:
$$ a = \mathrm{softmax}(e), \qquad y = \sum_i a_i \, x_i . $$Scaled dot-product similarity
In the encoder-decoder setting, the similarity function was a small feed-forward network. It does not have to be. A simpler choice is the dot product, $e_i = q \cdot x_i$, which costs one matrix multiplication. But the raw dot product grows with the dimension.
To see why, suppose the components of $q$ and $x_i$ are independent random variables with mean $0$ and variance $1$. Let $d$ be the dimension of $q$ and of the input vectors, and write the dot product as a sum over those $d$ components:
$$ q \cdot x_i = \sum_{j=1}^{d} q_j (x_i)_j $$Each term is a product of two independent variables with mean $0$ and variance $1$, so its mean is $0$. For independent $U$ and $V$, the variance of the product expands as
$$ \begin{aligned} \mathrm{Var}(UV) &= \mathrm{Var}(U)\,\mathrm{Var}(V) \\[0.5em] &\quad + \mathrm{Var}(U)\,E\!\left[V\right]^2 \\[0.5em] &\quad + \mathrm{Var}(V)\,E\!\left[U\right]^2 \end{aligned} $$With both means at zero and both variances at one, each term has variance $1$.
The terms are independent, so their variances add. The dot product therefore has mean $0$ and variance $d$, and its standard deviation is $\sqrt{d}$. Softmax is unchanged if every score shifts by the same constant, so a large typical magnitude is not itself the problem. What matters is the spread. The scores spread over a range of order $\sqrt{d}$. The gap between the largest and the rest widens with the dimension, and the softmax collapses toward a one-hot vector.
That collapse is harmless in the forward pass, but it is a problem for training: a saturated softmax has a near-zero gradient.
To see why, differentiate the softmax, writing it as
$$ a_i = \frac{\exp(e_i)}{S}, \qquad S = \sum_k \exp(e_k). $$For its own score the quotient rule gives
$$ \begin{aligned} \frac{\partial a_i}{\partial e_i} &= \frac{\exp(e_i)\, S - \exp(e_i)\exp(e_i)}{S^2} \\ &= a_i - a_i^2 \\ &= a_i(1 - a_i). \end{aligned} $$For a different score the numerator does not depend on $e_j$, so only the denominator changes,
$$ \frac{\partial a_i}{\partial e_j} = \frac{0 - \exp(e_i)\exp(e_j)}{S^2} = -a_i a_j . $$The two cases combine, with $\delta_{ij}$ equal to $1$ when $i = j$ and $0$ otherwise,
$$ \frac{\partial a_i}{\partial e_j} = a_i(\delta_{ij} - a_j). $$Near a one-hot vector, one probability is close to $1$ and the rest to $0$. The term $a_i(1 - a_i)$ is small whenever $a_i$ is near $0$ or near $1$ (it peaks at $a_i = 1/2$), and $a_i a_j$ is small because at least one of $a_i, a_j$ is near $0$.
To counteract this we divide the dot product by $\sqrt{d}$:
$$ e_i = \frac{q \cdot x_i}{\sqrt{d}} . $$This is the scaled dot product. The factor $1/\sqrt{d}$ keeps the score variance at $1$ for any dimension, so the softmax stays away from saturation and its gradient does not vanish.
Multiple queries
The single-query layer scores one query against the $N_x$ inputs. To process $N_q$ queries at once, stack them into a matrix $Q$ of shape $N_q \times d$, and the inputs into a matrix $X$ of shape $N_x \times d$. Each row of $Q$ is one query; each row of $X$ is one input vector. The shared dimension $d$ is what lets a single multiply score every query against every input.
The same three steps become three matrix operations:
$$ \begin{aligned} E &= \frac{Q X^{\mathsf{T}}}{\sqrt{d}} \\[0.85em] A &= \mathrm{softmax}(E) \\[0.85em] Y &= A X . \end{aligned} $$$E$ and $A$ are $N_q \times N_x$: one row per query, one column per input. Entry $E_{ij}$ is the score of how relevant input $j$ is to query $i$, so row $i$ of $E$ is the relevance of every input to that query. Softmax runs on each row independently, so every row of $A$ sums to $1$. $Y$ is $N_q \times d$. Row $i$ of $Y$ is the weighted sum of the inputs under row $i$ of $A$:
$$ Y_i = \sum_j A_{ij}\, X_j . $$The general attention layer is now complete. It takes a query and a set of inputs, scores each input’s relevance to that query, normalizes the scores into weights, and returns their weighted sum. The encoder-decoder setting does not fix the pieces, and the layer depends only on its arguments and parameters.
Self-attention layer
Self-attention is the attention layer specialized to a single set of inputs. The input is projected into three different representations: the queries $Q$, the keys $K$, and the values $V$, each through its own learned projection.
Splitting the input into query, key, and value
The attention layer above uses the input vector twice: in the score $E = Q X^{\mathsf{T}}$ and in the output $Y = A X$. These are two different jobs. The score decides where to look: how relevant each position is to the query. The output decides what to take: the content it contributes. A position can be highly relevant to a query yet carry little useful content, or the reverse. There is no reason one vector must do both.
So we project the input into three learned representations. A query matrix $W_q$ produces the queries. A key matrix $W_k$ produces the keys. The queries are matched against the keys to decide relevance. A value matrix $W_v$ produces the values, which supply the content combined into the output. All three come from the same input, but each is a separate learned representation. The keys decide relevance and the values supply content, so the two can differ:
$$ \begin{aligned} Q &= X W_q \\[0.85em] K &= X W_k \\[0.85em] V &= X W_v . \end{aligned} $$Each input row has dimension $d$, so $W_q$ and $W_k$ are $d \times d_q$ and $W_v$ is $d \times d_v$. The queries and keys share $d_q$, so the score below divides by $\sqrt{d_q}$. The values keep their own dimension $d_v$. The layer then computes
$$ \begin{aligned} E &= \frac{Q K^{\mathsf{T}}}{\sqrt{d_q}} \\[0.85em] A &= \mathrm{softmax}(E) \\[0.85em] Y &= A V . \end{aligned} $$The softmax runs across each row. Row $i$ of $Y$ is a weighted sum of the value vectors,
$$ Y_i = \sum_j A_{ij}\, V_j . $$Self-attention ignores order
Self-attention does not consider where a vector sits. The score between query $i$ and key $j$ depends only on the contents of the two vectors, not on their indices. As a result the layer is permutation equivariant: if you permute the input vectors, the output vectors appear in the same permuted order. If $\Pi$ is a permutation matrix and $f$ is a self-attention layer, then
$$ f(\Pi X) = \Pi f(X) . $$Each token’s output is unchanged except for its row index. The layer has no notion of order. For sequences that is a real limitation, because in language order carries much of the meaning. “dog bites man” and “man bites dog” are the same tokens in a different order. The layer can only respond by permuting those output vectors. For sequences, we encode each token’s position in its embedding through positional embeddings.
Complexity, parallelism, and path length
Let $n$ be the sequence length and $d$ the model dimension, so each token is a $d$-dimensional vector. The self-attention layer is a short chain of matrix multiplications. Counting those costs shows how the layer scales, and comparing it with a recurrent layer shows what we gain and what we pay.
Arithmetic cost
Take the usual case $d_q = d_v = d$, so each projection is square. The projections $Q = X W_q$, $K = X W_k$, and $V = X W_v$ each multiply an $n \times d$ matrix by a $d \times d$ matrix. Each costs $O(n d^2)$, so the three together cost $O(n d^2)$. The score matrix $E = Q K^{\mathsf{T}}$ multiplies $n \times d$ by $d \times n$, costing $O(n^2 d)$. Softmax over each of the $n$ rows is $O(n^2)$. The output $Y = A V$ multiplies $n \times n$ by $n \times d$, costing $O(n^2 d)$.
Adding these up, one self-attention layer costs
$$ O(n d^2 + n^2 d). $$Which term is larger depends on how $n$ compares with $d$. They are the same order when $n$ is comparable to $d$. The $n d^2$ term is quadratic in the model dimension; the $n^2 d$ term is quadratic in the sequence length. When the sequence is long ($n \gg d$), the $n^2 d$ term wins and the layer grows quadratically with $n$. That is the cost people usually quote for attention, $O(n^2 d)$. When $n \ll d$, the $n d^2$ term wins instead.
A recurrent layer such as an LSTM has no score matrix. It applies a $d \times d$ transform at each of $n$ steps, so its cost is $O(n d^2)$: linear in $n$, quadratic in $d$.
Both layers therefore share the $O(n d^2)$ cost of transforming every token. Self-attention adds an $O(n^2 d)$ term so that any two positions can meet in a single layer. As $n$ grows, the recurrent layer stays linear while that extra term grows quadratically, so for long sequences attention is the more expensive layer. In the regime where the Transformer was introduced, the sequences were sentence-length and $n$ was often smaller than $d$, so the extra term is the smaller of the two. Vaswani et al. compare the attention product $O(n^2 d)$ with the recurrent cost $O(n d^2)$ and call self-attention faster when $n \lt d$.
Operation count alone does not decide which layer is better. Two other quantities matter too: how many steps must run in sequence (sequential steps), and how far a signal travels between positions (path length). The table below is the comparison from Vaswani et al., with the complexity row written as the sum derived above. The next two subsections unpack the other two rows.
| Self-attention | Recurrent (e.g. LSTM) | |
|---|---|---|
| Complexity per layer | $O(n d^2 + n^2 d)$ | $O(n d^2)$ |
| Sequential steps | $O(1)$ | $O(n)$ |
| Longest path between positions | $O(1)$ | $O(n)$ |
Parallelism
Big-O complexity counts operations. It does not tell you wall-clock time. Every score in the $n \times n$ matrix is independent of every other score, so the whole matrix is one dense multiplication with no loop over positions. Nothing waits on a previous step. Sequential steps count how many operations must finish before the next can start. Self-attention needs $O(1)$ sequential steps. A recurrent layer must run $n$ steps, each depending on the last, so it needs $O(n)$ sequential steps.
On a GPU, dense matrix multiplications run in parallel. Self-attention therefore processes the whole sequence at once. A recurrent layer waits one token at a time, even when it performs fewer total operations. In the long-sequence regime self-attention does more arithmetic, but it does it in a single parallel multiplication that keeps the hardware busy. A recurrent layer spreads less work over a serial chain that leaves the hardware idle.
Path length
Path length is the number of steps a signal must cross to travel from one position to another. With the $n \times n$ score matrix, any two positions $i$ and $j$ connect in one attention operation, so the longest path is $O(1)$. In a recurrent layer, information travels only through the hidden state, so the path from position $1$ to position $n$ is $n$ steps long.
A long path is a long product of Jacobians. Gradients vanish through long products, which is why recurrent layers struggle to use a distant token. Self-attention joins any two positions in one hop, so it models long-range dependencies directly. That capability, not a smaller operation count, is what made self-attention replace recurrence.
When the quadratic cost matters
For sequences long enough that $n^2$ dominates, the quadratic cost is real: a recurrent layer’s linear growth does win on arithmetic. That is why efficient attention exists. Linear and sparse attention cut the number of pairwise scores. FlashAttention keeps the arithmetic quadratic but removes the $O(n^2)$ memory footprint of materializing the full score matrix. Self-attention replaced recurrence in the regime where the two were compared: the sentence-length sequences of sequence-to-sequence models. It did not replace recurrence because it is cheaper at every length.
Conclusion
Self-attention is the attention layer with the queries, the keys, and the values drawn from one sequence. We started with attention as a way for a decoder to consult the encoder. We generalized it into a layer that takes a query and a set of inputs and returns a weighted sum. Then we specialized that layer into self-attention, where the queries, keys, and values all come from the same input. The layer is a compact set of matrix operations. The layer projects the inputs into queries, keys, and values, takes a scaled dot product of the queries and keys, normalizes the scores with a softmax, and sums the values.
The resulting layer is self-contained. It takes a set of vectors, one per token, and returns a set of vectors of the same length, one output per input. It depends on nothing outside its own parameters and inputs. That is why it works as a reusable primitive: place it anywhere in a network where vectors need to exchange information.
Two properties follow. Because every output depends on every input, a single layer sees the whole sequence at once. There is no recurrence to step through, and no stack of layers needed to widen the view. Because the layer has no sequential dependency, it computes all the outputs together, so it is highly parallel. The cost is memory: the score matrix has one row per query and one column per key, so it grows as $O(n^2)$ in the sequence length.
What matters is not the mechanics but the properties they produce. Self-attention is order-agnostic, so for sequences its inputs must carry explicit positional information. It is also long-range and highly parallel, qualities a recurrent network does not have. That combination is why it became the primary computational building block of modern sequence models, and why the Transformer can scale as it does.
References
- Justin Johnson, Lecture 13: Attention, EECS 498-007/598-005 Deep Learning for Computer Vision, University of Michigan (2020).
- Hochreiter & Schmidhuber, Long Short-Term Memory (1997).
- Sutskever, Vinyals & Le, Sequence to Sequence Learning with Neural Networks (2014).
- Bahdanau, Cho & Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2014).
- Vaswani et al., Attention Is All You Need (2017).
- Child, Gray, Radford & Sutskever, Generating Long Sequences with Sparse Transformers (2019).
- Katharopoulos, Vyas, Pappas & Fleuret, Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention (2020).
- Dao, Fu, Ermon, Rudra & Ré, FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (2022).
- Dive into Deep Learning, 11. Attention Mechanisms and Transformers.