Transformers, large language models, sampling and fine-tuning
- Intermediate
- 1 h 30 min
- Lesson 4 of 4 in Deep learning and transformers
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
You will be able to
- Explain how text becomes tokens and embeddings, why self-attention alone cannot see word order, and how sinusoidal or rotary positions fix that.
- Compute scaled dot-product attention with tensor shapes, explain the square-root-of-d_k scale through the variance of a dot product, build multi-head attention and the causal mask, and state why the cost grows with the square of the sequence length.
- Describe a pre-norm transformer block (normalisation, attention, MLP, residual paths, GELU or SiLU), say why pre-norm trains more easily than post-norm, and estimate parameters with 12 L d squared.
- Explain next-token training with teacher forcing, why a KV cache removes repeated work and what it costs in memory, and how temperature, top-k and top-p change the next-token distribution.
- Compare pre-training, supervised fine-tuning, LoRA and preference tuning, count the parameters LoRA trains, choose between prompting, RAG and fine-tuning, and explain why a language model can hallucinate.
Concept
The previous lesson ended with recurrent networks, which read a sequence one step at a time and squeeze everything seen so far into one state. A transformer replaces that loop with attention: every position looks directly at every other position in one parallel step, and a stack of identical blocks refines the result. A large language model (LLM) is, at its core, a very large transformer trained to predict the next token. This lesson takes the mechanism apart at the ML level (shapes, scales, costs) and then covers how such a model is adapted and where it breaks.
| Idea | What it does | The question it answers |
|---|---|---|
| Tokenisation | Cuts text into sub-word pieces with integer ids | How do we feed text to a network with a fixed vocabulary? |
| Embedding | Looks up a learned vector for each id | What does the network actually compute on? |
| Positions | Adds order information | Unmasked attention is blind to order, so where does order come from? |
| Scaled dot-product attention | Weighted average of values, weights from query-key similarity | How does one token read from the others? |
| Causal mask | Hides future positions | How do we train on next-token prediction without cheating? |
| Block | Norm, attention, MLP, with residual paths | What is repeated, and what does it cost? |
| KV cache | Stores past keys and values | Why is generating token 1,000 not 1,000 times the work? |
| Sampling | Temperature, top-k, top-p | How do we turn probabilities into text? |
| LoRA, preference tuning | Cheap adaptation, behaviour shaping | How do we change a model we cannot afford to retrain? |
Why It Matters
Almost every modern language, code and chat system is a transformer, and questions about it are standard in ML and GenAI interviews (common industry pattern): walk through attention with shapes, say why the scores are scaled, explain the causal mask, estimate parameters or memory, say what a KV cache is, and choose between prompting, retrieval and fine-tuning. The reasons are practical. The quadratic cost of attention and the size of the KV cache decide how long a context you can afford to serve. Sampling settings decide whether an answer is repeatable or varied. LoRA decides whether you can adapt a large model on one GPU. And the way the model is trained explains why it states false things fluently.
Mental Model
Think of a meeting. Every participant (a token) writes a query card describing what they want to know, a key card describing what they can offer, and a value card holding what they would say. Everyone compares their query with every key; the match scores become a set of weights that sum to 1, and each participant leaves with a weighted blend of the values. Two details make it work. Without seat numbers the room cannot tell who spoke first, so positions are added to the cards. And in a language model every participant is only allowed to read cards from people who spoke earlier (the causal mask), which is what lets one pass over a sentence train every next-token prediction at once.
Tokens, embeddings and positions
A network cannot read characters directly, and a word-level vocabulary breaks on names, typos and new words. Sub-word tokenisation sits between the two: common words stay whole, rare ones are split into pieces. Byte pair encoding (BPE) builds the vocabulary by starting from characters and repeatedly merging the most frequent adjacent pair. Sennrich et al. adapted it for translation to handle rare and unseen words by encoding them as sequences of smaller units (Sennrich et al., abstract). The script runs six merges on a toy corpus (“low” 5 times, “lower” 2, “newest” 6, “widest” 3): the first merges are s+t (count 9) and e+st (count 9), then o+w (7), and the word “low” ends as one token while “lower” is low, e, r. The corpus is invented for this lesson; real vocabularies are learned on large text.
Each token id then indexes a row of a learned embedding matrix , with the vocabulary size. A lookup is the same as multiplying a one-hot row vector by (the script checks this, section 2), so the embedding is just the first linear layer of the network, applied to a one-hot input and implemented as an index. Its size is : for a vocabulary of 50,000 and that is 38,400,000 parameters (an illustrative size, not a claim about any named model). Vaswani et al. use learned embeddings and share the same matrix with the final pre-softmax linear layer (Vaswani et al., section 3.4).
Why attention needs positions
Self-attention without a mask treats its input as a set. If you shuffle the rows of , the output rows are shuffled the same way and nothing else changes: the script confirms this with a random 4 by 4 example (section 5, prints True). A bidirectional model built only from unmasked attention would read “dog bites man” and “man bites dog” identically. The fix is to inject position into the input (Dive into Deep Learning, positional encoding).
Vaswani et al. add a fixed sinusoidal encoding to the embeddings:
| Symbol | Meaning |
|---|---|
| Position in the sequence (0, 1, 2, …) | |
| Index of a sine-cosine pair of columns | |
| Embedding width |
Low columns oscillate quickly and high ones slowly, like the digits of a counter. For position 0 is and position 1 is about . They chose it because the encoding at is a linear function of the encoding at , which may help the model attend by relative offset, and because it might extrapolate to longer sequences; learned position embeddings gave nearly identical results in their experiment (section 3.5 and Table 3, row E). A causal mask breaks this symmetry on its own: Haviv et al. found that causal language models trained with no explicit positional encoding still learn positional information, and conjecture that causal attention lets a token infer how many predecessors it can attend to (Haviv et al., abstract). Explicit positions are still the standard design, and the shuffle test below is for unmasked attention. After adding positions, the same shuffle test is no longer a pure reorder of the outputs (section 5 of the script prints True for “not a pure reorder”).
Rotary position embedding (RoPE) takes another route: it rotates the query and key vectors by an angle that depends on position, so the attention score depends on the relative distance between tokens (Su et al., abstract). Which positional scheme a given production model uses is a design choice that changes between model families, and this lesson does not list them.
Scaled dot-product attention
Given queries , keys and values , attention is
| Symbol | Meaning | Shape |
|---|---|---|
| One query row per position that asks | ||
| One key row per position that can be read | ||
| One value row per readable position | ||
| Similarity of every query with every key | ||
| softmax | Applied to each row, so weights sum to 1 | |
| output | Weighted average of value rows |
In self-attention , , for the same input , so . The PyTorch function scaled_dot_product_attention computes exactly this, with the scale defaulting to where is the last dimension of the query (PyTorch docs).
Why divide by the square root of d_k
Suppose the components of a query and a key are independent with mean 0 and variance 1. Then the dot product has mean 0 and variance (Vaswani et al., section 3.2.1). Each term has variance 1 and there are independent terms. The standard deviation is , so dividing by it restores variance 1. Without it, large pushes scores into the tails, where softmax is almost one-hot and its gradient is almost zero; the authors suspected this is why unscaled dot-product attention does worse than additive attention for large .
The script samples 2,000 random pairs at each width. The measured variance of is 4.0 at , 16.4 at 16, 64.1 at 64, 270.3 at 256 and 1000.0 at 1,024 (theory: 4, 16, 64, 256, 1,024; the gap at 256 is sampling noise), and after dividing by it is 1.01, 1.02, 1.00, 1.06 and 0.98. Then it compares one query with 8 random keys at . Unscaled, the largest softmax weight is 0.9981 and the norm of the softmax Jacobian is 0.00366. Scaled, the largest weight is 0.2970 and the norm is 0.37223, about 100 times larger. The unscaled softmax is nearly saturated, so almost no gradient reaches the queries and keys. (One draw, seed 1, illustrates the effect; it is not a general constant.)
Multi-head attention and the causal mask
One attention gives each token one blend. Multi-head attention runs attentions in parallel on different learned projections, so different heads can look for different relations, then concatenates and mixes them with an output matrix (Dive into Deep Learning, multi-head attention). Vaswani et al. use and , so the total cost is similar to one head of full width. With , and the script prints: per head are , the score matrix is , a head output is , and the concatenation is . The four matrices hold weights, however many heads there are, because heads only slice the same matrices.
A causal mask sets every score where the key is later than the query to before the softmax, so those weights become exactly 0 (Vaswani et al., section 3.2.3). Row 0 then reads only token 0, row 2 reads tokens 0 to 2. The script shows weights of for row 0 and for row 2, rows summing to 1, and that changing the key and value of token 3 leaves output rows 0 to 2 unchanged while row 3 changes. Masking before the softmax matters: zeroing weights afterwards would leave rows that do not sum to 1.
Cost. The score matrix has entries, so attention costs time and memory when the matrix is stored (Vaswani et al., Table 1; Dive into Deep Learning notes the quadratic cost makes it slow for very long sequences). Doubling the context from 1,000 to 2,000 tokens takes the score matrix from 1,000,000 to 4,000,000 entries per head, four times as many. A recurrent layer costs but needs sequential steps, where attention needs (Table 1): that parallelism over positions is a main reason transformers replaced recurrent models for training.
The transformer block and its size
A block stacks two sub-layers, each wrapped in a residual connection (the skip connection from the last lesson). The first is multi-head self-attention, which mixes information across positions. The second is a position-wise MLP, applied to each position independently: a linear layer up to , a non-linearity, a linear layer back down. Vaswani et al. use and with ReLU (section 3.3). The block does the same thing at every layer with different weights, and a model is the stack.
Pre-norm and post-norm
The original paper normalises after the residual add, (section 3.1). Modern designs usually move the normalisation inside the residual branch, , which is called pre-norm. Xiong et al. show that with post-norm the gradients near the output are large at initialisation, so training needs a learning-rate warm-up, while with pre-norm the gradients are well behaved at initialisation, so they remove the warm-up and report comparable results with much less training time (Xiong et al., abstract). The intuition (derived here) is that pre-norm leaves a clean identity path from the input to the output, the same argument as the skip connection: the raw residual stream is never forced through a normalisation. The norm is LayerNorm or RMSNorm; the last lesson covered RMSNorm, which drops the mean subtraction and reports faster running time of 7% to 64% on different models in its abstract (Zhang and Sennrich). Which norm and which activation a given production model uses is a design choice that differs between models and releases; this lesson does not list them.
GELU and SiLU
ReLU zeroes every negative input. GELU multiplies the input by the standard normal cumulative distribution, , so each value is scaled by , the probability that a standard normal value is below (Hendrycks and Gimpel, abstract). SiLU multiplies the input by its sigmoid, (Elfwing et al., abstract); it is also called swish (common practice naming). Both are smooth, both dip slightly below zero for negative inputs, and both approach the identity for large positive inputs. The script prints, for : ReLU 0, GELU , SiLU ; for : 1, 0.8413, 0.7311; for : 3, 2.9960, 2.8577. They differ little in practice; which is better for a particular model is an empirical question, not a theorem.
Counting parameters
Per layer, attention has weights () and the MLP has . With the common ratio that is , so a layer holds about and a stack of layers about , ignoring biases, norm gains and embeddings:
| Symbol | Meaning |
|---|---|
| Model width | |
| Hidden width of the MLP | |
| Number of layers |
The script checks it for , : attention 1,048,576 plus MLP 2,097,152 equals 3,145,728, which is . Two of every three layer weights sit in the MLP. For , the formula gives 301,989,888; for , it gives 6,442,450,944 (about 6.44 billion). These are illustrative shapes, not a description of a specific model; real models differ (for example in how many key-value heads they use or whether the MLP is gated), so treat as an estimate (common practice).
Training a decoder and generating tokens
A decoder-only model has only causal self-attention blocks and a final linear layer from to the vocabulary size . It is trained to predict each token from the ones before it. With teacher forcing the whole true sequence is fed in at once, the causal mask stops each position seeing the future, and position is scored on predicting token . One pass over tokens therefore gives training targets. The loss is the average cross-entropy:
| Symbol | Meaning |
|---|---|
| The token at position | |
| The model’s softmax over the vocabulary after reading the first tokens |
A model that guesses uniformly over 50 tokens has loss nats, a perplexity of 50 (perplexity is the exponential of the loss: the number of equally likely choices it is effectively picking among). A model that puts probability 0.0066 on the true token (logits , true token 0) pays 5.0134, far worse than the a uniform guess over those 3 tokens would cost. A count-based bigram model on the invented 12-character string “abacabadabac” reaches 0.5517 on its own training text. Pre-training means minimising this loss on a very large text corpus; nothing in it mentions truth, helpfulness or safety.
At generation time the model has no future to feed in. It reads the prompt, produces a distribution for the next token, one token is chosen, appended, and the loop repeats. That is autoregressive decoding: each step depends on the previous choice, so steps cannot run in parallel. Other families exist (common practice): encoder-only models such as BERT read the whole sequence in both directions and are used for embeddings and classification, and encoder-decoder models such as T5 are used for translation and summarisation. This lesson follows the decoder-only design behind chat models.
The KV cache
Look at what changes between step and step of generation: one new token. The keys and values of all earlier tokens are the same as before, because earlier positions never see later ones. Recomputing them each step is wasted work. A KV cache stores the key and value rows of past tokens, so a step computes projections only for the new token and attends over the cache (Hugging Face docs). The script runs 12 tokens both ways with random weights and confirms the cached outputs equal the full causal recomputation to within 1e-12 (section 8). The saving in projection work for tokens is 5,050 key-value projections without a cache against 100 with one (the sum against ).
The price is memory. The cache holds keys and values for every layer, head, position and sequence:
| Symbol | Meaning |
|---|---|
| One tensor for keys, one for values | |
| Layers | |
| Number of key-value heads | |
| Width of each head | |
| Tokens held, per sequence | |
| Bytes per stored number (2 for 16-bit floats) |
For , , , and 2-byte numbers the script prints 2,147,483,648 bytes, 2.0 GiB, for one sequence; this is a worked example, not a measured figure for any model (derived here). A server holding many sequences at once multiplies it by the batch size, which is why the cache, not the weights, often limits long contexts. Sharing key-value heads across several query heads shrinks it: 8 key-value heads instead of 32 gives 0.5 GiB. PyTorch’s attention function has an enable_gqa option for exactly this case, where keys and values have fewer heads than the queries. The Hugging Face documentation also describes quantised and offloaded caches as ways to trade speed for memory.
Sampling: temperature, top-k and top-p
The model outputs a probability for every token. Greedy decoding always takes the largest. It is repeatable, but Holtzman et al. report that decoding to maximise likelihood “leads to text that is bland and strangely repetitive” (Holtzman et al., abstract). So most applications sample, and three settings shape the distribution before the draw.
Temperature divides the logits before the softmax: . Low sharpens (more like greedy), high flattens, and approaches greedy (derived here). With logits the script prints
| Setting | Probabilities | Entropy (nats) |
|---|---|---|
| 0.8292, 0.1122, 0.0413, 0.0152, 0.0021 | 0.609 | |
| 0.5630, 0.2071, 0.1256, 0.0762, 0.0280 | 1.206 | |
| 0.3745, 0.2272, 0.1769, 0.1378, 0.0836 | 1.491 |
Top-k keeps only the most probable tokens and renormalises: with at the result is 0.7311 and 0.2689. Top-p (nucleus sampling) keeps the smallest set of top tokens whose total probability reaches , then renormalises. Holtzman et al. propose it as sampling from the dynamic nucleus of the distribution: the set grows when the model is unsure and shrinks when it is confident, where a fixed cannot. At the set is 4 tokens (0.5630 + 0.2071 + 0.1256 = 0.8957 is below 0.9, so the fourth is added), giving 0.5793, 0.2131, 0.1293, 0.0784. At it is 2 tokens. Drawing 10,000 samples from the set gives frequencies 0.574, 0.219, 0.125, 0.082 and 0 for the removed token. Top-k is the simpler filter and is common practice.
In practice (common practice) apply temperature first, then the filter, then draw. Trade-offs: low temperature for tasks with one right answer such as extraction, higher for brainstorming; filters cut off the unreliable tail that sampling at would otherwise sometimes hit.
Pre-training, fine-tuning, LoRA and preference tuning
A model goes through stages, each changing a different thing.
Supervised fine-tuning (SFT) continues training on prompt-and-answer pairs with the same next-token loss, so the model learns the format and behaviour of an assistant. Updating all weights is expensive: the optimiser keeps extra state for every weight, and the model risks forgetting (common practice).
LoRA
LoRA freezes the pre-trained weights and trains a low-rank update next to selected matrices. Hu et al. report that for GPT-3 175B it can cut trainable parameters by 10,000 times and GPU memory by about 3 times compared with fine-tuning with Adam, performs on par or better in quality on the models they tried, and adds no extra inference latency (Hu et al., abstract). For a frozen the adapted layer is
| Symbol | Meaning |
|---|---|
| Frozen pre-trained weight | |
| The only trained matrices; their product has rank at most | |
| Rank, the width of the bottleneck | |
| Scaling constant; the update is multiplied by (Hu et al., section 4.1) |
Hu et al. initialise randomly (Gaussian) and at zero, so is zero at the start and the adapted model begins identical to the base; they scale the update by , which reduces the need to retune hyperparameters when changes (section 4.1). The script checks that the output equals at that start. A matrix has 16,777,216 weights; a rank-8 adapter adds , which is 0.3906%. If all four attention matrices in each of 32 layers got that adapter, 8,388,608 weights would train against 2,147,483,648 in those matrices (illustrative arithmetic, derived here). Because has the same shape as , it can be added in: the script merges for a 5 by 7 matrix with and gets the same output as base plus adapter. That is why merged LoRA costs nothing at inference, and also why adapters are small files you can swap per task. The trade-off is capacity: a rank- update cannot express every change, so very large domain shifts may need a higher rank or full fine-tuning (common practice). Quantised variants that keep the frozen base in fewer bits exist; this lesson does not cover them.
Preference tuning at overview level
SFT teaches the model what an answer looks like, not which of two plausible answers people prefer. Ouyang et al. build on SFT by having labelers rank model outputs and using the ranking data to fine-tune further with reinforcement learning from human feedback (RLHF); their 1.3B-parameter InstructGPT was preferred by humans over the 175B GPT-3, and it still makes simple mistakes (Ouyang et al., abstract). In this formulation a reward model is trained on the rankings, then the language model is trained with reinforcement learning to raise the reward while staying close to its starting point (Rafailov et al., abstract). Ouyang et al. train the reward model with the loss averaged over pairs, where is the answer labelers preferred and the other (section 3.5, equation 1). It is 0.6931 for a margin of 0, 0.3133 for a margin of 1 and 1.3133 when the margin is , so it is small when the chosen answer scores higher. Direct preference optimisation (DPO) rewrites the objective in closed form so a classification-style loss on preference pairs replaces the separate reward-model fitting step and the reinforcement-learning loop (Rafailov et al.). The details of both are covered in the GenAI course’s alignment lesson; at this level, know what each stage changes and what data it needs.
Limits: hallucination and choosing RAG or fine-tuning
A hallucination is generated text that is nonsensical or unfaithful to the provided source content, in the survey’s wording; Ji et al. review it across tasks and note it hurts real applications (Ji et al., section 2 and abstract). In everyday use the word also covers confident false statements about the world, which is the case this section explains. Why it happens follows from the training loss (derived here). Next-token training rewards text that is probable given the context, and it has no input that says whether a statement is true. A fluent false sentence can be as probable as a true one, and sampling picks tokens by probability. Preference tuning can shift this, but it optimises what raters rank higher, which is not the same as what is correct. Context length, an outdated training set and a prompt that asks for something the model never saw all raise the risk (common practice).
This is why the common design question is not “which is better” but “what is missing”.
| What is wrong | First tool | Why |
|---|---|---|
| Facts are missing, private or change often; answers need citations | Retrieval (RAG): fetch documents and put them in the prompt | Facts can be updated without training and traced to a source |
| Wrong format or tone, a simple task | Prompting with examples | Cheapest; no training |
| Consistent behaviour, domain style or shorter prompts at scale | Fine-tuning, often LoRA | Changes behaviour in the weights |
| Both knowledge and behaviour | Retrieval plus fine-tuning | Each fixes a different failure |
Fine-tuning mostly teaches behaviour and style, and is a poor way to add facts that change (common practice). Whichever you choose, measure on held-out examples of the real task: an improvement seen by eye on three prompts is not evidence.
Code
This standard-library script produced every number in the lesson that is computed here. Figures quoted from sources are not from the script: the Vaswani et al. hyperparameters (, ), the LoRA and InstructGPT figures in their abstracts, and the RMSNorm running-time range. It has fixed seeds and runs in about a second (Python 3.14).
import math
import random
import time
T0 = time.time()
def matmul(A, B):
return [[sum(a * b for a, b in zip(row, col)) for col in zip(*B)] for row in A]
def transpose(A):
return [list(r) for r in zip(*A)]
def softmax(xs):
m = max(xs)
es = [math.exp(x - m) for x in xs]
s = sum(es)
return [e / s for e in es]
def attention(Q, K, V, causal=False, offset=0, scale=True):
d_k = len(Q[0])
S = matmul(Q, transpose(K))
if scale:
S = [[s / math.sqrt(d_k) for s in row] for row in S]
if causal:
S = [[s if j <= i + offset else -math.inf for j, s in enumerate(row)] for i, row in enumerate(S)]
W = [softmax(row) for row in S]
return matmul(W, V), W
def rand_matrix(rng, r, c, scale=1.0):
return [[rng.gauss(0, scale) for _ in range(c)] for _ in range(r)]
print("== 1. Subword tokenisation: byte pair encoding on a toy corpus ==")
words = {("l", "o", "w"): 5, ("l", "o", "w", "e", "r"): 2, ("n", "e", "w", "e", "s", "t"): 6, ("w", "i", "d", "e", "s", "t"): 3}
merges = []
for step in range(6):
pairs = {}
for w, f in words.items():
for a, b in zip(w, w[1:]):
pairs[(a, b)] = pairs.get((a, b), 0) + f
best = max(pairs, key=lambda p: (pairs[p], p))
merges.append((best, pairs[best]))
new = {}
for w, f in words.items():
out, i = [], 0
while i < len(w):
if i + 1 < len(w) and (w[i], w[i + 1]) == best:
out.append(w[i] + w[i + 1]); i += 2
else:
out.append(w[i]); i += 1
new[tuple(out)] = f
words = new
for (pair, count) in merges:
print("merge", pair, "count", count)
print("segmentation after 6 merges:", {"".join(w): list(w) for w in words})
print("\n== 2. Embedding lookup equals one-hot times matrix ==")
rng = random.Random(0)
V, D = 6, 4
E = rand_matrix(rng, V, D)
tok = 3
onehot = [[1.0 if j == tok else 0.0 for j in range(V)]]
print("lookup equals one-hot product:", matmul(onehot, E)[0] == E[tok])
print("embedding table parameters, vocab 50,000 and d_model 768: %d" % (50000 * 768))
print("\n== 3. Why divide by sqrt(d_k) ==")
for d_k in (4, 16, 64, 256, 1024):
r = random.Random(d_k)
dots = []
for _ in range(2000):
q = [r.gauss(0, 1) for _ in range(d_k)]
k = [r.gauss(0, 1) for _ in range(d_k)]
dots.append(sum(a * b for a, b in zip(q, k)))
mean = sum(dots) / len(dots)
var = sum((x - mean) ** 2 for x in dots) / len(dots)
print("d_k %4d: variance of q.k = %7.1f (theory %4d); after dividing by sqrt(d_k): %.2f" % (d_k, var, d_k, var / d_k))
r = random.Random(1)
d_k, n = 256, 8
q = [r.gauss(0, 1) for _ in range(d_k)]
keys = [[r.gauss(0, 1) for _ in range(d_k)] for _ in range(n)]
raw = [sum(a * b for a, b in zip(q, k)) for k in keys]
for name, logits in (("unscaled", raw), ("scaled", [x / math.sqrt(d_k) for x in raw])):
p = softmax(logits)
jac_norm = math.sqrt(sum((p[i] * ((i == j) - p[j])) ** 2 for i in range(n) for j in range(n)))
print("d_k 256, 8 keys, %s: largest weight %.4f, softmax Jacobian norm %.5f" % (name, max(p), jac_norm))
print("\n== 4. Attention: shapes, causal mask, rows sum to one ==")
n, d_model, h = 10, 256, 4
d_k = d_model // h
print("n=%d, d_model=%d, h=%d: per head Q,K,V are %dx%d, scores %dx%d, head output %dx%d, concatenated %dx%d" % (n, d_model, h, n, d_k, n, n, n, d_k, n, d_model))
print("attention parameters W_Q,W_K,W_V,W_O (no bias): %d = 4 * %d^2" % (4 * d_model * d_model, d_model))
print("score matrix entries per head at n=1,000: %d; at n=2,000: %d (%dx)" % (1000 ** 2, 2000 ** 2, (2000 ** 2) // (1000 ** 2)))
rng = random.Random(2)
Q, K, V = rand_matrix(rng, 4, 3), rand_matrix(rng, 4, 3), rand_matrix(rng, 4, 2)
out, W = attention(Q, K, V, causal=True)
print("causal weights, row 0:", [round(x, 3) for x in W[0]], "; row 2:", [round(x, 3) for x in W[2]])
print("row sums:", [round(sum(r_), 6) for r_ in W])
V2 = [row[:] for row in V]
V2[3] = [100.0, -100.0]
K2 = [row[:] for row in K]
K2[3] = [9.0, 9.0, 9.0]
out2, _ = attention(Q, K2, V2, causal=True)
print("changing token 3 leaves output rows 0-2 unchanged:", out[:3] == out2[:3], "; row 3 changes:", out[3] != out2[3])
print("\n== 5. Positions: attention does not see order ==")
rng = random.Random(3)
X = rand_matrix(rng, 4, 4)
Wq, Wk, Wv = (rand_matrix(rng, 4, 4, 0.5) for _ in range(3))
def self_attn(X):
return attention(matmul(X, Wq), matmul(X, Wk), matmul(X, Wv))[0]
perm = [2, 0, 3, 1]
Xp = [X[i] for i in perm]
o, op = self_attn(X), self_attn(Xp)
print("permuting the inputs permutes the outputs the same way:", all(max(abs(a - b) for a, b in zip(op[k], o[perm[k]])) < 1e-12 for k in range(4)))
def sinusoid(n, d):
return [[math.sin(p / 10000 ** (j / d)) if j % 2 == 0 else math.cos(p / 10000 ** ((j - 1) / d)) for j in range(d)] for p in range(n)]
P = sinusoid(4, 4)
print("sinusoidal positions, d=4, pos 0..2:", [[round(x, 4) for x in row] for row in P[:3]])
Xpos = [[a + b for a, b in zip(x, p)] for x, p in zip(X, P)]
Xpos_p = [[a + b for a, b in zip(x, p)] for x, p in zip(Xp, P)]
o, op = self_attn(Xpos), self_attn(Xpos_p)
print("with positions added, a reorder of the tokens is no longer a pure reorder of the outputs:", not all(max(abs(a - b) for a, b in zip(op[k], o[perm[k]])) < 1e-9 for k in range(4)))
print("\n== 6. The block: parameters and activations ==")
d = 512
print("d=512, d_ff=2048: attention %d + MLP %d = %d per layer (12 d^2 = %d)" % (4 * d * d, 2 * d * 2048, 4 * d * d + 2 * d * 2048, 12 * d * d))
for d, L in ((1024, 24), (4096, 32)):
print("d=%d, L=%d: 12 L d^2 = %d (%.2f billion)" % (d, L, 12 * L * d * d, 12 * L * d * d / 1e9))
print("share of a layer's weights in the MLP: %.4f" % (8 / 12))
def gelu(x):
return 0.5 * x * (1 + math.erf(x / math.sqrt(2)))
def silu(x):
return x / (1 + math.exp(-x))
print("x relu gelu silu")
for x in (-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 3.0):
print("%5.1f %7.4f %7.4f %7.4f" % (x, max(0.0, x), gelu(x), silu(x)))
def rms(x, eps=1e-6):
s = math.sqrt(eps + sum(v * v for v in x) / len(x))
return [v / s for v in x]
print("RMS of a pre-norm residual input [3, -4, 12, 0]:", round(math.sqrt(sum(v * v for v in [3, -4, 12, 0]) / 4), 4), "-> after RMSNorm", [round(v, 4) for v in rms([3, -4, 12, 0])])
print("\n== 7. Next-token training and perplexity ==")
Vsz = 50
print("uniform guess over %d tokens: loss ln(%d) = %.4f nats, perplexity %.1f" % (Vsz, Vsz, math.log(Vsz), math.exp(math.log(Vsz))))
text = "abacabadabac"
counts = {}
for a, b in zip(text, text[1:]):
counts[(a, b)] = counts.get((a, b), 0) + 1
totals = {}
for (a, b), c in counts.items():
totals[a] = totals.get(a, 0) + c
nll = -sum(math.log(counts[(a, b)] / totals[a]) for a, b in zip(text, text[1:])) / (len(text) - 1)
print("a 12-character text gives %d next-token targets from one pass; bigram counts give loss %.4f" % (len(text) - 1, nll))
logits_wrong = [0.0, 0.0, 5.0]
p = softmax(logits_wrong)
print("true token index 0 with logits [0,0,5]: p=%.4f, loss %.4f" % (p[0], -math.log(p[0])))
print("uniform guess over those 3 tokens: ln 3 = %.4f" % math.log(3))
print("\n== 8. KV cache ==")
rng = random.Random(4)
d = 6
Wq, Wk, Wv = (rand_matrix(rng, d, d, 0.4) for _ in range(3))
xs = rand_matrix(rng, 12, d)
full_out, _ = attention(matmul(xs, Wq), matmul(xs, Wk), matmul(xs, Wv), causal=True)
Kc, Vc, cached_out, kv_proj = [], [], [], 0
for x in xs:
Kc += matmul([x], Wk)
Vc += matmul([x], Wv)
kv_proj += 1
o, _ = attention(matmul([x], Wq), Kc, Vc)
cached_out.append(o[0])
print("cached decoding equals full recomputation:", all(max(abs(a - b) for a, b in zip(cached_out[i], full_out[i])) < 1e-12 for i in range(12)))
n = 100
print("key/value projections for n=%d tokens: without a cache %d, with a cache %d" % (n, n * (n + 1) // 2, n))
L, kv_heads, head_dim, seq, nbytes = 32, 32, 128, 4096, 2
b = 2 * L * kv_heads * head_dim * seq * nbytes
print("KV cache: 2 * %d layers * %d heads * %d dims * %d tokens * %d bytes = %d bytes = %.1f GiB per sequence" % (L, kv_heads, head_dim, seq, nbytes, b, b / 2 ** 30))
print("with 8 shared KV heads instead of 32: %.1f GiB" % (b / 4 / 2 ** 30))
print("\n== 9. Sampling ==")
logits = [2.0, 1.0, 0.5, 0.0, -1.0]
for T in (0.5, 1.0, 2.0):
p = softmax([x / T for x in logits])
ent = -sum(x * math.log(x) for x in p)
print("T=%.1f probs %s entropy %.3f" % (T, [round(x, 4) for x in p], ent))
p = softmax(logits)
def top_k(p, k):
keep = sorted(range(len(p)), key=lambda i: (-p[i], i))[:k]
z = sum(p[i] for i in keep)
return [p[i] / z if i in keep else 0.0 for i in range(len(p))]
def top_p(p, thr):
order = sorted(range(len(p)), key=lambda i: (-p[i], i))
keep, c = [], 0.0
for i in order:
keep.append(i); c += p[i]
if c >= thr - 1e-12:
break
z = sum(p[i] for i in keep)
return [p[i] / z if i in keep else 0.0 for i in range(len(p))]
print("T=1 probs", [round(x, 4) for x in p])
print("top-k k=2:", [round(x, 4) for x in top_k(p, 2)])
print("top-p p=0.9:", [round(x, 4) for x in top_p(p, 0.9)])
print("top-p p=0.6:", [round(x, 4) for x in top_p(p, 0.6)])
rng = random.Random(5)
draws = [rng.choices(range(5), weights=top_p(p, 0.9))[0] for _ in range(10000)]
print("10,000 draws from the top-p 0.9 set, frequencies:", [round(draws.count(i) / 10000, 3) for i in range(5)])
print("\n== 10. LoRA ==")
d = 4096
r_, alpha = 8, 16
print("full matrix %d x %d: %d weights; rank-%d LoRA adds %d (%.4f%%)" % (d, d, d * d, r_, 2 * d * r_, 100 * 2 * d * r_ / (d * d)))
print("four attention matrices in each of 32 layers: %d trainable against %d in those matrices" % (4 * 32 * 2 * d * r_, 4 * 32 * d * d))
rng = random.Random(6)
d_out, d_in, r_ = 5, 7, 2
W0 = rand_matrix(rng, d_out, d_in)
A = rand_matrix(rng, r_, d_in, 0.3)
Bm = [[0.0] * r_ for _ in range(d_out)]
x = rand_matrix(rng, d_in, 1)
y0 = matmul(W0, x)
y_start = [[y0[i][0] + (alpha / r_) * matmul(Bm, matmul(A, x))[i][0]] for i in range(d_out)]
print("with B = 0 the adapted layer equals the frozen one:", y_start == y0)
Bm = rand_matrix(rng, d_out, r_, 0.3)
scale = alpha / r_
merged = [[W0[i][j] + scale * sum(Bm[i][k] * A[k][j] for k in range(r_)) for j in range(d_in)] for i in range(d_out)]
yb = matmul(Bm, matmul(A, x))
y_adapter = [[y0[i][0] + scale * yb[i][0]] for i in range(d_out)]
print("merged weights give the same output as base plus adapter:", max(abs(a[0] - b_[0]) for a, b_ in zip(matmul(merged, x), y_adapter)) < 1e-12)
print("shapes: W %dx%d, A %dx%d, B %dx%d" % (d_out, d_in, r_, d_in, d_out, r_))
print("\n== 11. Preference loss ==")
for diff in (-1.0, 0.0, 1.0, 3.0):
print("reward margin %.1f: loss -log sigmoid = %.4f" % (diff, math.log(1 + math.exp(-diff))))
print("\ntotal %.1f s" % (time.time() - T0))What to look for: section 1 (BPE merges), section 3 (variance of a dot product and the saturated softmax), section 4 (shapes, the causal weights and the future-token test), section 5 (the shuffle test and sinusoidal rows), section 6 (parameter counts and the activation table), section 7 (losses), section 8 (cached against full decoding, memory), section 9 (temperature, top-k, top-p), section 10 (LoRA arithmetic and merge), section 11 (the preference loss). In PyTorch the equivalents are nn.Embedding, F.scaled_dot_product_attention, nn.MultiheadAttention, nn.GELU, nn.SiLU and nn.RMSNorm.
Real-World Application
When you serve or adapt a language model, three numbers matter first. Context length drives the quadratic attention cost and the linear KV-cache memory, so estimate the cache from the formula before choosing a batch size. Sampling settings are product decisions: pick low temperature and a filter for structured output, and log the settings with every response so a bad answer can be reproduced. For adaptation, start with prompting and retrieval because they change nothing in the weights; reach for LoRA when behaviour, not knowledge, is the gap, evaluate on a held-out set, and keep the base model unchanged so you can swap adapters. The GenAI course goes deeper on the production side in its lessons “Tokenization and embeddings”, “Memory and the KV-cache”, “PEFT, LoRA and QLoRA in depth” and “Alignment and preference optimisation”; this lesson stays at the ML level. Treat hallucination as a property to measure, not a bug to wait out: check generated claims against retrieved sources where the task allows.
Interview Perspective
Expect “walk through self-attention with shapes”, “why divide by the square root of d_k”, “why multi-head”, “what is the causal mask and where is it applied”, “why is attention quadratic”, “how does a transformer know word order”, “what is the KV cache and what does it cost”, “pre-norm versus post-norm”, “what do temperature, top-k and top-p do”, “LoRA versus full fine-tuning”, “RAG versus fine-tuning” and “why do LLMs hallucinate”. A strong answer gives the formula, plugs in numbers, and states a trade-off. A weak answer says “attention lets the model focus” without shapes, or “fine-tune it” to add facts.
Provenance: Common industry pattern. These are standard fundamentals for ML and GenAI roles, not a verified list for any named company.
Practice Questions
- Basic: Queries are , keys , values . What are the shapes of the score matrix, the weights and the output, and what is the scale?
- Basic: Why is divided by and not by ?
- Intermediate: A model has , , . Estimate the non-embedding parameters, and the KV cache for one 8,192-token sequence with 16 key-value heads of width 128 in 16-bit numbers.
- Intermediate: Explain why is applied after the mask, and what row sums you expect if you zero weights after the softmax instead.
- Intermediate: Logits are . Compute the probabilities at , apply top-p 0.8, and give the renormalised distribution.
- Advanced: A LoRA adapter on an matrix has rank 16. How many parameters does it train, and what happens to inference cost after merging?
- Product-Company (Generated practice): A support bot gives out-of-date refund rules. The team proposes fine-tuning on last month’s policy. Argue for or against, and describe how you would test the fix.
- Product-Company (Generated practice): Answers from your chat model vary between identical requests and users complain. What would you change first, and what would you check before changing it?
Activity
Run the script, then change three things and predict the result before you look. In section 3 change the number of keys to 64 and say what happens to the largest unscaled weight. In section 8 change kv_heads to 4 and compute the cache size by hand. In section 9 add a sixth logit equal to the largest one and say which top-p set you expect at (watch the tie).
Homework
Implement the pieces from this lesson in homework/: a stable softmax, attention with the causal mask and an offset for cached decoding, multi-head attention with unequal head widths, sinusoidal positions, temperature, top-k and top-p filters, inverse-CDF sampling, a LoRA layer and its merge, and the parameter, KV-cache, GELU and SiLU calculations. The tests use non-square inputs (, ), asymmetric data and exact tie and boundary cases, so a wrong scale, a mask applied after the softmax or a swapped slice fails.
Quick Revision
- Tokens are sub-word ids (BPE merges frequent pairs); the embedding is a row lookup, equal to one-hot times a matrix. Unmasked attention is permutation-equivariant, so add sinusoidal or rotary positions (a causal mask leaks some position implicitly, Haviv et al.).
- : shapes and . has variance , the scale restores 1 and keeps softmax out of saturation. Mask before softmax. Cost .
- Multi-head: slice, attend, concatenate, multiply by . Heads add no weights beyond the four matrices.
- Pre-norm: keeps a clean residual path, and Xiong et al. trained it without warm-up with comparable results. Layer weights about ; stack about . GELU is , SiLU is .
- Pre-training minimises next-token cross-entropy with teacher forcing and a causal mask. A KV cache turns projections into and costs bytes per sequence.
- Temperature divides logits; top-k keeps tokens; top-p keeps the smallest set reaching ; both renormalise.
- LoRA: , trained weights, mergeable. SFT shows answers; RLHF and DPO use ranked answers. Hallucination follows from a likelihood objective with no truth signal. Missing facts: retrieval; behaviour: fine-tuning.
Check yourself
- Walk-through: Without notes, give every shape in one multi-head attention layer for , , , and say where the causal mask goes and what the KV cache would store for the 13th token.
- Variation: A model’s long-context serving runs out of GPU memory at a batch size that fits at short context. List two causes related to the cache and one change for each.
- Common misconception: “Scaling is just to keep numbers small”, “multi-head attention has times the parameters”, “a KV cache removes attention’s quadratic cost”, “temperature 0 makes the model truthful”, “LoRA changes the architecture at inference” and “fine-tuning is the right way to add new facts”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Cache strategies (Hugging Face Transformers documentation) (opens in a new tab)
Shows the cache classes and the speed and memory trade-offs in a real library.
Further reading
Dive into Deep Learning, Multi-Head Attention (opens in a new tab)
Shape-by-shape code for multi-head attention to compare with the homework.
Research papers
Attention Is All You Need (opens in a new tab)Essential
The original architecture; read sections 3.2 to 3.5 and Table 1 with this lesson's shapes beside you.
LoRA: Low-Rank Adaptation of Large Language Models (opens in a new tab)Essential
The method and its experiments, beyond the abstract figures quoted here.
On Layer Normalization in the Transformer Architecture (opens in a new tab)
The gradient argument behind pre-norm and dropping warm-up.
The Curious Case of Neural Text Degeneration (opens in a new tab)
Why plain likelihood decoding degenerates and how nucleus sampling was motivated.
Direct Preference Optimization: Your Language Model is Secretly a Reward Model (opens in a new tab)
The closed-form argument that removes the reward model and the RL loop.
More for this module: Deep learning and transformers resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Deep learning and transformers.
Check yourself20 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.