Transformer Architecture and Positional Encoding

Summary

The original Transformer (Vaswani et al. 2017) is an encoder-decoder stack of identical layers on each side. Every sub-layer, whether multi-head attention or a position-wise two-layer ReLU network, is wrapped as at constant width . Because attention is order-invariant, sinusoidal positional encodings are added to the input embeddings; their geometric progression of frequencies makes a linear function of . Trained with Adam, a warmup-then-inverse-square-root learning rate, dropout and label smoothing, the big model reached 28.4 BLEU on WMT14 English-German at training FLOPs, a fraction of the cost of earlier systems.

Overview

The model follows the standard sequence-transduction template (Sec. 3). The encoder maps input symbols to continuous representations . Given , the decoder emits one symbol at a time, and “at each step the model is auto-regressive, consuming the previously generated symbols as additional input when generating the next.” What is new is that both halves are built from attention and per-position feed-forward layers only, with no recurrence and no convolution.

The GPT family studied in the other notes of this cluster keeps only the decoder half, without cross-attention (Autoregressive Language Modeling and Pretraining). The layer anatomy described here is otherwise unchanged; Brown et al. note that GPT-3 uses pre-normalization and alternating dense and sparse attention patterns.

Main Content

Encoder and decoder layers ^def-layers

(Sec. 3.1)

  • Encoder layer: (1) multi-head self-attention; (2) position-wise feed-forward network.
  • Decoder layer: (1) masked multi-head self-attention; (2) multi-head attention over the encoder output; (3) position-wise feed-forward network.
  • Every sub-layer output is . To make the residual additions possible, all sub-layers and the embedding layers output dimension .
  • The decoder mask, “combined with fact that the output embeddings are offset by one position, ensures that the predictions for position can depend only on the known outputs at positions less than .”

Position-wise feed-forward network ^def-ffn

Applied “to each position separately and identically” (Eq. 2):

with input/output width and inner width . Parameters are shared across positions but differ between layers; equivalently, two convolutions with kernel size 1.

Attention mixes information across positions; the FFN transforms each position in place. Most parameters live in the FFN: per layer, attention has weights () and the FFN has .

Embeddings and output softmax ^def-embeddings

Learned embeddings map tokens to ; a learned linear map followed by a softmax turns decoder outputs into next-token probabilities. The same weight matrix is shared between the two embedding layers and the pre-softmax linear transformation, and in the embedding layers the weights are multiplied by (Sec. 3.4).

Sinusoidal positional encoding ^def-positional-encoding

Added to the input embeddings at the bottom of both stacks (Sec. 3.5):

Each dimension is a sinusoid; “the wavelengths form a geometric progression from to .”

Relative offsets are linear maps ^thm-pe-linear

For any fixed offset , is a linear function of (Sec. 3.5). Writing , each sine-cosine pair is rotated by the angle :

The rotation matrix does not depend on , so a single linear projection inside an attention head can implement “attend positions back”. The authors hypothesized this “would allow the model to easily learn to attend by relative positions”.

Learned positional embeddings gave “nearly identical results” (Table 3 row (E): 25.7 BLEU compared with 25.8 for the base model). The sinusoidal version was kept “because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.”

Why this design: layer-type comparison

Layer typeComplexity per layerSequential operationsMaximum path length
Self-attention
Recurrent
Convolutional
Self-attention (restricted to neighbors)

(Table 1; sequence length, representation dimension, kernel width.)

Training recipe ^alg-training

(Sec. 5)

  1. Data. WMT14 English-German, about 4.5M sentence pairs, byte-pair encoding with a shared vocabulary of about 37,000 tokens; English-French, 36M sentences, 32,000 word-pieces. Batches of roughly 25,000 source and 25,000 target tokens.
  2. Optimizer. Adam with , , .
  3. Learning rate (Eq. 3), linear warmup then inverse-square-root decay, with :
  1. Regularization. Dropout on each sub-layer output before the residual addition and on the sum of embeddings and positional encodings; label smoothing , which “hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.”
  2. Hardware. One machine with 8 P100 GPUs. Base model: 100,000 steps at 0.4 s/step (12 hours). Big model: 300,000 steps at 1.0 s/step (3.5 days).
  3. Inference. Average the last 5 (base) or 20 (big) checkpoints; beam search with beam size 4 and length penalty .

Results

ModelEN-DE BLEUEN-FR BLEUTraining FLOPs (EN-DE)
GNMT + RL24.639.92
ConvS2S25.1640.46
ConvS2S ensemble26.3641.29
Transformer (base)27.338.1
Transformer (big)28.441.8

(Table 2. The abstract and Table 2 give 41.8 for English-French; the running text of Sec. 6.1 says 41.0.) The big model beats all earlier systems, including ensembles, on English-German by more than 2 BLEU. A 4-layer Transformer also reached 91.3 F1 on WSJ constituency parsing with only 40K training sentences and 92.7 semi-supervised, showing that the architecture is not translation-specific (Sec. 6.3).

Ablations (Table 3, newstest2013 dev). Rows (C): deeper and wider is better: 2 layers give 23.7 BLEU, 6 layers 25.8 (base), gives 26.0, gives 26.2. Rows (D): removing dropout drops BLEU to 24.6, “dropout is very helpful in avoiding over-fitting.” The big model (, , , , 213M parameters) reaches 26.4 dev BLEU and perplexity 4.33, compared with the base model’s 25.8 and 4.92 at 65M parameters. “Bigger models are better” is the first hint of the regularity quantified in Neural Scaling Laws.

Examples

Counting the base model’s parameters. Kaplan et al. (Eq. 2.1) give the non-embedding count of a decoder-only Transformer as when : for attention plus for the FFN. Apply the same bookkeeping to the base encoder-decoder with :

  • Encoder: M.
  • Decoder: each layer has a second attention block, so M.
  • Shared embedding / softmax matrix: M.
  • Total M, against the 65M reported in Table 3. The remainder is biases, layer-norm gains and vocabulary-size rounding. (This is a back-of-envelope check, not a computation from the paper.)

Positional encoding in code.

import numpy as np
 
def positional_encoding(n_pos, d_model):
    pos = np.arange(n_pos)[:, None]
    i = np.arange(d_model // 2)[None, :]
    angle = pos / 10000 ** (2 * i / d_model)
    pe = np.empty((n_pos, d_model))
    pe[:, 0::2], pe[:, 1::2] = np.sin(angle), np.cos(angle)
    return pe

The inner product depends only on the offset : the encoding induces a stationary kernel over positions built from a bank of cosines. This is the same idea as a basis-function approximation to a stationary Gaussian-process kernel, where fixed sinusoid-like eigenfunctions are computed once and a linear model is fitted on top (Hilbert Space Gaussian Processes). Seasonal components in structural time-series models (Local Linear Trend and Seasonality) serve the analogous purpose of telling a model where it is within a cycle.

Connections

See Also