AI Logic

Architectures

Transformer

Updated:

Structure of the Transformer. The left shows the overall flow of the encoder and decoder; the right shows the inside of one layer (multi-head attention, residual connections with layer normalization, and a feed-forward network that is a two-layer MLP)

Background and overview

The Transformer is a neural network that processes sequences with attention alone. Vaswani et al. at Google proposed it in 2017 in the paper "Attention Is All You Need" as a model for machine translation.

Until then, the mainstream translation model was Seq2Seq, which reads a sentence one word at a time with an RNN such as LSTM. Because an RNN cannot compute the next word until the computation for the previous word is finished, it is hard to parallelize on GPUs, and it also struggles to capture relationships between distant words in long sentences.

The Transformer uses neither RNNs nor convolutions, and computes "how related" every pair of words in a sentence is all at once with attention. As a result:

  • All positions in a sentence can be computed in parallel, which makes training faster.
  • Even distant words are connected directly by a single attention step.

In the paper, it achieved a BLEU score of 28.4 on English→German translation (WMT 2014), exceeding the previous best results (including ensembles of multiple models) by more than 2 points. Since then, many of today's large language models and image models have been built on the Transformer, such as BERT, which uses only the encoder, GPT, which uses only the decoder, and ViT, which applies it to images.

Overall architecture

The Transformer consists of an encoder that reads the input sentence and a decoder that produces the output sentence one word at a time. In the figure at the head of the article, the left shows the overall flow and the right shows the inside of one layer.

For translation, information flows in the following order.

  1. Split the input sentence into tokens (words or parts of words) and turn them into vectors of length dmodel=512d_{\text{model}} = 512 with an embedding.
    • The paper uses a vocabulary of about 37,000 tokens built with BPE (shared between English and German).
    • The embeddings are multiplied by dmodel\sqrt{d_{\text{model}}}.
  2. Add a positional encoding to the embeddings.
    • Attention does not distinguish word order, so information about each word's position is added separately.
  3. Stack N=6N = 6 encoder layers to turn the vector of each word in the input sentence into one that reflects the whole sentence.
  4. Feed the decoder the output sentence produced so far, "shifted one position to the right" (the first element is the start symbol). As in steps 1–2, it passes through the embedding and positional encoding.
  5. Stack N=6N = 6 decoder layers. Each decoder layer refers to the output of the last encoder layer.
  6. Finally, a linear layer and the softmax function output the probability of the next word.
    • The two embeddings and this linear layer share the same weight matrix.

At inference time, the word chosen in step 6 is appended to the end of the decoder input, and steps 4–6 are repeated until the end symbol is produced. The paper uses beam search (beam width 4) to choose words.

Inside one layer

Encoder and decoder layers are stacks of several sublayers.

SublayerEncoder layerDecoder layerWhat it does
Self-attentionYesYes (future words masked)Gathers information among the words of the same sentence
Attention over the encoder outputNoYesDecides which words of the input sentence to look at
Feed-forwardYesYesTransforms the vector of each word separately

Every sublayer adds its input directly to its output (residual connection) and applies layer normalization.

Output=LayerNorm(x+Sublayer(x))\text{Output} = \mathrm{LayerNorm}\bigl(x + \mathrm{Sublayer}(x)\bigr)

Here xx is the input to the sublayer and Sublayer\mathrm{Sublayer} is the attention or feed-forward computation. So that residuals can be added, the outputs of all sublayers and embeddings have the same length dmodel=512d_{\text{model}} = 512.

Attention uses scaled dot-product attention. With the query QQ, key KK, and value VV computed from each word, it is calculated as follows.

Attention(Q,K,V)=softmax ⁣(QK⊀dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

The dot products of queries and keys produce weights for "which words to look at and how much", and the values are summed with those weights. In practice, this is done in parallel with h=8h = 8 "heads" as multi-head attention. Each head projects Q,K,VQ, K, V with separate linear layers to length dk=dv=512/8=64d_k = d_v = 512 / 8 = 64 before computing attention, and the 8 results are concatenated and passed through a linear layer. Each head can focus on a different relationship (for example, between a subject and its verb, or with nearby words).

Where Q,K,VQ, K, V come from depends on where the attention is used.

  • Encoder self-attention: Q,K,VQ, K, V all come from the output of the previous layer. Each word looks at every word of the input sentence.
  • Decoder self-attention: also computed from the output of the previous layer, but before the softmax, values at positions after the current one are set to βˆ’βˆž-\infty (masking). This keeps the model from seeing "answer" words during training that it should not have produced yet.
  • Attention over the encoder output: QQ comes from the decoder side, and KK and VV come from the encoder output. It decides which words of the input sentence to look at when producing a translated word.

Feed-forward is a two-layer MLP with ReLU between two linear layers.

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

W1W_1 is a 512Γ—2048512 \times 2048 weight matrix and W2W_2 is 2048Γ—5122048 \times 512, so the inner length is dff=2048d_{ff} = 2048. The same weights are applied to every word position separately (position-wise). The division of labor is that attention mixes information between words, and the feed-forward network transforms the features of each word.

The Transformer in the paper normalizes after adding the residual (Post-LN). Many later models (such as GPT-2) use Pre-LN, which normalizes before the sublayer, because Pre-LN tends to keep training stable even with deeper networks (Pre-LN and Post-LN).

Why it parallelizes better than RNNs

The paper compares self-attention, RNN, and convolutional layers from three viewpoints (nn is the sequence length, dd is the vector length, and kk is the kernel width of the convolution).

Layer typeComputation per layerSequential operationsPath length between distant positions
Self-attentionO(n2β‹…d)O(n^2 \cdot d)O(1)O(1)O(1)O(1)
RNNO(nβ‹…d2)O(n \cdot d^2)O(n)O(n)O(n)O(n)
ConvolutionO(kβ‹…nβ‹…d2)O(k \cdot n \cdot d^2)O(1)O(1)O(log⁑kn)O(\log_k n)

Self-attention can compute all positions at the same time (O(1)O(1) sequential operations), and any two positions are connected in one step. When the sequence length nn is shorter than the vector length dd (such as 512), as with sentences in translation, the computation per layer is also smaller than for an RNN.

The computation and memory of self-attention grow with the square of the sequence length nn. Doubling the sequence length makes the attention weight matrix four times larger. For long documents and high-resolution images, this becomes a bottleneck. Methods such as FlashAttention, which uses memory more efficiently, sparse attention, which narrows the range each position looks at, and linear attention, which reduces the computation to O(n)O(n), were proposed to address this problem.

Training setup and results

The main settings of the base model in the paper are as follows.

ItemValue
Number of layers NN6 for both encoder and decoder
Vector length dmodeld_{\text{model}}512
Inner length of feed-forward dffd_{ff}2048
Number of heads hh8 (dk=dv=64d_k = d_v = 64)
Dropout0.1 (applied to the output of each sublayer and to the embeddings + positional encodings)
Label smoothing0.1

Three training techniques are used.

  1. Optimization: Adam (Ξ²1=0.9\beta_1 = 0.9, Ξ²2=0.98\beta_2 = 0.98, Ο΅=10βˆ’9\epsilon = 10^{-9}).
  2. Learning rate: increase the learning rate linearly for the first 4,000 steps (warmup), then decrease it in inverse proportion to the square root of the step number.
lrate=dmodelβˆ’0.5β‹…min⁑(stepβˆ’0.5,Β stepβ‹…warmupβˆ’1.5),warmup=4000\mathit{lrate} = d_{\text{model}}^{-0.5} \cdot \min\bigl(\mathit{step}^{-0.5},\ \mathit{step} \cdot \mathit{warmup}^{-1.5}\bigr), \qquad \mathit{warmup} = 4000
  1. Regularization: dropout and label smoothing. According to the paper, label smoothing hurts perplexity but improves accuracy and BLEU.

The results are as follows.

  • Englishβ†’German (about 4.5 million sentence pairs): BLEU 28.4 with the large model (big).
  • Englishβ†’French (about 36 million sentences): BLEU 41.8 with big.
  • Training time: on 8 NVIDIA P100 GPUs, about 12 hours for base (100,000 steps) and 3.5 days for big (300,000 steps). It surpassed the previous best models at a far smaller computational cost.

Spread to later models

The Transformer architecture spread in forms that use only the parts suited to each purpose.

Parts usedRepresentative modelsMain uses
Encoder and decoderThe original Transformer, BART, mT5 of the T5 familyConverting the input into another sequence, such as translation and summarization
Encoder onlyBERT, RoBERTaUnderstanding text, such as sentence classification and retrieval
Decoder onlyGPT, GPT-3, LLaMAText generation (large language models)
Encoder applied to imagesViT, Swin TransformerImage classification and detection

Decoder-only models drop the attention over the encoder output and stack only masked self-attention and feed-forward layers. For representing position, besides sinusoids, methods such as learned positional embeddings and RoPE have come into use.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm

'''
Task: reverse a sequence of digits (a small stand-in for translation that needs no data download)
Example: input [3, 7, 1, 9, 4, ...] -> output [..., 4, 9, 1, 7, 3]
'''

# Hyperparameters
seq_len = 10            # sequence length
vocab_size = 12         # digits 0-9 plus start and end symbols
BOS, EOS = 10, 11
d_model = 128           # 512 in the paper's base model
nhead = 4               # 8 in the paper
num_layers = 3          # 6 in the paper
dim_feedforward = 512   # 2048 in the paper
batch_size = 64
steps = 3000
learning_rate = 5e-4

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


def make_batch(n):
  src = torch.randint(0, 10, (n, seq_len))
  tgt = torch.flip(src, dims=[1])
  tgt_in = torch.cat([torch.full((n, 1), BOS), tgt], dim=1)   # decoder input (shifted one to the right)
  tgt_out = torch.cat([tgt, torch.full((n, 1), EOS)], dim=1)  # target to predict
  return src.to(device), tgt_in.to(device), tgt_out.to(device)


# Sinusoidal positional encoding (Section 3.5 of the paper)
class PositionalEncoding(nn.Module):
  def __init__(self, d_model, max_len=512):
    super().__init__()
    pos = torch.arange(max_len).unsqueeze(1)
    div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
    pe = torch.zeros(max_len, d_model)
    pe[:, 0::2] = torch.sin(pos * div)
    pe[:, 1::2] = torch.cos(pos * div)
    self.register_buffer('pe', pe)

  def forward(self, x):  # x: [B, T, d_model]
    return x + self.pe[:x.size(1)]


class Seq2SeqTransformer(nn.Module):
  def __init__(self):
    super().__init__()
    self.embed = nn.Embedding(vocab_size, d_model)   # share the embedding between input and output
    self.pos = PositionalEncoding(d_model)
    self.transformer = nn.Transformer(
      d_model=d_model, nhead=nhead,
      num_encoder_layers=num_layers, num_decoder_layers=num_layers,
      dim_feedforward=dim_feedforward, dropout=0.1, batch_first=True)
    self.out = nn.Linear(d_model, vocab_size)

  def forward(self, src, tgt_in):
    scale = math.sqrt(d_model)                          # multiply embeddings by sqrt(d_model) (Section 3.4 of the paper)
    src_emb = self.pos(self.embed(src) * scale)
    tgt_emb = self.pos(self.embed(tgt_in) * scale)
    # mask that hides future positions in decoder self-attention
    tgt_mask = nn.Transformer.generate_square_subsequent_mask(tgt_in.size(1)).to(src.device)
    h = self.transformer(src_emb, tgt_emb, tgt_mask=tgt_mask)
    return self.out(h)                                  # softmax is computed inside the loss function


model = Seq2SeqTransformer().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate, betas=(0.9, 0.98), eps=1e-9)

# Training loop
model.train()
for step in tqdm(range(steps)):
  src, tgt_in, tgt_out = make_batch(batch_size)
  optimizer.zero_grad()
  logits = model(src, tgt_in)                           # [B, T, vocab_size]
  loss = criterion(logits.reshape(-1, vocab_size), tgt_out.reshape(-1))
  loss.backward()
  optimizer.step()

# Evaluation: predict and extend one token at a time (greedy decoding)
model.eval()
src, _, tgt_out = make_batch(1000)
with torch.no_grad():
  ys = torch.full((src.size(0), 1), BOS, device=device)
  for _ in range(seq_len):
    next_token = model(src, ys)[:, -1].argmax(dim=-1, keepdim=True)
    ys = torch.cat([ys, next_token], dim=1)

accuracy = (ys[:, 1:] == tgt_out[:, :-1]).all(dim=1).float().mean().item()
print(f"Exact sequence match rate: {accuracy * 100:.2f}%")

FAQ

Q. What is the difference between the Transformer and an RNN?
A.

An RNN processes words one at a time in order, so it cannot compute the next step until the previous one is finished. The Transformer uses attention to compute the relationships of all word pairs at once, so training can be parallelized and distant words are connected directly. In exchange, its computation and memory grow with the square of the sequence length.

Q. Why is positional encoding needed?
A.

Attention only computes how much each pair in a set of words is related, and does not distinguish order. As is, it cannot tell "the dog chases the cat" from "the cat chases the dog", so a vector representing each word's position is added to the embedding. The paper uses sinusoidal positional encoding.

Q. What are encoder-only and decoder-only models?
A.

The original Transformer has both an encoder and a decoder, but BERT uses only the encoder and specializes in tasks that understand text, while GPT uses only the decoder and specializes in text generation. Decoder-only models remove the attention over the encoder output and stack only self-attention that masks future words and feed-forward layers.

References

  1. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30 (NIPS 2017).
  2. Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer Normalization. arXiv:1607.06450.
  3. Sennrich, R., Haddow, B., & Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics, 1715–1725.