Attention (machine learning)
In the vast and complex world of machine learning, models often need a way to prioritize information—to know what truly matters in a sea of data. This is where 'attention' comes in: a groundbreaking mechanism that allows AI to dynamically focus on the most relevant parts of its input, much like we do when we concentrate. It's transformed how artificial intelligence understands everything from language to images, enabling capabilities once thought impossible. Attention mechanisms allow machine learning models to weigh the importance of different parts of an input sequence, dynamically focusing on what's most relevant. Inspired by human cognition, attention overcame a major limitation of earlier neural networks, particularly their struggle with long-range dependencies in data. The advent of self-attention and the Transformer architecture revolutionized AI, providing highly parallelizable and powerful models now foundational to modern large language models.
AI Summary
In the vast and complex world of machine learning, models often need a way to prioritize information—to know what truly matters in a sea of data. This is where 'attention' comes in: a groundbreaking mechanism that allows AI to dynamically focus on the most relevant parts of its input, much like we do when we concentrate. It's transformed how artificial intelligence understands everything from language to images, enabling capabilities once thought impossible.
- Attention mechanisms allow machine learning models to weigh the importance of different parts of an input sequence, dynamically focusing on what's most relevant.
- Inspired by human cognition, attention overcame a major limitation of earlier neural networks, particularly their struggle with long-range dependencies in data.
- The advent of self-attention and the Transformer architecture revolutionized AI, providing highly parallelizable and powerful models now foundational to modern large language models.
The AI's Spotlight
Imagine you're trying to understand a long, complex sentence. Your brain doesn't treat every word equally; it highlights the crucial ones and relates them to each other. In machine learning, 'attention' provides this exact ability—allowing models to assign importance to different parts of an input sequence.
This 'importance' is represented by what we call 'soft weights.' Unlike the 'hard weights' that are fixed during training, these soft weights are fluid. They change with every piece of new input, dynamically shifting the model's focus to whatever is most pertinent in that moment.
Inspired by Human Focus
The concept of machine attention draws direct inspiration from human cognition. Think of the 'cocktail party effect'—how you can tune into a single conversation amidst a noisy room, filtering out distractions. Early recurrent neural networks, or RNNs, struggled with this kind of selective focus.
RNNs process information sequentially, like reading a sentence one word at a time. The problem was, by the time they reached the end of a long sentence, critical information from the beginning often got 'attenuated,' or faded away. It was like trying to remember the start of a story after many chapters.
Attention offered a solution by giving every part of the input equal access to any other part, directly. Instead of just relying on the immediate past, a token—which can be a word or a part of an image—could now 'look' at any other token in the sequence to understand its context.
From Recurrence to Revolution
The journey of attention in machine learning accelerated dramatically in the mid-2010s. It began by enhancing 'encoder-decoder' models, particularly for tasks like language translation. These early models combined RNNs with attention, proving much more effective for longer sentences.
But the true game-changer arrived in 2017 with the 'Transformer' architecture. This design boldly removed the slower, sequential RNNs entirely, instead relying almost exclusively on a highly parallel and efficient form of attention called 'self-attention.' This innovation unlocked unprecedented speeds and performance.
How Attention Works: A Glimpse
At its core, attention involves comparing different parts of the input to determine their relevance. Imagine a 'query' vector asking: 'What other information in this sequence is important for me right now?' It then looks at a set of 'key' vectors, each representing a piece of information.
The more a key matches the query, the higher its 'score' or 'weight.' These weights are then used to combine corresponding 'value' vectors, essentially extracting the most relevant information and summing it up into a 'context vector'—a rich summary of what the model should focus on.
The 'I Love You' Translation
Let's consider translating 'I love you' into French: 'Je t'aime.' The attention mechanism doesn't just translate word-for-word in order. When generating 'je,' it might focus mostly on 'I.' But for 't',' it shifts its focus heavily to 'you.' And for 'aime,' it highlights 'love.'
This dynamic focusing creates an 'alignment matrix,' which maps how much each output word attends to each input word. It beautifully illustrates the nuanced, non-linear relationships models can learn.
I love you je 0.94 0.02 0.04 t' 0.11 0.01 0.88 aime 0.03 0.95 0.02
This 'soft' weighting is crucial. Sometimes, a single output word might need to consider multiple input words, like translating 'look it up' into 'cherchez-le.' Soft attention allows for this multiple-to-multiple alignment, creating a richer context than simply picking one 'best' input word.
Key Variants of Attention
The core attention idea has several powerful variations. 'Self-attention,' for instance, means the input sequence attends to itself. Every word in a sentence looks at every other word to understand its own context within that very sentence. This is fundamental to Transformers.
'Multi-head attention' takes this a step further. Instead of just one attention mechanism, it uses several 'heads' in parallel. Each head learns to focus on different aspects of the input, offering multiple perspectives. Their results are then combined, leading to a much richer and more robust understanding.
In computer vision, attention can operate on different dimensions. 'Spatial attention' focuses on specific regions of an image, while 'channel attention' emphasizes particular feature maps. Combinations of these allow models to zero in on the most informative visual details.
Optimizing Performance: FlashAttention
As input sequences grow longer—think millions of tokens—the attention mechanism can become a memory hog. Calculating the attention matrix grows with the square of the input length, demanding immense GPU memory. 'FlashAttention' is a clever optimization that tackles this challenge.
It breaks down the attention computation into smaller blocks that fit into a GPU's faster, on-chip memory. This reduces the need to store massive intermediate matrices, drastically lowering memory usage and boosting efficiency without sacrificing accuracy. It's like processing a giant puzzle in smaller, manageable sections.
Widespread Impact and Applications
Attention mechanisms are now ubiquitous across modern AI. In Natural Language Processing, they power large language models (LLMs) like GPT and BERT, excelling in tasks from translation and summarization to question answering. They are the backbone of conversational AI.
In computer vision, 'Vision Transformers' (ViTs) use attention to achieve state-of-the-art results in image classification, object detection, and image captioning. By focusing on relevant image regions, they improve accuracy and provide insights into model decision-making.
Attention Maps as Explanations
One fascinating application is using 'attention maps' to visualize what a model is looking at. These heatmaps show which parts of an image or text sequence were most attended to, offering a window into the model's 'thought process' and helping us interpret its decisions.
However, while attention maps are a valuable tool for understanding, their role as definitive explanations is still debated. Sometimes, high attention scores don't perfectly correlate with the biggest impact on a model's final output, reminding us that AI's inner workings can still hold mysteries.
The Mathematical Elegance
At its heart, the standard scaled dot-product attention mechanism elegantly combines three crucial components: 'Queries' (Q), 'Keys' (K), and 'Values' (V). These are typically matrices derived from the input data, allowing for efficient parallel computation.
This formula shows how Query (Q) is multiplied by the transpose of Key (K) to get an alignment score, scaled, and then passed through a softmax function to get the attention weights. These weights then multiply the Value (V) matrix to produce the final output, representing the weighted sum of information.
{\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{T}}{\sqrt {d_{k}}}}\right)VMulti-Head Attention: A Deeper Dive
Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. It's like having several attention mechanisms working in parallel, each learning a different way to 'focus' and extract relevance.
Here, each 'head' computes its own QKV attention, often after projecting the original Q, K, V into different subspaces using learnable matrices. The results from all heads are then concatenated and linearly transformed, blending these diverse perspectives into a unified output.
{\text{MultiHead}}(Q,K,V)={\text{Concat}}({\text{head}}_{1},...,{\text{head}}_{h})W^{O}Self-Attention: Looking Within
Self-attention is a special case where the Queries, Keys, and Values all originate from the same input sequence. This means the model processes a sequence by allowing each element within it to weigh the importance of all other elements in that same sequence.
For encoder self-attention, if H is the matrix of input vectors (e.g., word embeddings), then separate weight matrices ($W^Q$, $W^K$, $W^V$) project H into its Query, Key, and Value representations. The attention mechanism then processes these, allowing each element of H to
H'=\mathrm{Attention} (HW^{Q},HW^{K},HW^{V})Causal Masking: Preventing Peeking
In some scenarios, like when a model is generating new text word by word (autoregressive decoding), it shouldn't be allowed to 'peek' at future words it hasn't generated yet. This is where 'causal masking' comes in.
Causal masking modifies the attention scores such that elements can only attend to prior or current elements in the sequence, not future ones. Mathematically, it sets the attention weights for future positions to zero (or negative infinity before softmax), ensuring the model maintains its autoregressive integrity and generates output based only on what it has seen so far.
Article
Attention (machine learning)
Attention mechanism, overview
In machine learning, attention is a method that determines the importance of each component in a sequence relative to the other components in that sequence. In natural language processing, importance is represented by "soft" weights assigned to each word in a sentence. More generally, attention encodes vectors called token embeddings across a fixed-width sequence 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 serial recurrent neural network (RNN) language translation system, but a more recent design, namely the transformer, removed the slower sequential RNN and relied more heavily on the faster parallel attention scheme.
Inspired by ideas about attention in humans, the attention mechanism was developed to address the weaknesses of using information from the hidden 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 be attenuated. Attention allows a token equal access to any part of a sentence directly, rather than only through the previous state.
History
Attention (machine learning)
<table><thead><tr><th>1950s–1960s</th><th>Psychology and biology of attention. Cocktail party effect — focusing on content by filtering out background noise. Filter model of attention, partial report paradigm, and saccade control.</th></tr></thead><tbody><tr><td>1980s</td><td>Sigma-pi units, higher-order neural networks.</td></tr><tr><td>1990s</td><td>Fast weight controllers and dynamic links between neurons, anticipating key-value mechanisms in attention.</td></tr><tr><td>1998</td><td>The bilateral filter was introduced in image processing. It uses pairwise affinity matrices to propagate relevance across elements.</td></tr><tr><td>2005</td><td>Non-local means extended affinity-based filtering in image denoising, using Gaussian similarity kernels as fixed attention-like weights.</td></tr><tr><td>2014</td><td>seq2seq with RNN + Attention. 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.</td></tr><tr><td>2015</td><td>Attention was extended to vision for image captioning tasks.</td></tr><tr><td>2016</td><td>Self-attention was integrated into RNN-based models to capture intra-sequence dependencies. Self-attention was explored in decomposable attention models for natural language inference and structured self-attentive sentence embeddings.</td></tr><tr><td>2017</td><td>The Transformer architecture introduced in the research paper Attention is All You Need formalized scaled dot-product self-attention: Relation networks and set Transformers applied attention to unordered sets and relational reasoning, generalizing pairwise interaction models.</td></tr><tr><td>2018</td><td>Non-local neural networks extended attention to computer vision by capturing long-range dependencies in space and time. Graph attention networks applied attention mechanisms to graph-structured data.</td></tr><tr><td>2019–2020</td><td>Efficient Transformers, including Reformer, Linformer, and Performer, introduced scalable approximations of attention for long sequences.</td></tr><tr><td>2019+</td><td>Hopfield networks were reinterpreted as associative memory-based attention systems, and vision transformers (ViTs) achieved competitive results in image classification. Transformers were adopted across scientific domains, including AlphaFold for protein folding, CLIP for vision-language pretraining, and attention-based dense segmentation models like CCNet and DANet.</td></tr></tbody></table>
Additional surveys of the attention mechanism in deep learning are provided by Niu et al. and Soydaner.
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 the Transformer architecture, which replaced recurrence with attention mechanisms. As a result, Transformers became the foundation for models like BERT, T5 and generative pre-trained transformers (GPT).
Overview
Attention (machine learning)
The modern era of machine attention was revitalized by grafting an attention mechanism (Fig 1. orange) to an Encoder-Decoder.
<table><thead><tr><th></th><th>Fig 1. Encoder-decoder with attention. 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.</th></tr></thead><tbody><tr><td>Label</td><td>Description</td></tr><tr><td>100</td><td>Max. sentence length</td></tr><tr><td>300</td><td>Embedding size (word dimension)</td></tr><tr><td>500</td><td>Length of hidden vector</td></tr><tr><td>9k, 10k</td><td>Dictionary size of input & output languages respectively.</td></tr><tr><td>x, Y</td><td>9k and 10k 1-hot dictionary vectors. x → x implemented as a lookup 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.</td></tr><tr><td>x</td><td>300-long word embedding vector. The vectors are usually pre-calculated from other projects such as GloVe or Word2Vec.</td></tr><tr><td>h</td><td>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 a thought vector as Hinton calls it.</td></tr><tr><td>s</td><td>500-long decoder hidden state vector.</td></tr><tr><td>E</td><td>500 neuron recurrent 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.</td></tr><tr><td>D</td><td>2-layer decoder. The recurrent layer has 500 neurons and the fully-connected linear layer has 10k neurons (the size of the target vocabulary). The linear layer alone has 5 million (500 × 10k) weights – ~10 times more weights than the recurrent layer.</td></tr><tr><td>score</td><td>100-long alignment score</td></tr><tr><td>w</td><td>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.</td></tr><tr><td>A</td><td>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.</td></tr><tr><td>H</td><td>500×100. 100 hidden vectors h concatenated into a matrix</td></tr><tr><td>c</td><td>500-long context vector = H w. c is a linear combination of h vectors weighted by w.</td></tr></tbody></table>
Figure 2 shows the internal step-by-step operation of the attention block (A) in Fig 1.
$${\displaystyle {\begin{aligned}(XW{v})^{T}{[(W{k}X^{T}){({\underline {x}}W{q})^{T}}]{sm}}\end{aligned}}}$$
Interpreting attention weights
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 translating I love you to French. On the first pass through the decoder, 94% of the attention weight is on the first English word I, so the network offers the word je. On the second pass of the decoder, 88% of the attention weight is on the third English word you, so it offers t'. On the last pass, 95% of the attention weight is on the second English word love, so it offers aime.
In the I love you example, the second word love is aligned with the third word aime. Stacking soft row vectors together for je, t', and aime yields an alignment matrix:
<table><thead><tr><th></th><th>I</th><th>love</th><th>you</th></tr></thead><tbody><tr><td>je</td><td>0.94</td><td>0.02</td><td>0.04</td></tr><tr><td>t'</td><td>0.11</td><td>0.01</td><td>0.88</td></tr><tr><td>aime</td><td>0.03</td><td>0.95</td><td>0.02</td></tr></tbody></table>
Sometimes, alignment can be multiple-to-multiple. For example, the English phrase look it up corresponds to cherchez-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.
Variants
Attention (machine learning)
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). A "slow" neural network outputs the "fast" weights of another neural network through outer products. The slow network learns by gradient descent. It was later renamed as "linearized self-attention". • Bahdanau-style attention, also referred to as additive attention, • Luong-style attention, which is known as multiplicative 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, • positional attention and factorized positional attention.
For convolutional neural networks, attention mechanisms can be distinguished by the dimension on which they operate, namely: spatial attention, channel attention, or combinations.
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.
Optimizations
Flash attention
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 of GPU 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.
FlexAttention
FlexAttention is an attention kernel developed by Meta that allows users to modify attention scores prior to softmax and dynamically chooses the optimal attention algorithm.
Applications
Attention (machine learning)
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 on vision transformers (ViT), visualizing attention scores as a heat map (called saliency maps or attention maps) has become an important and routine way to inspect the decision making process of ViT models. 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.
Because vision transformers are typically trained in a self-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. Some class-sensitive interpretability methods originally developed for convolutional neural networks can be also applied to ViT, such as GradCAM, which back-propagates the gradients to the outputs of the final attention layer.
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, higher attention scores do not always correlate with greater impact on model performances.
Mathematical representation
Standard scaled dot-product attention
For matrices: ${\displaystyle Q\in \mathbb {R} ^{m\times d{k}},K\in \mathbb {R} ^{n\times d{k}}}$ and ${\displaystyle V\in \mathbb {R} ^{n\times d{v}}}$, the scaled dot-product, or QKV attention, is defined as: ${\displaystyle {\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{T}}{\sqrt {d{k}}}}\right)V\in \mathbb {R} ^{m\times d{v}}}$ where ${\displaystyle {}^{T}}$ denotes transpose and the softmax function is applied independently to every row of its argument. The matrix ${\displaystyle Q}$ contains ${\displaystyle m}$ queries, while matrices ${\displaystyle K,V}$ jointly contain an unordered set of ${\displaystyle n}$ key-value pairs. Value vectors in matrix ${\displaystyle V}$ are weighted using the weights resulting from the softmax operation, so that the rows of the ${\displaystyle m}$-by-${\displaystyle d{v}}$ output matrix are confined to the convex hull of the points in ${\displaystyle \mathbb {R} ^{d{v}}}$ given by the rows of ${\displaystyle V}$.
To understand the permutation invariance and permutation equivariance properties of QKV attention, let ${\displaystyle A\in \mathbb {R} ^{m\times m}}$ and ${\displaystyle B\in \mathbb {R} ^{n\times n}}$ be permutation matrices; and ${\displaystyle D\in \mathbb {R} ^{m\times n}}$ an arbitrary matrix. The softmax function is permutation equivariant in the sense that: ${\displaystyle {\text{softmax}}(ADB)=A\,{\text{softmax}}(D)B}$ By noting that the transpose of a permutation matrix is also its inverse, it follows that: ${\displaystyle {\text{Attention}}(AQ,BK,BV)=A\,{\text{Attention}}(Q,K,V)}$ which shows that QKV attention is equivariant with respect to re-ordering the queries (rows of ${\displaystyle Q}$); and invariant to re-ordering of the key-value pairs in ${\displaystyle K,V}$. 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: ${\displaystyle X\mapsto {\text{Attention}}(XT{q},XT{k},XT{v})}$ is permutation equivariant with respect to re-ordering the rows of the input matrix ${\displaystyle X}$ in a non-trivial way, because every row of the output is a function of all the rows of the input. Similar properties hold for multi-head attention, which is defined below.
Masked attention
When QKV attention is used as a building block for an autoregressive decoder, and when at training time all input and output matrices have ${\displaystyle n}$ rows, a masked attention variant is used: ${\displaystyle {\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{T}}{\sqrt {d{k}}}}+M\right)V}$ where the mask, ${\displaystyle M\in \mathbb {R} ^{n\times n}}$ is a strictly upper triangular matrix, with zeros on and below the diagonal and ${\displaystyle -\infty }$ in every element above the diagonal. The softmax output, also in ${\displaystyle \mathbb {R} ^{n\times n}}$ is then lower triangular, with zeros in all elements above the diagonal. The masking ensures that for all ${\displaystyle 1\leq i<j\leq n}$, row ${\displaystyle i}$ of the attention output is independent of row ${\displaystyle j}$ 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 attention
Decoder multiheaded cross-attention
Multi-head attention ${\displaystyle {\text{MultiHead}}(Q,K,V)={\text{Concat}}({\text{head}}{1},...,{\text{head}}{h})W^{O}}$ where each head is computed with QKV attention as: ${\displaystyle {\text{head}}{i}={\text{Attention}}(QW{i}^{Q},KW{i}^{K},VW{i}^{V})}$ and ${\displaystyle W{i}^{Q},W{i}^{K},W{i}^{V}}$, and ${\displaystyle W^{O}}$ are parameter matrices.
The permutation properties of (standard, unmasked) QKV attention apply here also. For permutation matrices, ${\displaystyle A,B}$: ${\displaystyle {\text{MultiHead}}(AQ,BK,BV)=A\,{\text{MultiHead}}(Q,K,V)}$ from which we also see that multi-head self-attention: ${\displaystyle X\mapsto {\text{MultiHead}}(XT{q},XT{k},XT{v})}$ is equivariant with respect to re-ordering of the rows of input matrix ${\displaystyle X}$.
Bahdanau (additive) attention
${\displaystyle {\text{Attention}}(Q,K,V)={\text{softmax}}(\tanh(W{Q}Q+W{K}K))V}$ where ${\displaystyle W{Q}}$ and ${\displaystyle W{K}}$ are learnable weight matrices.
Luong attention (general)
${\displaystyle {\text{Attention}}(Q,K,V)={\text{softmax}}(QWK^{T})V}$ where ${\displaystyle W}$ is a learnable weight matrix.
Self-attention
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 fixed lookup table. This gives a sequence of hidden vectors ${\displaystyle h{0},h{1},\dots }$. These can then be applied to a dot-product attention mechanism, to obtain${\displaystyle {\begin{aligned}h{0}'&=\mathrm {Attention} (h{0}W^{Q},HW^{K},HW^{V})\\h{1}'&=\mathrm {Attention} (h{1}W^{Q},HW^{K},HW^{V})\\&\;\,\vdots \end{aligned}}}$or more succinctly, ${\displaystyle H'=\mathrm {Attention} (HW^{Q},HW^{K},HW^{V})}$. 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.
Masking
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 ${\displaystyle w{ij}=0}$ for all ${\displaystyle i<j}$, called "causal masking". This attention mechanism is the "causally masked self-attention".