Inmachine learning,attention is a method that determines the importance of each component in a sequence relative to the other components in that sequence. Innatural language processing, importance is represented by "soft" weights assigned to each word in a sentence. More generally, attention encodesvectors calledtokenembeddings across a fixed-widthsequence that can range from tens to millions of tokens in size.
Unlike "hard" weights, which are computed during the backwards training pass, "soft" weights exist only in the forward pass and therefore change with every step of the input. Earlier designs implemented the attention mechanism in a serialrecurrent neural network (RNN) language translation system, but a more recent design, namely thetransformer, removed the slower sequential RNN and relied more heavily on the faster parallel attention scheme.
Inspired by ideas aboutattention in humans, the attention mechanism was developed to address the weaknesses of using information from thehidden layers of recurrent neural networks. Recurrent neural networks favor more recent information contained in words at the end of a sentence, while information earlier in the sentence tends to beattenuated. Attention allows a token equal access to any part of a sentence directly, rather than only through the previous state.
Fast weight controllers and dynamic links between neurons, anticipating key-value mechanisms in attention.[5][6][7][8]
1998
Thebilateral filter was introduced in image processing. It uses pairwise affinity matrices to propagate relevance across elements.[9]
2005
Non-local means extended affinity-based filtering in image denoising, using Gaussian similarity kernels as fixed attention-like weights.[10]
2014
seq2seq with RNN + Attention.[11] Attention was introduced to enhance RNN encoder-decoder translation, particularly for long sentences. See Overview section.
Attentional Neural Networks introduced a learned feature selection mechanism using top-down cognitive modulation, showing how attention weights can highlight relevant inputs.[12]
2015
Attention was extended to vision for image captioning tasks.[13][14]
2016
Self-attention was integrated into RNN-based models to capture intra-sequence dependencies.[15][16]
Self-attention was explored in decomposable attention models for natural language inference[17] and structured self-attentive sentence embeddings.[18]
Relation networks[20] and set Transformers[21] applied attention to unordered sets and relational reasoning, generalizing pairwise interaction models.
2018
Non-local neural networks[22] extended attention to computer vision by capturing long-range dependencies in space and time. Graph attention networks[23] applied attention mechanisms to graph-structured data.
2019–2020
Efficient Transformers, including Reformer,[24] Linformer,[25] and Performer,[26] introduced scalable approximations of attention for long sequences.
2019+
Hopfield networks were reinterpreted as associative memory-based attention systems,[27] andvision transformers (ViTs) achieved competitive results in image classification.[28]
Transformers were adopted across scientific domains, includingAlphaFold for protein folding,[29] CLIP for vision-language pretraining,[30] and attention-based dense segmentation models like CCNet[31] and DANet.[32]
Additional surveys of the attention mechanism in deep learning are provided by Niu et al.[33] and Soydaner.[34]
The major breakthrough came with self-attention, where each element in the input sequence attends to all others, enabling the model to capture global dependencies. This idea was central to theTransformer architecture, which replaced recurrence with attention mechanisms. As a result, Transformers became the foundation for models likeBERT,T5 andgenerative pre-trained transformers (GPT).[19]
The modern era of machine attention was revitalized by grafting an attention mechanism (Fig 1. orange) to an Encoder-Decoder.[citation needed]
Animated sequence of language translation
Fig 1. Encoder-decoder with attention.[35] Numerical subscripts (100, 300, 500, 9k, 10k) indicate vector sizes while lettered subscripts i and i − 1 indicate time steps. Pinkish regions in H matrix and w vector are zero values. See Legend for details.
Dictionary size of input & output languages respectively.
x,Y
9k and 10k1-hot dictionary vectors.x → x implemented as alookup table rather than vector multiplication.Y is the 1-hot maximizer of the linear Decoder layer D; that is, it takes the argmax of D's linear layer output.
x
300-long word embedding vector. The vectors are usually pre-calculated from other projects such asGloVe orWord2Vec.
h
500-long encoder hidden vector. At each point in time, this vector summarizes all the preceding words before it. The final h can be viewed as a "sentence" vector, or athought vector as Hinton calls it.
s
500-long decoder hidden state vector.
E
500 neuronrecurrent neural network encoder. 500 outputs. Input count is 800–300 from source embedding + 500 from recurrent connections. The encoder feeds directly into the decoder only to initialize it, but not thereafter; hence, that direct connection is shown very faintly.
D
2-layer decoder. The recurrent layer has 500 neurons and the fully-connected linear layer has 10k neurons (the size of the target vocabulary).[36] The linear layer alone has 5 million (500 × 10k) weights – ~10 times more weights than the recurrent layer.
score
100-long alignment score
w
100-long vector attention weight. These are "soft" weights which changes during the forward pass, in contrast to "hard" neuronal weights that change during the learning phase.
A
Attention module – this can be a dot product of recurrent states, or the query-key-value fully-connected layers. The output is a 100-long vector w.
H
500×100. 100 hidden vectors h concatenated into a matrix
c
500-long context vector = H * w. c is a linear combination of h vectors weighted by w.
Figure 2 shows the internal step-by-step operation of the attention block (A) in Fig 1.
Figure 2. The diagram shows the attention forward pass calculating correlations of the word "that" with other words in "See that girl run." Given the right weights from training, the network should be able to identify "girl" as a highly correlated word. Some things to note:
This example focuses on the attention of a single word "that". In practice, the attention of each word is calculated in parallel to speed up calculations. Simply changing the lowercase "x" vector to the uppercase "X" matrix will yield the formula for this.
Softmax scalingqWkT /√100 prevents a high variance inqWkT that would allow a single word to excessively dominate the softmax resulting in attention to only one word, as a discrete hard max would do.
Notation: the commonly written row-wisesoftmax formula above assumes that vectors are rows, which runs contrary to the standard math notation of column vectors. More correctly, we should take the transpose of the context vector and use the column-wisesoftmax, resulting in the more correct form
In translating between languages, alignment is the process of matching words from the source sentence to words of the translated sentence. Networks that perform verbatim translation without regard to word order would show the highest scores along the (dominant) diagonal of the matrix. The off-diagonal dominance shows that the attention mechanism is more nuanced.
Consider an example of translatingI love you to French. On the first pass through the decoder, 94% of the attention weight is on the first English wordI, so the network offers the wordje. On the second pass of the decoder, 88% of the attention weight is on the third English wordyou, so it offerst'. On the last pass, 95% of the attention weight is on the second English wordlove, so it offersaime.
In theI love you example, the second wordlove is aligned with the third wordaime. Stacking soft row vectors together forje,t', andaime yields analignment matrix:
I
love
you
je
0.94
0.02
0.04
t'
0.11
0.01
0.88
aime
0.03
0.95
0.02
Sometimes, alignment can be multiple-to-multiple. For example, the English phraselook it up corresponds tocherchez-le. Thus, "soft" attention weights work better than "hard" attention weights (setting one attention weight to 1, and the others to 0), as we would like the model to make a context vector consisting of a weighted sum of the hidden vectors, rather than "the best one", as there may not be a best hidden vector.
Comparison of the data flow in CNN, RNN, and self-attention
Many variants of attention implement soft weights, such as
fast weight programmers, or fast weight controllers (1992).[5] A "slow"neural network outputs the "fast" weights of another neural network throughouter products. The slow network learns by gradient descent. It was later renamed as "linearized self-attention".[37]
Bahdanau-style attention,[11] also referred to asadditive attention,
Luong-style attention,[38] which is known asmultiplicative attention,
Early attention mechanisms similar to modern self-attention were proposed using recurrent neural networks. However, the highly parallelizable self-attention was introduced in 2017 and successfully used in the Transformer model,
Forconvolutional neural networks, attention mechanisms can be distinguished by the dimension on which they operate, namely: spatial attention,[40] channel attention,[41] or combinations.[42][43]
These variants recombine the encoder-side inputs to redistribute those effects to each target output. Often, a correlation-style matrix of dot products provides the re-weighting coefficients. In the figures below, W is the matrix of context attention weights, similar to the formula in Overview section above.
1. encoder-decoder dot product
2. encoder-decoder QKV
3. encoder-only dot product
4. encoder-only QKV
5. Pytorch tutorial
Both encoder & decoder are needed to calculate attention.[38]
Both encoder & decoder are needed to calculate attention.[44]
Decoder isnot used to calculate attention. With only 1 input into corr, W is an auto-correlation of dot products. wij = xi xj.[45]
A fully-connected layer is used to calculate attention instead of dot product correlation.[47]
Legend
Label
Description
Variables X, H, S, T
Upper case variables represent the entire sentence, and not just the current word. For example, H is a matrix of the encoder hidden state—one word per column.
S, T
S, decoder hidden state; T, target word embedding. In thePytorch Tutorial variant training phase, T alternates between 2 sources depending on the level ofteacher forcing used. T could be the embedding of the network's output word; i.e. embedding(argmax(FC output)). Alternatively with teacher forcing, T could be the embedding of the known correct word which can occur with a constant forcing probability, say 1/2.
X, H
H, encoder hidden state; X, input word embeddings.
W
Attention coefficients
Qw, Kw, Vw, FC
Weight matrices for query, key, value respectively. FC is a fully-connected weight matrix.
Column-wise softmax(matrix of all combinations of dot products). The dot products arexi * xj in variant #3,hi* sj in variant 1, and column i ( Kw * H ) * column j ( Qw * S ) in variant 2, and column i ( Kw * X ) * column j ( Qw * X ) in variant 4. Variant 5 uses a fully-connected layer to determine the coefficients. If the variant is QKV, then the dot products are normalized by the√d whered is the height of the QKV matrices.
The size of the attention matrix is proportional to the square of the number of input tokens. Therefore, when the input is long, calculating the attention matrix requires a lot ofGPU memory. Flash attention is an implementation that reduces the memory needs and increases efficiency without sacrificing accuracy. It achieves this by partitioning the attention computation into smaller blocks that fit into the GPU's faster on-chip memory, reducing the need to store large intermediate matrices and thus lowering memory usage while increasing computational efficiency.[48]
FlexAttention[49] is an attention kernel developed byMeta that allows users to modify attention scores prior tosoftmax and dynamically chooses the optimal attention algorithm.
Attention is widely used in natural language processing, computer vision, and speech recognition. In NLP, it improves context understanding in tasks like question answering and summarization. In vision, visual attention helps models focus on relevant image regions, enhancing object detection and image captioning.
Attention maps as explanations for vision transformers
From the original paper onvision transformers (ViT), visualizing attention scores as a heat map (calledsaliency maps or attention maps) has become an important and routine way to inspect the decision making process of ViT models.[50] One can compute the attention maps with respect to any attention head at any layer, while the deeper layers tend to show more semantically meaningful visualization. Attention rollout is a recursive algorithm to combine attention scores across all layers, by computing the dot product of successive attention maps.[51]
Because vision transformers are typically trained in aself-supervised manner, attention maps are generally not class-sensitive. When a classification head is attached to the ViT backbone, class-discriminative attention maps (CDAM) combines attention maps and gradients with respect to the class[CLS] token.[52] Some class-sensitiveinterpretability methods originally developed forconvolutional neural networks can be also applied to ViT, such as GradCAM, whichback-propagates the gradients to the outputs of the final attention layer.[53]
Using attention as basis of explanation for the transformers in language and vision is not without debate. While some pioneering papers analyzed and framed attention scores as explanations,[54][55] higher attention scores do not always correlate with greater impact on model performances.[56]
For matrices: and, the scaled dot-product, or QKV attention, is defined as:where denotestranspose and thesoftmax function is applied independently to every row of its argument. The matrix contains queries, while matrices jointly contain anunordered set of key-value pairs. Value vectors in matrix are weighted using the weights resulting from the softmax operation, so that the rows of the-by- output matrix are confined to theconvex hull of the points in given by the rows of.
To understand the permutation invariance and permutation equivariance properties of QKV attention,[57] let and bepermutation matrices; and an arbitrary matrix. The softmax function is permutation equivariant in the sense that:By noting that the transpose of a permutation matrix is also its inverse, it follows that:which shows that QKV attention isequivariant with respect to re-ordering the queries (rows of); andinvariant to re-ordering of the key-value pairs in. These properties are inherited when applying linear transforms to the inputs and outputs of QKV attention blocks. For example, a simple self-attention function defined as: is permutation equivariant with respect to re-ordering the rows of the input matrix in a non-trivial way, because every row of the output is a function of all the rows of the input. Similar properties hold formulti-head attention, which is defined below.
When QKV attention is used as a building block for an autoregressive decoder, and when at training time all input and output matrices have rows, a masked attention variant is used:where the mask, is astrictly upper triangular matrix, with zeros on and below the diagonal and in every element above the diagonal. The softmax output, also in is thenlower triangular, with zeros in all elements above the diagonal. The masking ensures that for all, row of the attention output is independent of row of any of the three input matrices. The permutation invariance and equivariance properties of standard QKV attention do not hold for the masked variant.
Multi-head attentionwhere each head is computed with QKV attention as:and, and are parameter matrices.
The permutation properties of (standard, unmasked) QKV attention apply here also. For permutation matrices,:from which we also see that multi-head self-attention: is equivariant with respect to re-ordering of the rows of input matrix.
Self-attention is essentially the same as cross-attention, except that query, key, and value vectors all come from the same model. Both encoder and decoder can use self-attention, but with subtle differences.
For encoder self-attention, we can start with a simple encoder without self-attention, such as an "embedding layer", which simply converts each input word into a vector by a fixedlookup table. This gives a sequence of hidden vectors. These can then be applied to a dot-product attention mechanism, to obtainor more succinctly,. This can be applied repeatedly, to obtain a multilayered encoder. This is the "encoder self-attention", sometimes called the "all-to-all attention", as the vector at every position can attend to every other.
Decoder self-attention with causal masking, detailed diagram
For decoder self-attention, all-to-all attention is inappropriate, because during the autoregressive decoding process, the decoder cannot attend to future outputs that has yet to be decoded. This can be solved by forcing the attention weights for all, called "causal masking". This attention mechanism is the "causally masked self-attention".
^Broadbent, Donald E. (1958).Perception and Communication. Pergamon Press.
^Kowler, Eileen (1995). "The control of saccadic eye movements".Reviews of Oculomotor Research.5:1–70.
^Rumelhart, David E.; Hinton, G. E.; Mcclelland, James L. (1987-07-29)."A General Framework for Parallel Distributed Processing"(PDF). In Rumelhart, David E.; Hinton, G. E.; PDP Research Group (eds.).Parallel Distributed Processing, Volume 1: Explorations in the Microstructure of Cognition: Foundations. Cambridge, Massachusetts: MIT Press.ISBN978-0-262-68053-0.
^Xu, Kelvin; Ba, Jimmy; Kiros, Ryan (2015).Show, Attend and Tell: Neural Image Caption Generation with Visual Attention.arXiv:1502.03044.
^Vinyals, Oriol; Toshev, Alexander; Bengio, Samy; Erhan, Dumitru (2015). "Show and Tell: A Neural Image Caption Generator".2015 IEEE Conference on Computer Vision and Pattern Recognition (CVPR). pp. 3156–3164.doi:10.1109/CVPR.2015.7298935.ISBN978-1-4673-6964-0.
^Cheng, Jianpeng (2016). "Long Short-Term Memory-Networks for Machine Reading".arXiv:1601.06733 [cs.CL].
^Paulus, Romain (2017). "A Deep Reinforced Model for Abstractive Summarization".arXiv:1705.04304 [cs.CL].
^Parikh, Anees (2016).Decomposable Attention Model for Natural Language Inference. EMNLP.arXiv:1606.01933.
^Schlag, Imanol; Irie, Kazuki; Schmidhuber, Jürgen (2021). "Linear Transformers Are Secretly Fast Weight Programmers".ICML 2021. Springer. pp. 9355–9366.
^Zhu, Xizhou; Cheng, Dazhi; Zhang, Zheng; Lin, Stephen; Dai, Jifeng (2019). "An Empirical Study of Spatial Attention Mechanisms in Deep Networks".2019 IEEE/CVF International Conference on Computer Vision (ICCV). pp. 6687–6696.arXiv:1904.05873.doi:10.1109/ICCV.2019.00679.ISBN978-1-7281-4803-8.S2CID118673006.
^Woo, Sanghyun; Park, Jongchan; Lee, Joon-Young; Kweon, In So (2018-07-18). "CBAM: Convolutional Block Attention Module".arXiv:1807.06521 [cs.CV].
^Georgescu, Mariana-Iuliana; Ionescu, Radu Tudor; Miron, Andreea-Iuliana; Savencu, Olivian; Ristea, Nicolae-Catalin; Verga, Nicolae; Khan, Fahad Shahbaz (2022-10-12). "Multimodal Multi-Head Convolutional Attention with Various Kernel Sizes for Medical Image Super-Resolution".arXiv:2204.04218 [eess.IV].
^Mullenbach, James; Wiegreffe, Sarah; Duke, Jon; Sun, Jimeng; Eisenstein, Jacob (2018-04-16),Explainable Prediction of Medical Codes from Clinical Text,arXiv:1802.05695
^Bahdanau, Dzmitry; Cho, Kyunghyun; Bengio, Yoshua (2016-05-19),Neural Machine Translation by Jointly Learning to Align and Translate,arXiv:1409.0473
^Serrano, Sofia; Smith, Noah A. (2019-06-09),Is Attention Interpretable?,arXiv:1906.03731
^Lee, Juho; Lee, Yoonho; Kim, Jungtaek; Kosiorek, Adam R; Choi, Seungjin; Teh, Yee Whye (2018). "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks".arXiv:1810.00825 [cs.LG].