The paper "Attention Is All You Need" replaced recurrence with pure self-attention and launched the modern AI revolution. This chapter walks through every component of the Transformer visually — intuition first, equations second, code last.
Let's begin by looking at the model as a single black box. In a machine translation application, it takes a sentence in one language and outputs the translation in another.
Popping open that black box, we see an encoding component, a decoding component, and connections between them.
The Transformer was proposed in the paper "Attention is All You Need". It outperforms previous neural machine translation models and — critically — lends itself to parallelization. This is why Google Cloud recommends the Transformer as a reference model for their TPU hardware.
The encoding component is a stack of 6 encoders. The decoding component is a stack of 6 decoders. (There's nothing magical about six — you can experiment with other numbers.)
The encoders are all identical in structure (but do not share weights). Each one has two sub-layers:
The encoder's inputs first flow through a self-attention layer — which helps the encoder look at other words in the input sentence as it encodes a specific word. The outputs of self-attention are fed to a feed-forward neural network, applied identically to each position.
The decoder has both those layers, but between them is an encoder-decoder attention layer that helps the decoder focus on relevant parts of the input sentence:
As in NLP generally, we begin by turning each input word into a vector using an embedding algorithm. Each word is embedded into a vector of size 512.
The embedding only happens in the bottom-most encoder. In other encoders, the input is the output of the encoder directly below. The size of this list is a hyperparameter — typically the length of the longest sentence in the training dataset.
After embedding, each word flows through the two layers of the encoder. Here we see one key property: the word in each position flows through its own path. There are dependencies between paths in the self-attention layer, but the feed-forward layer has no such dependencies — so those paths can be executed in parallel.
An encoder receives a list of vectors as input. It passes them into a self-attention layer, then into a feed-forward neural network, then sends the output upwards to the next encoder.
Say we want to translate this sentence:
"The animal didn't cross the street because it was too tired"
What does "it" refer to? The street or the animal? It's simple for a human, but not for an algorithm. Self-attention allows the model to associate "it" with "animal".
As the model processes each word, self-attention lets it look at other positions in the input sequence for clues that help produce a better encoding for that word.
If you're familiar with RNNs, think of how maintaining a hidden state allows an RNN to incorporate its representation of previous words. Self-attention is the Transformer's method to bake the "understanding" of all relevant words — not just previous ones — into the one being processed.
Let's walk through the calculation step by step — first with vectors, then with matrices.
For each input vector, we create three vectors: a Query, a Key, and a Value — by multiplying the embedding by three weight matrices trained during training.
They're abstractions useful for calculating attention. Query = "what am I looking for?", Key = "what do I contain?", Value = "what do I actually provide?". The score between a query and key determines how much of the corresponding value to use.
Score each word against the current word by taking the dot product of the query with each key:
Divide scores by (for more stable gradients), then apply softmax:
The softmax score determines how much each word will be expressed at this position. The word at this position will naturally have the highest score, but it's useful to attend to relevant other words too.
Keep the values of words we want to focus on, and drown out irrelevant words (by multiplying by tiny numbers like 0.001).
This produces the output of self-attention for this position:
This vector is sent to the feed-forward neural network.
In practice, this is done with matrices for speed. Pack all embeddings into a matrix X, multiply by trained weight matrices:
Steps 2 through 6 condensed into one formula:
The paper refines self-attention with "multi-headed" attention, which improves performance in two ways:
When encoding "it" in our example sentence, one head focuses most on "the animal", while another focuses on "tired". The model's representation of "it" bakes in both "animal" and "tired".
Self-attention treats input as a set — it has no notion of word order. To address this, the Transformer adds a positional encoding vector to each input embedding. These vectors follow a specific pattern that helps the model determine position and relative distance.
If the embedding has dimensionality 4, a toy positional encoding would look like:
can be represented as a linear function of for any fixed offset k. This lets the model easily learn to attend by relative positions. The left half uses sine, the right half uses cosine — they're concatenated (or interleaved) to form each vector.
Each sub-layer (self-attention, FFN) in each encoder has a residual connection around it, followed by a layer-normalization step:
This also applies to the decoder sub-layers. If we think of a Transformer of 2 stacked encoders and decoders, each sub-layer has the same add-and-normalize wrapper. The residual connection ensures gradients flow directly through the network — this is why Transformers can stack many layers without vanishing gradients.
The encoder processes the input sequence. The output of the top encoder is transformed into attention vectors K and V, which are used by each decoder in its "encoder-decoder attention" layer.
Each decoding step outputs an element from the output sequence. The output of each step is fed to the bottom decoder in the next time step, and the decoders bubble up their results. Positional encodings are added to decoder inputs too.
Key differences in the decoder:
The decoder stack outputs a vector of floats. How do we turn that into a word? With a Linear layer followed by a Softmax layer.
The Linear layer projects the decoder output into a much larger vector — the logits vector. If the model knows 10,000 English words, the logits vector is 10,000 cells wide, each cell corresponding to the score of a unique word.
The softmax layer turns those scores into probabilities (all positive, all add up to 1.0). The cell with the highest probability is chosen, and the associated word is produced as output.
During training, an untrained model goes through the same forward pass. Since we have a labeled dataset, we can compare its output with the actual correct output.
Assume our output vocabulary contains only six words: "a", "am", "i", "thanks", "student", and "<eos>".
Once we define the output vocabulary, we use a vector of the same width to represent each word (one-hot encoding). We can then compare the model's probability distribution against the correct one-hot vector, and tweak all weights using backpropagation.
Say we're training on a simple example: translating "merci" into "thanks". We want the output to be a probability distribution indicating "thanks". But an untrained model produces random values:
We compare using cross-entropy loss — subtract one distribution from the other. For longer sentences (e.g. "je suis étudiant" → "i am a student"), we want each position to output the right probability distribution:
After training on a large dataset for enough time, the produced distributions would converge toward the desired output. Each position gets a little probability even for unlikely words — that's a useful property of softmax which helps the training process.
Since the model produces outputs one at a time, the simplest approach is greedy decoding: pick the highest-probability word at each step.
A better approach is beam search: keep the top B candidates at each step, running the model for each partial hypothesis, and keeping whichever version produces less total error.
In this example, beam_size=2 means we keep two partial hypotheses in memory. top_beams=2 means we return the top two complete translations. Both are hyperparameters you can experiment with.
| Property | RNN | CNN | Transformer |
|---|---|---|---|
| Max Path Length | O(n) | O(log n) | O(1) |
| Parallelizable | ❌ Sequential | ✅ Yes | ✅ Yes |
| Complexity per Layer | O(n · d²) | O(k · n · d²) | O(n² · d) |
| Long-Range Dependencies | Poor | Limited by kernel | Excellent |
The key advantages are:
Let's trace one complete forward pass through the full encoder-decoder architecture.
class PositionalEncoding(nn.Module): def __init__(self, d_model=512, max_len=5000): super().__init__() pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len).unsqueeze(1).float() div_term = torch.exp( torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model) ) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) self.register_buffer('pe', pe.unsqueeze(0)) def forward(self, x): return x + self.pe[:, :x.size(1)]
class MultiHeadAttention(nn.Module): def __init__(self, d_model=512, n_heads=8): super().__init__() self.n_heads = n_heads self.d_k = d_model // n_heads self.W_q = nn.Linear(d_model, d_model) self.W_k = nn.Linear(d_model, d_model) self.W_v = nn.Linear(d_model, d_model) self.W_o = nn.Linear(d_model, d_model) def forward(self, q, k, v, mask=None): B, T, _ = q.shape # Project and reshape to (B, heads, T, d_k) Q = self.W_q(q).view(B, T, self.n_heads, self.d_k).transpose(1, 2) K = self.W_k(k).view(B, -1, self.n_heads, self.d_k).transpose(1, 2) V = self.W_v(v).view(B, -1, self.n_heads, self.d_k).transpose(1, 2) # Scaled dot-product attention scores = (Q @ K.transpose(-2, -1)) / (self.d_k ** 0.5) if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) attn = torch.softmax(scores, dim=-1) out = (attn @ V).transpose(1, 2).contiguous().view(B, T, -1) return self.W_o(out)
class Transformer(nn.Module): def __init__(self, src_vocab, tgt_vocab, d_model=512): super().__init__() self.src_embed = nn.Embedding(src_vocab, d_model) self.tgt_embed = nn.Embedding(tgt_vocab, d_model) self.pos_enc = PositionalEncoding(d_model) self.encoder = nn.TransformerEncoder( nn.TransformerEncoderLayer(d_model, 8, batch_first=True), num_layers=6 ) self.decoder = nn.TransformerDecoder( nn.TransformerDecoderLayer(d_model, 8, batch_first=True), num_layers=6 ) self.output = nn.Linear(d_model, tgt_vocab) def forward(self, src, tgt): # Encode source src_emb = self.pos_enc(self.src_embed(src)) memory = self.encoder(src_emb) # Decode target (with causal mask) tgt_emb = self.pos_enc(self.tgt_embed(tgt)) tgt_mask = nn.Transformer.generate_square_subsequent_mask(tgt.size(1)) out = self.decoder(tgt_emb, memory, tgt_mask=tgt_mask) return self.output(out) # (B, tgt_len, tgt_vocab)
The Transformer has become the universal backbone of modern AI:
Read the "Attention Is All You Need" paper. Explore the Tensor2Tensor repo. Check out Harvard NLP's Annotated Transformer guide with PyTorch implementation. Content inspired by Jay Alammar's Illustrated Transformer.