How transformer attention works

A definition page for the attention mechanism in Vaswani and colleagues’ 2017 paper, “Attention Is All You Need.” The figures and architecture below are the ones in that paper, not a later product.

“Attention,” in the sense used by most modern language models, is a computation described in a 2017 research paper, not a brand and not a legal category. This page follows “Attention Is All You Need”, by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin. The authors, then at Google Brain, Google Research, and the University of Toronto, proposed a network they called the Transformer. The same paper is in the NeurIPS 2017 proceedings. Later systems change widths, depths, and training recipes. The numbers and diagrams below are the ones in that paper.

An abstract field of glowing connected nodes in dark space, with no people, logos, or readable text.
AI-generated

What the authors were replacing

The abstract states the starting point clearly. The dominant sequence transduction models of the time, the authors wrote, were based on recurrent or convolutional networks that included an encoder and a decoder, and the best of those models also connected the encoder and the decoder through an attention mechanism. The Transformer, they proposed, was a simpler architecture “based solely on attention mechanisms, dispensing with recurrence and convolutions entirely.”

That claim is about the architecture they published, not about every later system that borrowed the name. The paper’s own tests were machine translation and English constituency parsing.

Encoder, decoder, and a fixed width

Section 3 of the paper describes an encoder-decoder structure. The encoder maps an input sequence of symbol representations to a sequence of continuous representations. The decoder then generates an output sequence one symbol at a time, and is auto-regressive: at each step it consumes the symbols already produced as additional input.

Both stacks are built from identical layers. Section 3.1 says the encoder is a stack of (N = 6) identical layers. Each layer has two sub-layers: a multi-head self-attention mechanism, and a position-wise fully connected feed-forward network. A residual connection wraps each sub-layer, followed by layer normalization, which the authors write as (\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x))). To make those residual connections work, every sub-layer and the embedding layers produce outputs of dimension (d_{\text{model}} = 512).

The decoder is also a stack of (N = 6) identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer: encoder-decoder attention, so that decoder positions can attend over the encoder’s output. The paper also describes masking in the decoder’s self-attention so that a position cannot attend to subsequent positions, which preserves the auto-regressive property.

Attention as queries, keys, and values

Section 3.2 gives the general definition the rest of the paper uses. An attention function, the authors write, maps a query and a set of key-value pairs to an output. The query, keys, values, and output are all vectors. The output is a weighted sum of the values, and the weight on each value comes from a compatibility function of the query with the corresponding key.

That is the whole mechanism, stated without a product name: a query looks at keys, those comparisons become weights, and the weights mix the values.

Scaled dot-product attention

The particular function in the paper is called scaled dot-product attention. The input consists of queries and keys of dimension (d_k), and values of dimension (d_v). The authors compute the dot products of the query with all keys, divide each by (\sqrt{d_k}), and apply a softmax function to obtain the weights on the values.

In matrix form, with queries packed into (Q), keys into (K), and values into (V), they write:

[\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\left(\frac{QK^{T}}{\sqrt{d_k}}\right)V]

The paper compares this with additive attention and with unscaled dot-product attention. Dot-product attention, they write, is identical to their algorithm except for the scaling factor (1/\sqrt{d_k}). They say they scale the scores because, for large values of (d_k), the dot products grow in magnitude and push the softmax into a region with extremely small gradients. The square-root term is there to keep those scores in a more usable range. It is not a learned temperature; in this paper it is a fixed function of the key dimension.

Multi-head attention

Section 3.2.2 says the authors did not run a single attention function at the full (d_{\text{model}}) width. Instead they linearly project the queries, keys, and values (h) times with different learned projections, run attention in parallel on each projected version, concatenate the results, and project once more. They call this multi-head attention, and they write it as:

[\mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_h)W^{O}]

where each head is attention on a projected query, key, and value. The stated reason is that a single head’s averaging can inhibit the model from attending to information in different representation subspaces at different positions. Multi-head attention, they write, allows the model to do that jointly.

In this work they use (h = 8) parallel heads. For each head, (d_k = d_v = d_{\text{model}} / h = 64). Because each head is narrower, they write, the total computational cost is similar to that of single-head attention with full dimensionality.

The same section lists three uses of this block in the Transformer:

  • Encoder-decoder attention, where queries come from the previous decoder layer and the keys and values come from the encoder output, so every decoder position can attend over all positions in the input sequence.
  • Encoder self-attention, where queries, keys, and values all come from the previous encoder layer, so each position can attend to all positions in the previous encoder layer.
  • Decoder self-attention, with masking so that a position attends only to itself and to earlier positions.

Those three uses are the paper’s account of where attention sits in the model, not a later design pattern added by a vendor.

Feed-forward layers and positional encodings

Attention is not the only sub-layer. Section 3.3 describes a position-wise feed-forward network in every encoder and decoder layer: two linear transformations with a ReLU activation in between, applied to each position separately. The input and output width is again (d_{\text{model}} = 512); the inner width is (d_{ff} = 2048).

Because the model, as published, contains no recurrence and no convolution, section 3.5 says the authors had to inject information about the order of the tokens. They add positional encodings to the input embeddings at the bottoms of both stacks. The encodings have the same dimension as the embeddings so the two can be summed. In this paper the encodings are fixed sine and cosine functions of different frequencies, one even and one odd dimension at a time, with wavelengths in a geometric progression. The authors say they hypothesized that this would make it easier for the model to attend by relative position. They also note that learned positional embeddings were a possible alternative.

Why the authors emphasized parallelism

Table 1 in the paper compares layer types by complexity, by the number of sequential operations, and by maximum path length. A self-attention layer, they write, connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires a number of sequential operations that grows with the sequence length. The cost of a self-attention layer grows with the square of the sequence length times the representation width. The authors present that table as a reason the architecture can be trained with more parallel computation than a recurrent stack, at the cost of a quadratic term in sequence length.

Section 5.2 says they trained their models on one machine with eight NVIDIA P100 GPUs. For the base models, each training step took about 0.4 seconds, and they trained for 100,000 steps, or 12 hours. For the larger models, step time was 1.0 second, and they trained for 300,000 steps, or 3.5 days. Training data, in section 5.1, included the WMT 2014 English-German set of about 4.5 million sentence pairs, encoded with byte-pair encoding and a shared vocabulary of about 37,000 tokens, and a larger WMT 2014 English-French set of 36 million sentences.

What the paper reported on translation

The abstract and Table 2 report the translation results the authors wanted the architecture judged by. On the WMT 2014 English-to-German task, they reported 28.4 BLEU, which they said improved on the best existing results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French task, they reported a single-model BLEU score of 41.8 after training for 3.5 days on eight GPUs. Table 2 lists the base model separately, at 27.3 BLEU for English-to-German and 38.1 for English-to-French. Those are the paper’s reported scores on those test sets, not later replications, and BLEU is the metric they used, not a general quality grade.

The abstract also says the authors applied the model to English constituency parsing with large and limited training data, as a check that it generalized beyond the translation tasks.

How to read this page

This page is a reading of one paper. It does not say that every system now called a transformer uses (N = 6), (d_{\text{model}} = 512), eight heads, or sinusoidal positional encodings. It does not rank later models, and it is not a guide to implementing a training run. For the definition of a large language model as later terminology reports use that phrase, see What is a large language model?. For the working memory of a request, which is a different idea from the architecture in this paper, see What is a context window?.

The source for every architectural figure above is the 2017 paper, in the arXiv HTML and PDF and the NeurIPS 2017 PDF.