Slides · Deep learning and transformers
Transformers, large language models, sampling and fine-tuning
1 / 27
Transformers, LLMs and fine-tuning
Attention, the transformer block, generation with a KV cache, sampling, LoRA and preference tuning.
Concept
Why this is worth 90 minutes
- Almost every modern language model is a transformer, and attention, the causal mask, the KV cache and LoRA are standard interview topics (common industry pattern).
- The costs that decide what you can serve are visible in the formulas: quadratic attention, the size of the cache, the parameters per layer.
- The same mechanism explains why a model sounds sure when it is wrong.
Five things you will be able to do:
- Explain tokens, embeddings and positions.
- Compute attention with shapes, the scale and the mask.
- Describe the pre-norm block and estimate parameters.
- Explain next-token training, the KV cache and sampling.
- Compare SFT, LoRA and preference tuning, and choose between prompting, RAG and fine-tuning.
Concept
Tokens and embeddings
- Sub-word tokens: byte pair encoding starts from characters and repeatedly merges the most frequent adjacent pair. Rare words stay as pieces.
- In the toy corpus the first merge is
s+t(count 9), thene+st(count 9). - Embedding: a row of a learned V×dmodel matrix. A lookup equals a one-hot vector times the matrix.
- Vocabulary 50,000, width 768: 38,400,000 parameters (illustrative).
Sources[1] Neural Machine Translation of Rare Words with Subword Units[2] Attention Is All You Need
Math
Attention cannot see order
PE(p,2i)=sin(100002i/dp),PE(p,2i+1)=cos(100002i/dp)- Shuffle the input rows and the output rows are shuffled the same way: attention treats its input as a set.
- Add a position encoding to the embeddings. For d=4: position 0 is [0,1,0,1], position 1 is about [0.8415,0.5403,0.0100,1.0000].
- Learned positions gave nearly identical results in the original paper. Rotary embeddings rotate queries and keys so the score depends on relative distance.
Sources[2] Attention Is All You Need[3] Dive into Deep Learning, Self-Attention and Positional Encoding[4] RoFormer: Enhanced Transformer with Rotary Position Embedding[5] Transformer Language Models without Positional Encodings Still Learn Positional Information
Check yourself
Check: two sentences, one bag
A bidirectional model made only of unmasked attention layers, with no position information, reads “the dog chased the cat” and “the cat chased the dog”. What can you say about the vectors it computes for the word “dog” in each sentence, and what is the smallest change that fixes it?
Answer
The word “dog” has the same input vector in both sentences, and each position reads a weighted average of the same set of vectors, so the vector computed for “dog” is the same in both. The model cannot tell the sentences apart. Adding a position encoding to each embedding gives the same word a different input at different positions, which breaks the symmetry. (A causal mask breaks it implicitly: Haviv et al. found causal models without explicit positions still learn some position information.)
Math
Scaled dot-product attention
Attention(Q,K,V)=softmax(dkQK⊤)V- Shapes: Q is nq×dk, K is nk×dk, V is nk×dv. Scores nq×nk, output nq×dv.
- If q and k have independent components of mean 0 and variance 1, q⋅k has variance dk. Dividing by dk restores variance 1.
- Measured in the script: 270.3 at dk=256 before scaling (theory 256), about 1.06 after.
Sources[2] Attention Is All You Need[6] torch.nn.functional.scaled_dot_product_attention
Worked example
What the scale protects
One query, 8 random keys, dk=256:
| Scores | Largest softmax weight | Softmax Jacobian norm |
|---|---|---|
| Unscaled | 0.9981 | 0.00366 |
| Scaled | 0.2970 | 0.37223 |
- Unscaled, the softmax is almost one-hot, and almost no gradient reaches the queries and keys.
- One draw from seed 1: an illustration of the effect, not a constant.
Check yourself
Check: shapes and cost
Queries are 3 by 16, keys 5 by 16 and values 5 by 8. Give the score matrix, the output and the scale. Then say what happens to the number of score entries if both lengths are multiplied by 3.
Answer
Scores are 3 by 5, the output is 3 by 8 and the scale is 1/16=1/4. Both lengths times 3 make the matrix 9 by 15, which is 135 entries instead of 15: nine times as many, because the count grows with the product of the lengths.
Diagram
Multi-head attention and the causal mask
- n=10, dmodel=256, h=4: each head has a 10×64 query and a 10×10 score matrix.
- Mask before the softmax, so the rows still sum to 1.
Sources[2] Attention Is All You Need[7] Dive into Deep Learning, Multi-Head Attention
Diagram
The pre-norm block
- Attention mixes positions; the MLP works on each position separately.
- Norm is LayerNorm or RMSNorm; the original paper used post-norm, LayerNorm(x+Sublayer(x)).
Sources[2] Attention Is All You Need[8] On Layer Normalization in the Transformer Architecture[9] Root Mean Square Layer Normalization
Compare
Pre-norm and the activation
| Post-norm | Pre-norm |
|---|---|
| Normalises after the residual add | Normalises inside the branch |
| Large gradients near the output at initialisation, so it needs warm-up | Well-behaved gradients at initialisation, trained without warm-up with comparable results (Xiong et al.) |
- GELU: xΦ(x). SiLU: xσ(x). At x=−1: GELU −0.1587, SiLU −0.2689. At x=3: 2.9960 and 2.8577.
- Both are smooth and dip slightly below zero; which is better is empirical.
Sources[8] On Layer Normalization in the Transformer Architecture[10] Gaussian Error Linear Units (GELUs)[11] Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning
Check yourself
Check: parameters
A layer has d=1024, dff=4d and there are 24 layers. Estimate the attention and MLP weights and say which part is bigger.
Answer
Per layer 4d2+8d2=12d2, so 12⋅24⋅10242=301,989,888. The MLP holds 8d2 of every 12d2 (two thirds), so it is bigger than attention. Embeddings, biases and norms are extra.
Concept
Next-token training
- Feed the whole true sequence in once (teacher forcing); the causal mask hides the future; position t predicts token t+1. n tokens give n−1 targets.
- Loss: average cross-entropy. A uniform guess over 50 tokens costs ln50=3.9120 nats, perplexity 50.
- Nothing in the loss mentions truth, helpfulness or safety.
- Generation is autoregressive: choose a token, append, repeat. Steps cannot run in parallel.
Concept
The KV cache
- Earlier tokens never see later ones, so their keys and values do not change. Store them.
- Cached decoding matched full recomputation in the script. Projections for 100 tokens: 5,050 without a cache, 100 with.
- Cost: 2⋅L⋅Hkv⋅dhead⋅T⋅b bytes per sequence. 32 layers, 32 heads, width 128, 4,096 tokens, 2 bytes: 2.0 GiB.
- Sharing key-value heads shrinks it: 8 heads gives 0.5 GiB.
Sources[12] Cache strategies (Hugging Face Transformers documentation)[6] torch.nn.functional.scaled_dot_product_attention
Check yourself
Check: why memory, not compute?
A server runs fine at 2,000 tokens of context but runs out of memory at 16,000 tokens with the same batch. The weights did not change. Explain it, and name one change.
Answer
The cache grows linearly with tokens, so 8 times the context needs 8 times the cache for each sequence, while the weights stay fixed. Reduce the batch, share key-value heads, store the cache in fewer bits, or shorten the context.
Worked example
Temperature, top-k and top-p
Logits [2,1,0.5,0,−1]:
| Setting | Probabilities |
|---|---|
| T=0.5 | 0.8292, 0.1122, 0.0413, 0.0152, 0.0021 |
| T=1 | 0.5630, 0.2071, 0.1256, 0.0762, 0.0280 |
| T=2 | 0.3745, 0.2272, 0.1769, 0.1378, 0.0836 |
| top-k 2 at T=1 | 0.7311, 0.2689, 0, 0, 0 |
| top-p 0.9 at T=1 | 0.5793, 0.2131, 0.1293, 0.0784, 0 |
- Temperature divides the logits. Top-p keeps the smallest set that reaches p, so it adapts to how confident the model is.
Check yourself
Check: a nucleus
Using the same logits at T=1, which tokens does top-p 0.6 keep, and what are the final probabilities?
Answer
The top token has 0.5630, below 0.6, so the second (0.2071) is added to reach 0.7701. Two tokens are kept and renormalised: 0.7311 and 0.2689.
Diagram
From pre-training to a chat model
- InstructGPT: a 1.3B model was preferred by people over the 175B GPT-3, and still made simple mistakes.
- DPO replaces the reward model and the reinforcement-learning loop with a classification-style loss.
Sources[14] Training language models to follow instructions with human feedback[15] Direct Preference Optimization: Your Language Model is Secretly a Reward Model
Math
LoRA
W′x=Wx+rαB(Ax),trained weights=r(din+dout)- Freeze W. Start with B=0, so the adapted model begins identical to the base.
- 4096×4096: 16,777,216 weights. Rank 8 trains 65,536, which is 0.3906%.
- W+rαBA can be merged: no extra inference cost, and adapters are small files.
- Trade-off: a rank-r update has limited capacity.
Source[16] LoRA: Low-Rank Adaptation of Large Language Models
Check yourself
Check: the adapter
A frozen matrix is 5×7 and the adapter has rank 2. Give the shapes of A and B, the number of trained weights, and the cost of a merged adapter at inference.
Answer
A is 2×7 and B is 5×2: 2⋅(7+5)=24 trained weights, against 35 in the matrix. After merging there is one 5×7 matrix again, so the inference cost is unchanged.
Compare
What is missing decides the tool
| Problem | First tool |
|---|---|
| Facts missing, private or changing; citations needed | Retrieval (RAG) |
| Wrong format or tone | Prompting with examples |
| Consistent behaviour or style at scale | Fine-tuning, often LoRA |
| Knowledge and behaviour | Retrieval plus fine-tuning |
- Hallucination: next-token training rewards probable text and has no signal for truth, and sampling follows probability.
- Measure on held-out examples of the real task.
Source[17] Survey of Hallucination in Natural Language Generation
Code
A masked attention row in a few lines
Python
import math
def attention_row(scores, offset_i, values):
# scores: one query's Q.K scores, ALREADY divided by sqrt(d_k)
# mask keys later than the query, then softmax, then mix the values
masked = [s if j <= offset_i else -math.inf for j, s in enumerate(scores)]
m = max(masked)
es = [math.exp(s - m) for s in masked]
z = sum(es)
w = [e / z for e in es]
return [sum(w[j] * values[j][c] for j in range(len(values))) for c in range(len(values[0]))]- The homework adds the scale, multi-head slicing, positions, temperature, top-k, top-p, sampling, LoRA and size calculators.
Summary
Recap
- Tokens are sub-word ids; embeddings are row lookups; attention needs position information added.
- Attention is softmax(QK⊤/dk)V; the scale fixes the variance; mask before the softmax; cost grows with n2.
- Pre-norm blocks keep a clean residual path; a layer has about 12d2 weights.
- Teacher forcing gives n−1 targets per pass; the KV cache trades memory for repeated work; temperature, top-k and top-p shape the draw.
- LoRA trains r(din+dout) weights and merges; SFT shows answers, preference tuning ranks them; hallucination follows from a likelihood objective.
References
References & Sources (1 of 4)
Neural Machine Translation of Rare Words with Subword Units (opens in a new tab)
Rico Sennrich, Barry Haddow, Alexandra Birch2016ACL 2016 (arXiv:1508.07909)Paper
https://arxiv.org/abs/1508.07909
Used for Encoding rare and unseen words as sub-word units with byte pair encoding (abstract).
Attention Is All You Need (opens in a new tab)
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, et al.2017Advances in Neural Information Processing Systems 30 (NIPS 2017)Paper
arXiv 1706.03762 (opens in a new tab)https://arxiv.org/abs/1706.03762
Used for Scaled dot-product attention, the variance argument for the 1/sqrt(d_k) scale, h = 8 heads with d_k = d_v = 64, masking with minus infinity, d_model 512 and d_ff 2048 with ReLU, post-norm LayerNorm(x + Sublayer(x)), shared embedding and output matrices, sinusoidal positions and nearly identical learned positions (Table 3 row E), and the per-layer complexity table.
Dive into Deep Learning, Self-Attention and Positional Encoding (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_attention-mechanisms-and-transformers/self-attention-and-positional-encoding.html
Used for Attention ignores order, positions are added to the input, the sinusoidal formulas, the quadratic cost of self-attention.
RoFormer: Enhanced Transformer with Rotary Position Embedding (opens in a new tab)
Jianlin Su, Yu Lu, Shengfeng Pan, Ahmed Murtadha, et al.2021arXiv:2104.09864Preprint
https://arxiv.org/abs/2104.09864
Used for Rotary position embedding encodes absolute position by rotation and makes attention depend on relative distance (abstract).
Adi Haviv, Ori Ram, Ofir Press, Peter Izsak, et al.2022Findings of EMNLP 2022 (arXiv:2203.16634)Paper
https://arxiv.org/abs/2203.16634
Used for Causal language models without explicit positional encodings still learn positional information, and the authors conjecture that causal attention lets a token infer how many predecessors it can attend to (abstract).
References
References & Sources (2 of 4)
torch.nn.functional.scaled_dot_product_attention (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.functional.scaled_dot_product_attention.html
Used for The default scale 1/sqrt(d_k), the reference algorithm with -inf masking, and the enable_gqa option where keys and values have fewer heads.
Dive into Deep Learning, Multi-Head Attention (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_attention-mechanisms-and-transformers/multihead-attention.html
Used for Per-head projections, concatenation and an output matrix, with head widths set to the output width divided by h.
On Layer Normalization in the Transformer Architecture (opens in a new tab)
Ruibin Xiong, Yunchang Yang, Di He, Kai Zheng, et al.2020ICML 2020 (arXiv:2002.04745)Paper
https://arxiv.org/abs/2002.04745
Used for Post-norm has large gradients near the output at initialisation and needs warm-up, pre-norm has well-behaved gradients and trains without warm-up (abstract).
Root Mean Square Layer Normalization (opens in a new tab)
Biao Zhang, Rico Sennrich2019NeurIPS 2019 (arXiv:1910.07467)Paper
https://arxiv.org/abs/1910.07467
Used for RMSNorm drops mean-centring and reports 7% to 64% less running time (abstract).
Gaussian Error Linear Units (GELUs) (opens in a new tab)
Dan Hendrycks, Kevin Gimpel2016arXiv:1606.08415Paper
https://arxiv.org/abs/1606.08415
Used for GELU multiplies the input by the standard normal cumulative distribution (abstract).
References
References & Sources (3 of 4)
Stefan Elfwing, Eiji Uchibe, Kenji Doya2017arXiv:1702.03118Preprint
https://arxiv.org/abs/1702.03118
Used for SiLU is the sigmoid multiplied by its input (abstract).
Cache strategies (Hugging Face Transformers documentation) (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/transformers/en/kv_cache
Used for The KV cache stores key and value states so they are not recomputed, can become a memory bottleneck for long contexts, and can be quantised or offloaded.
The Curious Case of Neural Text Degeneration (opens in a new tab)
Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, et al.2019arXiv:1904.09751Paper
https://arxiv.org/abs/1904.09751
Used for Likelihood-maximising decoding gives bland, repetitive text, and nucleus sampling draws from a dynamic nucleus of the distribution (abstract).
Training language models to follow instructions with human feedback (opens in a new tab)
Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, et al.2022arXiv:2203.02155Paper
https://arxiv.org/abs/2203.02155
Used for Supervised fine-tuning on demonstrations then fine-tuning with human rankings; the 1.3B InstructGPT preferred over the 175B GPT-3; simple mistakes remain (abstract); the reward-model loss -log sigmoid(r(x, y_w) - r(x, y_l)) (section 3.5, equation 1).
Direct Preference Optimization: Your Language Model is Secretly a Reward Model (opens in a new tab)
Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, et al.2023arXiv:2305.18290Preprint
https://arxiv.org/abs/2305.18290
Used for RLHF fits a reward model and then uses reinforcement learning; DPO reduces the objective to a classification loss without those steps (abstract).
References
References & Sources (4 of 4)
LoRA: Low-Rank Adaptation of Large Language Models (opens in a new tab)
Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, et al.2021arXiv:2106.09685Paper
https://arxiv.org/abs/2106.09685
Used for LoRA freezes the weights and trains rank decomposition matrices; up to 10,000 times fewer trainable parameters and about 3 times less GPU memory for GPT-3 175B than Adam fine-tuning, and no extra inference latency (abstract); random Gaussian A, zero B and the alpha/r scaling (section 4.1).
Survey of Hallucination in Natural Language Generation (opens in a new tab)
Ziwei Ji, Nayeon Lee, Rita Frieske, Tiezheng Yu, et al.2022ACM Computing Surveys (arXiv:2202.03629)Paper
https://arxiv.org/abs/2202.03629
Used for Hallucination defined as generated text that is nonsensical or unfaithful to the provided source content (section 2), surveyed across tasks (abstract).
Keys: ← → move, Home End first and last, F full screen.