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.
Split the input sentence into tokens (words or parts of words) and turn them into vectors of length dmodelβ=512 with an embedding.
The paper uses a vocabulary of about 37,000 tokens built with BPE (shared between English and German).
Attention does not distinguish word order, so information about each word's position is added separately.
Stack N=6 encoder layers to turn the vector of each word in the input sentence into one that reflects the whole sentence.
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.
Stack N=6 decoder layers. Each decoder layer refers to the output of the last encoder layer.
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.
Sublayer
Encoder layer
Decoder layer
What it does
Self-attention
Yes
Yes (future words masked)
Gathers information among the words of the same sentence
Attention over the encoder output
No
Yes
Decides which words of the input sentence to look at
Feed-forward
Yes
Yes
Transforms 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))
Here x is the input to the sublayer and 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β=512.
Attention uses scaled dot-product attention. With the query Q, key K, and value V computed from each word, it is calculated as follows.
Attention(Q,K,V)=softmax(dkββQKβ€β)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=8 "heads" as multi-head attention. Each head projects Q,K,V with separate linear layers to length dkβ=dvβ=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,V come from depends on where the attention is used.
Encoder self-attention: Q,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 ββ (masking). This keeps the model from seeing "answer" words during training that it should not have produced yet.
Attention over the encoder output: Q comes from the decoder side, and K and V 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β
W1β is a 512Γ2048 weight matrix and W2β is 2048Γ512, so the inner length is dffβ=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 (n is the sequence length, d is the vector length, and k is the kernel width of the convolution).
Layer type
Computation per layer
Sequential operations
Path length between distant positions
Self-attention
O(n2β d)
O(1)
O(1)
RNN
O(nβ d2)
O(n)
O(n)
Convolution
O(kβ nβ d2)
O(1)
O(logkβn)
Self-attention can compute all positions at the same time (O(1) sequential operations), and any two positions are connected in one step. When the sequence length n is shorter than the vector length d (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 n. 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), were proposed to address this problem.
Training setup and results
The main settings of the base model in the paper are as follows.
Item
Value
Number of layers N
6 for both encoder and decoder
Vector length dmodelβ
512
Inner length of feed-forward dffβ
2048
Number of heads h
8 (dkβ=dvβ=64)
Dropout
0.1 (applied to the output of each sublayer and to the embeddings + positional encodings)
Label smoothing
0.1
Three training techniques are used.
Optimization: Adam (Ξ²1β=0.9, Ξ²2β=0.98, Ο΅=10β9).
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.
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.
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.