Transformer Architecture
Two stacks of identical layers built from attention, feed-forward blocks, residuals and normalisation. Where the parameters go and what later models changed.
Jump to a section
Two stacks of six identical layers
The model in Attention Is All You Need translated English to German with no recurrence and no convolution. Its base configuration trained for 100,000 steps, about 12 hours on one machine with eight P100 GPUs, and its layout is still the starting point for current language models.
Figure 1 of the paper has two stacks. The encoder reads the whole source sentence with no causal mask. The decoder reads the target sentence shifted right by one position, under a causal mask, and in every layer uses cross-attention to query the encoder's final output. Select a block in the diagram to see its role. The diagram keeps the paper's post-norm ordering; it is not GPT-2.
Represent tokens and positions
Source tokens and shifted target tokens enter separate embedding paths. The original model scales embeddings by √d_model and adds sinusoidal positions before either stack.
Encoder self-attention · all source positions
Original base model: d_model = 512, 8 heads, d_k = d_v = 64. Post-norm; dropout is inside the residual branch. This map shows structure, not live model activations.
Explore positional encodingVaswani et al. · Figure 1Compare with the original paper figure

The base model uses throughout. Both stacks have six layers, every attention sublayer has 8 heads of width 64, and the feed-forward layers expand to 2,048. Tokens come from a byte-pair vocabulary of about 37,000 entries shared by source and target, and the same embedding matrix serves both inputs and the output projection.
What one layer does to a token
Each encoder layer does two things in order. Attention lets each position gather information from the positions its mask permits; it is the only place information moves between positions. The feed-forward network (FFN) then transforms each position on its own, with the same weights at every position.
Both sublayers sit on a residual connection: the layer adds its output to its input instead of replacing it. A stack of these is easiest to read as one vector per position, the residual stream, that each sublayer reads from and writes a correction into. The identity path also carries gradients straight from the loss back to the embeddings.
The paper normalizes after each addition (post-norm):
Most current decoders, Llama 3 among them, normalize before each sublayer instead (pre-norm), which leaves the residual path as a pure identity:
The small block below is pre-norm. Its token vector has width 3. Attention normalizes the vector, compares a two-coordinate query against the permitted keys, and mixes three-coordinate values, so the attention output adds back onto the residual stream without changing its width.
Follow a token through a transformer
Inspect the residual stream, attention, MLP, and output distribution of one small, fully specified block.
Inspect a separate, small pre-norm calculation
Look up the token vector and add an authored position vector. These are the coordinates entering the residual stream.
- TokenreasonPosition 3
- Residual stream[0.9, 0.35, -0.14]Embedding + position, width 3
Inspect the fixed model weights
These authored values define this teaching block. Matrix rows are output features: multiply W by a column vector. There are no learned parameters here; embeddings and position vectors follow the four-token order, and vocabulary rows follow the five words in the prediction chart.
| 1 | 0.2 | -0.3 |
| 0.1 | 1 | 0.2 |
| 0.3 | -0.2 | 1 |
| 0.6 | 0.5 | -0.2 |
| 0 | 0 | 0 |
| 0.1 | -0.05 | 0.02 |
| 0.2 | -0.1 | 0.04 |
| 0.3 | -0.15 | 0.06 |
| 0.5 | 0.2 | -0.1 |
| 0.1 | 0.4 | 0.3 |
| 0.3 | -0.2 | 0.4 |
| 0.2 | 0.5 | 0.1 |
| 0.5 | 0 | 0.1 |
| 0.1 | 0.6 | 0 |
| 0 | 0.1 | 0.4 |
| 0.5 | -0.2 | 0.1 |
| -0.1 | 0.3 | 0.6 |
| 0.2 | 0.5 | -0.3 |
| -0.4 | 0.1 | 0.2 |
| 0.4 | -0.2 | 0.1 | 0.3 |
| 0.1 | 0.5 | -0.3 | 0.2 |
| -0.2 | 0.1 | 0.6 | 0.1 |
| 0.8 | 0.1 | -0.2 |
| 0.1 | 0.6 | 0.3 |
| 0.3 | -0.1 | 0.7 |
| -0.2 | 0.4 | 0.1 |
| 0.1 | -0.3 | 0.2 |
Inspect the intermediate tensors
| 1.307 | -0.187 | -1.121 |
| -0.736 | 1.414 | -0.678 |
| 0.157 | -1.296 | 1.138 |
| 1.248 | -0.047 | -1.2 |
| 0.728 | -0.28 |
| -0.017 | 0.288 |
| -0.294 | -0.161 |
| 0.734 | -0.254 |
| -0.019 | 0.056 |
| -0.775 | 0.492 |
| 0.762 | -0.503 |
| -0.097 | 0.106 |
| 0.542 | 0.019 | -0.467 |
| -0.436 | 0.775 | -0.13 |
| 0.193 | -0.762 | 0.326 |
| 0.504 | 0.097 | -0.485 |
| 1 | 0 | 0 | 0 |
| 0.475 | 0.525 | 0 | 0 |
| 0.331 | 0.369 | 0.3 | 0 |
| 0.236 | 0.147 | 0.392 | 0.225 |
| 1.257 | -0.377 | -0.265 | -0.513 | 0.039 |
| -0.451 | 0.594 | -0.772 | 0.682 | -0.613 |
| 0.165 | -0.54 | 0.891 | -0.598 | 0.645 |
| 1.242 | -0.438 | -0.138 | -0.578 | 0.124 |
Rows follow token order. Layer normalization uses ε = 10⁻⁵ with unit scale and zero shift. Attention output projection is the identity. Both sublayers add to the residual stream; the output head also receives a normalized representation.
If attention were zero, would the token representation disappear?
No. The first residual addition preserves the input. The MLP can still change that representation through its own residual branch.
The FFN then expands to four hidden features and contracts back to three. It moves nothing between positions, but its input already holds context that attention gathered, so a per-position operation can still make context-dependent changes. A final vocabulary projection turns the vector into five logits. Those logits compare candidate next tokens, while attention scores compare positions in the sequence; they have different roles and different shapes.
If attention returned zero here, the token would not vanish. The first residual addition preserves the input, and the FFN can still change it through its own residual branch.
Where the parameters are
In the original design the FFN is a two-layer MLP with a ReLU, expanding to :
That is weights, against for the query, key, value and output projections of attention, excluding biases. At , one encoder layer holds about 1.05 million attention weights and 2.10 million FFN weights. A decoder layer adds cross-attention, another 1.05 million.
Adding up the base model: six encoder layers at 3.15 million, six decoder layers at 4.19 million, and a shared embedding at 18.9 million give about 63 million weights. The paper reports 65 million for the base model. The FFNs hold 57 percent of the non-embedding weights: two thirds of each encoder layer and half of each decoder layer. Mixture-of-experts models replace this FFN, not attention, with a set of experts.
d, d_ff, vocab = 512, 2048, 37_000
attention = 4 * d * d
ffn = 2 * d * d_ff
encoder_layer = attention + ffn
decoder_layer = 2 * attention + ffn # self-attention and cross-attention
total = 6 * encoder_layer + 6 * decoder_layer + vocab * d
assert ffn == 2 * attention
assert 62_000_000 < total < 64_000_000Parameter counts are not compute. Dense attention also does arithmetic that grows with the square of the sequence length, and at long enough contexts that term dominates the FLOPs, not the FFN.
Post-norm, pre-norm and warmup
Post-norm puts a LayerNorm on the residual path itself, so the gradient reaching the lower layers passes through every normalization above it. Xiong et al. showed that at initialization a post-norm Transformer has large expected gradients for the parameters near the output, which makes a large learning rate unstable. They argue this is why post-norm needs a learning-rate warmup like the 4,000 steps in the original recipe.
Pre-norm keeps the residual path as an identity, and in their experiments it trained without warmup and reached comparable results in less time. Post-norm is not untrainable; it needs more care with initialization and schedules. Many current models also replace LayerNorm with RMSNorm, which drops the mean subtraction and rescales by the root mean square alone.
Encoders, decoders, and both
The same layer becomes three model families depending on the mask and the wiring.
Encoder-only models such as BERT and RoBERTa use bidirectional attention: every position sees the whole input. They produce representations for classification and retrieval, not text.
Decoder-only models such as GPT and Llama use a causal mask: each position sees itself and earlier positions only. Training computes a next-token prediction at every position in parallel; generation extends the prefix one token at a time from the last position's distribution.
Encoder-decoder models such as T5 and the original Transformer pair a bidirectional encoder with a causal decoder and join them through cross-attention. They suit tasks with a distinct input and output, like translation.
Order has to come from somewhere. Unmasked self-attention with no positional signal is permutation-equivariant: shuffle the inputs and the outputs shuffle the same way. The original model adds sinusoidal position encodings to the embeddings; later models build position into attention itself, as RoPE does. A causal mask also breaks the symmetry, since position sees exactly tokens.
In code
A pre-norm decoder block in PyTorch. Passing a causal mask is what makes it a decoder block; without one it is an encoder block.
1import torch
2from torch import Tensor, nn
3
4
5class TransformerBlock(nn.Module):
6 """Pre-norm decoder block: causal self-attention + position-wise FFN."""
7
8 def __init__(self, d_model: int, n_heads: int, mlp_ratio: int = 4, p: float = 0.1) -> None:
9 super().__init__()
10 self.ln1 = nn.LayerNorm(d_model)
11 self.attn = nn.MultiheadAttention(d_model, n_heads, dropout=p, batch_first=True)
12 self.ln2 = nn.LayerNorm(d_model)
13 self.ffn = nn.Sequential(
14 nn.Linear(d_model, mlp_ratio * d_model),
15 nn.GELU(),
16 nn.Linear(mlp_ratio * d_model, d_model),
17 nn.Dropout(p),
18 )
19
20 def forward(self, x: Tensor, attn_mask: Tensor | None = None) -> Tensor:
21 h = self.ln1(x)
22 # causal mask makes this a decoder block (each input token sees itself and earlier input tokens)
23 attn_out, _ = self.attn(h, h, h, attn_mask=attn_mask, need_weights=False)
24 x = x + attn_out # residual 1
25 x = x + self.ffn(self.ln2(x)) # residual 2 (pre-norm)
26 return x
27
28
29block = TransformerBlock(d_model=512, n_heads=8)
30seq = torch.randn(2, 16, 512)
31causal = torch.triu(torch.full((16, 16), float("-inf")), diagonal=1)
32assert block(seq, attn_mask=causal).shape == (2, 16, 512)This block uses GELU where the paper used ReLU, and pre-norm where the paper used post-norm. A real GPT-2 or Llama block differs in dimensions, activation and normalization details.
What later models changed
The skeleton has survived; the parts around it have not. Gated FFNs, grouped-query attention, mixture-of-experts and different vocabularies all change the parameter counts above, and most of the remaining changes target the cost of long contexts.
FlashAttention keeps exact softmax attention and changes how it runs on a GPU. Linear attention replaces the growing token history with a fixed-size recurrent state, and hybrids keep some full-attention layers. Qwen3.5-0.8B shows that hybrid at small scale. DeepSeek V4.1-Flash uses compressed sparse attention and reuses memory across layers. These are different answers to the same quadratic term.
Architecture reference: Vaswani et al., Figure 1 and §3. The interactive map is a LiminalML structural adaptation; the linked paper contains the original figure.
Sources and further reading
- Vaswani et al., Attention Is All You Need: original blocks, masks, and feed-forward dimensions.
- Xiong et al., On Layer Normalization in the Transformer Architecture: pre-norm, post-norm, and warmup.
- Zhang and Sennrich, Root Mean Square Layer Normalization: an alternative normalization method.
- Llama Team, The Llama 3 Herd of Models (2024): a current pre-norm decoder-only model.
Keep going
Ask your own question about Transformer Architecture, or start a guided session on it: six short pages, from the big picture to code you can run.