Transformers, large language models, sampling and fine-tuning

  • Intermediate
  • 1 h 30 min
  • Lesson 4 of 4 in Deep learning and transformers
  • Last verified

Open slides(27 slides)

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.

IdeaWhat it doesThe question it answers
TokenisationCuts text into sub-word pieces with integer idsHow do we feed text to a network with a fixed vocabulary?
EmbeddingLooks up a learned vector for each idWhat does the network actually compute on?
PositionsAdds order informationUnmasked attention is blind to order, so where does order come from?
Scaled dot-product attentionWeighted average of values, weights from query-key similarityHow does one token read from the others?
Causal maskHides future positionsHow do we train on next-token prediction without cheating?
BlockNorm, attention, MLP, with residual pathsWhat is repeated, and what does it cost?
KV cacheStores past keys and valuesWhy is generating token 1,000 not 1,000 times the work?
SamplingTemperature, top-k, top-pHow do we turn probabilities into text?
LoRA, preference tuningCheap adaptation, behaviour shapingHow 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.

Diagram: The input matrix is projected three ways into queries, keys and values.

X: n x d_model

Q = X Wq

K = X Wk

V = X Wv

scores = Q K^T / sqrt(d_k), n x n

causal mask: future scores = -inf

softmax over each row

output = weights x V

Diagram summary: The input matrix is projected three ways into queries, keys and values. Queries and keys give an n by n score matrix, which is scaled, masked so a token cannot see later tokens, and turned into row-wise weights by a softmax. The weights then mix the value rows to produce the output.

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 E∈RV×dmodelE\in\mathbb R^{V\times d_{\text{model}}}, with VV the vocabulary size. A lookup is the same as multiplying a one-hot row vector by EE (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 V⋅dmodelV\cdot d_{\text{model}}: for a vocabulary of 50,000 and dmodel=768d_{\text{model}}=768 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 XX, 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:

PE(p,2i)=sin⁡ ⁣(p100002i/d),PE(p,2i+1)=cos⁡ ⁣(p100002i/d)\mathrm{PE}_{(p,2i)}=\sin\!\left(\frac{p}{10000^{2i/d}}\right),\qquad \mathrm{PE}_{(p,2i+1)}=\cos\!\left(\frac{p}{10000^{2i/d}}\right)
SymbolMeaning
ppPosition in the sequence (0, 1, 2, …)
iiIndex of a sine-cosine pair of columns
ddEmbedding width dmodeld_{\text{model}}

Low columns oscillate quickly and high ones slowly, like the digits of a counter. For d=4d=4 position 0 is [0,1,0,1][0,1,0,1] and position 1 is about [0.8415,0.5403,0.0100,1.0000][0.8415,0.5403,0.0100,1.0000]. They chose it because the encoding at p+kp+k is a linear function of the encoding at pp, 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 Q∈Rnq×dkQ\in\mathbb R^{n_q\times d_k}, keys K∈Rnk×dkK\in\mathbb R^{n_k\times d_k} and values V∈Rnk×dvV\in\mathbb R^{n_k\times d_v}, attention is

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V
SymbolMeaningShape
QQOne query row per position that asksnq×dkn_q\times d_k
KKOne key row per position that can be readnk×dkn_k\times d_k
VVOne value row per readable positionnk×dvn_k\times d_v
QK⊤QK^{\top}Similarity of every query with every keynq×nkn_q\times n_k
softmaxApplied to each row, so weights sum to 1nq×nkn_q\times n_k
outputWeighted average of value rowsnq×dvn_q\times d_v

In self-attention Q=XWQQ=XW_Q, K=XWKK=XW_K, V=XWVV=XW_V for the same input XX, so nq=nk=nn_q=n_k=n. The PyTorch function scaled_dot_product_attention computes exactly this, with the scale defaulting to 1/dk1/\sqrt{d_k} where dkd_k 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 q⋅k=∑i=1dkqikiq\cdot k=\sum_{i=1}^{d_k}q_ik_i has mean 0 and variance dkd_k (Vaswani et al., section 3.2.1). Each term has variance 1 and there are dkd_k independent terms. The standard deviation is dk\sqrt{d_k}, so dividing by it restores variance 1. Without it, large dkd_k 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 dkd_k.

The script samples 2,000 random pairs at each width. The measured variance of q⋅kq\cdot k is 4.0 at dk=4d_k=4, 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 dk\sqrt{d_k} it is 1.01, 1.02, 1.00, 1.06 and 0.98. Then it compares one query with 8 random keys at dk=256d_k=256. 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 hh attentions in parallel on different learned projections, so different heads can look for different relations, then concatenates and mixes them with an output matrix WOW_O (Dive into Deep Learning, multi-head attention). Vaswani et al. use h=8h=8 and dk=dv=dmodel/h=64d_k=d_v=d_{\text{model}}/h=64, so the total cost is similar to one head of full width. With n=10n=10, dmodel=256d_{\text{model}}=256 and h=4h=4 the script prints: per head Q,K,VQ,K,V are 10×6410\times64, the score matrix is 10×1010\times10, a head output is 10×6410\times64, and the concatenation is 10×25610\times256. The four matrices WQ,WK,WV,WOW_Q,W_K,W_V,W_O hold 4⋅2562=262,1444\cdot256^2=262{,}144 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 −∞-\infty 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 [1,0,0,0][1,0,0,0] for row 0 and [0.362,0.408,0.230,0][0.362,0.408,0.230,0] 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 n×nn\times n entries, so attention costs O(n2d)O(n^2d) time and O(n2)O(n^2) 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 O(nd2)O(nd^2) but needs O(n)O(n) sequential steps, where attention needs O(1)O(1) (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 dffd_{\text{ff}}, a non-linearity, a linear layer back down. Vaswani et al. use dmodel=512d_{\text{model}}=512 and dff=2048d_{\text{ff}}=2048 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, LayerNorm(x+Sublayer(x))\mathrm{LayerNorm}(x+\mathrm{Sublayer}(x)) (section 3.1). Modern designs usually move the normalisation inside the residual branch, x+Sublayer(Norm(x))x+\mathrm{Sublayer}(\mathrm{Norm}(x)), 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.

Diagram: Each sub-layer sees a normalised copy of the stream, and its output is added back to the un-normalised stream.

x

Norm

Multi-head attention

+

Norm

MLP: up to d_ff, GELU or SiLU, down to d

+

next block

Diagram summary: Each sub-layer sees a normalised copy of the stream, and its output is added back to the un-normalised stream. The unmodified residual path runs straight from the block’s input to its output, which is the pre-norm design.

GELU and SiLU

ReLU zeroes every negative input. GELU multiplies the input by the standard normal cumulative distribution, x Φ(x)x\,\Phi(x), so each value is scaled by Φ(x)\Phi(x), the probability that a standard normal value is below xx (Hendrycks and Gimpel, abstract). SiLU multiplies the input by its sigmoid, x σ(x)x\,\sigma(x) (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 x=−1x=-1: ReLU 0, GELU −0.1587-0.1587, SiLU −0.2689-0.2689; for x=1x=1: 1, 0.8413, 0.7311; for x=3x=3: 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 4d24d^2 weights (WQ,WK,WV,WOW_Q,W_K,W_V,W_O) and the MLP has 2 d dff2\,d\,d_{\text{ff}}. With the common ratio dff=4dd_{\text{ff}}=4d that is 8d28d^2, so a layer holds about 12d212d^2 and a stack of LL layers about 12Ld212Ld^2, ignoring biases, norm gains and embeddings:

Player=4d2+2 d dff  → dff=4d   12d2,P≈12 L d2P_{\text{layer}}=4d^2+2\,d\,d_{\text{ff}}\;\xrightarrow{\,d_{\text{ff}}=4d\,}\;12d^2,\qquad P\approx 12\,L\,d^2
SymbolMeaning
ddModel width dmodeld_{\text{model}}
dffd_{\text{ff}}Hidden width of the MLP
LLNumber of layers

The script checks it for d=512d=512, dff=2048d_{\text{ff}}=2048: attention 1,048,576 plus MLP 2,097,152 equals 3,145,728, which is 12⋅512212\cdot512^2. Two of every three layer weights sit in the MLP. For d=1024d=1024, L=24L=24 the formula gives 301,989,888; for d=4096d=4096, L=32L=32 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 12Ld212Ld^2 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 dmodeld_{\text{model}} to the vocabulary size VV. 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 tt is scored on predicting token t+1t+1. One pass over nn tokens therefore gives n−1n-1 training targets. The loss is the average cross-entropy:

L=−1n−1∑t=1n−1ln⁡pθ ⁣(xt+1∣x1..t)\mathcal L=-\frac1{n-1}\sum_{t=1}^{n-1}\ln p_\theta\!\left(x_{t+1}\mid x_{1..t}\right)
SymbolMeaning
xtx_tThe token at position tt
pθ(⋅∣x1..t)p_\theta(\cdot\mid x_{1..t})The model’s softmax over the vocabulary after reading the first tt tokens

A model that guesses uniformly over 50 tokens has loss ln⁡50=3.9120\ln50=3.9120 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 [0,0,5][0,0,5], true token 0) pays 5.0134, far worse than the ln⁡3=1.0986\ln3=1.0986 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 tt and step t+1t+1 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 n=100n=100 tokens is 5,050 key-value projections without a cache against 100 with one (the sum 1+2+⋯+1001+2+\dots+100 against nn).

The price is memory. The cache holds keys and values for every layer, head, position and sequence:

bytes=2⋅L⋅Hkv⋅dhead⋅T⋅b\text{bytes}=2\cdot L\cdot H_{kv}\cdot d_{\text{head}}\cdot T\cdot b
SymbolMeaning
22One tensor for keys, one for values
LLLayers
HkvH_{kv}Number of key-value heads
dheadd_{\text{head}}Width of each head
TTTokens held, per sequence
bbBytes per stored number (2 for 16-bit floats)

For L=32L=32, Hkv=32H_{kv}=32, dhead=128d_{\text{head}}=128, T=4,096T=4{,}096 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 TT divides the logits before the softmax: pi∝ezi/Tp_i\propto e^{z_i/T}. Low TT sharpens (more like greedy), high TT flattens, and T→0T\to0 approaches greedy (derived here). With logits [2,1,0.5,0,−1][2,1,0.5,0,-1] the script prints

SettingProbabilitiesEntropy (nats)
T=0.5T=0.50.8292, 0.1122, 0.0413, 0.0152, 0.00210.609
T=1T=10.5630, 0.2071, 0.1256, 0.0762, 0.02801.206
T=2T=20.3745, 0.2272, 0.1769, 0.1378, 0.08361.491

Top-k keeps only the kk most probable tokens and renormalises: with k=2k=2 at T=1T=1 the result is 0.7311 and 0.2689. Top-p (nucleus sampling) keeps the smallest set of top tokens whose total probability reaches pp, 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 kk cannot. At p=0.9p=0.9 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 p=0.6p=0.6 it is 2 tokens. Drawing 10,000 samples from the p=0.9p=0.9 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 T=1T=1 would otherwise sometimes hit.

Pre-training, fine-tuning, LoRA and preference tuning

A model goes through stages, each changing a different thing.

Diagram: A model first learns language and knowledge from raw text, then learns to follow instructions from example answers, then is nudged toward...

Pre-training: next-token loss on a large corpus

Supervised fine-tuning: demonstrations of good answers

Preference tuning: RLHF or DPO on ranked answers

Deployment

Prompts, retrieval, tools

Diagram summary: A model first learns language and knowledge from raw text, then learns to follow instructions from example answers, then is nudged toward answers that people rank higher. Prompts, retrieval and tools are applied at use time without changing the weights.

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 W∈Rdout×dinW\in\mathbb R^{d_{\text{out}}\times d_{\text{in}}} the adapted layer is

W′x=Wx+αr B (Ax),A∈Rr×din,  B∈Rdout×r,  r≪min⁡(din,dout)W'x=Wx+\frac{\alpha}{r}\,B\,(Ax),\qquad A\in\mathbb R^{r\times d_{\text{in}}},\; B\in\mathbb R^{d_{\text{out}}\times r},\; r\ll\min(d_{\text{in}},d_{\text{out}})
SymbolMeaning
WWFrozen pre-trained weight
A,BA,BThe only trained matrices; their product has rank at most rr
rrRank, the width of the bottleneck
α\alphaScaling constant; the update is multiplied by α/r\alpha/r (Hu et al., section 4.1)

Hu et al. initialise AA randomly (Gaussian) and BB at zero, so BABA is zero at the start and the adapted model begins identical to the base; they scale the update by α/r\alpha/r, which reduces the need to retune hyperparameters when rr changes (section 4.1). The script checks that the output equals WxWx at that start. A 4096×40964096\times4096 matrix has 16,777,216 weights; a rank-8 adapter adds 8⋅(4096+4096)=65,5368\cdot(4096+4096)=65{,}536, 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 BABA has the same shape as WW, it can be added in: the script merges W+αrBAW+\tfrac{\alpha}{r}BA for a 5 by 7 matrix with r=2r=2 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-rr 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 −ln⁡σ(r(x,yw)−r(x,yl))-\ln\sigma\big(r(x,y_w)-r(x,y_l)\big) averaged over pairs, where ywy_w is the answer labelers preferred and yly_l 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 −1-1, 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 wrongFirst toolWhy
Facts are missing, private or change often; answers need citationsRetrieval (RAG): fetch documents and put them in the promptFacts can be updated without training and traced to a source
Wrong format or tone, a simple taskPrompting with examplesCheapest; no training
Consistent behaviour, domain style or shorter prompts at scaleFine-tuning, often LoRAChanges behaviour in the weights
Both knowledge and behaviourRetrieval plus fine-tuningEach 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 (h=8h=8, dff=2048d_{\text{ff}}=2048), 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).

Python

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 7×647\times 64, keys 11×6411\times 64, values 11×3211\times 32. What are the shapes of the score matrix, the weights and the output, and what is the scale?
  • Basic: Why is q⋅kq\cdot k divided by dk\sqrt{d_k} and not by dkd_k?
  • Intermediate: A model has d=2048d=2048, L=24L=24, dff=4dd_{\text{ff}}=4d. 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 softmax\mathrm{softmax} is applied after the mask, and what row sums you expect if you zero weights after the softmax instead.
  • Intermediate: Logits are [3,1,0][3,1,0]. Compute the probabilities at T=1T=1, apply top-p 0.8, and give the renormalised distribution.
  • Advanced: A LoRA adapter on an 11008×409611008\times4096 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 p=0.5p=0.5 (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 (nq≠nkn_q\neq n_k, dk≠dvd_k\neq d_v), 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.).
  • softmax(QK⊤/dk)V\mathrm{softmax}(QK^{\top}/\sqrt{d_k})V: shapes nq×nkn_q\times n_k and nq×dvn_q\times d_v. q⋅kq\cdot k has variance dkd_k, the scale restores 1 and keeps softmax out of saturation. Mask before softmax. Cost O(n2d)O(n^2d).
  • Multi-head: slice, attend, concatenate, multiply by WOW_O. Heads add no weights beyond the four matrices.
  • Pre-norm: x+Sublayer(Norm(x))x+\mathrm{Sublayer}(\mathrm{Norm}(x)) keeps a clean residual path, and Xiong et al. trained it without warm-up with comparable results. Layer weights about 12d212d^2; stack about 12Ld212Ld^2. GELU is xΦ(x)x\Phi(x), SiLU is xσ(x)x\sigma(x).
  • Pre-training minimises next-token cross-entropy with teacher forcing and a causal mask. A KV cache turns n(n+1)/2n(n+1)/2 projections into nn and costs 2LHkvdheadTb2LH_{kv}d_{\text{head}}Tb bytes per sequence.
  • Temperature divides logits; top-k keeps kk tokens; top-p keeps the smallest set reaching pp; both renormalise.
  • LoRA: W+αrBAW+\tfrac\alpha rBA, r(din+dout)r(d_{\text{in}}+d_{\text{out}}) 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 n=12n=12, dmodel=512d_{\text{model}}=512, h=8h=8, 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 hh 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

Further reading

Research papers

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.

0 of 20 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain how text becomes tokens and embeddings, why self-attention alone cannot see word order, and how sinusoidal or rotary positions fix that.

  1. Question 1 of 20A model has a vocabulary of 6 tokens and embedding width 4. What does looking up the embedding of token 3 compute?

    Choose one answer.

  2. Question 2 of 20Unmasked (bidirectional) self-attention is applied to the rows of X with no positional information. The rows are then shuffled before the layer. What happens to the output?

    Choose one answer.

  3. Question 3 of 20Which description of byte pair encoding is correct?

    Choose one answer.

  4. Question 4 of 20Vaswani et al. compared their sinusoidal position encoding with learned position embeddings. What did they report, and what reason did they give for choosing the sinusoids?

    Choose one answer.

ObjectiveCompute 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.

  1. Question 5 of 20Queries are 5 by 16, keys 9 by 16 and values 9 by 4. What are the score-matrix shape, the output shape and the scale applied to the scores?

    Choose one answer.

  2. Question 6 of 20Queries and keys have independent components with mean 0 and variance 1. Why is their dot product divided by the square root of d_k and not by d_k?

    Choose one answer.

  3. Question 7 of 20A team applies the causal mask by setting future attention weights to 0 after the softmax. What is wrong with this?

    Choose one answer.

  4. Question 8 of 20The context window is doubled from 4,000 to 8,000 tokens. By what factor does the number of score-matrix entries in one attention head change?

    Choose one answer.

ObjectiveDescribe 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.

  1. Question 9 of 20What is the main difference between pre-norm and post-norm transformer blocks, and why does it matter?

    Choose one answer.

  2. Question 10 of 20A transformer has d_model = 2048, 24 layers and d_ff = 4 d_model. Using the lesson's rule, about how many weights are in the attention and MLP blocks (no biases, norms or embeddings)?

    Choose one answer.

  3. Question 11 of 20Which statement about GELU and SiLU is correct?

    Choose one answer.

  4. Question 12 of 20In a standard transformer block, where do most of the weights sit when d_ff = 4 d_model, and which layer mixes information between positions?

    Choose one answer.

ObjectiveExplain 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.

  1. Question 13 of 20A decoder-only model is trained on a sequence of 20 tokens in one forward pass with a causal mask. How many next-token training targets does that pass provide, and why?

    Choose one answer.

  2. Question 14 of 20What does a KV cache save during generation, and what does it cost?

    Choose one answer.

  3. Question 15 of 20The next-token distribution is very confident: one token has probability 0.97 and the rest is spread thinly over 50,000 others. How do top-p = 0.9 and top-k = 50 differ here?

    Choose one answer.

  4. Question 16 of 20A product team wants more repeatable outputs from a sampling-based chat model without switching to greedy decoding. Which change does this, and why?

    Choose one answer.

ObjectiveCompare 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.

  1. Question 17 of 20A weight matrix of shape 8192 by 2048 gets a LoRA adapter of rank 4. How many parameters does the adapter train, and what happens to inference cost after merging?

    Choose one answer.

  2. Question 18 of 20A support assistant must answer from refund rules that change every week and must cite the policy page. Which first approach fits, and why?

    Choose one answer.

  3. Question 19 of 20Why can a language model state a false claim fluently?

    Choose one answer.

  4. Question 20 of 20Compared with RLHF as described in the DPO paper, what does direct preference optimisation change?

    Choose one answer.