Transformers with Keras
Understand the transformer from the inside, then train it, run it and validate it in Keras, through small exercises.
Learning goals: explain what attention does and why it matters; build a small transformer; train it with teacher forcing; generate with it; validate it honestly.
Why transformers?
Reading a sequence: two ways
Many data are sequences: words in a sentence, samples of a signal, patches of an image. A model must combine information coming from different positions. Two designs compete.
A recurrent network reads the sequence one element at a time and carries a single memory vector $h_t=f(h_{t-1},x_t)$. Information from position 1 reaches position $n$ only after $n-1$ updates, and may fade on the way. Training cannot be parallelized over positions, because $h_t$ needs $h_{t-1}$.
A transformer lets every position look directly at every other position through an operation called attention. The path between two positions has length 1 whatever their distance, and all positions are computed at the same time during training, which suits GPUs. The price is a cost that grows like $n^2$ with the length $n$ of the sequence, because every pair of positions interacts.
This is the architecture behind large language models, vision transformers, speech models and the vision-language models of the VLM Project. Here you build the smallest useful one yourself, in Keras, and train it, validate it and use it for inference.
The toy task: sort eight digits
To see attention at work we need a task where each output depends on all inputs. Sorting is one: the first output is the minimum of the eight digits, the second is the next one, and so on. The model reads a prompt such as 9 6 0 1 6 6 3 6 | and must write 0 1 3 6 6 6 6 9, one digit at a time, like a language model writing a sentence. The data are generated by the code of this page: no download, and a CPU is enough (about four minutes for the whole page).

Play the algorithm
One transformer. Two different loops.
Follow the eight-digit sorting task through training and inference. Watch what the model reads, what it predicts, and when its weights change.
Training: learn from the known answer
Digits + SEP + the true answer shifted by one position → token and position embeddings → two causal attention / feed-forward blocks → next-token scores at all positions → loss on the eight answer targets → backpropagation → update the weights. Repeat with another batch.
Inference: write an answer with fixed weights
Digits + SEP → the same trained network → read the scores at the last known position → select one token → append that prediction to the input. Repeat eight times. No target answer, loss, gradient or weight update is used.
Illustrated data flow, not a network running in your browser. Training predictions are illustrative; inference follows an ideal successful trace. A real model can make mistakes.
Objectives to carry out
- Turn the sorting task into next-token prediction with shifted targets and a loss that only counts the answer (Part 1).
- Write scaled dot-product attention with a causal mask in NumPy, then check the Keras layer against your counts and your causality test (Part 2).
- Assemble a transformer block and a complete model in Keras, and count its parameters by hand; place the architecture among encoders, decoders and encoder–decoders (Part 3).
- Train the model with teacher forcing and monitor a validation set; compare with the same model without attention; understand, and measure, why transformers need a lot of data (Part 4).
- Inference: generate the answer token by token and validate with an exact-match metric; touch the test set once; look at the attention maps (Part 5).
- Deliver a short report and discuss what the toy does and does not show (Part 6).
Each part starts with an explanation, then proposes small exercises with a very light Python starting code (TO DO lines). Its correction is folded just after it. Try before you open it.
How to work: environment and discipline
Install tensorflow==2.21.0 numpy matplotlib in an isolated Python environment (checked with Python 3.12 and TensorFlow CPU 2.21). Run the blocks in order in one notebook or session: later exercises reuse earlier variables. The test set is used once, at the end of Part 5, after every choice is frozen. A fixed random seed makes runs reproducible, but hardware and library versions can change exact scores.
import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersSEED = 42keras.utils.set_random_seed(SEED)L = 8 # number of digits to sortSEP = 10 # separator token; digits are the tokens 0..9VOCAB = 11 # 10 digits + SEPT = 2 * L # model input length: L digits, SEP, then L-1 digits already writtenD, HEADS, FFN = 64, 4, 128 # width, attention heads, hidden size of the feed-forward layer
Part 1 · Tokens, targets and positions
From a task to next-token prediction
A language model is trained on one simple question: given the tokens so far, which token comes next? We encode our task in the same way. A sequence of $2L+1$ tokens is written as the $L=8$ digits, a separator SEP, then the $L$ sorted digits:
The model receives the first $2L$ tokens (inputs) and must predict the same sequence shifted by one position (targets): at the position of SEP it predicts $y_1$, at the position of $y_1$ it predicts $y_2$, and so on. Feeding the true previous tokens during training is called teacher forcing: all the positions are learned in a single pass. The loss must ignore the positions inside the prompt, where the next digit is random and unpredictable: we give them a weight $0$.
Exercise 1.1 · build the sequences
- Draw
nrandom digit sequences, sort them, and concatenate digits,SEPand sorted digits. - Cut inputs (all but the last token) and targets (all but the first), and build a weight array that is 1 only where the target is a sorted digit.
- Check that training and validation sets share no prompt.
def make_sequences(n, rng): x = ... # TO DO: n random sequences of L digits y = ... # TO DO: the same digits, sorted tokens = ... # TO DO: digits, SEP, sorted digits: 2L+1 tokens inputs = ... # TO DO: what the model reads targets = ... # TO DO: the token that follows each position weights = ... # TO DO: 1 only where the target is a sorted digit return x, inputs, targets, weightsrng = np.random.default_rng(SEED)x_tr, in_tr, out_tr, w_tr = make_sequences(20000, rng)x_va, in_va, out_va, w_va = make_sequences(2000, rng)x_te, in_te, out_te, w_te = make_sequences(2000, rng)print(in_tr.shape, out_tr.shape, w_tr.sum(axis=1)[0])print("example:", in_tr[0], "->", out_tr[0])overlap = ... # TO DO: sequences present in both training and validationprint("train/validation overlap:", len(overlap))
Show the correction
# A sequence is: 8 digits, SEP, then the same digits sorted: 2L+1 = 17 tokens.def make_sequences(n, rng): # x has shape (n, 8): one row of random digits per example. The generator rng makes the data reproducible. x = rng.integers(0, 10, size=(n, L)) # n random sequences of L digits # Sorting each row (axis=1) gives the answer that the model must learn to write. y = np.sort(x, axis=1) # the same digits, sorted # np.full((n, 1), SEP) is a column of separators: tokens has shape (n, 17). tokens = np.concatenate([x, np.full((n, 1), SEP), y], axis=1) # digits, SEP, sorted digits: 2L+1 tokens # The model reads the first 16 tokens... # ...and must predict the same sequence shifted by one position (teacher forcing): at position i it predicts token i+1. inputs = tokens[:, :-1] # what the model reads targets = tokens[:, 1:] # the token that follows each position # Inside the prompt the next digit is random, so those positions must not count in the loss: weight 0 everywhere... # ...except from the position of SEP (index L) to the end, where the target is a sorted digit. weights = np.zeros(targets.shape, dtype="float32") # 1 only where the target is a sorted digit weights[:, L:] = 1.0 return x, inputs, targets, weightsrng = np.random.default_rng(SEED)x_tr, in_tr, out_tr, w_tr = make_sequences(20000, rng)x_va, in_va, out_va, w_va = make_sequences(2000, rng)x_te, in_te, out_te, w_te = make_sequences(2000, rng)print(in_tr.shape, out_tr.shape, w_tr.sum(axis=1)[0])print("example:", in_tr[0], "->", out_tr[0])# A set of tuples makes the comparison fast. 0 means that no validation prompt was seen during training.overlap = {tuple(r) for r in x_tr} & {tuple(r) for r in x_va} # sequences present in both training and validationprint("train/validation overlap:", len(overlap))
With 20,000 training, 2,000 validation and 2,000 test sequences of $10^8$ possible prompts, an accidental overlap is very unlikely, but the check costs one line. A validation set that repeats training examples hides over-fitting.
Embeddings and positions
A token is an integer. The first layer maps it to a vector of $D=64$ numbers learned during training (an embedding). Attention treats the sequence as a set: if you permute the tokens, the outputs are permuted in the same way and nothing tells the model which token comes first. We therefore add a second learned vector that depends only on the position:
\[h_i = E_{\text{token}}[t_i] + E_{\text{position}}[i].\]Exercise 1.2 · token and position embeddings
- Create a token embedding and a position embedding inside a Keras layer.
- In
call, add them with broadcasting. - Check the output shape and the number of parameters by hand: $11\cdot64+16\cdot64$.
class TokenAndPosition(layers.Layer): """Token embedding + learned position embedding.""" def __init__(self, vocab, length, width, **kw): super().__init__(**kw) self.tok = ... # TO DO: one vector of size `width` per token self.pos = ... # TO DO: one vector per position def call(self, tokens): positions = ... # TO DO: 0, 1, ..., T-1 return ... # TO DO: (batch, T, width) + (T, width), broadcastemb = TokenAndPosition(VOCAB, T, D)h = emb(in_tr[:3])print(h.shape, emb.count_params())
Show the correction
# A custom Keras layer: sub-layers are created in __init__, the computation is written in call.class TokenAndPosition(layers.Layer): """Token embedding + learned position embedding.""" def __init__(self, vocab, length, width, **kw): super().__init__(**kw) # Table of vocab x width numbers: row t is the vector of token t. It is learned during training. self.tok = layers.Embedding(vocab, width) # one vector of size `width` per token # Same idea for the positions: row i is the vector added to whatever token sits at position i. self.pos = layers.Embedding(length, width) # one vector per position def call(self, tokens): # tf.shape(tokens)[1] is the length of the sequence (16): positions = [0, 1, ..., 15]. positions = tf.range(tf.shape(tokens)[1]) # 0, 1, ..., T-1 # (batch, 16, width) + (16, width): the position table is broadcast over the batch. return self.tok(tokens) + self.pos(positions) # (batch, T, width) + (T, width), broadcastemb = TokenAndPosition(VOCAB, T, D)# Output shape (3, 16, 64); parameters: 11*64 (tokens) + 16*64 (positions) = 1,728.h = emb(in_tr[:3])print(h.shape, emb.count_params())
The output has shape (batch, 16, 64); the position embedding of shape (16, 64) is added to every sequence of the batch. The layer has $11\cdot64+16\cdot64=1{,}728$ parameters.
Part 2 · Self-attention, step by step
Queries, keys and values
Think of a small library. Each position $i$ prepares a query $q_i$ (“what am I looking for?”), a key $k_i$ (“what do I contain?”) and a value $v_i$ (“what do I give if you read me?”). They are three linear maps of the same vector $h_i$. Position $i$ compares its query with every key, turns the similarities into weights that sum to 1 with a softmax, and returns the weighted average of the values:
\[\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\Big(\frac{QK^{\top}}{\sqrt d}+M\Big)V,\qquad M_{ij}=\begin{cases}0&j\le i\\-\infty&j>i.\end{cases}\]The factor $1/\sqrt d$ keeps the scores of order 1 when the dimension $d$ grows (otherwise the softmax saturates). The matrix $M$ is the causal mask: when the model writes the digit at position $i$, it is not allowed to read positions after $i$, since they are not written yet at inference time.

Why the mask works. The weight $W_{ij}=e^{s_{ij}}/\sum_l e^{s_{il}}$ is exactly $0$ when $s_{ij}=-\infty$, so the output at position $i$ is $\sum_{j\le i}W_{ij}v_j$ and uses only positions $j\le i$. Changing a later token cannot change an earlier output. You will check it numerically.
Exercise 2.1 · attention in NumPy
- Compute the scaled scores $QK^\top/\sqrt d$.
- Apply the causal mask by replacing the scores above the diagonal by a very negative number.
- Apply a softmax along each row and return the weighted values with the weights.
- Check that the rows sum to 1, that the future receives no weight, and that changing the last token leaves the earlier outputs unchanged.
def softmax(z): z = z - z.max(axis=-1, keepdims=True) e = np.exp(z) return e / e.sum(axis=-1, keepdims=True)def attention(Q, K, V, causal=True): d = Q.shape[-1] scores = ... # TO DO: similarity of every query with every key, scaled if causal: future = ... # TO DO: True above the diagonal (positions in the future) scores = ... # TO DO: a future position gets a score of -infinity W = ... # TO DO: each row sums to 1 return ... # TO DO: weighted average of the valuesrng2 = np.random.default_rng(0)Q, K, V = (rng2.normal(size=(5, 4)) for _ in range(3))out, W = attention(Q, K, V)print(np.round(W, 2))print("rows sum to 1:", np.allclose(W.sum(axis=1), 1))print("no weight on the future:", np.allclose(np.triu(W, 1), 0))K2, V2 = K.copy(), V.copy(); K2[4] += 5; V2[4] += 5 # change only the LAST positionout2, _ = attention(Q, K2, V2)print("positions 0..3 unchanged:", np.allclose(out[:4], out2[:4]))
Show the correction
# Subtracting the maximum of each row does not change the result but avoids overflows in exp.def softmax(z): z = z - z.max(axis=-1, keepdims=True) e = np.exp(z) return e / e.sum(axis=-1, keepdims=True)def attention(Q, K, V, causal=True): d = Q.shape[-1] # Q @ K.T is the (T, T) matrix of dot products between every query and every key; dividing by sqrt(d) keeps the scores of order 1. scores = Q @ K.T / np.sqrt(d) # similarity of every query with every key, scaled if causal: # np.triu(..., k=1) keeps the entries above the diagonal: they are the pairs (i, j) with j > i, i.e. positions in the future of i. future = np.triu(np.ones_like(scores), k=1) == 1 # True above the diagonal (positions in the future) # -1e9 plays the role of -infinity: after the exponential its weight is 0. scores = np.where(future, -1e9, scores) # a future position gets a score of -infinity # Softmax along each row: the weights of a reading position sum to 1. W = softmax(scores) # each row sums to 1 # Each output is a weighted average of the values; W is returned too, so that we can look at it. return W @ V, W # weighted average of the valuesrng2 = np.random.default_rng(0)Q, K, V = (rng2.normal(size=(5, 4)) for _ in range(3))out, W = attention(Q, K, V)print(np.round(W, 2))print("rows sum to 1:", np.allclose(W.sum(axis=1), 1))print("no weight on the future:", np.allclose(np.triu(W, 1), 0))# Causality test: perturb only the last position (key and value) and check that the earlier outputs do not move.K2, V2 = K.copy(), V.copy(); K2[4] += 5; V2[4] += 5 # change only the LAST positionout2, _ = attention(Q, K2, V2)print("positions 0..3 unchanged:", np.allclose(out[:4], out2[:4]))
The first row is $[1,0,0,0,0]$: the first token can only read itself. The weights are a probability distribution, so each output is a convex combination of the values. Subtracting the row maximum in the softmax avoids overflows without changing the result.
Several heads
One attention pattern may not be enough: sorting needs to find the smallest remaining digit, but also to remember which digits were already written. Multi-head attention runs $h$ attentions in parallel on $d=D/h$ dimensions each, then concatenates and mixes them with an output matrix. In Keras it is layers.MultiHeadAttention(num_heads, key_dim). With $D=64$ and $4$ heads it has four matrices $D\times D$ (queries, keys, values, output) with their biases.
Exercise 2.2 · the Keras attention layer
- Create a
MultiHeadAttentionwith 4 heads of dimension 16 and apply it to the embeddings of three sequences withuse_causal_mask=True. - Count its parameters by hand and compare with
count_params(). - Change the last position of the input and check that the earlier outputs do not change.
mha = layers.MultiHeadAttention(num_heads=HEADS, key_dim=D // HEADS)h = emb(in_tr[:3])y1 = mha(h, h, use_causal_mask=True)by_hand = ... # TO DO: four D x D matrices (Q, K, V, output) with their biasesprint(y1.shape, mha.count_params(), by_hand)h2 = h.numpy().copy(); h2[:, -1] += 1.0 # change the last position onlyy2 = mha(tf.constant(h2), tf.constant(h2), use_causal_mask=True)same = ... # TO DO: do the earlier positions still produce the same output?print("earlier positions unchanged:", same)
Show the correction
# 4 heads of dimension 16: 4*16 = 64 = D, the width of the embeddings.mha = layers.MultiHeadAttention(num_heads=HEADS, key_dim=D // HEADS)h = emb(in_tr[:3])# Self-attention: the same tensor h is used as query and as value (and key). use_causal_mask=True adds the mask M of the course.y1 = mha(h, h, use_causal_mask=True)# Four matrices (queries, keys, values, output), each D x D plus D biases: 4 * (64*64 + 64) = 16,640.by_hand = 4 * (D * D + D) # four D x D matrices (Q, K, V, output) with their biasesprint(y1.shape, mha.count_params(), by_hand)# Same causality test as in NumPy, now on the Keras layer.h2 = h.numpy().copy(); h2[:, -1] += 1.0 # change the last position onlyy2 = mha(tf.constant(h2), tf.constant(h2), use_causal_mask=True)# Compare all positions except the last one; atol absorbs rounding errors.same = np.allclose(y1[:, :-1], y2[:, :-1], atol=1e-5) # do the earlier positions still produce the same output?print("earlier positions unchanged:", same)
The $16{,}640=4\cdot(64\cdot64+64)$ parameters do not depend on the sequence length: the same weights are applied at every position, as a convolution shares its kernel.
Part 3 · The transformer block and the model
The transformer block
A block alternates two sub-layers, each wrapped in a residual connection and preceded by a layer normalization:
\[x\leftarrow x+\operatorname{Attention}(\operatorname{LN}(x)),\qquad x\leftarrow x+\operatorname{FFN}(\operatorname{LN}(x)).\]- Attention exchanges information between positions.
- The feed-forward network $\operatorname{FFN}(x)=W_2\,\mathrm{gelu}(W_1x)$ transforms each position separately, with a hidden size $128$ here.
- The residual connection gives every layer a shortcut for the information and for the gradient, which makes deep stacks trainable.
- Layer normalization rescales each position to a stable mean and variance.
The output of the last block is a vector for each position. A Dense(11) layer turns it into 11 scores (logits), one per token; a softmax turns them into probabilities for the next token.
Exercise 3.1 · build the model
- Complete
block: self-attention with a causal mask and residual connection, then feed-forward layers and residual connection. - Complete
build_transformer: embedding, a stack of blocks, a final normalization, and aDensehead with one output per token. - Count the parameters by hand (embeddings 1,728; one block 33,472; final normalization 128; head 715) and compare with
model.summary().
def block(x, index, attention=True): if attention: h = layers.LayerNormalization(name=f"ln_a{index}")(x) h = ... # TO DO: causal self-attention x = ... # TO DO: residual connection h = layers.LayerNormalization(name=f"ln_f{index}")(x) h = ... # TO DO: feed-forward layer, applied to each position separately return ... # TO DO: residual connectiondef build_transformer(n_blocks=2, attention=True): tokens = keras.Input(shape=(T,), dtype="int32") x = TokenAndPosition(VOCAB, T, D)(tokens) for i in range(n_blocks): x = ... # TO DO: stack the blocks x = layers.LayerNormalization()(x) logits = ... # TO DO: one score per vocabulary token, at every position return keras.Model(tokens, logits)model = build_transformer()model.summary()print("parameters:", model.count_params())
Show the correction
# Pre-norm block: each sub-layer receives a normalized input and its result is ADDED to the input.def block(x, index, attention=True): if attention: # Names make it possible to find the layers again later (Part 5 reads the attention weights). h = layers.LayerNormalization(name=f"ln_a{index}")(x) h = layers.MultiHeadAttention(HEADS, D // HEADS, name=f"attn{index}")(h, h, use_causal_mask=True) # causal self-attention # Residual connection: the layer only has to learn a correction to x, and the gradient can flow through the addition unchanged. x = layers.Add()([x, h]) # residual connection h = layers.LayerNormalization(name=f"ln_f{index}")(x) # Feed-forward network: expand to FFN=128 units with a smooth non-linearity (gelu), then come back to D=64. Applied to each position independently. h = layers.Dense(FFN, activation="gelu")(h) # feed-forward layer, applied to each position separately h = layers.Dense(D)(h) # Second residual connection. return layers.Add()([x, h]) # residual connection# n_blocks and attention are parameters so that Part 4 can train a control model without attention.def build_transformer(n_blocks=2, attention=True): # Input: integer tokens of shape (batch, T=16). tokens = keras.Input(shape=(T,), dtype="int32") # (batch, 16, 64) after the embeddings. x = TokenAndPosition(VOCAB, T, D)(tokens) for i in range(n_blocks): x = block(x, i, attention) # stack the blocks x = layers.LayerNormalization()(x) # One score per vocabulary token at every position: (batch, 16, 11). No softmax here: the loss will use from_logits=True, which is numerically safer. logits = layers.Dense(VOCAB)(x) # one score per vocabulary token, at every position return keras.Model(tokens, logits)model = build_transformer()model.summary()print("parameters:", model.count_params())
Two blocks make $2\cdot33{,}472+1{,}728+128+715=69{,}515$ parameters. Note the argument attention: with False the block keeps only its feed-forward part, which processes each position in isolation. We use this variant in Part 4 as a control experiment.
Encoder, decoder, encoder–decoder
The model of this page is a decoder-only transformer: one stack of blocks with a causal mask, where the prompt and the answer are parts of the same sequence. This is the design of GPT-style language models. The original transformer of Vaswani et al. (2017), made for translation, has two stacks, and three families exist. They differ by the mask of the self-attention and by one extra layer:
| Family | Self-attention | Typical use | Examples |
|---|---|---|---|
| Encoder-only | bidirectional (no mask) | representations, classification, image encoders | BERT, ViT, the vision side of a VLM |
| Decoder-only | causal | generation, language models | GPT, Llama, this page |
| Encoder–decoder | bidirectional in the encoder, causal in the decoder, plus cross-attention | transformation of a source sequence into a target sequence | original transformer, T5, Whisper |
The encoder reads the whole source (a sentence to translate, an audio spectrogram) with full self-attention and produces a memory $M$: one vector per source position. The decoder writes the target token by token. In addition to its causal self-attention, each decoder block has a cross-attention layer: its queries come from the decoder, its keys and values from the memory,
\[\operatorname{CrossAttention}(H_{\text{dec}},M)=\operatorname{softmax}\!\Big(\frac{(H_{\text{dec}}W_Q)(MW_K)^{\top}}{\sqrt d}\Big)\,MW_V,\]with no mask, since the whole source is known. This is how the decoder “looks at” the source while it writes. Our sorting task could be solved in this way too (the encoder reads the digits, the decoder writes the sorted ones); a decoder-only model needs only one stack, which is simpler to scale, and is why most large language models use it. The VLM Project mixes the ideas: it reads image tokens and question tokens together with bidirectional attention, like an encoder, and reads its answer at one position.
Exercise 3.2 · cross-attention
- Apply a
MultiHeadAttentionwith the decoder states asqueryand the encoder memory askeyandvalue; there is no causal mask. - Check the shapes of the output and of the attention weights: each target position distributes its attention over the 10 source positions.
- Change the last target position: do the other outputs change? Change the whole source: does the output change?
memory = tf.random.normal((2, 10, D)) # encoder output: 10 source positionstarget = tf.random.normal((2, 6, D)) # decoder states: 6 target positionscross = layers.MultiHeadAttention(HEADS, D // HEADS)out = ... # TO DO: queries come from the decoder, keys and values from the encoder_, w = ... # TO DO: the attention weights of the same callprint(out.shape, w.shape) # (2, 6, 64) and (2, 4, 6, 10)print("each target position distributes its attention over the 10 source positions:", np.allclose(w.numpy().sum(axis=-1), 1))target2 = target.numpy().copy(); target2[:, -1] += 1.0 # change the last target position onlyout2 = cross(query=tf.constant(target2), value=memory, key=memory)... # TO DO: does cross-attention mix target positions?memory2 = memory + 1.0 # change the whole sourceprint("outputs depend on the source:", not np.allclose(out, cross(query=target, value=memory2, key=memory2), atol=1e-5))
Show the correction
# Stand-ins for the output of an encoder (10 source positions) and for the states of a decoder (6 target positions).memory = tf.random.normal((2, 10, D)) # encoder output: 10 source positionstarget = tf.random.normal((2, 6, D)) # decoder states: 6 target positionscross = layers.MultiHeadAttention(HEADS, D // HEADS)# query = decoder states, key = value = encoder memory. No causal mask: the whole source is known.out = cross(query=target, value=memory, key=memory) # queries come from the decoder, keys and values from the encoder# return_attention_scores=True also returns the weights, of shape (batch, heads, 6 target, 10 source)._, w = cross(query=target, value=memory, key=memory, return_attention_scores=True) # the attention weights of the same callprint(out.shape, w.shape) # (2, 6, 64) and (2, 4, 6, 10)print("each target position distributes its attention over the 10 source positions:", np.allclose(w.numpy().sum(axis=-1), 1))# Perturb only the last target position.target2 = target.numpy().copy(); target2[:, -1] += 1.0 # change the last target position onlyout2 = cross(query=tf.constant(target2), value=memory, key=memory)# Cross-attention treats each target position separately, so the other rows are unchanged.print("other target positions unchanged:", np.allclose(out[:, :-1], out2[:, :-1], atol=1e-5)) # does cross-attention mix target positions?memory2 = memory + 1.0 # change the whole sourceprint("outputs depend on the source:", not np.allclose(out, cross(query=target, value=memory2, key=memory2), atol=1e-5))
The weights have shape (batch, heads, 6, 10): one row per target position, one column per source position. Cross-attention does not mix target positions (they are treated independently, so changing the last one leaves the others unchanged); the mixing of target positions is the job of the causal self-attention. The parameter count is the same as for self-attention: $4\cdot(64\cdot64+64)$.
Part 4 · Train with teacher forcing, and why it needs data
Teacher forcing, weights and validation
Training minimizes the average cross-entropy over the positions that carry a weight $1$:
\[\mathcal L=-\frac{\sum_{i}w_i\log p_\theta(t_{i+1}\mid t_{\le i})}{\sum_i w_i}.\]In Keras this is sample_weight in fit. The validation set is passed with its own weights; the learning curve is the only thing allowed to guide the choice of the epoch (early stopping: stop when the validation loss no longer improves and restore the best weights). The test set stays untouched.
Exercise 4.1 · train, validate and run a control
- Complete
train: Adam optimizer, token-level cross-entropy from logits, the training weights and the validation tuple with weights. - Train the transformer, then train a control with
attention=Falsefor 15 epochs. - For each model, report the best epoch, the validation loss and the validation token accuracy, and plot the loss curves.
def train(model, epochs=40, rate=2e-3): model.compile(optimizer=keras.optimizers.Adam(rate), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), weighted_metrics=[keras.metrics.SparseCategoricalAccuracy(name="acc")]) stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=5, restore_best_weights=True) return model.fit(in_tr, out_tr, sample_weight=..., # TO DO: the loss counts only the sorted digits validation_data=..., # TO DO: validation data with the same weights batch_size=128, epochs=epochs, callbacks=[stop], verbose=0)keras.utils.set_random_seed(SEED)history = train(model)no_attention = build_transformer(attention=False)history_na = train(no_attention, epochs=15)for name, hist in [("transformer", history), ("without attention", history_na)]: best = int(np.argmin(hist.history["val_loss"])) print(f"{name:18s} best epoch {best+1:2d} val loss {hist.history['val_loss'][best]:.3f} val token accuracy {hist.history['val_acc'][best]:.3f}")plt.plot(history.history["loss"], label="train"); plt.plot(history.history["val_loss"], "--", label="validation")plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()
Show the correction
# weighted_metrics makes the accuracy use the same weights as the loss: only the sorted digits count.def train(model, epochs=40, rate=2e-3): model.compile(optimizer=keras.optimizers.Adam(rate), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), weighted_metrics=[keras.metrics.SparseCategoricalAccuracy(name="acc")]) # Stop when the validation loss has not improved for 5 epochs and put back the best weights: the epoch is chosen on validation, not on training. stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=5, restore_best_weights=True) return model.fit(in_tr, out_tr, # sample_weight multiplies the loss of each position by 0 or 1: this is how the prompt is ignored. sample_weight=w_tr, # the loss counts only the sorted digits validation_data=(in_va, out_va, w_va), # validation data with the same weights batch_size=128, epochs=epochs, callbacks=[stop], verbose=0)# Same seed before each model: the comparison between the two models is fair.keras.utils.set_random_seed(SEED)history = train(model)# Control model: same sizes, but the blocks have no attention, so no position can look at another.no_attention = build_transformer(attention=False)history_na = train(no_attention, epochs=15)for name, hist in [("transformer", history), ("without attention", history_na)]: # The best epoch is the one with the lowest validation loss; we report the metrics at that epoch. best = int(np.argmin(hist.history["val_loss"])) print(f"{name:18s} best epoch {best+1:2d} val loss {hist.history['val_loss'][best]:.3f} val token accuracy {hist.history['val_acc'][best]:.3f}")plt.plot(history.history["loss"], label="train"); plt.plot(history.history["val_loss"], "--", label="validation")plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()
In the reference run the transformer stops at epoch 32 with a validation loss of about $0.000$ and a token accuracy of $1.000$. The model without attention stays at a validation loss of $0.605$ and a token accuracy of $0.455$: it can learn which digits are frequent, but it cannot compare a position with the others, which is exactly what sorting needs. This is the interest of attention in one experiment. (One seed, one task: the exact numbers can vary, the gap does not.)
Why does a transformer need so much data?
Large language models are trained on trillions of tokens. Yet, as Exercise 4.2 will show, our small model learns to sort digits from a few hundred examples. Both facts are true, and the difference is instructive: the amount of data that a transformer needs depends on the complexity of what it must learn and on the size of the model. Four reasons, from the weakest assumption to the hardest optimization, explain why real problems ask for so much.
1. Almost no built-in structure (inductive bias). A convolutional network assumes that useful features are local and that the same pattern can appear anywhere (weight sharing, translation equivariance); a recurrent network assumes that the order of reading matters. Attention assumes almost nothing: every pair of positions may interact, and the position is only a learned vector. The set of functions that the model can represent is huge, and the data must select the right one, including facts that a convolution gets for free. This is observed: a vision transformer trained on ImageNet alone (1.3 million images) is worse than a ResNet of the same size; with 14 to 300 million images it becomes better (Dosovitskiy et al., 2021). The less structure we impose, the more data we must provide.
2. Capacity and the data term of the loss. A block has about $12D^2$ parameters when the feed-forward width is $4D$ (here $8D^2$ with width $2D$), and a model has $N$ of them: from $7\times10^4$ in our model to hundreds of billions in language models. Classical statistical learning theory says that, to be sure that the training error is close to the true error, the number of examples must grow with the capacity of the class: a bound of order $n\gtrsim p/\varepsilon^2$ for $p$ parameters. This is a worst-case guarantee, loose for deep networks, which generalize with more parameters than examples. The empirical law fitted on language models (Kaplan et al., 2020; Hoffmann et al., 2022) is more informative:
\[\mathcal L(N,D)\;\approx\;E+\frac{A}{N^{\alpha}}+\frac{B}{D^{\beta}},\qquad \alpha\approx0.34,\ \beta\approx0.28,\]where $D$ is the number of training tokens and $E$ the irreducible loss of the text itself. Two terms compete: a model that is too small cannot represent the function, and an amount of data that is too small leaves an error $B/D^{\beta}$ that no architecture can remove. Since $\beta$ is small, halving this error requires about $2^{1/\beta}\approx12$ times more data. The compute-optimal choice found by Hoffmann et al. is about 20 tokens per parameter, so a model must see data in proportion to its size.
3. A start on a flat region (a saddle). In one attention head the score is bilinear in the two matrices that must be learned, $s_{ij}=(W_Qx_i)^{\top}(W_Kx_j)/\sqrt d$. By the chain rule,
\[\frac{\partial\mathcal L}{\partial W_Q}=\frac1{\sqrt d}\sum_{i,j}\frac{\partial\mathcal L}{\partial s_{ij}}\,W_Kx_j\,x_i^{\top},\qquad \frac{\partial\mathcal L}{\partial W_K}=\frac1{\sqrt d}\sum_{i,j}\frac{\partial\mathcal L}{\partial s_{ij}}\,W_Qx_i\,x_j^{\top}.\]Each gradient is proportional to the other matrix. At $W_Q=W_K=0$ both vanish: this is a saddle point, and if both matrices are small, of size $\varepsilon$, the gradients are of size $\varepsilon$ and the scores move slowly. Moreover, small scores mean an almost uniform softmax: the output at position $i$ is then nearly the average of $i$ values, so a relevant token contributes only a fraction $1/i$ of the output, and the gradient that would sharpen the attention towards it is diluted in the same proportion. The two matrices must grow together before the loss decreases: the loss stays on a plateau for a while, and then drops suddenly. On a harder task or with fewer examples, the plateau is expected to be longer, because the weak signal “this token matters” is estimated from fewer samples and is dominated by noise (we do not measure this effect here). This is also why the learning-rate warm-up, Adam, the residual connections and the normalization of the block are not optional details (Xiong et al., 2020).
4. Attention alone loses information with depth. Without the residual connections and the feed-forward layers, a stack of attention layers produces outputs that all tend to the same vector: the rank of the representation collapses doubly exponentially with the depth (Dong et al., 2021). The skip connections and the feed-forward layers prevent it, but they also make the optimization landscape harder, which again calls for many steps on diverse data.
What we have seen in this course. The sorting model needs about 5,000 gradient steps and the model without attention never gets there; the VLM Project stays at chance on the position question with a smaller model or a larger learning rate, and fails on colour–shape pairs absent from its 9 training pairs, because it memorized them instead of composing them. The next exercise measures the effect of the number of examples on the sorting task, where the effect turns out to be modest. In practice, one pays this price once (pretraining on huge corpora), then adapts a pretrained model with little data (fine-tuning), or injects structure (convolutional stem, data augmentation, a smaller model) when data are scarce.
Exercise 4.2 · how many examples are needed?
- Complete
train_on(n): train a fresh transformer on the first $n$ sequences for the same number of gradient steps (5,000), whatever $n$ is. - Return the training accuracy and the validation accuracy at the end of training.
- Run it for $n=250$, $1{,}000$, $4{,}000$ and $20{,}000$ and comment on the gap between training and validation accuracy.
def train_on(n, steps=5000, batch=128): """Train a fresh transformer on the first n training sequences, for the same number of gradient steps.""" keras.utils.set_random_seed(SEED) net = build_transformer() net.compile(optimizer=keras.optimizers.Adam(2e-3), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), weighted_metrics=[keras.metrics.SparseCategoricalAccuracy(name="acc")]) epochs = ... # TO DO: the same number of gradient steps whatever n is hist = net.fit(in_tr[:n], out_tr[:n], sample_weight=w_tr[:n], validation_data=(in_va, out_va, w_va), validation_freq=max(1, epochs // 20), batch_size=batch, epochs=epochs, verbose=0) train_acc = ... # TO DO: accuracy on the training sequences at the end val_acc = ... # TO DO: accuracy on the validation sequences at the end return train_acc, val_accprint(f"{'sequences':>10s} {'train acc':>10s} {'val acc':>10s}")for n in [250, 1000, 4000, 20000]: tr_acc, va_acc = train_on(n) print(f"{n:10d} {tr_acc:10.3f} {va_acc:10.3f}")
Show the correction
# A fresh model every time, so that the runs are independent.def train_on(n, steps=5000, batch=128): """Train a fresh transformer on the first n training sequences, for the same number of gradient steps.""" keras.utils.set_random_seed(SEED) net = build_transformer() net.compile(optimizer=keras.optimizers.Adam(2e-3), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), weighted_metrics=[keras.metrics.SparseCategoricalAccuracy(name="acc")]) # With n sequences and a batch of 128 there are n/128 steps per epoch, so epochs = steps * 128 / n keeps the total number of steps constant: only the amount of data changes. epochs = steps * batch // n # the same number of gradient steps whatever n is hist = net.fit(in_tr[:n], out_tr[:n], sample_weight=w_tr[:n], # validation_freq limits the cost of validating after every epoch when there are many epochs. validation_data=(in_va, out_va, w_va), validation_freq=max(1, epochs // 20), batch_size=batch, epochs=epochs, verbose=0) # The last logged value: we measure how well the model fits its training data... train_acc = hist.history["acc"][-1] # accuracy on the training sequences at the end # ...and how well it does on data it has not seen. The difference is the generalization gap. val_acc = hist.history["val_acc"][-1] # accuracy on the validation sequences at the end return train_acc, val_accprint(f"{'sequences':>10s} {'train acc':>10s} {'val acc':>10s}")for n in [250, 1000, 4000, 20000]: tr_acc, va_acc = train_on(n) print(f"{n:10d} {tr_acc:10.3f} {va_acc:10.3f}")
| training sequences | train accuracy | validation accuracy |
|---|---|---|
| 250 | 1.000 | 0.970 |
| 1,000 | 1.000 | 0.999 |
| 4,000 | 1.000 | 1.000 |
| 20,000 | 1.000 | 1.000 |
Same model, same seed, same number of gradient steps (5,000); accuracy over the sorted digits, teacher-forced. The model fits its training data perfectly in every case. What changes is the generalization gap: 3 points with 250 sequences (an exact-match error on the eight digits of roughly one sequence in five), 0.1 point with 1,000, none beyond. The error does fall as the data grow, as the data term of the scaling law predicts, but it is small from the start. Do not conclude that transformers need little data: this task has a short, exact, noise-free rule and the prompts are drawn uniformly. Real language, images or demonstrations have an enormous number of regularities, rare cases and noise, a model with billions of parameters, and a target function that is far more complex. Try a harder variant yourself (longer sequences, sorting with a noisy digit, or $L=16$) and see how the 250-sequence row degrades.
Part 5 · Inference and validation
Writing the answer token by token
At inference time the true answer is unknown. The model generates: it reads the prompt and SEP, predicts the first digit, appends it to the sequence, reads the longer sequence, predicts the next digit, and so on. With greedy decoding we always keep the most likely token (argmax); language models often sample instead to produce varied text.
The input of the network has a fixed length $T=16$; we complete the part that is not written yet with zeros. Because of the causal mask, those positions cannot influence the position we read. Compare training and inference: training is one parallel pass; inference is a loop of $L$ passes, each one using the previous outputs. An error at step $k$ is then fed back as an input: a model can be accurate token by token yet fail on a complete answer. This is why we validate with the exact match of the whole output.
Exercise 5.1 · generate and validate
- Complete
generate: read the logits at the last written position, take theargmax, append it and repeat $L$ times. - Compute the exact-match accuracy (all eight digits correct) and the digit accuracy on the validation set.
- Print one prompt, the generated answer and the expected one.
def generate(model, x): seq = np.concatenate([x, np.full((len(x), 1), SEP)], axis=1) # start from the prompt: digits and SEP for _ in range(L): padded = np.concatenate([seq, np.zeros((len(x), T - seq.shape[1]), dtype=int)], axis=1) # fill up to length T logits = ... # TO DO: scores at every position step = ... # TO DO: the most likely next token, read at the last real position seq = ... # TO DO: append it and repeat return seq[:, L + 1:]pred = generate(model, x_va)exact = ... # TO DO: the whole output must be rightdigit = (pred == np.sort(x_va, axis=1)).mean()print(f"validation: exact match {exact:.3f}, digits {digit:.3f}")print(x_va[0], "->", pred[0], "expected", np.sort(x_va[0]))
Show the correction
# x holds the prompts (n, 8). The sequence starts as digits + SEP and grows by one token per pass.def generate(model, x): seq = np.concatenate([x, np.full((len(x), 1), SEP)], axis=1) # start from the prompt: digits and SEP for _ in range(L): # The network expects T=16 tokens: the positions not written yet are filled with zeros. Thanks to the causal mask they cannot influence the position that we read. padded = np.concatenate([seq, np.zeros((len(x), T - seq.shape[1]), dtype=int)], axis=1) # fill up to length T logits = model.predict(padded, verbose=0) # scores at every position # Row seq.shape[1] - 1 is the last written position: its logits give the next token. argmax = greedy decoding. step = logits[:, seq.shape[1] - 1].argmax(axis=-1) # the most likely next token, read at the last real position # Feed the prediction back as input: this is the autoregressive loop. seq = np.concatenate([seq, step[:, None]], axis=1) # append it and repeat # Drop the prompt and SEP: only the 8 generated digits are returned. return seq[:, L + 1:]pred = generate(model, x_va)# .all(axis=1) is True only when the 8 digits of an example are all correct; the mean of these booleans is the exact-match rate.exact = (pred == np.sort(x_va, axis=1)).all(axis=1).mean() # the whole output must be rightdigit = (pred == np.sort(x_va, axis=1)).mean()print(f"validation: exact match {exact:.3f}, digits {digit:.3f}")print(x_va[0], "->", pred[0], "expected", np.sort(x_va[0]))
The validation exact match is $1.000$ in the reference run; the generated digits come from the loop and not from the teacher-forced pass, so this number is a stronger statement than the token accuracy of Part 4.
Exercise 5.2 · final test, once
- Freeze the model chosen on validation. Do not change anything after this point.
- Compute the test exact match and the baseline “copy the prompt unchanged”.
- Print a few mistakes if there are any, with the expected answer.
chosen = model # frozen after validation: nothing below changes the weightspred_te = generate(chosen, x_te)exact_te = ... # TO DO: final exact-match accuracy on the test partitioncopy_baseline = ... # TO DO: baseline: copy the input unchangedprint(f"test: exact match {exact_te:.3f} (copying the input: {copy_baseline:.3f})")wrong = np.where(~(pred_te == np.sort(x_te, axis=1)).all(axis=1))[0][:5]for i in wrong: print(x_te[i], "->", pred_te[i], "expected", np.sort(x_te[i]))
Show the correction
# No training, no threshold or epoch choice from now on: the test set is only read.chosen = model # frozen after validation: nothing below changes the weightspred_te = generate(chosen, x_te)exact_te = (pred_te == np.sort(x_te, axis=1)).all(axis=1).mean() # final exact-match accuracy on the test partition# A trivial baseline gives the scale: a prompt that is already sorted is rare.copy_baseline = (x_te == np.sort(x_te, axis=1)).all(axis=1).mean() # baseline: copy the input unchangedprint(f"test: exact match {exact_te:.3f} (copying the input: {copy_baseline:.3f})")# Indices of the mistakes (first five): always look at them before changing anything.wrong = np.where(~(pred_te == np.sort(x_te, axis=1)).all(axis=1))[0][:5]for i in wrong: print(x_te[i], "->", pred_te[i], "expected", np.sort(x_te[i]))
The test exact match is $1.000$, against $0.000$ for the baseline that copies the prompt. The task is easy for a transformer with 69,515 parameters; it is a toy chosen so that every step can be checked, not a measure of what transformers can do. If a mistake appears, look at it before changing the model, and never tune on the test set.
Exercise 5.3 · look at the attention
- Complete
attention_maps: rebuild the input of an attention layer from the model, and call the layer withreturn_attention_scores=True. - Plot the four heads of the last block for one validation example.
- Describe what a row means. Which positions does the model read when it writes the third sorted digit?
def attention_maps(model, tokens, block_index=0): """Attention weights (batch, heads, T, T) of one block.""" ln = model.get_layer(f"ln_a{block_index}") h = keras.Model(model.input, ln.output)(tokens) # the input of the attention layer return weights.numpy()sample = in_va[:1]maps = attention_maps(chosen, sample, block_index=1)[0]fig, axes = plt.subplots(1, HEADS, figsize=(14, 3.6))for k, ax in enumerate(axes): ... # TO DO: one map per head: row = reading position, column = attended position ax.set_title(f"head {k}") ax.set_xlabel("attended position"); ax.set_ylabel("reading position")plt.tight_layout(); plt.show()
Show the correction
# To read the weights we rebuild the input of the attention layer (the output of the LayerNorm before it) and call the layer ourselves.def attention_maps(model, tokens, block_index=0): """Attention weights (batch, heads, T, T) of one block.""" ln = model.get_layer(f"ln_a{block_index}") # A sub-model from the model input to the LayerNorm output. h = keras.Model(model.input, ln.output)(tokens) # the input of the attention layer # Same layer object, so the same learned weights; this time we also ask for the attention weights (batch, heads, 16, 16). _, weights = model.get_layer(f"attn{block_index}")(h, h, use_causal_mask=True, return_attention_scores=True) return weights.numpy()sample = in_va[:1]# Block 1 is the last one (indices start at 0).maps = attention_maps(chosen, sample, block_index=1)[0]fig, axes = plt.subplots(1, HEADS, figsize=(14, 3.6))for k, ax in enumerate(axes): # Row = reading position, column = attended position; the matrix is lower-triangular because of the causal mask. ax.imshow(maps[k], cmap="viridis") # one map per head: row = reading position, column = attended position ax.set_title(f"head {k}") ax.set_xlabel("attended position"); ax.set_ylabel("reading position")plt.tight_layout(); plt.show()
Each head produces a lower-triangular matrix. Inspect the rows at and after SEP: they show where the model looks while it writes. Visual inspection suggests a mechanism but does not prove it: attention weights are not an explanation by themselves.
Part 6 · Deliverables and limits
Build a defensible experiment
- Check the parameter counts by hand: embeddings, one block, the complete model.
- Explain teacher forcing and why the loss uses weights.
- Report training and validation curves, the chosen epoch and how it was chosen.
- Compare the transformer with the model without attention and explain the gap.
- Report validation and test exact match, with the copy baseline.
- Extension: train with $L=12$ digits, or with 1 block instead of 2, or with a single head, and report what changes on validation only.
Deliver a rerunnable notebook, a short table of results, the attention figure and a paragraph of limits.
What the results do not show
Sorting eight digits is a small, noise-free task with a fixed length and a known answer. The model has a fixed context of 16 positions: it cannot sort 12 digits without retraining, and the learned position embeddings carry no information beyond that range. The cost of attention grows like $T^2$, which is why long contexts are expensive. Real language models use much larger vocabularies, subword tokens, sampling, caching of keys and values during generation, and billions of parameters trained on huge corpora. They also make mistakes that exact-match checks like this one would reveal: validate the behaviour you care about, not only the training loss.
References and related learning
Papers, documentation and lectures
- A. Vaswani et al., Attention is all you need, NeurIPS 2017.
- Keras documentation: MultiHeadAttention and text classification with a transformer.
- A. Dosovitskiy et al., An image is worth 16x16 words, ICLR 2021 (vision transformers and the amount of data).
- J. Kaplan et al., Scaling laws for neural language models, 2020; J. Hoffmann et al., Training compute-optimal large language models, 2022.
- R. Xiong et al., On layer normalization in the transformer architecture, ICML 2020; Y. Dong et al., Attention is not all you need: pure attention loses rank doubly exponentially with depth, ICML 2021.
- J. Alammar, The Illustrated Transformer.
- A. Karpathy, Let’s build GPT: from scratch, in code (lecture).
- Next on this site: How LLMs learn to reason and do mathematics, and the VLM Project, which feeds image patches to the same architecture. Earlier: Neural networks with Keras.