Slides · Deep learning and transformers

Transformers, large language models, sampling and fine-tuning

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:

  1. Explain tokens, embeddings and positions.
  2. Compute attention with shapes, the scale and the mask.
  3. Describe the pre-norm block and estimate parameters.
  4. Explain next-token training, the KV cache and sampling.
  5. 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), then e+st (count 9).
  • Embedding: a row of a learned V×dmodelV\times d_{\text{model}} matrix. A lookup equals a one-hot vector times the matrix.
  • Vocabulary 50,000, width 768: 38,400,000 parameters (illustrative).

Sources1 Neural Machine Translation of Rare Words with Subword Units2 Attention Is All You Need

Math

Attention cannot see order

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)
  • 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=4d=4: position 0 is [0,1,0,1][0,1,0,1], position 1 is about [0.8415,0.5403,0.0100,1.0000][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.

Sources2 Attention Is All You Need3 Dive into Deep Learning, Self-Attention and Positional Encoding4 RoFormer: Enhanced Transformer with Rotary Position Embedding5 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 ⁣(QK⊤dk)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V
  • Shapes: QQ is nq×dkn_q\times d_k, KK is nk×dkn_k\times d_k, VV is nk×dvn_k\times d_v. Scores nq×nkn_q\times n_k, output nq×dvn_q\times d_v.
  • If qq and kk have independent components of mean 0 and variance 1, q⋅kq\cdot k has variance dkd_k. Dividing by dk\sqrt{d_k} restores variance 1.
  • Measured in the script: 270.3 at dk=256d_k=256 before scaling (theory 256), about 1.06 after.

Sources2 Attention Is All You Need6 torch.nn.functional.scaled_dot_product_attention

Worked example

What the scale protects

One query, 8 random keys, dk=256d_k=256:

ScoresLargest softmax weightSoftmax Jacobian norm
Unscaled0.99810.00366
Scaled0.29700.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.

Source2 Attention Is All You Need

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/41/\sqrt{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

Diagram: Queries and keys give a score matrix that is scaled, masked so a position cannot read later positions, and turned into row weights by a...

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: Queries and keys give a score matrix that is scaled, masked so a position cannot read later positions, and turned into row weights by a softmax; the weights mix the value rows. With several heads, each head slices the same projection matrices, and the heads are concatenated and multiplied by WOW_O.
  • n=10n=10, dmodel=256d_{\text{model}}=256, h=4h=4: each head has a 10×6410\times64 query and a 10×1010\times10 score matrix.
  • Mask before the softmax, so the rows still sum to 1.

Sources2 Attention Is All You Need7 Dive into Deep Learning, Multi-Head Attention

Diagram

The pre-norm block

Diagram: Each sub-layer reads a normalised copy of the stream and its output is added back to the un-normalised stream, so a clean residual path...

x

Norm

Multi-head attention

+

Norm

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

+

next block

Diagram summary: Each sub-layer reads a normalised copy of the stream and its output is added back to the un-normalised stream, so a clean residual path runs through the whole 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))\mathrm{LayerNorm}(x+\mathrm{Sublayer}(x)).

Sources2 Attention Is All You Need8 On Layer Normalization in the Transformer Architecture9 Root Mean Square Layer Normalization

Compare

Pre-norm and the activation

Post-normPre-norm
Normalises after the residual addNormalises inside the branch
Large gradients near the output at initialisation, so it needs warm-upWell-behaved gradients at initialisation, trained without warm-up with comparable results (Xiong et al.)
  • GELU: x Φ(x)x\,\Phi(x). SiLU: x σ(x)x\,\sigma(x). At x=−1x=-1: GELU −0.1587-0.1587, SiLU −0.2689-0.2689. At x=3x=3: 2.9960 and 2.8577.
  • Both are smooth and dip slightly below zero; which is better is empirical.

Sources8 On Layer Normalization in the Transformer Architecture10 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=1024d=1024, dff=4dd_{\text{ff}}=4d and there are 24 layers. Estimate the attention and MLP weights and say which part is bigger.

Answer

Per layer 4d2+8d2=12d24d^2+8d^2=12d^2, so 12⋅24⋅10242=301,989,88812\cdot24\cdot1024^2=301{,}989{,}888. The MLP holds 8d28d^2 of every 12d212d^2 (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 tt predicts token t+1t+1. nn tokens give n−1n-1 targets.
  • Loss: average cross-entropy. A uniform guess over 50 tokens costs ln⁡50=3.9120\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.

Source2 Attention Is All You Need

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⋅b2\cdot L\cdot H_{kv}\cdot d_{\text{head}}\cdot T\cdot 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.

Sources12 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][2,1,0.5,0,-1]:

SettingProbabilities
T=0.5T=0.50.8292, 0.1122, 0.0413, 0.0152, 0.0021
T=1T=10.5630, 0.2071, 0.1256, 0.0762, 0.0280
T=2T=20.3745, 0.2272, 0.1769, 0.1378, 0.0836
top-k 2 at T=1T=10.7311, 0.2689, 0, 0, 0
top-p 0.9 at T=1T=10.5793, 0.2131, 0.1293, 0.0784, 0
  • Temperature divides the logits. Top-p keeps the smallest set that reaches pp, so it adapts to how confident the model is.

Source13 The Curious Case of Neural Text Degeneration

Check yourself

Check: a nucleus

Using the same logits at T=1T=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

Diagram: A model learns language from raw text, then to follow instructions from example answers, then is nudged toward answers that people rank...

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 learns language from raw text, then 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.
  • 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.

Sources14 Training language models to follow instructions with human feedback15 Direct Preference Optimization: Your Language Model is Secretly a Reward Model

Math

LoRA

W′x=Wx+αr B (Ax),trained weights=r (din+dout)W'x=Wx+\frac{\alpha}{r}\,B\,(Ax),\qquad \text{trained weights}=r\,(d_{\text{in}}+d_{\text{out}})
  • Freeze WW. Start with B=0B=0, so the adapted model begins identical to the base.
  • 4096×40964096\times4096: 16,777,216 weights. Rank 8 trains 65,536, which is 0.3906%.
  • W+αrBAW+\tfrac\alpha rBA can be merged: no extra inference cost, and adapters are small files.
  • Trade-off: a rank-rr update has limited capacity.

Source16 LoRA: Low-Rank Adaptation of Large Language Models

Check yourself

Check: the adapter

A frozen matrix is 5×75\times7 and the adapter has rank 2. Give the shapes of AA and BB, the number of trained weights, and the cost of a merged adapter at inference.

Answer

AA is 2×72\times7 and BB is 5×25\times2: 2⋅(7+5)=242\cdot(7+5)=24 trained weights, against 35 in the matrix. After merging there is one 5×75\times7 matrix again, so the inference cost is unchanged.

Compare

What is missing decides the tool

ProblemFirst tool
Facts missing, private or changing; citations neededRetrieval (RAG)
Wrong format or tonePrompting with examples
Consistent behaviour or style at scaleFine-tuning, often LoRA
Knowledge and behaviourRetrieval 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.

Source17 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\mathrm{softmax}(QK^{\top}/\sqrt{d_k})V; the scale fixes the variance; mask before the softmax; cost grows with n2n^2.
  • Pre-norm blocks keep a clean residual path; a layer has about 12d212d^2 weights.
  • Teacher forcing gives n−1n-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)r(d_{\text{in}}+d_{\text{out}}) weights and merges; SFT shows answers, preference tuning ranks them; hallucination follows from a likelihood objective.

References

References & Sources (1 of 4)

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

    Used for Encoding rare and unseen words as sub-word units with byte pair encoding (abstract).

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

    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.

  3. Dive into Deep Learning, Self-Attention and Positional Encoding (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    Used for Attention ignores order, positions are added to the input, the sinusoidal formulas, the quadratic cost of self-attention.

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

    Used for Rotary position embedding encodes absolute position by rotation and makes attention depend on relative distance (abstract).

  5. Transformer Language Models without Positional Encodings Still Learn Positional Information (opens in a new tab)

    Adi Haviv, Ori Ram, Ofir Press, Peter Izsak, et al.2022Findings of EMNLP 2022 (arXiv:2203.16634)Paper

    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)

  1. torch.nn.functional.scaled_dot_product_attention (opens in a new tab)

    PyTorch2026Documentation

    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.

  2. Dive into Deep Learning, Multi-Head Attention (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    Used for Per-head projections, concatenation and an output matrix, with head widths set to the output width divided by h.

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

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

  4. Root Mean Square Layer Normalization (opens in a new tab)

    Biao Zhang, Rico Sennrich2019NeurIPS 2019 (arXiv:1910.07467)Paper

    Used for RMSNorm drops mean-centring and reports 7% to 64% less running time (abstract).

  5. Gaussian Error Linear Units (GELUs) (opens in a new tab)

    Dan Hendrycks, Kevin Gimpel2016arXiv:1606.08415Paper

    Used for GELU multiplies the input by the standard normal cumulative distribution (abstract).

References

References & Sources (3 of 4)

  1. Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (opens in a new tab)

    Stefan Elfwing, Eiji Uchibe, Kenji Doya2017arXiv:1702.03118Preprint

    Used for SiLU is the sigmoid multiplied by its input (abstract).

  2. Cache strategies (Hugging Face Transformers documentation) (opens in a new tab)

    Hugging Face2026Documentation

    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.

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

    Used for Likelihood-maximising decoding gives bland, repetitive text, and nucleus sampling draws from a dynamic nucleus of the distribution (abstract).

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

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

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

    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)

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

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

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

    Used for Hallucination defined as generated text that is nonsensical or unfaithful to the provided source content (section 2), surveyed across tasks (abstract).