Cheat sheet: the maths behind language models
The few calculations that appear again and again. Each one is worked with small numbers in a lesson.
Softmax
- Turns scores into chances that add up to 1.
- Subtract the largest score first: same chances, no overflow.
chance(i) = e^(score i - max) / sum of e^(score - max)
scores 1000 and 1001 give 0.27 and 0.73
Learn more: Tokens and sampling settings
Temperature
- Divide the scores by T before softmax.
- T below 1 sharpens; T above 1 flattens.
chance(i) = e^(score i / T) / sum of e^(score / T)
Learn more: Tokens and sampling settings
A text as a chain of chances
- The chance of a whole text is the product of next-token chances.
- Programs add logarithms instead, to avoid numbers too small to store.
0.1 x 0.05 x 0.2 = 0.001
Learn more: How large language models work
Attention as a weighted mix
- A word receives the sum of other words' values times weights that add up to 1.
- Real attention scores a query against every key, scales, then uses softmax.
0.75 x 10 + 0.25 x 2 = 8
Learn more: Transformers and attention
RMSNorm
- Divide a vector by its root mean square (no subtracting the average).
vector (1, 7): mean of squares = (1 + 49) / 2 = 25, root = 5
result (0.2, 1.4)
Learn more: Transformers and attention
Counting parameters
- Each layer adds about 12 x width squared (attention 4, feed-forward 8).
- The word table adds vocabulary x width.
parameters = 12 x layers x width^2 + vocabulary x width
Learn more: Designing a language model
Memory and work
- Weights memory = parameters x bytes per weight.
- Full training state is about 16 bytes per parameter before activations.
- Training work is about 6 x parameters x tokens.
8 billion x 16 bytes = about 128 GB
Learn more: Designing a language model · From laptop to big hardware: scaling training
LoRA
- Two thin matrices next to a frozen big one.
100 x 2 + 2 x 100 = 400 numbers, 4% of 10,000
LoRA-FA trains r x d; VeRA trains r + d
Learn more: Fine-tuning: SFT, LoRA, QLoRA and preference tuning
Latency
- ITL is the time from the first to the last token divided by the number of gaps.
(5.5 - 0.5) / (101 - 1) = 0.05 s
Learn more: Calling an LLM from your application