from_scratch.llm
The Transformer
08

The transformer block

multi-head attention + MLP + residuals + norm
steps/04_transformer/08_transformer_block.py ► Open as notebook (with output)

One head is the atom; the block is the molecule GPT stacks. Multi-head attention runs several heads in parallel, a feed-forward MLP lets each token think, and residual connections + layernorm make deep stacks trainable.

Shape in equals shape out — which is precisely why you can stack 4, 12, or 96 of them. GPT-3 is 96 of these in a row.

x = x + MHA(LN(x)) · x = x + FFN(LN(x)) (pre-norm residual)attention mixes across tokens; the FFN mixes across features; residuals + norm keep deep stacks trainable.
The theory

A transformer block combines four ideas. Multi-head attention runs several attention operations in parallel low-dimensional subspaces, letting different heads specialize (one tracks the previous letter, another the start of the word), then concatenates them. The position-wise feed-forward network (two linear layers around a nonlinearity, ~4× wider) gives each token nonlinear processing on its own.

The other two ideas make depth trainable. Residual connections (x = x + sublayer(x)) create identity shortcuts so gradients flow through dozens of layers without vanishing, and each block only has to learn a small correction. LayerNorm normalizes each token's vector to a stable scale; applying it before each sublayer (pre-norm) trains more stably than after. The slogan: attention mixes information across tokens, the FFN processes each token — gather, then think, repeated N times.

Animation
Visual walkthrough
Parallel attention heads running across token rows.
Many headsMultiple attention heads inspect the same sequence from different subspaces.
Transformer sublayers wrapped by residual arcs and normalization rings.
Residual and normSkip paths and normalization keep the block trainable while sublayers do useful work.
Identical transformer blocks stacked vertically with matching input and output shapes.
Stackable blockShape in equals shape out, so GPT can stack the same block repeatedly.
The notebook · steps/04_transformer/08_transformer_block.ipynb — code cells & their output. Open & run on GitHub →
In [1]
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)


class Head(nn.Module):
    """One causal self-attention head (same as #7)."""

    def __init__(self, n_embd, head_size):
        super().__init__()
        self.key = nn.Linear(n_embd, head_size, bias=False)
        self.query = nn.Linear(n_embd, head_size, bias=False)
        self.value = nn.Linear(n_embd, head_size, bias=False)
        self.head_size = head_size

    def forward(self, x):
        B, T, C = x.shape
        q, k, v = self.query(x), self.key(x), self.value(x)
        scores = q @ k.transpose(-2, -1) / self.head_size ** 0.5
        mask = torch.tril(torch.ones(T, T, device=x.device))
        scores = scores.masked_fill(mask == 0, float("-inf"))
        weights = F.softmax(scores, dim=-1)
        return weights @ v


class MultiHeadAttention(nn.Module):
    """Several heads in parallel, concatenated and projected back to n_embd."""

    def __init__(self, n_embd, n_heads):
        super().__init__()
        head_size = n_embd // n_heads
        self.heads = nn.ModuleList(
            [Head(n_embd, head_size) for _ in range(n_heads)]
        )
        self.proj = nn.Linear(n_embd, n_embd)   # mix the heads' outputs

    def forward(self, x):
        out = torch.cat([h(x) for h in self.heads], dim=-1)  # (B, T, n_embd)
        return self.proj(out)


class FeedForward(nn.Module):
    """Per-token MLP. Expands to 4x then back — the standard transformer ratio."""

    def __init__(self, n_embd):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd),
            nn.ReLU(),
            nn.Linear(4 * n_embd, n_embd),
        )

    def forward(self, x):
        return self.net(x)


class TransformerBlock(nn.Module):
    """Attention + feed-forward, each wrapped in (layernorm -> sublayer -> add).

    Note the residual form `x = x + sublayer(ln(x))`: the network only has to
    learn what to ADD to x, which is what makes very deep stacks trainable.
    """

    def __init__(self, n_embd, n_heads):
        super().__init__()
        self.ln1 = nn.LayerNorm(n_embd)
        self.attn = MultiHeadAttention(n_embd, n_heads)
        self.ln2 = nn.LayerNorm(n_embd)
        self.ffwd = FeedForward(n_embd)

    def forward(self, x):
        x = x + self.attn(self.ln1(x))   # tokens gather info from each other
        x = x + self.ffwd(self.ln2(x))   # each token then thinks on its own
        return x
In [2]
B, T, C = 2, 6, 32      # batch, tokens, embedding dim
n_heads = 4
x = torch.randn(B, T, C)

block = TransformerBlock(n_embd=C, n_heads=n_heads)
out = block(x)

n_params = sum(p.numel() for p in block.parameters())
print(f"input  shape: {tuple(x.shape)}")
print(f"output shape: {tuple(out.shape)}   <- identical, so blocks stack")
print(f"{n_heads} heads, each of size {C // n_heads}")
print(f"block parameters: {n_params}\n")

# Demonstrate stacking: feed the output straight into more blocks.
blocks = nn.Sequential(*[TransformerBlock(C, n_heads) for _ in range(3)])
deep_out = blocks(x)
print(f"after stacking 3 blocks: {tuple(deep_out.shape)}  (still B, T, C)")
print("\nStacking N of these — plus embeddings and a final classifier — IS")
print("a GPT. That's exactly what we assemble in #9.")
Output
input  shape: (2, 6, 32)
output shape: (2, 6, 32)   <- identical, so blocks stack
4 heads, each of size 8
block parameters: 12608

after stacking 3 blocks: (2, 6, 32)  (still B, T, C)

Stacking N of these — plus embeddings and a final classifier — IS
a GPT. That's exactly what we assemble in #9.