The Transformer Block
Residual stream, normalization, feed-forward layers and positional information.
Attention moves information between positions; everything else in a transformer works on one position at a time. The block wraps the two in residual connections and normalization, receives positional information from somewhere, and is stacked dozens of times. Here you assemble it, count its parameters and FLOPs, and see which choices keep a deep stack trainable.
What you’ll learn
- Write the pre-LN block , , contrast it with post-LN, and read the result as a residual stream.
- Derive the parameter count of a block, about with , and of a whole model, about plus embeddings, and check it against GPT-2.
- Compare learned absolute, sinusoidal, relative-bias, rotary and ALiBi position information.
- Distinguish encoder and decoder blocks, place cross-attention, and explain tied input and output embeddings.
- Derive the training cost of about FLOPs per token, and the correction from attention, relative to the weights.
Two sublayers and a residual stream
A transformer block applies two sublayers to the sequence of token vectors : multi-head attention, the only operation that mixes positions, and a position-wise feed-forward network (FFN), a two-layer MLP applied to every token separately with shared weights. In the pre-LN arrangement used by most models since GPT-2, each sublayer reads a normalized copy of its input and adds its result back:
import torch.nn as nn
class Block(nn.Module):
"""Pre-LN decoder block: x + Attn(LN(x)), then x + FFN(LN(x))."""
def __init__(self, d, n_heads):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = MultiHeadAttention(d, n_heads) # from Self-Attention & Multi-Head Attention
self.ffn = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
def forward(self, x): # x: (B, T, d), the residual stream
x = x + self.attn(self.ln1(x), causal=True) # read a normalized copy, add the result
x = x + self.ffn(self.ln2(x))
return xA post-LN block, as in the 2017 paper, would instead compute x = ln1(x + attn(x)) and x = ln2(x + ffn(x)), normalizing after each addition.
The residual stream. Unroll the additions over blocks: the final state of every token is its embedding plus the sum of everything each sublayer wrote,
Each sublayer reads the current sum through a normalization and writes an increment, so the stream acts as a shared communication channel (Elhage et al., 2021): an attention head in layer 3 can read what a feed-forward layer in layer 1 wrote. The Emergence lesson Reading the Residual Stream decodes intermediate states directly.
Pre-LN versus post-LN. In pre-LN the stream itself is never normalized, so the gradient has an identity path from the loss to every layer. In post-LN every path passes through a normalization; Xiong et al. (2020) showed that at initialization the gradients near the output are then large, which is why post-LN transformers needed a learning-rate warmup, while pre-LN ones can train without it. GPT-2 moved normalization to the input of each sub-block and added a final one after the last block (Radford et al., 2019). Normalization & Stability in Transformers follows the story to the instabilities of large models.
Which property of the pre-LN block is missing from the post-LN block?
- An identity path along the residual stream from the output back to the embeddings, untouched by any normalization
- Attention between positions
- A learned scale and shift in the normalization
- A feed-forward network at every position
Show the answer
A. An identity path along the residual stream from the output back to the embeddings, untouched by any normalization
Pre-LN adds each sublayer's output to an unnormalized stream, so contains the identity. Post-LN normalizes after every addition, so every gradient path passes through normalizations, which produces the large gradients near the output at initialization that Xiong et al. (2020) analyzed.
Counting parameters
Attention has and four bias vectors (Self-Attention & Multi-Head Attention):
The FFN has two matrices and biases of sizes and ; the two LayerNorms have a gain and a bias each:
So a block holds parameters, two-thirds of them in the FFN. A model adds a token embedding , learned position vectors if it uses them, a final LayerNorm, and an output layer, which is often the embedding itself (below):
GPT-2's smallest model has , , a vocabulary of tokens, learned positions and an output layer tied to the token embedding. How many parameters does it have in total, in millions?
Show the answer
124.4 M
Blocks: M. Token embedding: M. Positions: M. Final LayerNorm: . Total . Embeddings are 32% of this small model but a negligible fraction of large ones, which is why scaling laws count only the non-embedding .
Tied embeddings. The output layer maps the final state to a logit for every token, with , the same shape as the embedding table. Press and Wolf (2017) and Inan, Khosravi and Socher (2017) proposed setting , which saves parameters and gave better language models at the time; the original transformer shared these weights too, scaling the embeddings by . Many large models of the mid-2020s untie them again, since the saving is small at their scale.
Two-thirds of a block's weights sit in the FFN, which is therefore the natural place to add capacity without adding computation: a mixture of experts replaces it by several FFNs and a router that sends each token to one or two of them.
Where position comes from
Without position information, self-attention is permutation-equivariant, so every transformer injects position somewhere: added to the inputs, added to the attention scores, or rotated into the queries and keys. A causal mask leaks some position information by itself, but all major models add it explicitly. The main schemes, in one line each:
| Scheme | What it does | Kind | Used in |
|---|---|---|---|
| Learned absolute | a learned vector added to the embedding of position | absolute; undefined beyond | BERT, GPT-2 |
| Sinusoidal | fixed sines and cosines of geometrically spaced frequencies added to the embedding | absolute, fixed; offsets act as rotations | the original transformer |
| Relative representations | learned vectors for each offset , clipped at a maximum distance, added to the keys and values | relative, learned | Shaw, Uszkoreit & Vaswani (2018) |
| Relative bias buckets | one learned scalar per head and offset bucket added to the score; 32 buckets growing logarithmically up to offset 128, shared across layers | relative, learned | T5 (Raffel et al., 2020) |
| Rotary (RoPE) | queries and keys rotated in 2-D pairs by angles proportional to their positions, in every layer | relative in the score, fixed | Su et al. (2021); most open LLMs of the mid-2020s |
| ALiBi | a fixed penalty added to the scores, with a different slope per head | relative, fixed | Press, Smith & Lewis (2022) |
The choice matters most for length. A model with learned absolute positions has no vector for position at all. Sinusoidal codes and rotary angles are defined everywhere but produce combinations never seen in training beyond , so rotary models are extended by rescaling positions or frequencies and fine-tuning briefly. ALiBi's penalty confines most heads to a recent window, which keeps perplexity stable on longer inputs but does not by itself make distant tokens useful.
Which scheme changes the attention scores but adds nothing to the token embeddings, and depends only on the distance between query and key?
- Learned absolute positions
- Sinusoidal positions
- ALiBi
- None: every scheme adds a vector to the embeddings
Show the answer
C. ALiBi
ALiBi subtracts from each score of head and leaves the embeddings alone. T5's bucketed biases are similar but learned; RoPE also leaves the embeddings alone but rotates queries and keys instead of adding to the scores.
Encoders, decoders and the output
| Block | Sublayers, each with a residual connection and normalization | Used in |
|---|---|---|
| Encoder | self-attention without a mask, then FFN | BERT; the encoder half of T5 and of the original transformer; vision transformers |
| Decoder-only | causal self-attention, then FFN | the GPT series and most large language models |
| Decoder of an encoder–decoder | causal self-attention, then cross-attention to the encoder's output, then FFN | the original transformer, T5, Whisper |
In an encoder–decoder model the encoder runs once over the input, and every decoder block's cross-attention reads the encoder's final states, projected to keys and values separately in each layer. A decoder-only model has no cross-attention: it reads the input as the beginning of its own sequence, so one stack serves both roles. At the top, a final normalization and the output layer turn each position's state into logits over the vocabulary; in a decoder, position predicts token .
Think first An encoder–decoder translator and a decoder-only model both translate a 100-token sentence into a 100-token sentence. Where does each one look up the source sentence while writing the translation?
The encoder–decoder encodes the source once with bidirectional attention; each decoder layer's cross-attention then queries those 100 encoder states. The decoder-only model sees the source as the first 100 tokens of its own sequence, so the translation's tokens attend to them through ordinary causal self-attention, and the source tokens themselves are processed causally, each seeing only the source tokens before it.
FLOPs per token
Multiplying a vector by an weight matrix costs FLOPs, one multiply and one add per weight. Every weight of the blocks is used once per token, so the dense part of the forward pass costs twice the non-embedding parameter count:
Attention adds work that no weight accounts for. A token at position forms scores and a weighted sum of values, FLOPs per layer. Averaged over a causal sequence of length , :
The backward pass computes, for every weight matrix, a gradient with respect to its input and one with respect to the weights, each as costly as the forward product: about twice the forward pass. Training therefore costs about three forward passes:
Example: GPT-3 has billion parameters and was trained on about billion tokens, so FLOPs, matching the Brown et al. (2020) report. With its and the attention term adds only . Neural Scaling Laws builds on .
A model with width is trained on sequences of tokens. How large is the attention term relative to the dense term , in percent?
Show the answer
67 %
. At it would be only about 8%. Long-context training is where the quadratic part of attention stops being a rounding error, which motivates the kernels of Efficient Transformers.
Key takeaways
- A pre-LN block adds attention and an FFN to an unnormalized residual stream, then , keeping an identity path that makes deep stacks trainable without warmup; post-LN normalizes after each addition.
- A block has parameters with , two-thirds in the FFN; a model has about plus for embeddings (124.4 million in total for GPT-2 small, with tied output weights).
- Position enters as learned or sinusoidal vectors added to the input, learned relative biases on the scores, rotations of queries and keys (RoPE) or fixed distance penalties (ALiBi); relative schemes depend only on the offset.
- Encoder, decoder-only and encoder–decoder blocks differ only in masking and cross-attention; decoder-only models read their input as a prefix.
- Training costs about FLOPs per token, in total, with attention adding a fraction that matters only for long contexts.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A decoder has blocks of width with . About how many non-embedding parameters does it have?
- About million
- About million
- About billion
- About million
Show the answer
D. About million
. With GPT-2's vocabulary and 1,024 learned positions this is GPT-2 medium, about 355 million parameters in total.
Which update is a pre-LN block?
- , then
- , then
- , then
Show the answer
B. , then
Each sublayer reads a normalized copy and adds its output to the unnormalized stream, keeping an identity path for gradients. The first option is the original post-LN block.
About how many FLOPs does it take to train a model with non-embedding parameters on tokens, ignoring attention?
Show the answer
B.
: per token forward and about backward.
What does tying the input and output embeddings do?
- It uses the token embedding table as the output layer's weights, saving parameters
- It forces the model to output the same token it reads
- It shares the attention weights across layers
- It ties each position's embedding to its token
Show the answer
A. It uses the token embedding table as the output layer's weights, saving parameters
The logits become : a token's score is the inner product of the final state with that token's own embedding. In GPT-2 small this saves 38.6 million of the 124 million parameters.
Go deeper
- Feed-Forward Layers as Memories · Key–value memories, gated variants and the search for where facts live.
- Mixture of Experts · Sparse routing, load balancing and conditional computation at scale.
- Anatomy of a Modern LLM · RMSNorm, SwiGLU, rotary embeddings and grouped-query attention: what changed since 2017.
Further reading
- A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
- R. Xiong et al., "On layer normalization in the transformer architecture," ICML (2020).
- N. Elhage et al., "A mathematical framework for transformer circuits," Transformer Circuits Thread (2021).
- J. Kaplan et al., "Scaling laws for neural language models," arXiv:2001.08361 (2020).
- O. Press & L. Wolf, "Using the output embedding to improve language models," EACL (2017).