Chapter 4 / 16

Transformer Architecture and Attention

Intermediate 4–5 h · Prerequisites: Neural Networks and Deep Learning

Learning objectives

  • Explain tokens, embeddings and positional information
  • Derive scaled dot-product attention and causal masking
  • Implement multi-head self-attention and a transformer block in PyTorch
  • Distinguish encoder, decoder and encoder–decoder models

Introduction

The transformer, introduced in 2017 in "Attention Is All You Need", is the architecture behind practically every current large language model. Its central idea – attention – lets every position in a sequence look at every other position and decide what is relevant. In this chapter you follow text from tokens to embeddings, derive attention step by step, implement multi-head self-attention and a complete GPT-style transformer block in PyTorch, and check your implementation against PyTorch's built-in function.

Earlier sequence models (recurrent networks) processed text one token after another, which made training slow and long-range dependencies hard to learn. Attention connects all positions directly and is computed with matrix multiplications, so training parallelises perfectly on GPUs. That combination – direct long-range connections plus hardware efficiency – is why transformers could be scaled to billions of parameters and trillions of training tokens.

Tokens and embeddings

Models do not read characters or words but tokens. Subword tokenizers such as byte-pair encoding (BPE) split text into frequent pieces: common words become one token, rare words several. A tokenizer maps each piece to an integer ID from a fixed vocabulary (typically tens of thousands to a few hundred thousand entries).

An embedding layer is a learned lookup table: token ID → vector of model dimension d_model (for example 768 or 4096). After training, tokens used in similar contexts have similar vectors.

Token counts matter in practice: context limits, latency and API prices are all measured in tokens, and the same text can need very different token counts in different languages.

Positional information

Attention itself has no notion of order: without positional information, shuffling the input tokens simply shuffles the output (the lab proves this). Word order must therefore be injected.

The original transformer adds fixed sinusoidal position vectors to the embeddings. GPT-2 learned one position vector per index. Many current models use rotary position embeddings (RoPE), which rotate query and key vectors by a position-dependent angle so attention scores depend on relative distance.

Scaled dot-product attention

Each token's vector is projected three times with learned matrices: a query (what am I looking for?), a key (what do I offer?) and a value (what do I pass on?).

The attention score between position i and j is the dot product of query i and key j, divided by √d_k (the head dimension). Without the scaling, scores grow with the dimension, the softmax saturates and gradients vanish.

A softmax over each row turns the scores into weights that sum to 1. The output for position i is the weighted sum of all value vectors: Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V.

Causal masking: a language model must not see the future while learning to predict the next token. Scores for positions j > i are set to −∞ before the softmax, so their weights become exactly 0. The first token can only attend to itself.

Cost: the score matrix has sequence × sequence entries, so compute and memory grow quadratically with context length – the reason for optimised kernels such as FlashAttention, which PyTorch's scaled_dot_product_attention can use automatically.

Multi-head attention

Instead of one attention over the full dimension, the model splits d_model into h heads of size d_model / h and runs attention in each head independently. Different heads can specialise – for example on the previous token, on syntactic relations, or on matching brackets.

The head outputs are concatenated and mixed by an output projection. The total cost is about the same as single-head attention with the full dimension.

The transformer block

A block combines two sub-layers: multi-head attention (tokens exchange information) and a position-wise feed-forward network (each token is processed individually, typically expanding to 4 × d_model and back).

Each sub-layer is wrapped in a residual connection and layer normalisation. Modern GPT-style models use pre-norm: x + Attention(LayerNorm(x)), then x + MLP(LayerNorm(x)) – more stable to train than the original post-norm arrangement.

A model stacks N identical blocks (12 in GPT-2 small, many more in large models). A final layer norm and a linear language-model head map each position to logits over the vocabulary; softmax and sampling then pick the next token.

Encoder, decoder and encoder–decoder models

Encoder-only models (e.g. BERT) use bidirectional attention – every token sees the whole input. They produce representations for classification, search and embeddings.

Decoder-only models (e.g. the GPT family and most current chat LLMs) use causal attention and generate text token by token.

Encoder–decoder models (e.g. the original transformer, T5) encode an input with bidirectional attention and decode an output with causal self-attention plus cross-attention to the encoder – well suited to translation and summarisation.

Key terminology

Token
Unit of text produced by the tokenizer; mapped to an integer ID.
Embedding
Learned vector representation of a token (or a text) in d_model dimensions.
Query, key, value
Three learned projections of each token: queries are compared with keys, values are mixed by the resulting weights.
Causal mask
Mask that prevents attention to later positions so a model can be trained to predict the next token.
Attention head
One of several parallel attention computations on a slice of the model dimension.
Context window
Maximum number of tokens a model can attend to at once.
Layer normalisation
Normalises each token's vector to zero mean and unit variance with learned scale and shift.
RoPE
Rotary position embedding: encodes positions by rotating queries and keys, making scores depend on relative distance.

Architecture diagrams

Scaled dot-product attention

flowchart LR
  X[Token vectors] --> Q[Query projection]
  X --> K[Key projection]
  X --> V[Value projection]
  Q --> S[Scores = Q times K transposed / sqrt d]
  K --> S
  S --> M[Causal mask]
  M --> SM[Softmax per row]
  SM --> O[Weights times V]
  V --> O
  O --> OUT[Output vectors]
The mask is applied only in causal (decoder) attention.

A GPT-style decoder model

flowchart TB
  T[Token IDs] --> E[Token embedding + positions]
  E --> B1[LayerNorm - multi-head causal attention - add residual]
  B1 --> B2[LayerNorm - feed-forward MLP - add residual]
  B2 --> N[Repeat block N times]
  N --> LN[Final LayerNorm]
  LN --> H[LM head - logits over vocabulary]
  H --> P[Softmax and sampling - next token]
Pre-norm blocks with residual connections are stacked N times.

Practical examples

Resolving a pronoun. In 'The server rejected the request because it was malformed', an attention head can learn to put high weight from 'it' on 'request' – the model resolves the reference from context instead of fixed rules.

Code completion. When completing a closing bracket or a variable name, attention can look back thousands of tokens to the matching opening bracket or declaration in a single step.

Working code

Project: implementing self-attention and a transformer block

Tested with: Python 3.13, PyTorch 2.15 (CPU)

# pip install torch
# python ch4_attention.py
"""Chapter 4 – self-attention from scratch, checked against PyTorch."""
import math
import torch
import torch.nn.functional as F
from torch import nn

torch.manual_seed(0)

def scaled_dot_product_attention(q, k, v, causal=False):
    """q, k, v: (batch, heads, seq, head_dim)."""
    d = q.size(-1)
    scores = q @ k.transpose(-2, -1) / math.sqrt(d)          # (batch, heads, seq, seq)
    if causal:
        seq = q.size(-2)
        mask = torch.triu(torch.ones(seq, seq, dtype=torch.bool), diagonal=1)
        scores = scores.masked_fill(mask, float("-inf"))     # no attention to future tokens
    weights = scores.softmax(dim=-1)                         # each row sums to 1
    return weights @ v, weights

q, k, v = (torch.randn(1, 2, 5, 8) for _ in range(3))
out, weights = scaled_dot_product_attention(q, k, v, causal=True)
reference = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print("output shape:", tuple(out.shape))
print("matches PyTorch:", torch.allclose(out, reference, atol=1e-6))
print("row sums:", weights[0, 0].sum(dim=-1).round(decimals=4).tolist())
print("first token attends only to itself:", weights[0, 0, 0].round(decimals=3).tolist())


class MultiHeadSelfAttention(nn.Module):
    def __init__(self, d_model: int, n_heads: int):
        super().__init__()
        assert d_model % n_heads == 0
        self.n_heads, self.head_dim = n_heads, d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model)   # one projection for Q, K and V
        self.out = nn.Linear(d_model, d_model)

    def forward(self, x, causal=True):
        b, t, c = x.shape
        q, k, v = self.qkv(x).split(c, dim=-1)
        # (b, t, c) -> (b, heads, t, head_dim)
        q, k, v = (z.view(b, t, self.n_heads, self.head_dim).transpose(1, 2) for z in (q, k, v))
        y, _ = scaled_dot_product_attention(q, k, v, causal)
        y = y.transpose(1, 2).contiguous().view(b, t, c)  # concatenate the heads
        return self.out(y)


class TransformerBlock(nn.Module):
    """Pre-norm decoder block as used in GPT-style models."""
    def __init__(self, d_model=64, n_heads=4):
        super().__init__()
        self.ln1, self.ln2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
        self.attn = MultiHeadSelfAttention(d_model, n_heads)
        self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))

    def forward(self, x):
        x = x + self.attn(self.ln1(x))   # residual connection around attention
        x = x + self.mlp(self.ln2(x))    # residual connection around the MLP
        return x


def sinusoidal_positions(seq_len: int, d_model: int) -> torch.Tensor:
    pos = torch.arange(seq_len).unsqueeze(1)
    div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
    pe = torch.zeros(seq_len, d_model)
    pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * div), torch.cos(pos * div)
    return pe

block = TransformerBlock()
tokens = torch.randn(2, 10, 64) + sinusoidal_positions(10, 64)
print("block output shape:", tuple(block(tokens).shape))
print("parameters in one block:", sum(p.numel() for p in block.parameters()))
Expected output
output shape: (1, 2, 5, 8)
matches PyTorch: True
row sums: [1.0, 1.0, 1.0, 1.0, 1.0]
first token attends only to itself: [1.0, 0.0, 0.0, 0.0, 0.0]
block output shape: (2, 10, 64)
parameters in one block: 49984

The from-scratch attention matches torch.nn.functional.scaled_dot_product_attention. The causal mask leaves the first token with weight 1.0 on itself. A block keeps the shape (batch, sequence, d_model), which is why blocks can be stacked.

Practice Lab

These exercises turn the formulas into intuition. Chapter 5 builds a complete small GPT from these parts.

Inspect the causal mask

Beginner

Print the full attention weight matrix weights[0, 0] (5 × 5) for causal=True and causal=False. Describe the pattern.

  • Look at the upper triangle.
Show solution
_, w_causal = scaled_dot_product_attention(q, k, v, causal=True)
_, w_full = scaled_dot_product_attention(q, k, v, causal=False)
print(w_causal[0, 0].round(decimals=2))   # upper triangle is exactly 0
print(w_full[0, 0].round(decimals=2))     # every entry > 0, rows still sum to 1

Count the parameters by hand

Intermediate

Derive a formula for the parameters of one block as a function of d_model and verify it gives 49,984 for d_model = 64. Compare the attention part with torch.nn.MultiheadAttention(64, 4).

  • Linear(a, b) has a·b weights and b biases; LayerNorm(d) has 2·d parameters.
Show solution
# attention: qkv d·3d + 3d, out d·d + d          -> 4d² + 4d
# MLP:       d·4d + 4d, 4d·d + d                   -> 8d² + 5d
# 2 LayerNorms: 4d                                 -> total 12d² + 13d
d = 64
print(12 * d * d + 13 * d)                         # 49984
mha = nn.MultiheadAttention(64, 4, batch_first=True)
print(sum(p.numel() for p in mha.parameters()))    # 16640 = 4d² + 4d, same as ours

Prove that attention needs positions

Advanced

Apply MultiHeadSelfAttention(64, 4) with causal=False to a random sequence of 6 tokens and to the same tokens in permuted order. Show that the outputs are the same up to the permutation. Then add sinusoidal positions after permuting and show that this property breaks.

  • Compare y[:, perm] with the output for x[:, perm].
Show solution
attn = MultiHeadSelfAttention(64, 4)
x, perm = torch.randn(1, 6, 64), torch.tensor([3, 0, 5, 1, 4, 2])
print(torch.allclose(attn(x, causal=False)[:, perm], attn(x[:, perm], causal=False), atol=1e-5))  # True
pe = sinusoidal_positions(6, 64)
print(torch.allclose(attn(x + pe, causal=False)[:, perm],
                     attn(x[:, perm] + pe, causal=False), atol=1e-5))                    # False
# Without positions, attention treats the input as a set; positions make order matter.

Practise with OOHM

Reinforce the chapter's vocabulary and concepts with dictation, rapid typing and quizzes on this topic.

Please log in to use this AI feature.

Knowledge check

1. What is the formula of scaled dot-product attention?
2. Why divide the scores by √d_k?
3. What does the causal mask prevent?
4. How do compute and memory of standard attention scale with sequence length n?
5. Why are positional encodings needed?
6. Which family do most current chat LLMs belong to?
7. What does the feed-forward network in a block do?
8. What does a token embedding layer do?
9. What is the benefit of multiple attention heads?
10. In a pre-norm block, where is LayerNorm applied?

Common mistakes and troubleshooting

Generated text repeats or the model 'cheats' during training (loss far too low).
Cause: Missing or wrong causal mask – the model sees the token it is supposed to predict.
Fix: Check that the upper triangle of the weight matrix is zero; compare with is_causal=True.
RuntimeError: view size is not compatible with input tensor's size and stride.
Cause: view() after transpose() on a non-contiguous tensor.
Fix: Call .contiguous() before .view(), or use .reshape().
Out-of-memory with long inputs.
Cause: The attention matrix grows quadratically with sequence length.
Fix: Use torch.nn.functional.scaled_dot_product_attention (optimised kernels), shorter contexts or smaller batches.

Summary

  • Text becomes tokens, tokens become embeddings, positions are added or encoded with RoPE.
  • Attention = softmax(QKᵀ / √d_k) · V; the causal mask enables next-token prediction.
  • A transformer block is attention plus MLP, each with residual connection and LayerNorm.
  • Encoder, decoder and encoder–decoder models differ in masking and purpose.

Learning outcomes

  • You can implement and test attention and a transformer block from scratch.
  • You can read transformer code and model cards and explain their parts.

Official documentation