5. The Transformer Block
The building block of modern AI
If you've seen any diagram of a modern language model, you've seen the same box repeated over and over: an attention sub-layer, a feed-forward sub-layer, some normalization, some arrows looping back on themselves. That repeated unit is the transformer block — the architectural heartbeat of every GPT, BERT, LLaMA, and Gemini model in existence.
We spent the last article building up multi-head attention in detail. Now we zoom out one level and look at everything that wraps around it. The transformer block is elegant: just a handful of components, each doing a specific job, combined in a way that scales extraordinarily well.
Why a "block" at all?
A single attention operation is powerful, but one layer isn't enough to learn the kinds of hierarchical, compositional patterns that language requires. The solution is depth: stack the same structure many times, letting each layer build on the representations learned by the layer before it.
GPT-2 small uses 12 blocks. GPT-3 uses 96. LLaMA-3 70B uses 80. The block is the unit of depth — making it as clean and reusable as possible is what allows models to scale.
Layer Normalization
The first thing that happens inside a transformer block is normalization. Before feeding activations into either sub-layer, we apply Layer Normalization (LayerNorm).
LayerNorm works by computing the mean and variance of a single token's embedding vector across its feature dimensions, then rescaling:
where μ and σ are computed across the d_model dimensions of that one token's vector, and γ and β are learned scale and shift parameters.
Why does this help? Deep networks are prone to internal covariate shift — the distribution of activations changes as weights update, making it hard for later layers to learn stable patterns. LayerNorm keeps each token's activation vector in a well-behaved range regardless of what happened in earlier layers, which dramatically stabilizes training.
Pre-norm vs post-norm
The original 2017 "Attention Is All You Need" paper placed LayerNorm after the residual add (post-norm). Most modern models use pre-norm — normalizing before the attention and FFN operations. Pre-norm turns out to be more stable, especially at scale, and allows training without the careful learning rate warmup that post-norm requires. All the GPT-family models use pre-norm.
Residual connections
After the attention sub-layer computes its output, we don't just pass that output along. We add the original input back:
output = x + Attention(LayerNorm(x))
This is a residual (or skip) connection, borrowed from ResNets. The idea is simple but the effect is profound.
The vanishing gradient problem. In a deep network, gradients get multiplied by many small numbers as they flow backward through layers. By the time they reach the early layers, they've shrunk to near zero — those layers barely learn anything.
Residual connections give gradients a shortcut. The gradient can flow straight back through the + operation without passing through any learned transformation, ensuring early layers always receive a meaningful signal.
Beyond gradients, residual connections mean each block only needs to learn a correction to the current representation rather than a complete transformation from scratch. This is a much easier learning problem.
The feed-forward network
After attention (with its residual add), each token passes through a feed-forward network (FFN). This is just two linear layers with a nonlinearity between them:
FFN(x) = W₂ · activation(W₁ · x + b₁) + b₂
The key detail is the dimension expansion. If the model dimension is d_model (say, 768 for GPT-2 small), the first linear layer expands to 4 × d_model (3072), the nonlinearity fires, and the second layer contracts back to d_model.
This expansion-contraction pattern gives the FFN a large "working space" to perform its computation. Research has shown that FFN layers act as a kind of key-value memory — storing factual associations that attention can look up. The four-times expansion has become a default that works well, though some recent models experiment with different ratios or use gated variants like SwiGLU.
The original paper used ReLU as the nonlinearity. Modern models almost universally use GELU (Gaussian Error Linear Unit), which has a smoother shape and works slightly better in practice.
Positional encoding
There's a subtle problem with attention: it's permutation-invariant. If you shuffle all the tokens in a sequence, the attention weights will adjust accordingly, and the output will be a reshuffled version of what you'd get from the original order. The model has no idea that "dog bites man" and "man bites dog" are different.
To fix this, we inject positional information into the token embeddings before they enter any transformer block. The original paper used sinusoidal encoding:
For each position in the sequence, this generates a unique vector where each dimension oscillates at a different frequency. Low-indexed dimensions change quickly (distinguishing nearby positions); high-indexed dimensions change slowly (distinguishing distant positions). The result is a kind of coordinate system for the sequence.
Here's what that looks like visually — each row is a position, each column is a dimension of the encoding:
Modern models increasingly use learned positional embeddings (just look up a position's encoding in a learned table) or RoPE (Rotary Position Embedding), which encodes relative positions directly into the attention computation rather than adding a fixed offset to the input. But sinusoidal encoding is still the clearest way to understand what positional encoding is trying to accomplish.
The full transformer block
With all the pieces on the table, here's how they fit together:
- Input: A sequence of token embeddings, shape [seq_len, d_model]. Positional encodings have been added before the first block.
- LayerNorm: Normalize each token's vector across d_model dimensions.
- Multi-Head Attention: Each token attends to all others. Output shape is still [seq_len, d_model].
- Residual add: Add the original (pre-norm) input back to the attention output.
- LayerNorm: Normalize again.
- FFN: Two linear layers with a nonlinearity. Each token is processed independently here.
- Residual add: Add the post-first-residual value back to the FFN output.
- Output: Refined token embeddings, same shape [seq_len, d_model], passed to the next block.
Notice that the output has the exact same shape as the input. This is what makes stacking trivial: the output of block N is the input of block N+1, no reshaping required.
Tensor shapes throughout
For a concrete example: GPT-2 small has d_model = 768, 12 attention heads (so d_head = 64), and a sequence length of up to 1024.
A batch of 4 sequences passing through one transformer block:
| Stage | Shape |
|---|---|
| Input | [4, 1024, 768] |
| After LayerNorm | [4, 1024, 768] |
| Q, K, V projections | [4, 12, 1024, 64] each |
| Attention output | [4, 1024, 768] |
| After residual add | [4, 1024, 768] |
| FFN intermediate | [4, 1024, 3072] |
| FFN output | [4, 1024, 768] |
| After residual add | [4, 1024, 768] |
The key observation: everything stays at [batch, seq_len, d_model] at the block boundaries. The internal expansions (heads, FFN width) are implementation details that the outer structure never sees.
Stacking blocks
A complete transformer model is mostly just many of these blocks stacked end to end. Stack 12 and you have GPT-2 small. Stack 96 and you're in GPT-3 territory. Each block has its own set of parameters — the attention weight matrices and FFN weight matrices — so more blocks means more parameters and more expressive power.
Parameter count per block (GPT-2 small, d_model = 768):
- Attention Q, K, V projections: 3 × 768 × 768 = 1.77M
- Attention output projection: 768 × 768 = 590K
- FFN first layer: 768 × 3072 = 2.36M
- FFN second layer: 3072 × 768 = 2.36M
- LayerNorm parameters (γ, β): ~3K (negligible)
Total per block: ~7.09M. Times 12 blocks: ~85M parameters, which matches GPT-2 small's published count.
Try it: step through a transformer block
The widget below walks you through a single token's journey through one transformer block. You'll see the tensor values (simplified to 8 dimensions) and the shape annotation change at each sub-layer, with the active component highlighted in the flow diagram.
The transformer block in one sentence: normalize, attend, add back, normalize again, project through a wide FFN, add back again — and repeat this dozens of times.
The components are individually simple. The power comes from depth (stacking gives hierarchical representations), width (large d_model means rich per-token state), and scale (more parameters capture more patterns). In the next article, we'll look at how these blocks are arranged into a complete GPT-style model — with an embedding table at the front, a language model head at the back, and training objective tying it all together.