- Introduced by
- Vaswani, A. et al.
- Year
- 2017
- Type
- Attention mechanism (Transformer core)
What does it do?
Multi-head self-attention, introduced by Vaswani and colleagues in 2017, lets every position in a sequence relate itself to all other positions in a single parallel step.
It is the core operation of the Transformer architecture and underlies BERT, GPT, and T5. At each position, the output is a learned weighted combination of information drawn from the whole sequence.
The intuition behind the method
Earlier sequence models read text one step at a time, so information from distant words had to survive many intermediate updates. This made long-range relationships hard to capture and slow to compute. Self-attention lets each token look directly at every other token and decide how much weight to give each one, so context that depends on distant words is combined in a single parallel pass.
History
Self-attention was introduced by Vaswani and colleagues in the 2017 paper 'Attention Is All You Need', which proposed the Transformer architecture and dispensed with recurrence entirely. It quickly became the foundation of large pre-trained language models: Devlin and colleagues built BERT on bidirectional Transformers in 2019, and the same mechanism underlies GPT and T5.
When to use it
Choose self-attention when your data is sequential and the relationships between distant elements carry much of the signal, for example text in which meaning depends on context far apart. It needs a large training set relative to model size, because with small samples it cannot learn reliable representations. For small tasks, start from a pre-trained model or use a simpler baseline. Training large Transformers is generally impractical without GPU or other accelerator hardware; small models can run on CPUs at reduced speed. A positional encoding is needed so that order is represented. Do not choose it for short, tabular, or small-sample problems where a tree-based model is likely to perform as well, or for very long sequences where the quadratic memory cost is prohibitive.
Limitations and considerations
- Attention-score computation grows quadratically with sequence length in both compute and memory, which makes very long inputs expensive.
- Training large models generally requires GPU or other accelerator hardware.
- Attention alone is order-agnostic, so positional information must be supplied separately.
- On small datasets the many projection parameters are fitted from limited data, so the model overfits and does not learn reliable representations.
- Attention weights show where the model placed weight, not a validated explanation of its prediction.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Connects any two positions directly in one step, avoiding the chain of intermediate updates that recurrent networks need to carry long-range dependencies.
- Computation across positions is parallel rather than sequential, so training maps well onto GPU hardware.
- Separate heads, each with its own projections, let the model track several kinds of relationship within the same layer.
- Serves as the shared backbone of BERT, GPT, and T5, so models pre-trained on it can be fine-tuned for new tasks.
Applications
- Text classification and other supervised natural-language tasks.
- Prediction and representation learning over sequential data.
- Pre-training and fine-tuning of large language models such as BERT and GPT.
- Any setting where long-range relationships between sequence elements must be modelled.
How it works
How it works
Each input position is mapped by three learned weight matrices (W_Q, W_K, W_V) into a query, a key, and a value vector. The query encodes what a position is looking for, the key encodes what a position offers for matching, and the value encodes the content passed on when it is matched.
Formula
Q = XW_Q,\; K = XW_K,\; V = XW_V
Each query is compared with every key through a dot product, divided by the square root of the key dimension to keep the scores in a stable range, and normalised with a softmax to give attention weights. The output at each position is the weighted sum of all value vectors, so it draws on the entire sequence in one operation.
Formula
\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)VThe projection and attention steps are repeated in parallel for h heads. Head i has its own projection matrices W_i^Q, W_i^K, W_i^V and computes head_i = Attention(X W_i^Q, X W_i^K, X W_i^V), so that different heads can attend to different representation subspaces and specialise in different relationships. The head outputs are concatenated and multiplied by the output matrix W_O to return to a single representation.
Formula
\text{head}_i = \text{Attention}(XW_i^Q, XW_i^K, XW_i^V),\quad \text{MultiHead}(X) = \text{Concat}(\text{head}_1,\dots,\text{head}_h)W_OCommon pitfalls
- Training on too little data: the mechanism overfits rather than learning useful representations, and starting from a pre-trained model and fine-tuning it is usually a better option for small tasks.
- Omitting positional encoding leaves the model unable to distinguish word order, so inputs that differ only in order look identical to it.
- Underestimating the quadratic cost of long sequences, which can exhaust memory during training.
- Using a Transformer for small tabular problems where a random forest or XGBoost model is the more appropriate baseline.
Frequently asked questions
Why is the attention score scaled by the square root of the key dimension?
Without scaling, dot products grow large as the key dimension increases, pushing the softmax into regions with vanishing gradients. Dividing by the square root of the key dimension keeps the scores in a stable range.
What do the multiple heads add?
Each head learns its own query, key, and value projections, so different heads can attend to different kinds of relationships at once. Their outputs are concatenated and projected back together into a single representation.
Why is positional encoding needed?
Self-attention treats positions as interchangeable, so on its own it has no notion of order. Positional encoding injects information about each token's position so the model can use word order.
How much data does it need?
It is data-hungry, and no single threshold applies; the requirement depends on model size and task. Small training sets lead to overfitting and unreliable representations, so in that regime fine-tuning a pre-trained model or using a simpler model such as random forest or XGBoost is usually preferable.
Do high attention weights explain a prediction?
Not by themselves. Attention weights show where the model placed weight, but they are not a validated explanation of why it made a prediction. Judge the model by held-out performance, not by reading the weights.
Related methods
Sources
Vaswani, A. et al. (2017). Attention Is All You Need. NeurIPS.
Open publication referenceDevlin, J. et al. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL.
Open publication referenceBATDI-BASARAN-nitel-arastirmada-yapay-zeka-II (Artificial Intelligence Tools in Qualitative Research II), p. 162