Skip to main content

Reading “Attention Is All You Need”: The Original Transformer Paper

In 2017, Vaswani and seven co-authors, most of them then at Google Brain or Google Research, published Attention Is All You Need and introduced the Transformer. The paper is about machine translation, and its model is an encoder–decoder; most of today’s large language models keep only the decoder half. That context makes the paper easier to read. The authors were asking whether a translation model could do without recurrence and convolution altogether, not how to build a chat model.

What follows goes through the paper in its own order. Section, table and equation numbers refer to arXiv version 7. Worked numerical examples of attention itself are in Attention Mechanism; modern components such as RMSNorm, RoPE, GQA and SwiGLU are covered in Transformers: Original Architecture and Modern Blocks and are not repeated here.

The 2017 Problem: Recurrence Makes Training Wait​

Section 1 starts from the state of the art at the time: recurrent networks such as LSTMs and GRUs led in language modelling and machine translation. A recurrent model computes along the sequence one position at a time, producing hidden state hth_t from ht−1h_{t-1} and the input at position tt. The authors point out that this inherently sequential computation rules out parallelism within a training example. The problem grows with sequence length, because memory also limits how many examples fit in a batch. Factorization tricks and conditional computation had improved efficiency, but the fundamental constraint of sequential computation remained.

Attention was already a standard part of translation models. It relates two positions directly regardless of their distance, yet it was almost always used together with a recurrent network. The paper proposes removing recurrence entirely and relying on attention alone to draw global dependencies between input and output.

Section 2 sets the Transformer beside another line of work that also reduced sequential computation. The Extended Neural GPU, ByteNet and ConvS2S use convolutions to compute hidden representations for all positions in parallel. In those models, however, the number of operations needed to relate signals from two arbitrary positions grows with their distance, linearly for ConvS2S and logarithmically for ByteNet, which makes distant dependencies harder to learn. The Transformer reduces this to a constant number of operations. The authors name the cost as well: averaging attention-weighted positions reduces the effective resolution, which is what multi-head attention is meant to counteract.

So the paper is after two things at once: how much of training can run in parallel, and how long a path a signal must travel between two distant positions. Table 1 in Section 4 puts both into complexity terms.

The Architecture as the Paper Defines It​

Section 3 keeps the general framework of sequence transduction models. The encoder maps an input sequence of symbols (x1,…,xn)(x_1,\dots,x_n) to continuous representations z=(z1,…,zn)\mathbf z=(z_1,\dots,z_n). Given z\mathbf z, the decoder generates an output sequence (y1,…,ym)(y_1,\dots,y_m) one symbol at a time. Each step is autoregressive: the symbols generated so far are fed back as additional input for the next one.

Original Transformer: encoder on the left, masked decoder on the right, with cross-attention joining them.Open full-size image

The encoder is on the left and the decoder on the right; the N× beside each stack means the same layer is repeated N=6N=6 times. The arrows that bypass each sublayer are residual connections, and “Add & Norm” means add first, then apply layer normalization. Of the three inputs to the decoder’s middle attention sublayer, two come from the encoder output and one from the decoder itself.

Section 3.1 describes the two stacks. The encoder has N=6N=6 identical layers, each with two sublayers: multi-head self-attention and a position-wise fully connected feed-forward network. The decoder also has N=6N=6 layers and adds a third sublayer, which performs multi-head attention over the output of the encoder stack.

Each sublayer is wrapped in a residual connection followed by layer normalization, so the output of a sublayer is

LayerNorm⁡(x+Sublayer⁡(x)).\operatorname{LayerNorm}\big(x+\operatorname{Sublayer}(x)\big).

Normalization comes after the residual addition, an ordering later called Post-Norm. To make the residual additions possible, every sublayer and both embedding layers produce outputs of dimension dmodel=512d_{\text{model}}=512.

The decoder’s self-attention is masked so that a position cannot attend to later positions. Together with output embeddings shifted right by one position, this ensures that the prediction for position ii depends only on known outputs at positions less than ii. To train the model to output [A, B, EOS], for example, the decoder receives [BOS, A, B]; the position that predicts B can see only BOS and A.

Three Uses of Attention in the Model​

Section 3.2.3 lists three places where the model uses multi-head attention. The computation is identical in all three; what changes is where the queries, keys and values come from, and which positions are visible:

UseQueries fromKeys and values fromEach position can see
Encoder self-attentionOutput of the previous encoder layerSame placeAll positions of the previous encoder layer
Decoder self-attentionOutput of the previous decoder layerSame placePositions up to and including itself
Encoder–decoder attentionOutput of the previous decoder layerOutput of the encoderAll positions of the input sequence

The third is what is usually called cross-attention; it follows the typical encoder–decoder attention of earlier sequence-to-sequence models. The decoder’s mask is implemented inside scaled dot-product attention: before the softmax, every value that corresponds to an illegal connection is set to −∞-\infty, so its weight is exactly zero.

Scaled Dot-Product Attention: Why Scale the Dot Products​

Section 3.2 defines attention plainly: it maps a query and a set of key–value pairs to an output, which is a weighted sum of the values, with each weight computed by a compatibility function of the query and the corresponding key. Section 3.2.1 uses the dot product as that function. Packing many queries into a matrix QQ, and the keys and values into KK and VV, gives Equation (1):

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V.\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V.

Here dkd_k is the dimension of queries and keys, and dvd_v the dimension of values. The two most common attention functions at the time were additive attention and dot-product attention; the latter differs from the equation above only by the scaling factor 1/dk1/\sqrt{d_k}. Their theoretical complexity is similar, but dot-product attention runs on highly optimized matrix multiplication and is much faster and more space-efficient in practice.

Why scale? Experiments cited by the paper found the two mechanisms similar for small dkd_k, while additive attention outperformed unscaled dot-product attention for larger dkd_k. The authors suspect that for large dkd_k the dot products grow large in magnitude and push the softmax into regions with extremely small gradients. A footnote gives the reason: if the components of qq and kk are independent random variables with mean 0 and variance 1, then q⋅k=∑i=1dkqikiq\cdot k=\sum_{i=1}^{d_k}q_ik_i has mean 0 and variance dkd_k. Dividing by dk\sqrt{d_k} brings the variance back to 1.

With the paper’s dk=64d_k=64, the standard deviation of a dot product is about 8. Suppose two keys have unscaled scores of 8 and 0. The softmax gives the first a weight of about 0.9997, nearly one-hot, and the softmax derivative p(1−p)p(1-p) falls to about 0.0003. Divided by 8, the scores become 1 and 0, the weights about 0.73 and 0.27, and the derivative about 0.20. This is only a hand calculation. The paper presents the gradient explanation as a suspicion and runs no separate experiment on it.

The figure below runs the same computation on a seven-word sentence. To keep the arithmetic readable, its vectors have only two dimensions, so scores are divided by 2\sqrt2; in the paper the divisor is 64=8\sqrt{64}=8. Turn on the causal mask to see how decoder self-attention hides later words, or switch to “Both heads” for a preview of the multi-head concatenation in the next section.

Attention inside one sentence

Choose the word that asks (the query). Each step adds one part of the calculation.

Query word

Each row is one query and each column one key. Every row is its own softmax and adds up to 100%. Select a row to make that word the query.

q(it) = [2.2, 0]

Keykq·k/√2Weight
The[0.2, 0]0.314.0%
cat[2, 0.4]3.1166%
slept[0.3, 1.6]0.474.7%
because[0, 0.2]0.002.9%
it[1, 0.3]1.5614%
was[0.1, 0.5]0.163.4%
tired[0.4, 1.4]0.625.5%

Head 1: meaning · Weighted sum

Thecatsleptbecauseitwastiredo(it)

Output o1 = Σ w·v = [2.67, 1.16]

Head 1: meaning · All queries

ThecatsleptbecauseitwastiredThe10201710141216cat5133269926slept555741558because821208131019it466531435was73614615814tired554941559

The vectors are chosen by hand so that two patterns are easy to see. Heads in a trained model are rarely this clean.

Multi-Head Attention: Eight Heads of 64 Dimensions​

Rather than performing one attention function on dmodeld_{\text{model}}-dimensional queries, keys and values, Section 3.2.2 projects them hh times with different learned projections to dkd_k, dkd_k and dvd_v dimensions, runs attention on each projection in parallel, concatenates the hh outputs of dimension dvd_v, and projects once more:

MultiHead⁡(Q,K,V)=Concat⁡(head1,…,headh) WO,headi=Attention⁡(QWiQ, KWiK, VWiV).\begin{aligned} \operatorname{MultiHead}(Q,K,V)&=\operatorname{Concat}(\mathrm{head}_1,\dots,\mathrm{head}_h)\,W^O,\\ \mathrm{head}_i&=\operatorname{Attention}(QW_i^Q,\,KW_i^K,\,VW_i^V). \end{aligned}

The projection matrices have shapes WiQ,WiK∈Rdmodel×dkW_i^Q,W_i^K\in\mathbb R^{d_{\text{model}}\times d_k}, WiV∈Rdmodel×dvW_i^V\in\mathbb R^{d_{\text{model}}\times d_v} and WO∈Rhdv×dmodelW^O\in\mathbb R^{hd_v\times d_{\text{model}}}. The paper uses h=8h=8 heads with dk=dv=dmodel/h=64d_k=d_v=d_{\text{model}}/h=64 each.

Follow the shapes for a 10-token sentence. The input is 10×51210\times512. Each head projects it to 10×6410\times64 queries, keys and values, computes a 10×1010\times10 weight matrix and outputs 10×6410\times64. Concatenating eight heads returns 10×51210\times512, which is multiplied by the 512×512512\times512 matrix WOW^O. Because each head is smaller, the total computation is similar to single-head attention at full dimensionality. With these shapes, one multi-head attention sublayer holds four 512×512512\times512 weight matrices, 1,048,576 weights in total.

The authors’ argument is that multi-head attention lets the model attend jointly to information from different representation subspaces at different positions; with a single head, averaging inhibits this. Rows (A) of Table 3 test the claim, as discussed below.

The Other Three Components​

Position-Wise Feed-Forward Networks​

In Section 3.3, every encoder and decoder layer also contains a fully connected feed-forward network applied to each position separately and identically. It consists of two linear transformations with a ReLU in between, Equation (2):

FFN⁡(x)=max⁡(0, xW1+b1) W2+b2.\operatorname{FFN}(x)=\max(0,\,xW_1+b_1)\,W_2+b_2.

Positions within a layer share parameters, while different layers use different ones; the paper notes that this can also be described as two convolutions with kernel size 1. Input and output have dmodel=512d_{\text{model}}=512 dimensions and the inner layer has dff=2048d_{ff}=2048. At that size, W1W_1 and W2W_2 hold 2×512×2048=2,097,1522\times512\times2048=2{,}097{,}152 weights, about twice the projection weights of one attention sublayer. The title says attention is all you need, yet in each encoder layer the FFN holds twice as many weights as attention; only the decoder, with its second attention sublayer, brings the two roughly level. Attention moves information between positions; the FFN then processes each position on its own.

Embeddings and Weight Sharing​

Section 3.4 uses learned embeddings to turn input and output tokens into dmodeld_{\text{model}}-dimensional vectors, and the usual learned linear transformation and softmax to turn decoder output into next-token probabilities. The paper shares one weight matrix between the two embedding layers and the pre-softmax linear transformation, and in the embedding layers multiplies those weights by dmodel\sqrt{d_{\text{model}}} (about 22.6). The paper does not give a reason for this scaling.

Sharing one embedding table between source and target languages requires both sides to use the same vocabulary. That is the setup for English–German: Section 5.1 states that sentences were encoded with byte-pair encoding (BPE) and a shared source–target vocabulary of about 37000 tokens. General tokenization and vocabulary practice is covered in Tokenization and Text Representations Inside a Model.

Sinusoidal Positional Encoding​

With neither recurrence nor convolution, the model needs some other source of information about the relative or absolute position of tokens if it is to use their order. Section 3.5 adds “positional encodings” to the input embeddings at the bottom of the encoder and decoder stacks. The encodings have the same dimension dmodeld_{\text{model}} as the embeddings, so the two can be summed. The paper uses sine and cosine functions of different frequencies:

PE(pos, 2i)=sin⁡ ⁣(pos100002i/dmodel),PE(pos, 2i+1)=cos⁡ ⁣(pos100002i/dmodel).\begin{aligned} PE_{(pos,\,2i)}&=\sin\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right),\\ PE_{(pos,\,2i+1)}&=\cos\!\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right). \end{aligned}

Here pospos is the position and ii the dimension. Each dimension of the encoding corresponds to a sinusoid, sine in even dimensions and cosine in odd ones, with each pair sharing a frequency; the wavelengths form a geometric progression from 2π2\pi to 10000⋅2π10000\cdot2\pi. At position 1, the first pair of dimensions is sin⁡1≈0.841\sin 1\approx0.841 and cos⁡1≈0.540\cos 1\approx0.540. For the last pair (i=255i=255) the denominator is about 9647, and the sine is only about 0.0001. Early dimensions change quickly with position and late ones change slowly; together they distinguish many positions.

The authors chose this function because they hypothesized it would let the model easily learn to attend by relative position: for any fixed offset kk, PEpos+kPE_{pos+k} can be written as a linear function of PEposPE_{pos}. For a single frequency ω\omega this is the angle-addition identity. Moving from (sin⁡ωp,cos⁡ωp)(\sin\omega p,\cos\omega p) to (sin⁡ω(p+k),cos⁡ω(p+k))(\sin\omega(p+k),\cos\omega(p+k)) takes one 2×22\times2 rotation matrix that depends only on kk.

The paper also tried learned positional embeddings and found nearly identical results (Table 3, row (E)). It kept the sinusoidal version because it “may” let the model extrapolate to sequences longer than those seen in training. That is the authors’ expectation; the paper reports no extrapolation experiment.

Why Self-Attention: Reading Table 1​

Section 4 compares self-attention layers with recurrent and convolutional layers on one task: mapping a variable-length sequence (x1,…,xn)(x_1,\dots,x_n) to another of equal length (z1,…,zn)(z_1,\dots,z_n), with xi,zi∈Rdx_i,z_i\in\mathbb R^d. It uses three criteria: total computational complexity per layer; the amount of computation that can be parallelized, measured by the minimum number of sequential operations; and the path length between long-range dependencies in the network. The shorter the paths that forward and backward signals must traverse, the easier long-range dependencies are to learn.

In Table 1, nn is the sequence length, dd the representation dimension, kk the convolution kernel size and rr the neighbourhood size in restricted self-attention:

Layer typeComplexity per layerSequential operationsMaximum path length
Self-attentionO(n2⋅d)O(n^2\cdot d)O(1)O(1)O(1)O(1)
RecurrentO(n⋅d2)O(n\cdot d^2)O(n)O(n)O(n)O(n)
ConvolutionalO(k⋅n⋅d2)O(k\cdot n\cdot d^2)O(1)O(1)O(log⁡kn)O(\log_k n)
Self-attention (restricted)O(r⋅n⋅d)O(r\cdot n\cdot d)O(1)O(1)O(n/r)O(n/r)

Start with the last two columns. A self-attention layer connects all positions with a constant number of sequential operations; a recurrent layer needs O(n)O(n). Position 50 has to wait for the 49 states before it, and a signal from word 1 passes through 49 state updates before it reaches word 50. In self-attention, those two positions are connected directly within one layer.

Then the complexity column. Self-attention layers are faster than recurrent layers when the sequence length nn is smaller than the representation dimension dd. The authors note that this is most often the case for the sentence representations used by state-of-the-art translation models, such as word-piece and byte-pair representations. Plug in d=512d=512: at n=50n=50, n2d=1,280,000n^2d=1{,}280{,}000 against nd2=13,107,200nd^2=13{,}107{,}200, an order of magnitude less for self-attention; at n=2000n=2000, the first becomes 2.048×1092.048\times10^9, about four times the second. The O(1)O(1) in the table means the work inside a layer can run in parallel, not that self-attention is cheap. For very long sequences, the authors suggest restricting attention to a neighbourhood of size rr centred on the output position, at the cost of raising the maximum path length to O(n/r)O(n/r), and leave this for future work.

The convolution row needs a word of explanation. A single convolutional layer with kernel width k<nk\lt n does not connect every pair of positions. Doing so takes a stack of O(n/k)O(n/k) layers for contiguous kernels, or O(log⁡kn)O(\log_k n) for dilated convolutions, which lengthens the longest paths. Convolutional layers are generally more expensive than recurrent ones by a factor of kk. Separable convolutions bring the complexity down to O(k⋅n⋅d+n⋅d2)O(k\cdot n\cdot d+n\cdot d^2), but even with k=nk=n that equals a self-attention layer plus a position-wise feed-forward layer, which is exactly the combination the Transformer uses.

The authors mention a side benefit: self-attention could yield more interpretable models. In the appendix visualizations, individual heads appear to learn different tasks, and some seem to follow the syntactic and semantic structure of sentences; several heads in layer 5, for instance, link “making” to the distant “more difficult”. How much attention weights actually prove is a separate question, discussed in the section on interpreting weights in Attention Mechanism.

Training Setup​

Section 5 gives the training details. The training times and costs in Table 2 follow directly from the hardware and step counts described here.

Data, Hardware and Schedule​

Section 5.1: English–German uses the standard WMT 2014 dataset of about 4.5 million sentence pairs, with a shared BPE vocabulary of about 37000 tokens. English–French uses the much larger WMT 2014 English–French dataset of 36M sentences, with a 32000 word-piece vocabulary. Sentence pairs were batched by approximate length, with each batch holding about 25000 source tokens and 25000 target tokens.

Section 5.2: all models were trained on one machine with 8 NVIDIA P100 GPUs. Base models took about 0.4 seconds per step and were trained for 100,000 steps, about 12 hours. Big models took 1.0 seconds per step and were trained for 300,000 steps, about 3.5 days.

Optimizer and Learning-Rate Warmup​

Section 5.3 uses Adam with β1=0.9\beta_1=0.9, β2=0.98\beta_2=0.98 and ϵ=10−9\epsilon=10^{-9}. The learning rate varies with the training step ss according to Equation (3), where ww is the number of warmup steps:

lrate=dmodel−0.5⋅min⁡(s−0.5, s⋅w−1.5).\text{lrate}=d_{\text{model}}^{-0.5}\cdot\min\left(s^{-0.5},\ s\cdot w^{-1.5}\right).

The rate increases linearly for the first ww steps and then decreases in proportion to the inverse square root of the step number. The paper sets w=4000w=4000. With dmodel=512d_{\text{model}}=512, the rate peaks at step 4000 at (512×4000)−0.5≈7.0×10−4(512\times4000)^{-0.5}\approx7.0\times10^{-4} and has fallen to about 1.4×10−41.4\times10^{-4} by step 100,000.

Regularization​

Section 5.4 describes residual dropout and label smoothing. Residual dropout is applied to the output of each sublayer before it is added to the sublayer input and normalized, and also to the sums of embeddings and positional encodings in both stacks. The base model uses Pdrop=0.1P_{drop}=0.1. Label smoothing uses ϵls=0.1\epsilon_{ls}=0.1, moving part of the target probability from the correct token to the others during training. According to the paper, this hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU. Rows (D) of Table 3 show the effect.

Results​

Machine Translation: Table 2​

Section 6.1 reports BLEU on newstest2014. These are the numbers in Table 2; training cost is in floating-point operations (FLOPs), and empty cells are empty in the original:

ModelEN-DE BLEUEN-FR BLEUTraining cost EN-DETraining cost EN-FR
ByteNet23.75
Deep-Att + PosUnk39.21.0⋅10201.0\cdot10^{20}
GNMT + RL24.639.922.3⋅10192.3\cdot10^{19}1.4⋅10201.4\cdot10^{20}
ConvS2S25.1640.469.6⋅10189.6\cdot10^{18}1.5⋅10201.5\cdot10^{20}
MoE26.0340.562.0⋅10192.0\cdot10^{19}1.2⋅10201.2\cdot10^{20}
Deep-Att + PosUnk Ensemble40.48.0⋅10208.0\cdot10^{20}
GNMT + RL Ensemble26.3041.161.8⋅10201.8\cdot10^{20}1.1⋅10211.1\cdot10^{21}
ConvS2S Ensemble26.3641.297.7⋅10197.7\cdot10^{19}1.2⋅10211.2\cdot10^{21}
Transformer (base)27.338.13.3⋅10183.3\cdot10^{18}(merged with left cell)
Transformer (big)28.441.82.3⋅10192.3\cdot10^{19}(merged with left cell)

On English–German, the big model beats the best previously reported results, ensembles included, by more than 2.0 BLEU, reaching 28.4; even the base model surpasses all previously published models and ensembles. On English–French, the big model outperforms all previously published single models at less than a quarter of the training cost of the previous state-of-the-art model. The English–French big model used dropout 0.1 instead of the big model’s usual 0.3. There is one inconsistency in the English–French score: the abstract and Table 2 give 41.8, while the text of Section 6.1 gives 41.0.

The cost column is an estimate, not a measurement. The paper multiplies training time, the number of GPUs and an estimate of each GPU’s sustained single-precision throughput, taking 9.5 TFLOPS for a P100. Twelve hours on 8 GPUs gives about 3.3×10183.3\times10^{18} for the base model, and 3.5 days gives about 2.3×10192.3\times10^{19} for the big model, matching the table. In the original, each Transformer has a single cost figure spanning the English–German and English–French columns.

The same section gives the decoding setup. Base models average the last 5 checkpoints, written at 10-minute intervals; big models average the last 20. Beam search uses a beam size of 4 and length penalty α=0.6\alpha=0.6. The maximum output length is the input length plus 50, with early termination when possible.

Model Variations: Table 3​

Section 6.2 changes the base model one aspect at a time and evaluates on the English–German development set, newstest2013, using beam search but no checkpoint averaging. Perplexities (PPL) are per word-piece and should not be compared with per-word perplexities. This is why the base model’s BLEU here is 25.8, which cannot be compared directly with the 27.3 on the test set in Table 2. Unlisted values in Table 3 are identical to the base model:

RowChangePPL (dev)BLEU (dev)Params (×10⁶)
baseN=6N=6, dmodel=512d_{\text{model}}=512, dff=2048d_{ff}=2048, h=8h=8, dk=dv=64d_k=d_v=64, Pdrop=0.1P_{drop}=0.1, ϵls=0.1\epsilon_{ls}=0.1, 100K steps4.9225.865
(A)h=1h=1, dk=dv=512d_k=d_v=5125.2924.9
(A)h=4h=4, dk=dv=128d_k=d_v=1285.0025.5
(A)h=16h=16, dk=dv=32d_k=d_v=324.9125.8
(A)h=32h=32, dk=dv=16d_k=d_v=165.0125.4
(B)dk=16d_k=165.1625.158
(B)dk=32d_k=325.0125.460
(C)N=2N=26.1123.736
(C)N=4N=45.1925.350
(C)N=8N=84.8825.580
(C)dmodel=256d_{\text{model}}=256, dk=dv=32d_k=d_v=325.7524.528
(C)dmodel=1024d_{\text{model}}=1024, dk=dv=128d_k=d_v=1284.6626.0168
(C)dff=1024d_{ff}=10245.1225.453
(C)dff=4096d_{ff}=40964.7526.290
(D)Pdrop=0.0P_{drop}=0.05.7724.6
(D)Pdrop=0.2P_{drop}=0.24.9525.5
(D)ϵls=0.0\epsilon_{ls}=0.04.6725.3
(D)ϵls=0.2\epsilon_{ls}=0.25.4725.7
(E)Learned positional embedding instead of sinusoids4.9225.7
bigN=6N=6, dmodel=1024d_{\text{model}}=1024, dff=4096d_{ff}=4096, h=16h=16, Pdrop=0.3P_{drop}=0.3, 300K steps4.3326.4213

Each group makes one point:

  • (A) Number of heads: computation is held constant while the number of heads and the per-head dimensions change. Single-head attention is 0.9 BLEU worse than the best setting, and quality also drops with too many heads.
  • (B) Key size: reducing dkd_k hurts quality. The authors take this to suggest that determining compatibility is not easy and that a more sophisticated compatibility function than the dot product may help.
  • (C) Size: bigger models are better, as expected.
  • (D) Regularization: dropout helps a great deal against overfitting; without it, BLEU drops to 24.6. Removing label smoothing gives a lower perplexity (4.67) but lowers BLEU from 25.8 to 25.3, as Section 5.4 describes.
  • (E) Positional encoding: learned positional embeddings and sinusoids give nearly identical results.

English Constituency Parsing: Table 4​

To test whether the Transformer generalizes beyond translation, Section 6.3 applies it to English constituency parsing. The output of this task is subject to strong structural constraints and is significantly longer than the input, and RNN sequence-to-sequence models had not reached state-of-the-art results with small amounts of data.

The authors trained a 4-layer Transformer with dmodel=1024d_{\text{model}}=1024. One setting uses only the Wall Street Journal (WSJ) portion of the Penn Treebank, about 40K training sentences, with a 16K vocabulary. A semi-supervised setting adds the larger high-confidence and BerkeleyParser corpora, about 17M sentences, with a 32K vocabulary. Only a small number of experiments on the Section 22 development set selected the dropout (attention and residual), learning rates and beam size; all other parameters were unchanged from the English–German base translation model. At inference the maximum output length was raised to the input length plus 300, with a beam size of 21 and α=0.3\alpha=0.3 in both settings.

Table 4 reports F1 on Section 23 of the WSJ:

ParserTrainingWSJ 23 F1
Vinyals & Kaiser et al. (2014)WSJ only, discriminative88.3
Petrov et al. (2006)WSJ only, discriminative90.4
Zhu et al. (2013)WSJ only, discriminative90.4
Dyer et al. (2016)WSJ only, discriminative91.7
Transformer (4 layers)WSJ only, discriminative91.3
Zhu et al. (2013)semi-supervised91.3
Huang & Harper (2009)semi-supervised91.3
McClosky et al. (2006)semi-supervised92.1
Vinyals & Kaiser et al. (2014)semi-supervised92.1
Transformer (4 layers)semi-supervised92.7
Luong et al. (2015)multi-task93.0
Dyer et al. (2016)generative93.3

The paper concludes that, despite no task-specific tuning, the model does better than all previously reported models except the Recurrent Neural Network Grammar (RNNG, Dyer et al. 2016). Row by row: with WSJ only, 91.3 is below the RNNG’s 91.7; in the semi-supervised group, 92.7 is the highest; the multi-task (93.0) and generative RNNG (93.3) results are higher but use different training setups. Unlike RNN sequence-to-sequence models, the Transformer outperforms the BerkeleyParser (Petrov et al. 2006, 90.4) even when trained only on the 40K WSJ sentences.

What Held Up and What Changed​

The paper’s core computations have largely survived unchanged: the scaled dot-product attention formula, the concatenation and output projection of multi-head attention, residual connections, position-wise feed-forward layers, and training every position in parallel. What changed is mostly how these parts are combined:

  • Topology: many large language models keep only the decoder stack, with no encoder and no cross-attention. Context visibility and output heads for the three families are in Encoder, Decoder, and Encoder–Decoder; the rules for generating one token at a time are in Autoregressive Generation and Decoding.
  • Where normalization goes: Xiong et al. (2020) analysed the paper’s Post-LN arrangement. At initialization, the gradients of parameters near the output layer are large, so a large learning rate makes training unstable; they use this to explain why learning-rate warmup is needed. With layer normalization moved inside the residual branch (Pre-LN), training without warmup reached comparable results. Modern models commonly use Pre-Norm and RMSNorm, as described in the block section of Transformers.
  • Position information: after sinusoids came learned absolute positions, relative position biases and RoPE. RoPE encodes absolute position with a rotation matrix while building explicit relative-position dependency into the self-attention computation. Where each method acts is compared in the position table of Transformers.
  • Heads and caching: when generating token by token, the keys and values of earlier positions are cached. Multi-query attention (MQA) and grouped-query attention (GQA) let several query heads share fewer key/value heads to shrink that cache; see Attention Variants and KV-Cache Compression.
  • FFN: ReLU is often replaced by GELU or by gated forms such as SwiGLU; see Activations and Gated Feed-Forward Networks.
  • Sequence length: Table 1’s assumption that nn is smaller than dd no longer holds for long contexts, where the n2n^2 term becomes the main cost. Kernels such as FlashAttention lower peak memory, but exact attention still needs quadratic computation. Worked shape and memory estimates are in Transformers.

In the conclusion, the authors set out three plans: apply the Transformer to input and output modalities other than text; investigate local, restricted attention to handle large inputs and outputs such as images, audio and video efficiently; and make generation less sequential. The code used to train and evaluate the models was released in tensor2tensor.

Explore connectionsOpen network