Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 4 of 13
Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
Build the parts of a transformer in PyTorch and print the shape at every step: one self-attention head, the word-order problem and learned positions, two heads with nn.MultiheadAttention, and a block of 872 numbers that keeps the shape [1, 4, 8] so blocks stack.
What you will learn
- Write one self-attention head in PyTorch: query, key, value, scaled scores and softmax
- Show that attention alone ignores word order, and fix it with learned position vectors
- Use nn.MultiheadAttention and read its per-head weight shape
- Build a transformer block with add and norm, and see why blocks stack
Before you start
- Attention Explained Without the Maths
- The Same Network in PyTorch
Picture a meeting. Four people sit around a table, and before anyone speaks, each one decides how much to listen to everyone else. One might listen mostly to the person on the left and a bit to the others. When they speak, what they say is a blend of what they heard.
That's self-attention. The people are words, and the listening is a set of numbers. The idea is in Attention Explained Without the Maths. Here we write it down in PyTorch.
Not a full model, just the blocks. Four words go in and we print the shape at every step. There's no training and no GPU, so it all runs in a few seconds on a CPU. If you can follow the shapes, you can follow a transformer.
The result first
The sentence is the tea is hot. Here's everything shapes.py prints:
words: ['the', 'tea', 'is', 'hot']
ids: [1, 4]
embedded: [1, 4, 8]
weights: [1, 4, 4]
out: [1, 4, 8]
tea listens: [0.23, 0.29, 0.26, 0.22]
row sum: 1.0
no positions, same vectors: True
with positions, same vectors: False
heads: [1, 2, 4, 4]
each head sees: 4 numbers per word
block in: [1, 4, 8]
block out: [1, 4, 8]
3 blocks out: [1, 4, 8]
numbers in one block: 872
Four words, so the ids have shape [1, 4]: one sentence, four words. Each word becomes 8 numbers, so it's [1, 4, 8]. After attention it's still [1, 4, 8], and after a whole block, still [1, 4, 8]. Only the numbers inside change, because each word now carries something from the others. The rest of the article explains each line.
Setting up four words
import torch
from torch import nn
from attention import Block, SelfAttention, add_positions
torch.manual_seed(7)
DIM, HEADS = 8, 2
words = ["the", "tea", "is", "hot"]
ids = torch.tensor([[0, 1, 2, 3]])
print("words:", words)
print("ids:", list(ids.shape))
embed = nn.Embedding(4, DIM)
x = embed(ids)
print("embedded:", list(x.shape))
nn.Embedding(4, DIM) is a lookup table: one row of 8 numbers per word (more in Embeddings). Nothing here is trained, so these numbers are random, fixed by seed 7.
One head of self-attention
Every word makes three things from its 8 numbers: a query (what I'm looking for), a key (what I can offer) and a value (what I'll actually say). Here's attention.py:
import math
import torch
from torch import nn
class SelfAttention(nn.Module):
"""One head: every token listens to every token."""
def __init__(self, dim):
super().__init__()
self.query = nn.Linear(dim, dim, bias=False)
self.key = nn.Linear(dim, dim, bias=False)
self.value = nn.Linear(dim, dim, bias=False)
def forward(self, x):
q = self.query(x)
k = self.key(x)
v = self.value(x)
scores = q @ k.transpose(-2, -1)
scores = scores / math.sqrt(k.size(-1))
weights = scores.softmax(dim=-1)
return weights @ v, weights
- Three small linear layers make the query, the key and the value for every word.
q @ k.transpose(-2, -1)matches every query against every key. With four words that's a 4x4 grid of scores, one row per word.- Dividing by the square root of the size (here √8) scales the scores down so they don't grow too large.
softmax(dim=-1)turns each row into shares that add up to one.weights @ vgives each word its new 8 numbers: a blend of all the values, weighted by those shares.
head = SelfAttention(DIM)
out, weights = head(x)
print("weights:", list(weights.shape))
print("out:", list(out.shape))
row = weights[0, 1].detach()
print("tea listens:", [round(v, 2) for v in row.tolist()])
print("row sum:", round(row.sum().item(), 2))
weights: [1, 4, 4]
out: [1, 4, 8]
tea listens: [0.23, 0.29, 0.26, 0.22]
row sum: 1.0
Look at the row for tea: 0.23, 0.29, 0.26, 0.22. Almost even, and that's honest. Nothing is trained, so the head has no reason to care about one word more than another. Training is what makes these numbers mean something.
Attention can't see word order
Now flip the sentence to hot is tea the and run the same head:
flipped = x.flip(1)
out2, _ = head(flipped)
same = torch.allclose(out, out2.flip(1), atol=1e-5)
print("no positions, same vectors:", same)
no positions, same vectors: True
The same vectors come out, just in flipped order. Attention on its own can't tell one word order from another. The fix: each seat in the sentence gets its own learned vector, added to the word.
def add_positions(x, positions):
"""Add a learned vector for each seat."""
seats = torch.arange(x.size(1))
return x + positions(seats)
positions = nn.Embedding(4, DIM)
p1 = add_positions(x, positions)
p2 = add_positions(flipped, positions)
a, _ = head(p1)
b, _ = head(p2)
same = torch.allclose(a, b.flip(1), atol=1e-5)
print("with positions, same vectors:", same)
with positions, same vectors: False
Now order matters.
Several heads
One meeting gives one way of listening. So we run a few small meetings side by side, here two heads. The 8 numbers split into 4 for each head. PyTorch has this built in as nn.MultiheadAttention:
multi = nn.MultiheadAttention(
DIM, HEADS, batch_first=True
)
out3, per_head = multi(
p1, p1, p1, average_attn_weights=False
)
print("heads:", list(per_head.shape))
print("each head sees:", DIM // HEADS, "numbers per word")
heads: [1, 2, 4, 4]
each head sees: 4 numbers per word
[1, 2, 4, 4] reads as one sentence, two heads, four words listening to four words. We pass p1 three times because in self-attention the queries, keys and values all come from the same words. average_attn_weights=False keeps one grid per head instead of their average. Each head can learn to watch for something different, and their answers are joined back into 8 numbers.
The whole block
class Block(nn.Module):
"""Attention, small network, add and norm."""
def __init__(self, dim, heads):
super().__init__()
self.attn = nn.MultiheadAttention(
dim, heads, batch_first=True
)
self.norm1 = nn.LayerNorm(dim)
self.ff = nn.Sequential(
nn.Linear(dim, 4 * dim),
nn.ReLU(),
nn.Linear(4 * dim, dim),
)
self.norm2 = nn.LayerNorm(dim)
def forward(self, x):
out, _ = self.attn(x, x, x)
x = self.norm1(x + out)
return self.norm2(x + self.ff(x))
- Attention runs first.
x + outadds its answer to what came in, andLayerNormnormalises, so nothing that came in gets lost.- A small network (8 to 32 to 8) works on each word on its own, with another add and norm.
block = Block(DIM, HEADS)
print("block in:", list(p1.shape))
print("block out:", list(block(p1).shape))
blocks = [Block(DIM, HEADS) for _ in range(3)]
stack = nn.Sequential(*blocks)
print("3 blocks out:", list(stack(p1).shape))
count = sum(p.numel() for p in block.parameters())
print("numbers in one block:", count)
block in: [1, 4, 8]
block out: [1, 4, 8]
3 blocks out: [1, 4, 8]
numbers in one block: 872
Because the shape doesn't change, blocks stack: three blocks out is still [1, 4, 8]. One block here holds 872 numbers to learn (288 in attention, 32 in the two norms, 552 in the small network). Bigger models use the same pieces with larger sizes and more blocks.
The project also has two tests that pin down the two rules from this article:
import torch
from attention import Block, SelfAttention
def test_weights_add_up_to_one():
x = torch.rand(1, 4, 8)
_, weights = SelfAttention(8)(x)
total = weights.sum(dim=-1)
assert torch.allclose(total, torch.ones(1, 4))
def test_block_keeps_the_shape():
x = torch.rand(1, 4, 8)
assert Block(8, 2)(x).shape == x.shape
2 passed in 3.58s
Common mistakes
- Softmax on the wrong axis. It must run over the last axis (
dim=-1), so each word's row of shares adds up to one. - Forgetting positions. Without them, the sentence is a bag of words to attention.
- Leaving out
batch_first=True.nn.MultiheadAttentionthen expects the sentence length first, not the batch. - A dimension that heads can't split. The embedding size must divide evenly by the number of heads (8 / 2 = 4 here).
- Reading meaning into untrained weights. Near-even rows like 0.23, 0.29, 0.26, 0.22 are what an untrained head gives.
Quick recap
| Piece | What it does | Shape in this run |
|---|---|---|
nn.Embedding | Word id to 8 numbers | [1, 4] to [1, 4, 8] |
| Self-attention head | Each word takes a blend of the others via query, key, value | weights [1, 4, 4], out [1, 4, 8] |
| Positions | A learned vector per seat, so order matters | [1, 4, 8] |
nn.MultiheadAttention | Several heads side by side | weights [1, 2, 4, 4] |
| Block | Attention + add and norm + small network + add and norm | [1, 4, 8] in and out, 872 numbers |
Try it yourself
Set HEADS to 4 and say what the heads: line will print before you run it. Then check how many numbers each head sees now.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Attention Explained Without the Maths: Query, Key, Value and the Word "it"
Next →Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.