Module 2 of 126 lessons

Mathematics and Foundations

Just enough maths to read any transformer paper: every idea is shown as a picture first, then as an equation, then as a few lines of NumPy.

Course contents · Module 2 of 12
← Build Claude from scratch
98 lessons · 12 modules
  1. 1Understanding Claude and modern AI6
    1. 1.1What is Claude?
    2. 1.2What is an LLM?
    3. 1.3How ChatGPT, Claude, Gemini and other AI assistants work
    4. 1.4AI, machine learning, deep learning, transformers and LLMs
    5. 1.5What happens when you send a message to an AI?
    6. 1.6Tokens, context windows and embeddings
  2. 2Mathematics and foundations6
    1. 2.1Essential linear algebra
    2. 2.2Vectors, matrices and matrix multiplication
    3. 2.3Probability and statistics
    4. 2.4Softmax, gradients and loss functions
    5. 2.5Neural networks and backpropagation
    6. 2.6Practical Python demonstrations
  3. 3Neural network from scratch7
    1. 3.1Set up Python and NumPy
    2. 3.2Build neurons and layers
    3. 3.3Implement forward propagation
    4. 3.4Implement backpropagation
    5. 3.5Implement gradient descent
    6. 3.6Train a small neural network without PyTorch or TensorFlow
    7. 3.7Visualize training and loss
  4. 4Understanding transformers9
    1. 4.1Why traditional RNNs have limitations
    2. 4.2The transformer architecture
    3. 4.3Tokenization and embeddings
    4. 4.4Positional encoding
    5. 4.5Self-attention and multi-head attention
    6. 4.6Query, Key and Value explained visually
    7. 4.7Feed-forward networks
    8. 4.8Layer normalization and residual connections
    9. 4.9Implement a simplified transformer in NumPy
  5. 5Build a GPT-like model9
    1. 5.1Tokenizer implementation
    2. 5.2Vocabulary creation
    3. 5.3Dataset preparation
    4. 5.4Next-token prediction
    5. 5.5Building a decoder-only transformer
    6. 5.6Training a tiny language model
    7. 5.7Text generation and temperature
    8. 5.8Top-k and top-p sampling
    9. 5.9Understanding hallucinations and limitations
  6. 6How Claude is different9
    1. 6.1Claude's architecture at a conceptual level
    2. 6.2Constitutional AI
    3. 6.3Supervised fine-tuning
    4. 6.4Reinforcement learning from human feedback
    5. 6.5Preference optimization
    6. 6.6Safety training and alignment
    7. 6.7System prompts and instruction following
    8. 6.8Long-context processing
    9. 6.9Tool use and agentic behavior
  7. 7Build your own AI assistant10
    1. 7.1Design a Claude-like chat interface
    2. 7.2Conversation management
    3. 7.3System instructions
    4. 7.4Chat history and context management
    5. 7.5Streaming responses
    6. 7.6Markdown and code rendering
    7. 7.7Syntax highlighting
    8. 7.8Error handling
    9. 7.9File upload and document understanding concepts
    10. 7.10Building a frontend chatbot
  8. 8Memory and RAG8
    1. 8.1What is AI memory?
    2. 8.2Short-term vs long-term memory
    3. 8.3Embeddings and vector databases
    4. 8.4Semantic search
    5. 8.5Retrieval-Augmented Generation (RAG)
    6. 8.6Chunking and document retrieval
    7. 8.7Build a basic document Q&A system
    8. 8.8Context injection and source citations
  9. 9Function calling and agents9
    1. 9.1What is function calling?
    2. 9.2Tool definitions and JSON schemas
    3. 9.3Calling external tools
    4. 9.4Tool execution loops
    5. 9.5Search, calculator and other tools
    6. 9.6Multi-step reasoning and planning
    7. 9.7Agent architecture
    8. 9.8Safety restrictions and tool permissions
    9. 9.9Build a basic tool-using AI agent
  10. 10Fine-tuning and training8
    1. 10.1Pretraining vs fine-tuning
    2. 10.2Dataset collection and cleaning
    3. 10.3Instruction datasets
    4. 10.4Fine-tuning concepts
    5. 10.5LoRA and QLoRA
    6. 10.6GPU and VRAM requirements
    7. 10.7Training costs and realistic hardware requirements
    8. 10.8Model evaluation and benchmarking
  11. 11Deployment and production9
    1. 11.1Model inference
    2. 11.2Quantization
    3. 11.3CPU vs GPU inference
    4. 11.4Running open-source LLMs locally
    5. 11.5Ollama and Hugging Face concepts
    6. 11.6API design
    7. 11.7Docker deployment
    8. 11.8Monitoring and logging
    9. 11.9Security, rate limiting and cost optimization
  12. 12Capstone project8
    1. 12.1Capstone overview and architecture
    2. 12.2The conversational UI
    3. 12.3Conversation history and system prompts
    4. 12.4Streaming output with Markdown and code
    5. 12.5Configurable model providers and error handling
    6. 12.6Document Q&A and memory
    7. 12.7Tool calling
    8. 12.8Testing, deployment and the capstone challenge

Lesson 2.1Module 2: Mathematics and foundations

Essential linear algebra

  • ⏱ 15 min read
  • Beginner

Learning objectives

  • Tell scalars, vectors, matrices and tensors apart by their number of axes and their shape.
  • See a vector both as a list of numbers and as an arrow, and add and scale vectors in both pictures.
  • Compute a dot product, a vector length (norm) and a cosine similarity by hand and in NumPy.
  • Explain why "similar meaning" becomes "similar direction" for word embeddings inside an LLM.
  • Use the transpose and read the shape of every array before you trust a result.

Every number a language model touches lives in an array. The token "cat" becomes a list of a few thousand numbers, a layer of the network is a grid of numbers, and a whole batch of sentences is a block of numbers with three or four axes. Linear algebra is simply the toolbox for working with such arrays: adding them, stretching them, comparing them and combining them. You don't need the whole subject to understand transformers. You need about five ideas, and this lesson covers the first three: what the objects are, how to measure them, and how to compare two of them.

We go slowly and concretely. Every idea appears first as a picture, then in words, then as an equation, then as a few lines of NumPy that you can run.

Analogy: directions on a treasure map

A vector is like an instruction on a treasure map: "walk 3 steps east and 2 steps north". You can write it as a list, [3, 2], or draw it as an arrow from where you stand. Two instructions that point roughly the same way take you to similar places, even if one is longer. LLMs store the "meaning" of each token as such an instruction, just in hundreds or thousands of directions instead of two. Words with related meanings end up as arrows pointing in similar directions, and measuring "how much do two arrows point the same way" is exactly what the dot product and cosine similarity do.

Scalars, vectors, matrices and tensors

All four are just arrays of numbers. What tells them apart is how many axes (directions you can index along) they have:

  • A scalar is a single number, such as a temperature setting of 0.7 or a learning rate. It has 0 axes.
  • A vector is a list of numbers, such as [0.2, -1.0, 0.5, 0.3]. It has 1 axis. Its length along that axis is its dimension: this one is a 4-dimensional vector.
  • A matrix is a rectangular grid with rows and columns. It has 2 axes. A matrix with 4 rows and 3 columns has shape (4, 3).
  • A tensor is the general word for an array with any number of axes. In practice people use it for 3 or more: a batch of 2 sentences, each 5 tokens long, each token a 4-number vector, is a tensor of shape (2, 5, 4).

NumPy calls the number of axes ndim and the size along each axis shape. Reading shapes is the most useful debugging habit in all of machine learning: when something goes wrong in model code, it is very often because an array has a shape you didn't expect. Real models are full of shapes like (batch, sequence_length, model_width); in a large model the last number can be several thousand.

0.7 scalar shape () vector shape (4,) matrix shape (4, 3) tensor shape (2, 5, 4)
Four kinds of array. The only difference is the number of axes. The tensor here is 2 sentences × 5 tokens × 4 numbers per token (two stacked grids).

A vector is a list and an arrow

Take the vector a = [3, 2]. As a list, it is two numbers. As an arrow, it starts at the origin, goes 3 units along the first axis and 2 units along the second. The two pictures are the same object, and you will switch between them all the time: the list is what the computer stores, the arrow is what helps you think.

a = [3, 2] b = [1, 3] a + b = [4, 5] 123412345
Adding vectors. As lists, add position by position: [3, 2] + [1, 3] = [4, 5]. As arrows, put b's tail on a's head (dashed); the sum is the arrow from the start to the end.

Two operations follow directly from the two pictures:

  • Addition: add matching positions. [3, 2] + [1, 3] = [4, 5]. As arrows, walk one instruction and then the other. Inside a transformer, adding vectors is everywhere: the token's meaning vector is added to a position vector (lesson 4.4), and every block adds its output back onto its input (the "residual connection" of lesson 4.8).
  • Scaling: multiply every position by one number. 2 × [3, 2] = [6, 4], the same direction but twice as long; -1 × [3, 2] points the opposite way.

Nothing changes when there are more than two numbers. You can't draw a 768-dimensional arrow, but the rules are identical: add position by position, scale every position. The maths was designed to work the same in any number of dimensions, which is why intuition from 2-D pictures carries over surprisingly well.

The dot product: how much two vectors agree

The single most important operation in this whole course is the dot product. Multiply the two vectors position by position, then add up the results. For a = [3, 2] and b = [1, 3]: 3×1 + 2×3 = 3 + 6 = 9. The answer is one number, a scalar.

a·b=∑i=1naibi=a1b1+a2b2+⋯+anbn

In words: walk along both vectors together, multiply each pair of matching numbers, and add all the products into one total. The big ∑ ("sigma") just means "add up, for i from 1 to n".

Why is this useful? Think of each position as a feature. Suppose position 1 means "is an animal" and position 2 means "is a vehicle". The dot product rewards positions where both vectors are large and positive (they agree), punishes positions where one is positive and the other negative (they disagree), and ignores positions where either is near zero (one of them doesn't care). So a big positive dot product means "these two point the same way", around zero means "unrelated", and a big negative one means "opposites".

In self-attention, every token computes the dot product of its "query" vector with every other token's "key" vector to decide how much attention to pay to it. Every neuron in a network computes a dot product of its inputs with its weights. When people say a GPU is "fast at AI", they mostly mean it is fast at doing billions of dot products in parallel.

Length (norm) and cosine similarity

The dot product mixes two things: whether the vectors point the same way, and how long they are. Double one vector and the dot product doubles, even though the direction didn't change. To separate the two, we need the length of a vector, called its norm. By Pythagoras, the arrow [3, 2] has length √(3² + 2²) = √13 ≈ 3.606. Notice that this is the square root of the vector's dot product with itself.

‖a‖=∑i=1nai2=a·a

In words: square every number, add the squares, take the square root. It is Pythagoras' theorem, extended to any number of dimensions.

Divide the dot product by both lengths and the size drops out, leaving only the direction. That number is the cosine similarity. It is always between -1 and 1: 1 means "exactly the same direction", 0 means "at right angles, unrelated", -1 means "exactly opposite".

cosθ=a·b‖a‖‖b‖

In words: the cosine of the angle θ between two arrows equals their dot product divided by the product of their lengths. Same direction gives 1, a right angle gives 0, opposite directions give -1.

For our example: cos θ = 9 / (3.606 × 3.162) ≈ 0.789, an angle of about 38°. Try it in the demo below: change the angles and lengths and watch which numbers move. Notice that making an arrow longer changes the dot product but leaves the cosine alone.

Dot product and cosine explorerInteractive

Why LLMs care: meaning as direction

An LLM turns every token into a vector called an embedding (you met these in lesson 1.6). Nobody writes these vectors by hand. They start as random numbers and are adjusted during training until tokens used in similar contexts end up pointing in similar directions. After training, "cat" and "kitten" have a high cosine similarity, "cat" and "carburettor" a low one. Search systems use the same trick: embed a question and a pile of documents, then return the documents whose vectors have the highest cosine similarity with the question. You build exactly that in module 8.

Real embeddings have hundreds to thousands of dimensions, and the individual positions usually don't have tidy human meanings like "is an animal". Our toy example below uses 3 hand-made numbers per word so you can follow every calculation.

The transpose

One more operation is used constantly: the transpose, written AT, which flips a matrix over its diagonal so rows become columns. A (4, 3) matrix becomes (3, 4), and the number in row 1, column 2 moves to row 2, column 1. You'll see it in attention (QKT) and in backpropagation, where gradients flow through a layer by multiplying with the transposed weights. In NumPy it is just .T.

The same ideas in NumPy

# @run
# Lesson 2.1: scalars, vectors, matrices and tensors; dot product, norm, cosine similarity, transpose.
import numpy as np

# 1. Four kinds of array, told apart by their number of axes (ndim) and their shape
temperature = np.array(0.7)                          # scalar: 0 axes
embedding = np.array([0.2, -1.0, 0.5, 0.3])          # vector: 1 axis of length 4
weights = np.arange(12.0).reshape(4, 3)              # matrix: 4 rows x 3 columns
batch = np.zeros((2, 5, 4))                          # tensor: 2 sentences x 5 tokens x 4 numbers
for name, t in [("scalar", temperature), ("vector", embedding), ("matrix", weights), ("tensor", batch)]:
    print(f"{name:7s} ndim={t.ndim}  shape={t.shape}  size={t.size}")

# 2. Toy 3-D "word embeddings" (hand-made, real ones have hundreds or thousands of numbers)
words = {
    "cat":    np.array([0.9, 0.8, 0.1]),
    "kitten": np.array([0.8, 0.9, 0.2]),
    "car":    np.array([0.1, 0.2, 0.9]),
}

def norm(v):
    return np.sqrt(np.sum(v * v))                    # length of the arrow (same as np.linalg.norm)

def cosine(a, b):
    return np.dot(a, b) / (norm(a) * norm(b))        # dot product of the two directions only

print()
cat, kitten, car = words["cat"], words["kitten"], words["car"]
print(f"dot(cat, kitten)  = {np.dot(cat, kitten):.3f}")
print(f"dot(cat, car)     = {np.dot(cat, car):.3f}")
print(f"|cat| = {norm(cat):.3f}   np.linalg.norm agrees: {bool(np.isclose(norm(cat), np.linalg.norm(cat)))}")
for a, b in [("cat", "kitten"), ("cat", "car"), ("kitten", "car")]:
    c = cosine(words[a], words[b])
    angle = np.degrees(np.arccos(np.clip(c, -1.0, 1.0)))
    print(f"cosine({a}, {b}) = {c:.3f}  angle = {angle:5.1f} degrees")

# 3. Scaling a vector changes its length and its dot products, but not its cosine
big_cat = 10 * cat
print()
print(f"dot(10*cat, kitten) = {np.dot(big_cat, kitten):.3f}  cosine = {cosine(big_cat, kitten):.3f}")

# 4. Transpose swaps rows and columns
print()
print("weights shape:", weights.shape, "-> weights.T shape:", weights.T.shape)
print("row 1 of weights:     ", weights[1])
print("column 1 of weights.T:", weights.T[:, 1])
  1. np.array(0.7), np.array([...]), np.arange(12.0).reshape(4, 3), np.zeros((2, 5, 4)): build one array of each kind. reshape rearranges the 12 numbers 0 to 11 into 4 rows of 3 without copying them.
  2. t.ndim, t.shape, t.size: the number of axes, the size along each axis, and the total count of numbers (the product of the shape).
  3. words = {...}: three hand-made 3-D "embeddings". The first two numbers are large for the two cat words; the third is large for "car".
  4. norm(v): square each number (v * v multiplies element by element), sum, square-root. The line after checks it against NumPy's built-in np.linalg.norm.
  5. cosine(a, b): the dot product divided by both lengths, exactly the equation above.
  6. np.arccos(np.clip(c, -1.0, 1.0)): turns the cosine back into an angle. clip protects against values like 1.0000000002 that rounding can produce and that arccos would reject.
  7. big_cat = 10 * cat: scaling multiplies the dot product by 10 (1.460 becomes 14.600) but leaves the cosine at 0.990. Direction, not size, is what cosine measures.
  8. weights.T: the transpose; row 1 of the matrix is column 1 of its transpose.
scalar  ndim=0  shape=()  size=1
vector  ndim=1  shape=(4,)  size=4
matrix  ndim=2  shape=(4, 3)  size=12
tensor  ndim=3  shape=(2, 5, 4)  size=40

dot(cat, kitten)  = 1.460
dot(cat, car)     = 0.340
|cat| = 1.208   np.linalg.norm agrees: True
cosine(cat, kitten) = 0.990  angle =   8.2 degrees
cosine(cat, car) = 0.303  angle =  72.3 degrees
cosine(kitten, car) = 0.389  angle =  67.1 degrees

dot(10*cat, kitten) = 14.600  cosine = 0.990

weights shape: (4, 3) -> weights.T shape: (3, 4)
row 1 of weights:      [3. 4. 5.]
column 1 of weights.T: [3. 4. 5.]

"cat" and "kitten" are 8° apart (cosine 0.990): nearly the same direction. "cat" and "car" are 72° apart (cosine 0.303). That ordering is what a trained embedding model gives you for real words, just with far more numbers.

Why the dot product equals |a| |b| cos θ, and what happens in high dimensions

The geometric identity. The law of cosines says that for a triangle with sides of length |a|, |b| and |a − b|, the third side satisfies |a − b|² = |a|² + |b|² − 2|a||b| cos θ. Expand the left side with the dot product instead: (a − b)·(a − b) = a·a − 2 a·b + b·b = |a|² + |b|² − 2 a·b. Comparing the two expressions gives a·b = |a||b| cos θ. So the "multiply and add" recipe and the "lengths and angle" picture are the same thing, in any number of dimensions.

High-dimensional surprises. Pick two random vectors with 1,000 independent random numbers each. Their cosine is almost always very close to 0: in high dimensions, random directions are nearly at right angles. That is good news for embeddings, because there is room for a huge number of almost-unrelated directions, and it is why a cosine of, say, 0.3 between two real embeddings can already mean "clearly related".

Why attention divides by √d. If the entries of two vectors are independent with mean 0 and variance 1, their dot product has variance d (the sum of d products, each with variance 1). With d = 128 the dot products are typically around ±11, large enough to push softmax (lesson 2.4) into extreme, almost one-hot outputs with tiny gradients. Transformers therefore divide by √d to bring the typical size back to about 1. You will see this "scaled dot-product attention" in lesson 4.5.

Normalised vectors. If every vector is first divided by its own length (made a unit vector), the dot product is the cosine. Vector databases often store unit vectors for exactly this reason: a plain dot product is cheaper than a cosine.

Common mistakes and debugging tips

Using * when you meant a dot product

In NumPy, a * b multiplies element by element and returns a vector; np.dot(a, b) or a @ b also adds the products and returns one number. Mixing them up gives a result of the wrong shape, which may only crash several lines later.

Fix: print the shape of results while learning. A dot product of two vectors has shape ().

Comparing raw dot products of vectors with different lengths

A long vector gets large dot products with everything, so ranking documents by raw dot product can favour whichever vectors happen to be longest rather than most similar.

Fix: use cosine similarity, or normalise every vector to length 1 first (then the dot product equals the cosine).

Confusing dimension with number of axes

"A 768-dimensional embedding" is a vector: one axis of length 768. It is not a 768-axis tensor. Mixing the two words leads to wrong reshapes.

Fix: say "shape (768,)" instead of "768-dimensional" whenever there's room for doubt.

arccos returns nan

Floating-point rounding can make a cosine slightly bigger than 1 (for example 1.0000000000000002), and arccos is undefined there.

Fix: clip to the valid range first: np.arccos(np.clip(c, -1, 1)).

Key takeaways

  • Scalars, vectors, matrices and tensors are arrays with 0, 1, 2 and 3+ axes; always know the shape.
  • A vector is both a list of numbers and an arrow. Addition and scaling work position by position.
  • The dot product (multiply and add) measures agreement; the norm measures length; cosine similarity measures direction only.
  • Embeddings place related tokens in similar directions, so cosine similarity measures relatedness.

Exercise: nearest neighbour by cosine

Add a fourth word, "truck": [0.2, 0.1, 0.95], to the dictionary in vectors.py. Write a function most_similar(word) that returns the other word with the highest cosine similarity to it. First predict by hand (no code) which word is closest to "truck", then check with your function for every word.

Hint

Loop over words.items(), skip the word itself, compute cosine(words[word], vec), and keep the best. Python's max(..., key=...) can do the "keep the best" part in one line.

Show a solution
words["truck"] = np.array([0.2, 0.1, 0.95])

def most_similar(word):
    others = [w for w in words if w != word]
    return max(others, key=lambda w: cosine(words[word], words[w]))

for w in words:
    print(w, "->", most_similar(w))
cat -> kitten
kitten -> cat
car -> truck
truck -> car

"truck" points almost entirely along the third axis, like "car", so their cosine is about 0.99. The cat words stay each other's nearest neighbours.

Check your understanding

A batch holds 8 sentences of 16 tokens, each token a 512-number vector. What is its shape?

  1. (512, 16, 8)
  2. (8, 16, 512)
  3. (8 × 16 × 512,)
By convention the batch axis comes first, then the sequence position, then the features of each token: (8, 16, 512). Option 1 reverses the order; option 3 is the same numbers flattened into one long vector, which loses the structure.

You multiply vector a by 5. What happens to its cosine similarity with b?

  1. It is multiplied by 5
  2. It is multiplied by 25
  3. It stays the same
Scaling changes the length but not the direction, and cosine divides the length out. The dot product, however, is multiplied by 5 (option 1 describes the dot product, not the cosine).

What is the dot product of [1, 2, 3] and [4, 0, -1]?

  1. 1
  2. 5
  3. [4, 0, -3]
1×4 + 2×0 + 3×(-1) = 4 + 0 − 3 = 1. Option 3 is the element-wise product (a * b) before the adding step; a dot product is always a single number.

Lesson 2.2Module 2: Mathematics and foundations

Vectors, matrices and matrix multiplication

  • ⏱ 16 min read
  • Beginner

Learning objectives

  • Multiply a matrix by a vector and a matrix by a matrix, by hand, as a set of dot products.
  • Apply the shape rule (m, n) @ (n, p) → (m, p) and predict the shape of any product before running it.
  • See a matrix as a function that moves points, and explain why the order of multiplication matters.
  • Write a neural-network layer as X @ W + b, including broadcasting the bias over a batch.
  • Tell @ (matrix multiplication) from * (element-wise) in NumPy.

If the dot product is the most important operation in deep learning, matrix multiplication is the second, and it is really just a big organised pile of dot products. Nearly all the arithmetic inside a transformer, and therefore nearly all the time and money spent training and running one, goes into multiplying matrices. In this lesson you will compute a product by hand, learn the one shape rule that prevents most bugs, and see why a neural-network layer is a single line of NumPy.

Analogy: a recipe card for a café

A café sells three drinks and each needs some amount of milk, coffee and sugar. Write that as a table: one row per drink, one column per ingredient. If today's orders are "2 lattes, 1 mocha, 3 espressos", working out how much milk to buy means taking the order list and the milk column, multiplying matching entries and adding: a dot product. Doing it for every ingredient at once is a vector times a matrix. Doing it for every day of the week at once (one row of orders per day) is a matrix times a matrix. A neural-network layer is the same calculation, with "orders" replaced by input features and "ingredients" replaced by output features.

A matrix times a vector: many dot products at once

Write the café data as a matrix R with 3 rows (latte, mocha, espresso) and 2 columns (milk in dl, coffee shots):

R=[211.5102],o=[213]

In words: R holds the recipe (rows are drinks, columns are milk and coffee); o holds today's orders (2 lattes, 1 mocha, 3 espressos).

Total milk = 2×2 + 1×1.5 + 3×0 = 5.5 dl. Total coffee = 2×1 + 1×1 + 3×2 = 9 shots. Each answer is the dot product of the orders with one column, and the result [5.5, 9] is the product o @ R. The shapes tell the story: a vector of 3 orders times a (3, 2) table gives 2 totals.

The same thing is true in general: multiplying by a matrix turns a vector with n numbers into a vector with p numbers, and each output number is a dot product of the input with one column. So a matrix is a machine that computes p different weighted sums of its input at once. That is exactly what a layer of neurons is: p neurons, each with its own column of weights.

Matrix times matrix: rows meet columns

Now do it for several order lists at once by stacking them as rows of a matrix. The product C = A @ B is defined cell by cell: the entry in row i, column j of C is the dot product of row i of A with column j of B.

Cij=∑k=1nAikBkj

In words: to fill the cell in row i and column j of the result, walk along row i of A and down column j of B at the same time, multiply the pairs and add them up. The shared index k runs over the inner dimension n.

Step through it below. Each click fills one cell of the result and shows the dot product that produced it. Try "Shuffle" to get new numbers and predict a cell before you reveal it.

Matrix multiplication, one cell at a timeInteractive

The shape rule

A dot product needs two vectors of the same length. So for A @ B to work, each row of A must be as long as each column of B: the number of columns of A must equal the number of rows of B. Write the shapes side by side and the rule is easy to see:

(m,n) @ (n,p) → (m,p) inner sizes must match, then vanish outer sizes give the result
The shape rule. Inner sizes must be equal; the result keeps the outer sizes. (3, 4) @ (4, 2) → (3, 2) works; (4, 2) @ (3, 4) fails because 2 ≠ 3.

Before you run any matrix code, write down the shapes and apply this rule. It takes five seconds and catches most bugs. The amount of work also follows from the shapes: the result has m × p cells, and each needs n multiply-adds, so a product costs m × n × p multiply-adds. Doubling the width of a layer (both n and p) makes it about four times as expensive, which is a big part of why bigger models cost so much more to run.

A matrix is a function that moves points

There is a second, geometric way to see a matrix: it is a function that takes a vector (a point) and returns another vector (the moved point). A 2×2 matrix can rotate, stretch, squash, flip or shear the plane. For example the matrix with rows [0, -1] and [1, 0] rotates every point 90° anticlockwise, and the matrix with rows [2, 0] and [0, 1] stretches the horizontal direction by 2.

Applying one matrix and then another is the same as applying their product once. That's why matrix multiplication is defined the odd row-times-column way: it is exactly "compose the two functions". It also explains why order matters: "rotate then stretch" is not the same as "stretch then rotate", just as "put on socks, then shoes" is not "shoes, then socks". In general A @ B ≠ B @ A, and the code below shows a concrete case.

A layer of a neural network is such a function from one space of features to another. Its weights decide how the input is rotated, stretched and mixed. Stacking layers composes these functions, and the non-linear "activation" between them (lesson 2.5) lets the stack bend space in ways a single matrix cannot.

A layer is X @ W + b

Put a batch of inputs into the rows of a matrix X of shape (batch, n_in). Put the weights of the layer into W of shape (n_in, n_out), one column per output neuron. Then X @ W has shape (batch, n_out): every input gets every neuron's weighted sum in a single operation. Add a bias vector b of shape (n_out,) and you have a linear layer (also called a dense or fully connected layer).

Y(batch,nout)=X(batch,nin)W(nin,nout)+b(nout)

In words: every row of X (one input) is multiplied by the weight matrix to give one row of outputs, and the same bias vector is added to every row.

Adding a (n_out,) vector to a (batch, n_out) matrix works because of broadcasting: NumPy lines up shapes from the right, and where one array is missing an axis (or has size 1 on it), it acts as if the array were repeated along that axis. Broadcasting is very handy and also a classic source of silent bugs; lesson 2.6 shows one that turns a 3-number result into a 3×3 matrix.

Inside a transformer, the token vectors of a whole sequence form the rows of X, and attention, the feed-forward network and the final "which token comes next" layer are all matrix multiplications of this kind (lesson 4.7).

Matrix multiplication three ways in NumPy

The file below multiplies a batch of 3 token vectors (4 features each) by a 4→2 layer with plain loops, with dot products, and with @, then shows the shape rule failing, matrices as transformations, broadcasting, and @ versus *.

# @run
# Lesson 2.2: matrix multiplication three ways (loops, dot products, @), shape rules, broadcasting, @ versus *.
import numpy as np

def matmul_loops(A, B):
    """Row-times-column with plain Python loops: out[i][j] = sum over k of A[i][k] * B[k][j]."""
    m, n = A.shape
    n2, p = B.shape
    if n != n2:
        raise ValueError(f"inner sizes differ: {A.shape} @ {B.shape}")
    out = np.zeros((m, p))
    for i in range(m):              # every row of A ...
        for j in range(p):          # ... meets every column of B
            total = 0.0
            for k in range(n):      # walk along the shared inner axis
                total += A[i, k] * B[k, j]
            out[i, j] = total
    return out

def matmul_dots(A, B):
    """Same thing, but each output cell is one dot product (row i of A with column j of B)."""
    return np.array([[np.dot(A[i, :], B[:, j]) for j in range(B.shape[1])] for i in range(A.shape[0])])

# A "batch" of 3 token vectors with 4 features each, and a layer that maps 4 features to 2
X = np.array([[1.0, 2.0, 0.0, -1.0],
              [0.5, 0.0, 1.0, 2.0],
              [-1.0, 1.0, 1.0, 0.0]])
W = np.array([[0.2, -0.5],
              [0.1, 0.3],
              [-0.4, 0.8],
              [0.6, 0.3]])

Y_loops = matmul_loops(X, W)
Y_dots = matmul_dots(X, W)
Y = X @ W
print("X", X.shape, "@ W", W.shape, "->", Y.shape)
print(np.round(Y, 3))
print("loops == @:", bool(np.allclose(Y_loops, Y)), "  dots == @:", bool(np.allclose(Y_dots, Y)))
print("multiply-adds needed: m*n*p =", X.shape[0] * X.shape[1] * W.shape[1])

# The shape rule: inner sizes must match
try:
    matmul_loops(W, X)              # (4, 2) @ (3, 4): inner sizes 2 and 3 differ
except ValueError as e:
    print("error:", e)

# A bigger random check (fixed seed, so the result is always the same)
rng = np.random.default_rng(0)
A = rng.normal(size=(30, 20))
B = rng.normal(size=(20, 10))
print("random (30,20) @ (20,10): loops == @ ->", bool(np.allclose(matmul_loops(A, B), A @ B)))

# A matrix is a function that moves points: rotate by 90 degrees, then stretch x by 2
rotate = np.array([[0.0, -1.0],
                   [1.0, 0.0]])
stretch = np.array([[2.0, 0.0],
                    [0.0, 1.0]])
point = np.array([1.0, 1.0])
print()
print("rotate @ p             =", rotate @ point)
print("stretch @ (rotate @ p) =", stretch @ (rotate @ point))
print("(stretch @ rotate) @ p =", (stretch @ rotate) @ point, " (same: composing = multiplying)")
print("rotate @ stretch =", (rotate @ stretch).tolist(), " order matters")
print("stretch @ rotate =", (stretch @ rotate).tolist())

# Broadcasting: add one bias vector to every row of the batch
b = np.array([0.1, -0.2])
print()
print("Y", Y.shape, "+ b", b.shape, "->", (Y + b).shape)
print(np.round(Y + b, 3))

# @ is matrix multiplication; * multiplies element by element (and needs compatible shapes)
P = np.array([[1.0, 2.0], [3.0, 4.0]])
Q = np.array([[10.0, 20.0], [30.0, 40.0]])
print()
print("P @ Q =", (P @ Q).tolist())
print("P * Q =", (P * Q).tolist())
  1. matmul_loops(A, B): the definition, literally. The two outer loops visit every output cell (i, j); the inner loop walks along the shared axis k and accumulates A[i, k] * B[k, j]. It raises an error if the inner sizes differ.
  2. matmul_dots(A, B): the same, but each cell is one call to np.dot of a row (A[i, :]) and a column (B[:, j]).
  3. X and W: a batch of 3 inputs with 4 features, and a layer mapping 4 features to 2. Y = X @ W has shape (3, 2).
  4. np.allclose(...): compares floating-point arrays with a small tolerance. Never test floats with ==, because tiny rounding differences are normal.
  5. matmul_loops(W, X): (4, 2) @ (3, 4) breaks the shape rule, so our function raises the error and the except prints it.
  6. rotate, stretch: applying them one after the other equals applying stretch @ rotate once; swapping the order gives a different matrix.
  7. Y + b: broadcasting adds the bias to every row.
  8. P @ Q versus P * Q: matrix product versus element-by-element product. Same inputs, completely different answers.
X (3, 4) @ W (4, 2) -> (3, 2)
[[-0.2  -0.2 ]
 [ 0.9   1.15]
 [-0.5   1.6 ]]
loops == @: True   dots == @: True
multiply-adds needed: m*n*p = 24
error: inner sizes differ: (4, 2) @ (3, 4)
random (30,20) @ (20,10): loops == @ -> True

rotate @ p             = [-1.  1.]
stretch @ (rotate @ p) = [-2.  1.]
(stretch @ rotate) @ p = [-2.  1.]  (same: composing = multiplying)
rotate @ stretch = [[0.0, -1.0], [2.0, 0.0]]  order matters
stretch @ rotate = [[0.0, -2.0], [1.0, 0.0]]

Y (3, 2) + b (2,) -> (3, 2)
[[-0.1  -0.4 ]
 [ 1.    0.95]
 [-0.4   1.4 ]]

P @ Q = [[70.0, 100.0], [150.0, 220.0]]
P * Q = [[10.0, 40.0], [90.0, 160.0]]

Notice "multiply-adds needed: m*n*p = 24" for a tiny (3, 4) @ (4, 2). A single layer of a large model multiplies matrices with thousands of rows and columns for every token, which is why the hardware that runs LLMs is built around fast matrix multiplication.

Why matrix multiplication dominates the cost of LLMs

Counting FLOPs. Hardware speed is quoted in floating-point operations per second (FLOP/s). A multiply-add counts as 2 operations, so (m, n) @ (n, p) costs about 2mnp FLOPs. A linear layer with weight matrix (n, p) applied to one token therefore costs about 2 FLOPs per weight. That gives the widely used rule of thumb that running a model costs about 2 × (number of parameters) FLOPs per token, and training costs roughly 3 times that again (forward pass plus a backward pass that is about twice as expensive). These are approximations for dense transformers in general, not figures for any particular model.

Why GPUs. Every cell of a matrix product can be computed independently of the others, so the work can be split across thousands of small arithmetic units. GPUs and other AI accelerators include specialised matrix units that multiply small tiles of matrices in a single instruction, and the speed of moving numbers from memory to those units is often the real limit. NumPy's @ calls an optimised BLAS library on your CPU; our loop version is thousands of times slower for large matrices, which is why you should never write the loops in real code.

Parameters live in matrices. A layer from 4,096 features to 4,096 features has a 4,096 × 4,096 matrix: about 16.8 million weights. Transformers have many such matrices per block and many blocks, which is how parameter counts reach the billions. When people talk about a model's "size", they mostly mean the total number of entries in these matrices.

Associativity. Order matters, but grouping doesn't: (A @ B) @ C equals A @ (B @ C). The cost can differ hugely, though. With shapes (1000, 1000), (1000, 1000) and (1000, 1), the left grouping costs about 10⁹ multiply-adds and the right about 2 × 10⁶. Libraries for chained products pick the cheap order for you.

Common mistakes and debugging tips

"shapes not aligned" or "matmul: Input operand 1 has a mismatch"

The inner sizes differ. Usually a matrix should have been transposed, or the operands are in the wrong order (W @ X instead of X @ W).

Fix: print both shapes, write them as (m, n) @ (n, p), and decide which one needs .T or swapping. Don't transpose at random until it runs: it may run and be wrong.

Assuming A @ B == B @ A

Matrix multiplication is not commutative. Even when both orders are allowed (square matrices), they usually give different results, as the rotate/stretch example shows.

Fix: follow the data: the input comes first in the X @ W convention used in this course and in most NumPy and PyTorch code.

Using * for a matrix product

* multiplies element by element. For two (2, 2) matrices both * and @ run without error, so the bug is silent.

Fix: use @ (or np.matmul) for matrix products, and check a tiny case by hand.

Broadcasting a bias along the wrong axis

A bias of shape (batch,) instead of (n_out,) either errors or, if batch happens to equal n_out, silently adds the wrong numbers.

Fix: the bias has one number per output feature: shape (n_out,). Test with a batch size different from the output size so mistakes surface.

Key takeaways

  • Each cell of A @ B is the dot product of a row of A with a column of B.
  • Shape rule: (m, n) @ (n, p) → (m, p); the cost is m·n·p multiply-adds.
  • A matrix is a function that moves points; multiplying matrices composes those functions, so order matters.
  • A linear layer on a batch is X @ W + b, with the bias broadcast over the rows.

Exercise: shapes of a tiny transformer step

A batch of 2 sentences, each 5 tokens, each token a vector of 8 numbers, is stored in X with shape (2, 5, 8). (a) A weight matrix Wq has shape (8, 4). What is the shape of Q = X @ Wq? (b) How many multiply-adds does it take? (c) K has the same shape as Q. What shape do you get from Q @ K.transpose(0, 2, 1), and what could each number mean? Then check (a) and (c) in NumPy with arrays of zeros.

Hint

With more than two axes, @ treats the leading axes as a batch and multiplies the last two axes as matrices. transpose(0, 2, 1) swaps the last two axes of each sentence.

Show a solution

(a) Each sentence is a (5, 8) matrix; (5, 8) @ (8, 4) → (5, 4), so Q is (2, 5, 4). (b) 2 sentences × 5 × 8 × 4 = 320 multiply-adds. (c) For each sentence, (5, 4) @ (4, 5) → (5, 5), so the result is (2, 5, 5): one dot product for every pair of tokens in a sentence. Those are the raw attention scores, how much each token "matches" each other token (lesson 4.6).

import numpy as np
X = np.zeros((2, 5, 8))
Wq = np.zeros((8, 4))
Q = X @ Wq
K = Q.copy()
print(Q.shape, (Q @ K.transpose(0, 2, 1)).shape)
(2, 5, 4) (2, 5, 5)

Check your understanding

Which product is allowed, and what is its shape?

  1. (3, 4) @ (3, 4) → (3, 4)
  2. (5, 2) @ (5, 2) → (2, 2)
  3. (6, 3) @ (3, 7) → (6, 7)
The inner sizes must match: 3 and 3 in option 3, giving the outer sizes (6, 7). In options 1 and 2 the inner sizes (4 and 3, 2 and 5) differ; option 2 would work only as A.T @ A.

A layer maps 512 features to 2,048 features. How many weights are in its matrix (ignoring the bias)?

  1. 1,048,576
  2. 2,560
  3. 2,048
The matrix has shape (512, 2048), so it holds 512 × 2,048 = 1,048,576 weights. 2,560 is the sum of the sizes, and 2,048 is the size of the bias vector.

For two (2, 2) NumPy arrays P and Q, what does P * Q compute?

  1. The matrix product
  2. The element-wise product
  3. The dot product of the flattened arrays
* multiplies matching positions; the matrix product is P @ Q. Neither operator flattens the arrays.

Lesson 2.3Module 2: Mathematics and foundations

Probability and statistics

  • ⏱ 15 min read
  • Beginner

Learning objectives

  • Describe a probability distribution over a vocabulary and check that it is valid.
  • Sample from a distribution with a seeded random generator and explain why samples wobble around the true probabilities.
  • Compute an expectation, a variance and a standard deviation.
  • Use conditional probability and the chain rule to score a whole sentence, and explain why we add log-probabilities.
  • Standardise data to mean 0 and standard deviation 1.

A language model never "knows" the next word. At every step it produces a probability distribution: a number for every token in its vocabulary saying how likely that token is to come next. Then the application samples one token from that distribution, appends it, and asks again. Training is about making those probabilities good, and generation is about sampling from them well. So probability is not a side topic for LLMs; it is the language they speak. This lesson covers the handful of ideas you need, each tied to something a model actually does.

Analogy: a weighted spinner

Picture a board-game spinner divided into slices of different sizes: "the" gets 40% of the circle, "cat" 25%, "sat" 15%, and so on. The slices must cover the whole circle exactly, no more and no less: that's why probabilities add up to 1. Spinning once gives one word; spinning a thousand times gives each word roughly in proportion to its slice. A language model builds a fresh spinner for every next token, based on everything written so far, and generating text is spinning it again and again.

Probability distributions

A probability is a number between 0 (impossible) and 1 (certain). A distribution assigns a probability to every possible outcome, and the probabilities of all outcomes add up to exactly 1. For a vocabulary of 5 words, a valid next-word distribution might be:

TokenthecatsatonmatTotal
P(token)0.400.250.150.120.081.00
0≤P(x)≤1and∑xP(x)=1

In words: every outcome gets a probability between 0 and 1, and adding the probabilities of all possible outcomes gives exactly 1.

A real model's vocabulary has tens of thousands to a few hundred thousand tokens, so its distribution has that many entries, most of them tiny. The raw outputs of the network (called logits) are arbitrary real numbers, not probabilities; a function called softmax turns them into a valid distribution. That's the topic of lesson 2.4.

Sampling, randomness and seeds

To sample means to pick one outcome at random with the given probabilities. A simple method: draw a random number u between 0 and 1, then walk through the outcomes adding up their probabilities until the running total passes u. With the table above, u = 0.3 lands in "the" (0 to 0.40), u = 0.5 lands in "cat" (0.40 to 0.65), and so on. Bigger slices catch more random numbers.

Computers produce "random" numbers with a pseudo-random generator: a deterministic formula that produces a sequence that looks random. Start it from the same seed and you get the same sequence every time. We use fixed seeds in every course file (np.random.default_rng(0)) so that your output matches ours exactly; in a chatbot you'd normally let the seed vary so answers differ.

Draw only a few samples and the counts are lumpy; draw many and the fraction of each outcome settles close to its true probability. This is the law of large numbers, and you can watch it happen below.

Sample the next tokenInteractive

true probability fraction of samples so far

The demo uses its own small random generator in JavaScript, so its numbers won't match the Python file below; the behaviour is the same.

Expectation, variance and standard deviation

Sometimes the outcomes are numbers, or we attach a number to each outcome. Then we can ask for the average we'd expect over many samples: the expectation (or expected value, or mean). It is a weighted average, with the probabilities as weights.

E[X]=∑xP(x)xVar[X]=E[(X−E[X])2]

In words: the expectation multiplies each possible value by its probability and adds them up. The variance is the expected squared distance from that mean; it measures how spread out the values are. The standard deviation is the square root of the variance, which puts the spread back in the original units.

Example: let X be the number of letters in the sampled word. "on" has 2 letters, the others 3. E[X] = 0.40×3 + 0.25×3 + 0.15×3 + 0.12×2 + 0.08×3 = 2.88. The variance is small (0.1056) because almost every outcome is 3. In deep learning, the mean and variance appear constantly: weights are initialised with a chosen variance so signals neither explode nor vanish (module 3), and layer normalisation rescales each token vector to mean 0 and variance 1 (lesson 4.8).

Conditional probability and the chain rule

Probabilities change when you know something. The probability that the next word is "mat" is small in general, but much larger if the previous word is "the" and the sentence is about a cat sitting. This is conditional probability, written P(A∣B), "the probability of A given B".

P(A∣B)=P(A,B)P(B)

In words: among all the situations where B happens, what fraction also have A? Divide the probability of both happening by the probability of B.

With counts from text it is very concrete. In the tiny corpus "the cat sat on the mat the cat ran on the rug", the word "the" is followed by: cat, mat, cat, rug. So P(cat | the) = 2/4 = 0.5, P(mat | the) = 1/4 and P(rug | the) = 1/4. A model built only from such counts is a bigram model; you saw one in lesson 1.2 and build a proper tokenizer and dataset for a neural one in module 5.

Rearranging the definition gives P(A, B) = P(B) × P(A | B), and applying that repeatedly gives the chain rule of probability. It is the foundation of every GPT-style model: the probability of a whole sequence is the product of "next token given everything before it".

P(w1,…,wT)=∏t=1TP(wt∣w1,…,wt−1)

In words: the probability of a whole text is the probability of the first token, times the probability of the second given the first, times the probability of the third given the first two, and so on. The big ∏ ("pi") means "multiply together".

This one equation explains why a language model only needs to learn one thing, "predict the next token given the previous ones", to be able to score or generate any text.

Why we use log-probabilities

Multiplying hundreds of probabilities together causes a practical problem. If a 400-token answer gives each token probability 0.01, the product is 10⁻⁸⁰⁰, far smaller than the smallest number a 64-bit float can hold (about 10⁻³⁰⁸). The computer rounds it to exactly 0 (underflow), and every long text looks equally impossible.

The fix is to work with logarithms. The log of a product is the sum of the logs, so instead of multiplying tiny numbers we add moderate negative numbers: log(0.01) ≈ −4.6, and 400 of them add up to about −1,842, which is easy to store. The logarithm keeps the order (a larger probability always has a larger log), so nothing is lost. That's why model code is full of log_softmax, why training losses are written as negative log-probabilities, and why APIs that expose token probabilities usually return "logprobs".

log∏t=1Tpt=∑t=1Tlogpt

In words: the log of a product of probabilities equals the sum of their logs, which turns an underflowing product into a well-behaved sum.

Standardising data

One last statistics tool: to standardise a list of numbers, subtract the mean and divide by the standard deviation. The result (a "z-score") has mean 0 and standard deviation 1, and each value now says "how many standard deviations above or below average". Networks train much more smoothly when their inputs and internal signals are on such a common scale, and normalisation layers do this inside every transformer block.

All of it in NumPy

# @run
# Lesson 2.3: a probability distribution over a tiny vocabulary, sampling with a fixed seed,
# expectation and variance, log-probabilities, conditional probability and normalisation.
import numpy as np

vocab = ["the", "cat", "sat", "on", "mat"]
probs = np.array([0.40, 0.25, 0.15, 0.12, 0.08])     # a "next token" distribution
print(f"probabilities sum to {probs.sum():.2f}")

# 1. Sampling: draw 10,000 tokens and compare how often each appears with its true probability
rng = np.random.default_rng(0)                      # fixed seed: the same "random" draws every run
for n in (100, 10_000):
    draws = rng.choice(len(vocab), size=n, p=probs)  # indices 0..4
    counts = np.bincount(draws, minlength=len(vocab))
    print(f"\n{n} samples")
    print("token  true   empirical")
    for tok, p, c in zip(vocab, probs, counts):
        print(f"{tok:5s}  {p:.3f}  {c / n:.3f}")

# 2. Expectation and variance of a random variable: the number of letters in the sampled word
lengths = np.array([len(w) for w in vocab], dtype=float)   # [3, 3, 3, 2, 3]
mean = np.sum(probs * lengths)                              # E[X] = sum of p(x) * x
var = np.sum(probs * (lengths - mean) ** 2)                 # Var[X] = E[(X - E[X])^2]
print(f"\nE[length] = {mean:.3f}   Var[length] = {var:.4f}   std = {np.sqrt(var):.4f}")

# 3. Why we add log-probabilities instead of multiplying probabilities
p_tokens = np.full(400, 0.01)               # 400 tokens, each predicted with probability 0.01
print(f"\nproduct of 400 probabilities: {np.prod(p_tokens)}")        # underflows to 0.0
log_total = np.sum(np.log(p_tokens))
print(f"sum of their logs:            {log_total:.2f}")
print(f"average log-prob per token:   {log_total / 400:.4f}")

# 4. Conditional probability from counts: P(next | previous) in a tiny corpus
corpus = "the cat sat on the mat the cat ran on the rug".split()
pairs = list(zip(corpus[:-1], corpus[1:]))
after_the = [nxt for prev, nxt in pairs if prev == "the"]
print(f"\nwords after 'the': {after_the}")
for w in sorted(set(after_the)):
    print(f"P({w:3s} | the) = {after_the.count(w)}/{len(after_the)} = {after_the.count(w) / len(after_the):.2f}")

# 5. Normalisation: shift to mean 0 and scale to standard deviation 1
x = np.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
z = (x - x.mean()) / x.std()
print(f"\nx: mean = {x.mean():.2f}, std = {x.std():.2f}")
print("z:", np.round(z, 2))
print(f"z: mean = {abs(z.mean()):.2f}, std = {z.std():.2f}")
  1. probs = np.array([...]): the next-token distribution from the table. The first print confirms it sums to 1.
  2. rng = np.random.default_rng(0): a generator with seed 0, so every run draws the same "random" tokens.
  3. rng.choice(len(vocab), size=n, p=probs): draws n token indices with the given probabilities.
  4. np.bincount(draws, minlength=5): counts how often each index 0 to 4 was drawn; dividing by n gives the empirical fraction.
  5. np.sum(probs * lengths): the expectation, a probability-weighted sum. The variance line is the same with squared distances from the mean.
  6. np.prod(p_tokens): 400 probabilities of 0.01 multiplied together underflow to exactly 0.0. np.sum(np.log(p_tokens)) gives the usable answer −1842.07.
  7. pairs = list(zip(corpus[:-1], corpus[1:])): every (previous word, next word) pair; filtering on prev == "the" and counting gives the conditional probabilities.
  8. (x - x.mean()) / x.std(): standardisation; the last line confirms mean 0 and standard deviation 1.
probabilities sum to 1.00

100 samples
token  true   empirical
the    0.400  0.340
cat    0.250  0.240
sat    0.150  0.150
on     0.120  0.120
mat    0.080  0.150

10000 samples
token  true   empirical
the    0.400  0.400
cat    0.250  0.247
sat    0.150  0.152
on     0.120  0.125
mat    0.080  0.077

E[length] = 2.880   Var[length] = 0.1056   std = 0.3250

product of 400 probabilities: 0.0
sum of their logs:            -1842.07
average log-prob per token:   -4.6052

words after 'the': ['cat', 'mat', 'cat', 'rug']
P(cat | the) = 2/4 = 0.50
P(mat | the) = 1/4 = 0.25
P(rug | the) = 1/4 = 0.25

x: mean = 5.00, std = 2.00
z: [-1.5 -0.5 -0.5 -0.5  0.   0.   1.   2. ]
z: mean = 0.00, std = 1.00

With 100 samples "mat" came up 15% of the time although its true probability is 8%: small samples wobble. With 10,000 samples every fraction is within about half a percentage point. When you see a chatbot give a strange answer once, remember that it is one spin of the spinner.

Entropy, perplexity and the maximum-likelihood view of training

Surprise. The quantity −log P(x) is called the surprise (or information content) of an outcome: certain events (P = 1) have surprise 0, rare events have a large surprise. The entropy of a distribution is its expected surprise, H = −Σ P(x) log P(x). A distribution that puts all its weight on one token has entropy 0; a uniform distribution over V tokens has the maximum, log V.

Perplexity. Language models are often scored by the average negative log-probability they give to the real tokens of a test text. Exponentiating that average gives the perplexity. In the file above the average log-probability is −4.6052, so the perplexity is e^4.6052 = 100: the model is as uncertain as if it were choosing uniformly among 100 tokens at every step. Lower is better.

Maximum likelihood. Training a language model means adjusting its parameters to make the training text as probable as possible (maximum likelihood). By the chain rule and the log trick, that is the same as minimising the sum of −log P(next token | previous tokens) over all positions: the cross-entropy loss you meet in the next lesson. So "predict the next token" and "maximise the probability of the data" are the same objective written two ways.

Bayes' rule. Swapping the roles in the conditional-probability definition gives P(A | B) = P(B | A) P(A) / P(B). It is how you update a belief after seeing evidence, and it underlies much of classical machine learning, though LLM training itself uses the maximum-likelihood objective directly.

Common mistakes and debugging tips

Probabilities that don't add up to 1

Hand-typed or rounded probabilities often sum to 0.99 or 1.01, and rng.choice raises "probabilities do not sum to 1".

Fix: normalise: p = p / p.sum(). Better, produce probabilities with softmax, which always sums to 1.

Judging a model from one sample

Sampling is random. One odd output may be a low-probability draw rather than a broken model, and one good output doesn't prove the model is reliable.

Fix: fix the seed while debugging, and evaluate on many samples or on probabilities directly (log-likelihood) rather than on single generations.

Multiplying many probabilities and getting 0

Products of many small numbers underflow to 0.0 in floating point, so long sequences all score 0.

Fix: sum log-probabilities instead. Compare sequences by their total (or average) log-probability.

Confusing P(A | B) with P(B | A)

"The probability that the next word is 'mat' given the previous word is 'the'" is not "the probability that the previous word was 'the' given the next is 'mat'". They can be very different numbers.

Fix: read the bar as "given" and ask which event you already know.

Key takeaways

  • A language model outputs a probability distribution over its vocabulary at every step; generation samples from it.
  • Seeds make random draws reproducible; small samples wobble around the true probabilities.
  • The chain rule turns "probability of a text" into a product of next-token probabilities.
  • Use log-probabilities: products become sums and nothing underflows.

Exercise: score a sentence with a bigram model

Using the corpus from sampling.py ("the cat sat on the mat the cat ran on the rug"), estimate P(next | previous) from counts for every pair. Then compute the log-probability of the sentence "the cat ran on the mat", treating the first word as given (so only the 5 transitions count). Which transition is the least likely? What would happen to the score of "the dog sat"?

Hint

Count pairs with collections.Counter(zip(corpus[:-1], corpus[1:])) and single words with Counter(corpus[:-1]). P(b | a) = count(a, b) / count(a as a previous word). Add math.log of each transition.

Show a solution
import math
from collections import Counter

corpus = "the cat sat on the mat the cat ran on the rug".split()
pairs = Counter(zip(corpus[:-1], corpus[1:]))
firsts = Counter(corpus[:-1])

def p(nxt, prev):
    return pairs[(prev, nxt)] / firsts[prev]

sentence = "the cat ran on the mat".split()
total = 0.0
for prev, nxt in zip(sentence[:-1], sentence[1:]):
    total += math.log(p(nxt, prev))
    print(f"P({nxt} | {prev}) = {p(nxt, prev):.2f}")
print(f"log-probability = {total:.4f}")
P(cat | the) = 0.50
P(ran | cat) = 0.50
P(on | ran) = 1.00
P(the | on) = 1.00
P(mat | the) = 0.25
log-probability = -2.7726

"mat after the" (0.25) is the least likely step. "the dog sat" contains a pair never seen in the corpus, so its probability is 0 and math.log(0) fails: count-based models can't handle unseen combinations. Smoothing (adding a small count to every pair) is the classic patch; neural language models avoid the problem by generalising through embeddings, which is a big reason they replaced count models.

Check your understanding

A model gives the next token probabilities 0.5, 0.3 and 0.1 for its only three tokens. What is wrong?

  1. Probabilities must be integers
  2. They add up to 0.9, not 1
  3. Nothing, any positive numbers will do
A distribution must cover all outcomes: the probabilities must add up to exactly 1. Probabilities are real numbers between 0 and 1, not integers, and arbitrary positive numbers are scores (logits), not probabilities.

Why do language models add log-probabilities instead of multiplying probabilities?

  1. Products of many small probabilities underflow to 0 in floating point; sums of logs don't
  2. Logs make the model more accurate
  3. Multiplication is not allowed for probabilities
The log turns the product into a sum of moderate numbers and keeps the order, so nothing is lost. It doesn't change what the model predicts (option 2), and multiplying probabilities is mathematically fine (option 3); it just breaks in floating point.

You sample 20 tokens from a distribution where "cat" has probability 0.25 and get "cat" 9 times. What is the best conclusion?

  1. The sampler is broken
  2. The true probability is 0.45
  3. Small samples vary; draw many more before concluding anything
9 of 20 is unusual but quite possible by chance. The law of large numbers only promises that fractions get close to the true probabilities as the number of samples grows.

Lesson 2.4Module 2: Mathematics and foundations

Softmax, gradients and loss functions

  • ⏱ 18 min read
  • Intermediate

Learning objectives

  • Turn raw scores (logits) into probabilities with softmax, and implement it in a numerically stable way.
  • Explain what temperature does to a distribution.
  • Measure how wrong a prediction is with mean squared error and cross-entropy loss.
  • Read a derivative as a slope and a gradient as "the uphill direction", and check one numerically.
  • Run gradient descent and choose a learning rate that is neither too small nor too large.

This lesson connects the previous three into the core loop of machine learning. A model produces scores; softmax turns them into probabilities; a loss function measures how wrong those probabilities are; the gradient says which way to change each parameter to make the loss smaller; and gradient descent takes a small step that way. Repeat that billions of times over trillions of tokens and you have pretraining. Repeat it a few hundred times on a toy problem and you have the code at the end of this module. The mechanism is the same.

Analogy: walking downhill in fog

Imagine standing on a hillside in thick fog, trying to reach the bottom of the valley. You can't see the valley, but you can feel the slope under your feet. The sensible strategy is to feel which way is steepest downhill, take a step that way, and repeat. The height of the ground is the loss, your position is the model's parameters, the slope you feel is the gradient, and the length of your step is the learning rate. Steps that are too short take forever; steps that are too long overshoot the valley and land you higher up on the other side.

Softmax: from scores to probabilities

The last layer of a language model produces one number per vocabulary token, called a logit. Logits can be any real numbers, positive or negative, and they don't add up to anything in particular. A larger logit means "more likely", but we need a proper distribution to sample from and to score. Softmax does the conversion in two moves: make every score positive by exponentiating it (ez is always positive, and bigger scores stay bigger), then divide by the total so everything adds up to 1.

softmax(z)i=ezi∑j=1Vezj

In words: raise e (about 2.718) to the power of each score, then divide each result by the sum of all of them. The outputs are positive and add up to 1, and the largest score gets the largest share.

Example with 4 tokens and logits [2.0, 1.0, 0.1, −1.0]: the exponentials are about 7.39, 2.72, 1.11 and 0.37, which sum to 11.58, so the probabilities are 0.638, 0.235, 0.095 and 0.032. Notice that only differences between logits matter: adding the same constant to every logit multiplies every exponential by the same factor, which cancels in the division.

That property gives us the standard stability trick. If a logit is 1000, e1000 overflows to infinity and the division produces nan ("not a number"). Subtracting the largest logit from all of them first makes the largest exponent 0, so no exponential can exceed 1, and the answer is mathematically unchanged. Every real implementation does this.

Temperature

Before softmax, generation code often divides every logit by a number T called the temperature. With T < 1 the differences between logits grow, so the distribution becomes sharper and the top token dominates; with T > 1 the differences shrink, so the distribution flattens and unlikely tokens get picked more often. As T approaches 0 sampling becomes "always pick the top token" (greedy decoding). Temperature doesn't change the model at all; it only changes how we sample from it. You'll use it, with top-k and top-p, in lesson 5.7.

Softmax, temperature and cross-entropyInteractive

Loss functions: one number for "how wrong"

To improve a model automatically, we need a single number that is small when its predictions are good and large when they are bad. That's a loss function. Two are enough for this course.

Mean squared error (MSE) is for predicting numbers: take each prediction minus its target, square it (so errors in both directions count and big errors count a lot), and average.

MSE=1N∑i=1N(y^i−yi)2

In words: for each of the N examples, square the difference between the prediction (y-hat) and the true value, then take the average of those squares.

Cross-entropy is for predicting categories, such as the next token. It looks only at the probability the model gave to the correct answer and takes its negative logarithm. If the model gave the right token probability 1, the loss is −log 1 = 0. If it gave 0.5, the loss is 0.69; 0.1 gives 2.30; 0.001 gives 6.91. Being confidently wrong is punished heavily, which is what we want.

L=−logpy=−zy+log∑j=1Vezj

In words: the loss is minus the log of the probability given to the correct token y. Written with the logits, it is "log of the sum of all exponentials, minus the correct logit", which is how code computes it without ever forming tiny probabilities.

This is exactly the "negative log-probability of the next token" from lesson 2.3, averaged over every position of every training text. When a paper reports a language model's training loss of, say, 2.0, it means the model gives the true next token an average log-probability of −2.0 (a probability of roughly e⁻² ≈ 0.14 in a geometric-average sense).

Derivatives: the slope of a function

To lower the loss we need to know which way to move each parameter. That is what a derivative tells us: how fast a function's output changes when you nudge its input. Geometrically it's the slope of the curve at that point. Take f(x)=(x−3)2+1, a bowl with its bottom at x = 3. At x = 0 the slope is −6 (going right goes steeply down), at x = 3 it is 0 (the bottom), at x = 5 it is +4.

f′(x)≈f(x+h)−f(x−h)2hfor a tiny h

In words: the slope at x is about "rise over run" between two points just to the left and right of x. As h shrinks this becomes the exact derivative. This is the "numerical derivative" we use to check hand-derived formulas.

For the bowl, calculus gives the exact formula f′(x)=2(x−3). You don't need to be good at calculus for this course: a few rules (the derivative of xn is nxn−1, of ex is itself, of log x is 1/x, plus the chain rule of the next lesson) cover everything, and the numerical check tells you when you got one wrong.

A model has many parameters, so the loss is a function of many inputs. A partial derivative is the slope with respect to one input while the others are held still. Collect all the partial derivatives into a vector and you have the gradient, written ∇L. The gradient points in the direction in which the function increases fastest; the opposite direction, −∇L, is steepest downhill.

Gradient descent

Gradient descent is the walking-downhill strategy written as one line: subtract a small multiple of the gradient from the parameters, and repeat.

θnew=θold−η∇L(θold)

In words: the new parameters θ ("theta") are the old ones minus the learning rate η ("eta") times the gradient of the loss. Where the slope is positive, the parameter goes down; where it is negative, it goes up; at the bottom the slope is zero and nothing moves.

The learning rate η is the most important setting in training. Try three values in the demo: too small and progress is painfully slow; well chosen and you reach the bottom in a few steps; too large and each step overshoots so far that the walk zig-zags outwards and diverges.

Gradient descent on a bowlInteractive

Softmax and cross-entropy in NumPy

# @run
# Lesson 2.4: softmax (naive and stable), temperature, cross-entropy, and a gradient check
# showing that the gradient of softmax + cross-entropy with respect to the logits is p - y.
import numpy as np

def softmax_naive(z):
    e = np.exp(z)
    return e / e.sum()

def softmax(z, temperature=1.0):
    z = np.asarray(z, dtype=float) / temperature
    z = z - z.max()                  # stability trick: the largest logit becomes 0, so exp() <= 1
    e = np.exp(z)
    return e / e.sum()

def cross_entropy(z, target):
    """Loss = -log(probability given to the correct class), computed stably with log-sum-exp."""
    z = np.asarray(z, dtype=float)
    m = z.max()
    log_sum_exp = m + np.log(np.sum(np.exp(z - m)))
    return log_sum_exp - z[target]   # = -log softmax(z)[target]

vocab = ["cat", "dog", "car", "sky"]
logits = np.array([2.0, 1.0, 0.1, -1.0])
p = softmax(logits)
print("logits:", logits)
print("probs: ", np.round(p, 4), " sum =", f"{p.sum():.4f}")

# 1. Why the max-subtraction matters
big = logits + 1000.0                # same differences, so the same probabilities
with np.errstate(over="ignore", invalid="ignore"):
    print("naive softmax of logits + 1000: ", softmax_naive(big))
print("stable softmax of logits + 1000:", np.round(softmax(big), 4))

# 2. Temperature: divide the logits before softmax
for t in (0.5, 1.0, 2.0):
    print(f"T = {t}: ", np.round(softmax(logits, t), 3))

# 3. Cross-entropy: the "surprise" at the correct answer
for target in range(len(vocab)):
    print(f"correct = {vocab[target]:3s}  p = {p[target]:.4f}  loss = -log p = {cross_entropy(logits, target):.4f}")

# 4. Gradient check: numerical slope of the loss for each logit versus the formula p - y
target = 0
y = np.zeros(len(logits))
y[target] = 1.0                       # one-hot vector of the correct class
analytic = softmax(logits) - y

h = 1e-5
numeric = np.zeros(len(logits))
for i in range(len(logits)):
    up, down = logits.copy(), logits.copy()
    up[i] += h
    down[i] -= h
    numeric[i] = (cross_entropy(up, target) - cross_entropy(down, target)) / (2 * h)   # central difference

print("\nanalytic p - y:", np.round(analytic, 6))
print("numeric slope: ", np.round(numeric, 6))
print("max difference below 1e-6:", bool(np.max(np.abs(analytic - numeric)) < 1e-6))
  1. softmax_naive(z): the textbook formula. Correct on paper, but it overflows for large logits.
  2. z = z - z.max(): the stability trick. Same probabilities, but no exponential can be larger than 1.
  3. cross_entropy(z, target): computes −log softmax(z)[target] as "log-sum-exp minus the correct logit", also with the max subtracted. It never takes the log of a tiny probability.
  4. big = logits + 1000.0: the naive version returns nan everywhere (inf / inf); the stable one gives the same probabilities as the original logits.
  5. softmax(logits, t) for T = 0.5, 1, 2: the top probability goes 0.862 → 0.638 → 0.451 as the temperature rises.
  6. The loss table: the loss for each possible correct token. Each step down the list adds exactly 1.0 to the loss here because those logits happen to differ by about 1 (2.0, 1.0, 0.1, −1.0): the loss depends on the correct token's logit relative to the rest.
  7. analytic = softmax(logits) - y: the gradient of the loss with respect to the logits is "predicted probabilities minus the one-hot target".
  8. The loop with up and down: nudges each logit by ±0.00001 and measures the change in the loss (the numerical derivative). It matches p - y to 6 decimals.
logits: [ 2.   1.   0.1 -1. ]
probs:  [0.6381 0.2347 0.0954 0.0318]  sum = 1.0000
naive softmax of logits + 1000:  [nan nan nan nan]
stable softmax of logits + 1000: [0.6381 0.2347 0.0954 0.0318]
T = 0.5:  [0.862 0.117 0.019 0.002]
T = 1.0:  [0.638 0.235 0.095 0.032]
T = 2.0:  [0.451 0.274 0.174 0.101]
correct = cat  p = 0.6381  loss = -log p = 0.4493
correct = dog  p = 0.2347  loss = -log p = 1.4493
correct = car  p = 0.0954  loss = -log p = 2.3493
correct = sky  p = 0.0318  loss = -log p = 3.4493

analytic p - y: [-0.361934  0.234731  0.095435  0.031767]
numeric slope:  [-0.361934  0.234731  0.095435  0.031767]
max difference below 1e-6: True

That last result, gradient = p − y, is one of the most useful facts in deep learning. It says: push up the logit of the correct token (its gradient is p − 1, negative, so descent increases it) and push down every other logit in proportion to how much probability it wrongly received. Every language model's training starts its backward pass with exactly this.

Slopes, gradients and learning rates in NumPy

# @run
# Lesson 2.4: derivatives as slopes, partial derivatives, the gradient, and 1-D gradient descent
# with three learning rates (too small, good, too large).
import numpy as np

def f(x):
    return (x - 3.0) ** 2 + 1.0          # a bowl with its lowest point at x = 3

def df(x):
    return 2.0 * (x - 3.0)               # its derivative, worked out by hand

# 1. A derivative is a slope: compare the formula with a tiny "rise over run"
h = 1e-6
for x in (0.0, 3.0, 5.0):
    numeric = (f(x + h) - f(x - h)) / (2 * h)
    print(f"x = {x:.1f}  f(x) = {f(x):5.2f}  slope by formula = {df(x):5.2f}  numeric = {numeric:5.2f}")

# 2. Partial derivatives and the gradient of g(x, y) = x^2 * y + 3y
def g(v):
    x, y = v
    return x * x * y + 3.0 * y

def grad_g(v):
    x, y = v
    return np.array([2.0 * x * y, x * x + 3.0])     # [dg/dx, dg/dy]

v = np.array([1.0, 2.0])
numeric = np.array([(g(v + h * e) - g(v - h * e)) / (2 * h) for e in np.eye(2)])
print(f"\ng(1, 2) = {g(v):.1f}")
print("gradient by formula:", grad_g(v))
print("gradient numerically:", np.round(numeric, 4))
print("tiny step along +gradient changes g by", f"{g(v + 0.01 * grad_g(v)) - g(v):+.4f}")
print("tiny step along -gradient changes g by", f"{g(v - 0.01 * grad_g(v)) - g(v):+.4f}")

# 3. Gradient descent on f with three learning rates
print()
for lr in (0.05, 0.4, 1.05):
    x = 0.0
    path = [x]
    for step in range(12):
        x = x - lr * df(x)            # step downhill: against the slope
        path.append(x)
    shown = "  ".join(f"{p:.2f}" for p in path[:7])
    print(f"lr = {lr:<4}  x: {shown} ...  after 12 steps x = {x:.3f}, f(x) = {f(x):.3f}")
  1. f and df: the bowl and its derivative worked out by hand.
  2. The first loop compares df(x) with the numerical rise-over-run at three points. They agree, so the formula is right.
  3. g(v) and grad_g(v): a function of two inputs, g=x2y+3y, and its gradient [2xy, x² + 3]. At (1, 2) both partial derivatives are 4.
  4. for e in np.eye(2): np.eye(2) gives the unit vectors [1, 0] and [0, 1], so each numerical derivative nudges one input at a time: that is what "partial" means.
  5. Stepping 0.01 along +gradient raises g; along −gradient lowers it. That is the whole justification for gradient descent.
  6. x = x - lr * df(x): gradient descent with three learning rates. 0.05 crawls (x is only 2.153 after 12 steps), 0.4 lands on 3 almost at once, 1.05 overshoots further each time and diverges.
x = 0.0  f(x) = 10.00  slope by formula = -6.00  numeric = -6.00
x = 3.0  f(x) =  1.00  slope by formula =  0.00  numeric =  0.00
x = 5.0  f(x) =  5.00  slope by formula =  4.00  numeric =  4.00

g(1, 2) = 8.0
gradient by formula: [4. 4.]
gradient numerically: [4. 4.]
tiny step along +gradient changes g by +0.3265
tiny step along -gradient changes g by -0.3137

lr = 0.05  x: 0.00  0.30  0.57  0.81  1.03  1.23  1.41 ...  after 12 steps x = 2.153, f(x) = 1.718
lr = 0.4   x: 0.00  2.40  2.88  2.98  3.00  3.00  3.00 ...  after 12 steps x = 3.000, f(x) = 1.000
lr = 1.05  x: 0.00  6.30  -0.63  6.99  -1.39  7.83  -2.31 ...  after 12 steps x = -6.415, f(x) = 89.648
Deriving "gradient = p − y" and why cross-entropy pairs with softmax

Write the loss with logits: L = −zy + log Σj ezj. Take the partial derivative with respect to one logit zk. The first term contributes −1 if k = y and 0 otherwise. The second term is log of a sum; its derivative is (derivative of the sum) / (the sum) = ezk / Σj ezj = pk. Together: ∂L/∂zk = pk − [k = y], which is p − y with y one-hot.

∂L∂zk=pk−yk

In words: the slope of the loss with respect to each logit is the probability the model gave that token minus 1 for the correct token (or minus 0 for any other).

Why this pairing is so good. The gradient is bounded between −1 and 1 and never vanishes while the model is wrong: if the correct token has probability 0.001, the push on its logit is −0.999, as strong as it can be. Compare MSE on probabilities, whose gradient includes an extra factor from the softmax's slope that becomes tiny exactly when the model is confidently wrong, so learning stalls. That's why classification and language modelling use cross-entropy.

Log-sum-exp. The expression log Σ ezj is a smooth version of max(z): it's always a little above the largest logit. Computing it as m + log Σ ezj − m with m = max(z) is exact and never overflows, which is why frameworks provide a fused, stable "cross-entropy from logits" function and you should use it instead of softmax followed by log.

Real optimisers. Plain gradient descent on the full dataset is rare. Real training uses stochastic gradient descent on small random batches (cheaper, noisier steps) and optimisers such as Adam, which keep running averages of gradients to adapt the step size per parameter. Module 3 implements momentum and Adam (lesson 3.5).

Common mistakes and debugging tips

Softmax returns nan

Some logit was large enough that exp overflowed to infinity, and inf / inf is nan. It often shows up only after a model has trained for a while and its logits have grown.

Fix: subtract the max before exponentiating, and compute the loss from logits with log-sum-exp rather than taking log(softmax(z)).

Adding the gradient instead of subtracting it

The gradient points uphill. A sign slip turns gradient descent into gradient ascent and the loss climbs steadily.

Fix: the update is param -= lr * grad. If the loss rises from the very first step, check the sign before anything else.

Loss explodes or oscillates

The learning rate is too large: each step overshoots the minimum, as with η = 1.05 in the output above.

Fix: lower the learning rate by a factor of 3 to 10 and try again; plot the loss per step to see the difference between "slow" and "unstable".

Trusting a hand-derived gradient without checking

A wrong derivative rarely crashes. The model just trains badly, and you can lose days blaming the data or the learning rate.

Fix: compare with the central difference (f(x+h) − f(x−h)) / 2h on a few random inputs, as both files in this lesson do.

Key takeaways

  • Softmax exponentiates and normalises logits; subtract the max first for numerical stability.
  • Temperature divides the logits: below 1 sharpens, above 1 flattens. It changes sampling, not the model.
  • Cross-entropy = −log(probability of the correct token); with softmax its gradient is simply p − y.
  • The gradient points uphill; gradient descent steps against it, with a learning rate that must be tuned.

Exercise: gradient descent on the logits

Use the functions in softmax.py. Start from logits = [2.0, 1.0, 0.1, -1.0] and treat the logits themselves as parameters. The correct token is "car" (index 2), which currently has probability 0.095. Run 20 steps of gradient descent with learning rate 1.0 using the gradient softmax(z) - y, printing the loss every 5 steps. Predict first: which logits will go up and which down?

Hint

Build y as a one-hot vector with a 1 at index 2. Each step: z = z - lr * (softmax(z) - y). Only the correct logit has a negative gradient.

Show a solution
z = np.array([2.0, 1.0, 0.1, -1.0])
y = np.zeros(4)
y[2] = 1.0
for step in range(21):
    if step % 5 == 0:
        print(f"step {step:2d}  loss {cross_entropy(z, 2):.4f}  p(car) {softmax(z)[2]:.4f}")
    z = z - 1.0 * (softmax(z) - y)
print("final logits:", np.round(z, 3))
step  0  loss 2.3493  p(car) 0.0954
step  5  loss 0.1868  p(car) 0.8296
step 10  loss 0.0826  p(car) 0.9207
step 15  loss 0.0528  p(car) 0.9486
step 20  loss 0.0388  p(car) 0.9620
final logits: [-0.172 -0.318  3.894 -1.304]

Only "car" goes up; the others go down in proportion to the probability they had, so "cat" (the old favourite) drops the most. Progress slows as p(car) approaches 1 because the gradient p − y shrinks. Notice the logits still sum to 2.1, as at the start: the gradient p − y always sums to zero.

Check your understanding

What happens to softmax's output if you add 100 to every logit?

  1. Every probability grows
  2. The largest probability becomes 1
  3. Nothing: only differences between logits matter
Adding a constant multiplies every exponential by the same factor, which cancels when dividing by the sum. That is why subtracting the max is safe. Probabilities can't all grow, because they must still sum to 1.

The model gives the correct token probability 0.01. What is the cross-entropy loss for that position?

  1. About 4.6
  2. 0.01
  3. 0.99
−log(0.01) = log(100) ≈ 4.605. The loss is the negative log of the correct token's probability, not the probability itself (0.01) or the missing probability (0.99).

During training the loss jumps up and down and grows larger over time. What is the most likely cause?

  1. The learning rate is too small
  2. The learning rate is too large
  3. Softmax is missing the stability trick
Overshooting steps make the loss oscillate and grow, as with η = 1.05 in gradients.py. A too-small learning rate makes the loss fall slowly but steadily. A missing stability trick produces nan values rather than a growing loss.

Lesson 2.5Module 2: Mathematics and foundations

Neural networks and backpropagation

  • ⏱ 20 min read
  • Intermediate

Learning objectives

  • Write a neuron as a dot product plus a bias followed by an activation, and a layer as a matrix product.
  • Explain why a non-linear activation is needed between layers.
  • Draw a computation as a graph and apply the chain rule backwards through it (backpropagation).
  • Read and extend a tiny automatic-differentiation engine, and check its gradients numerically.
  • Follow the shapes of the gradients through a two-layer network written with matrices.

In lesson 2.4 we could write the derivative of a small function by hand. A real network has millions or billions of parameters, chained through dozens of layers, and we need the derivative of the loss with respect to every one of them, at every training step. Backpropagation is the algorithm that does this efficiently: one pass forward to compute the loss, one pass backward to compute all the gradients, at a cost of roughly two forward passes. It is nothing more than the chain rule from calculus, applied carefully in the right order. Once you see it on a graph of five nodes you understand what PyTorch does for a model with billions of parameters.

Analogy: tracing blame back through a factory

A factory produces a cake through stations: mixing, baking, icing. A customer complains it is too sweet by a certain amount. The icing station can say how much of the sweetness came through it and passes the rest of the complaint back to the baker, who passes a share back to the mixer, and so on. Each station only needs to know its own local effect ("if my input had been 1 gram sweeter, my output would have been 0.8 grams sweeter") and the complaint arriving from the station after it. Multiplying local effects along the line tells every station, and every knob at every station, how much it contributed. That's backpropagation: blame flows backwards, multiplied by local slopes.

A neuron and a layer

An artificial neuron takes a vector of inputs, computes a dot product with its own weights, adds a bias, and passes the result through an activation function. The weights say how much each input matters; the bias shifts the threshold; the activation adds a bend.

a=φ(w·x+b)=φ(∑i=1nwixi+b)

In words: multiply each input by its weight, add them up, add the bias, then apply the activation function φ ("phi"). The result a is the neuron's output, its "activation".

A layer is many neurons reading the same inputs, each with its own weights. Stacking their weight vectors as columns gives exactly the X @ W + b of lesson 2.2, followed by the activation applied to every number. A network is layers in a chain: the outputs of one are the inputs of the next.

Common activations:

  • ReLU: max(0, z). Negative inputs become 0, positive ones pass unchanged. Cheap and widely used.
  • tanh and sigmoid: smooth S-shaped curves squashing any input into (−1, 1) and (0, 1). Sigmoid turns a score into a probability for yes/no questions.
  • GELU and SwiGLU-style gated activations: smooth relatives of ReLU commonly used in transformer feed-forward layers (lesson 4.7).

Why the bend matters

Without activations, a layer is a matrix, and two layers in a row are two matrices, whose product (lesson 2.2) is again a single matrix. A hundred linear layers would collapse into one linear layer and could only draw straight-line boundaries. A non-linear activation between layers breaks that collapse. With enough neurons, a network of linear layers and simple bends can approximate essentially any reasonable function, which is the deep reason neural networks are so flexible. The bends are where the "intelligence" gets room to happen; the matrices decide where to bend.

Computations as graphs

Any calculation can be drawn as a computational graph: boxes for operations, arrows for the values flowing between them. Here is a one-neuron network with a squared-error loss, using x = 3, w = 0.5, b = 1 and target t = 2:

  1. Forward: multiply the input by the weight, p = 0.5 × 3 = 1.5.
  2. Forward: add the bias, z = 1.5 + 1 = 2.5.
  3. Forward: ReLU keeps 2.5 (it is positive); compare with the target, d = 2.5 − 2 = 0.5.
  4. Forward: the loss is L = 0.5² = 0.25. Now go backwards, starting with dL/dL = 1.
  5. Backward: the local slope of d² is 2d = 1.0, so dL/dd = 1 × 1.0 = 1.0. Subtracting a constant has slope 1, so dL/da = 1.0.
  6. Backward: ReLU has slope 1 where its input is positive, so dL/dz = 1.0. Addition has slope 1 for both inputs: dL/dp = 1.0 and dL/db = 1.0.
  7. Backward: for p = w·x the slope with respect to w is x, so dL/dw = 3 × 1.0 = 3.0, and with respect to x it is w, so dL/dx = 0.5.
Forward then backward. Values flow left to right; gradients flow right to left, each multiplied by the local slope of the box it passes through. Use the step player to follow both passes.

The chain rule

The rule that makes this work: if L depends on a, and a depends on z, then the sensitivity of L to z is the sensitivity of L to a times the sensitivity of a to z. Slopes multiply along a chain. If doubling-speed gears are connected to tripling-speed gears, the last gear turns six times as fast as the first.

∂L∂w=∂L∂d·∂d∂a·∂a∂z·∂z∂p·∂p∂w=1.0·1·1·1·3=3.0

In words: how much the loss changes per unit change of w is the product of the local slopes along the path from w to the loss. Here every link has slope 1 except the first (2d = 1.0) and the last (x = 3), so the answer is 3.

Backpropagation organises this so nothing is computed twice. Start at the loss with gradient 1. Visit the nodes in reverse order. At each node, take the gradient that has arrived from above (the "upstream" gradient), multiply by the node's local slope with respect to each of its inputs, and add the result to each input's gradient. When a value feeds into several places, its gradient is the sum of what comes back from each. Every node only needs to know its own local derivative: for a + b it's 1 and 1, for a * b it's b and a, for ReLU it's 1 or 0, for tanh it's 1 − tanh².

Then gradient descent (lesson 2.4) uses those gradients: dL/dw = 3 is positive, so lowering w lowers the loss. With learning rate 0.02 the new w is 0.5 − 0.02 × 3 = 0.44.

Backprop through one neuronInteractive

Drag the bias below −1.5 so that z becomes negative: ReLU outputs 0, its local slope is 0, and every gradient to the left of it becomes 0. The neuron is "dead" for this input and gradient descent can't move w or b at all. This is a real problem in large networks, and one reason smoother activations are popular.

A tiny autograd engine

Frameworks such as PyTorch record every operation as you compute, building the graph automatically, and loss.backward() walks it backwards. That is called automatic differentiation (autograd). The file below implements one for single numbers in about 80 lines. It is a simplified teaching version Simplified: real frameworks work on whole tensors at once and run on GPUs, but the logic is the same.

# @run
# Lesson 2.5: a tiny scalar automatic-differentiation engine ("micro-autograd").
# Every Value remembers which Values produced it and how to pass gradients back to them.
import math

class Value:
    def __init__(self, data, parents=(), op="", label=""):
        self.data = float(data)
        self.grad = 0.0                  # dLoss/dself, filled in by backward()
        self._parents = parents          # the Values this one was computed from
        self._back = lambda: None        # how to push my grad into my parents' grads
        self.op = op
        self.label = label

    def __repr__(self):
        return f"Value({self.label or self.op} data={self.data:.4f} grad={self.grad:.4f})"

    @staticmethod
    def wrap(x):
        return x if isinstance(x, Value) else Value(x)

    def __add__(self, other):
        other = Value.wrap(other)
        out = Value(self.data + other.data, (self, other), "+")
        def back():                       # d(a+b)/da = 1 and d(a+b)/db = 1
            self.grad += out.grad
            other.grad += out.grad
        out._back = back
        return out

    def __mul__(self, other):
        other = Value.wrap(other)
        out = Value(self.data * other.data, (self, other), "*")
        def back():                       # d(a*b)/da = b and d(a*b)/db = a
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._back = back
        return out

    def __neg__(self):
        return self * -1.0

    def __sub__(self, other):
        return self + (-Value.wrap(other))

    def __pow__(self, k):                 # k is a plain number
        out = Value(self.data ** k, (self,), f"**{k}")
        def back():                       # d(a^k)/da = k * a^(k-1)
            self.grad += k * self.data ** (k - 1) * out.grad
        out._back = back
        return out

    __radd__ = __add__
    __rmul__ = __mul__

    def relu(self):
        out = Value(max(0.0, self.data), (self,), "relu")
        def back():                       # slope 1 where the input was positive, else 0
            self.grad += (1.0 if self.data > 0 else 0.0) * out.grad
        out._back = back
        return out

    def tanh(self):
        t = math.tanh(self.data)
        out = Value(t, (self,), "tanh")
        def back():                       # d tanh(a)/da = 1 - tanh(a)^2
            self.grad += (1.0 - t * t) * out.grad
        out._back = back
        return out

    def backward(self):
        # Order the graph so every node comes after everything it depends on (topological sort) ...
        order, seen = [], set()
        def visit(v):
            if id(v) not in seen:
                seen.add(id(v))
                for p in v._parents:
                    visit(p)
                order.append(v)
        visit(self)
        # ... then walk it backwards, starting from dLoss/dLoss = 1 (the chain rule, one node at a time)
        self.grad = 1.0
        for v in reversed(order):
            v._back()

# 1. The worked example from the lesson: L = (relu(w*x + b) - t)^2
x, w, b, t = Value(3.0, label="x"), Value(0.5, label="w"), Value(1.0, label="b"), Value(2.0, label="t")
p = w * x;         p.label = "p"
z = p + b;         z.label = "z"
a = z.relu();      a.label = "a"
d = a - t;         d.label = "d"
L = d ** 2;        L.label = "L"
L.backward()
for v in (x, w, b, p, z, a, d, L):
    print(v)

# 2. Gradient check on a messier expression: compare backprop with finite differences
def expr(u, v, s):
    return ((u * v + s).tanh() * u + v ** 2) * 0.5

vals = [0.7, -1.3, 0.4]
inputs = [Value(q) for q in vals]
out = expr(*inputs)
out.backward()
h = 1e-6
print(f"\nf = {out.data:.6f}")
for i, name in enumerate("uvs"):
    hi = list(vals); hi[i] += h
    lo = list(vals); lo[i] -= h
    numeric = (expr(*map(Value, hi)).data - expr(*map(Value, lo)).data) / (2 * h)
    print(f"df/d{name}: backprop = {inputs[i].grad:+.6f}   numeric = {numeric:+.6f}   match = {abs(inputs[i].grad - numeric) < 1e-6}")

# 3. Use the gradients: nudge w and b downhill a few times (gradient descent on one example)
w, b = Value(0.5), Value(1.0)
for step in range(6):
    L = ((w * 3.0 + b).relu() - 2.0) ** 2
    w.grad = b.grad = 0.0              # gradients accumulate with +=, so reset them every step
    L.backward()
    print(f"step {step}: loss = {L.data:.5f}  dL/dw = {w.grad:+.4f}  dL/db = {b.grad:+.4f}")
    w.data -= 0.02 * w.grad
    b.data -= 0.02 * b.grad
  1. class Value: wraps one number (data) with a slot for its gradient (grad), the Values it was computed from (_parents), and a function _back that knows how to push gradient into those parents.
  2. __add__: computes the sum and records a back function. The local slope of a sum is 1 for both inputs, so each parent's grad gets out.grad added.
  3. __mul__: the local slope with respect to each input is the other input, so self.grad += other.data * out.grad.
  4. The += everywhere matters: if a Value is used twice, gradients from both uses must add up, not overwrite each other.
  5. __pow__, relu, tanh: each defines only its own local derivative (k·ak−1, 1-or-0, 1 − tanh²).
  6. backward(): visit performs a depth-first search that lists each node after everything it depends on (a topological order). Then it sets the loss's own gradient to 1 and calls _back on the nodes in reverse order.
  7. Part 1 rebuilds the graph from the diagram above. The printed gradients match the step player: dL/dw = 3, dL/db = 1, dL/dx = 0.5.
  8. Part 2 is a gradient check: for a messier expression it compares every backprop gradient with the central difference. All three match.
  9. Part 3 runs gradient descent on w and b. Gradients must be reset to 0 before each backward() because of the +=; forgetting this is a classic bug (PyTorch's optimizer.zero_grad() exists for the same reason).
Value(x data=3.0000 grad=0.5000)
Value(w data=0.5000 grad=3.0000)
Value(b data=1.0000 grad=1.0000)
Value(p data=1.5000 grad=1.0000)
Value(z data=2.5000 grad=1.0000)
Value(a data=2.5000 grad=1.0000)
Value(d data=0.5000 grad=1.0000)
Value(L data=0.2500 grad=1.0000)

f = 0.680519
df/du: backprop = -0.589487   numeric = -0.589487   match = True
df/dv: backprop = -1.109108   numeric = -1.109108   match = True
df/ds: backprop = +0.272703   numeric = +0.272703   match = True
step 0: loss = 0.25000  dL/dw = +3.0000  dL/db = +1.0000
step 1: loss = 0.09000  dL/dw = +1.8000  dL/db = +0.6000
step 2: loss = 0.03240  dL/dw = +1.0800  dL/db = +0.3600
step 3: loss = 0.01166  dL/dw = +0.6480  dL/db = +0.2160
step 4: loss = 0.00420  dL/dw = +0.3888  dL/db = +0.1296
step 5: loss = 0.00151  dL/dw = +0.2333  dL/db = +0.0778

The loss falls from 0.25 towards 0 because each step moves w and b a little against their gradients. That is a neural network learning, in its smallest possible form.

The same thing with matrices

Real networks don't backpropagate one number at a time. Each layer's backward step is again a couple of matrix multiplications. For a layer z=xW+b with upstream gradient δ=∂L/∂z:

∂L∂W=xTδ,∂L∂b=δ,∂L∂x=δWT

In words: the gradient for a weight is "the input that flowed into it times the error that came back out" (an outer product for one example); the bias gradient is just the error; and the error passed to the previous layer goes back through the transposed weights. Every gradient has the same shape as the thing it belongs to.

# @run
# Lesson 2.5: one forward and one backward pass through a tiny two-layer network written with matrices,
# then a gradient check that compares every backprop gradient with a finite-difference estimate.
import numpy as np

rng = np.random.default_rng(0)
x = np.array([1.0, 2.0])                  # one input example with 2 features
t = 1.0                                   # its target output
W1 = rng.normal(0.0, 0.5, size=(2, 3))    # layer 1: 2 inputs -> 3 hidden units
b1 = np.zeros(3)
W2 = rng.normal(0.0, 0.5, size=(3, 1))    # layer 2: 3 hidden units -> 1 output
b2 = np.zeros(1)

def forward(W1, b1, W2, b2):
    z1 = x @ W1 + b1                      # (2,) @ (2, 3) -> (3,)   weighted sums of the hidden layer
    h = np.maximum(0.0, z1)               # ReLU: negative sums become 0
    y = h @ W2 + b2                       # (3,) @ (3, 1) -> (1,)   the network's prediction
    loss = 0.5 * (y[0] - t) ** 2          # squared error (the 0.5 makes the derivative tidy)
    return z1, h, y, loss

z1, h, y, loss = forward(W1, b1, W2, b2)
print("z1 =", np.round(z1, 4))
print("h  =", np.round(h, 4))
print(f"y  = {y[0]:.4f}   loss = {loss:.4f}")

# Backward pass: the chain rule, from the loss back to every parameter
dy = np.array([y[0] - t])                 # dL/dy, shape (1,)
dW2 = np.outer(h, dy)                     # dL/dW2: input of the layer times error of the layer -> (3, 1)
db2 = dy                                  # dL/db2 -> (1,)
dh = W2 @ dy                              # (3, 1) @ (1,) -> (3,): error sent back to the hidden units
dz1 = dh * (z1 > 0)                       # ReLU lets the gradient through only where z1 > 0
dW1 = np.outer(x, dz1)                    # (2, 3), same shape as W1
db1 = dz1                                 # (3,)
print()
for name, g, p in [("W1", dW1, W1), ("b1", db1, b1), ("W2", dW2, W2), ("b2", db2, b2)]:
    print(f"d{name} shape {g.shape} == {name} shape {p.shape}: {g.shape == p.shape}")
print("dW1 =")
print(np.round(dW1, 4) + 0.0)            # "+ 0.0" turns -0.0 into 0.0 for printing

# Gradient check: nudge every single parameter up and down and measure the change in the loss
params = {"W1": W1, "b1": b1, "W2": W2, "b2": b2}
grads = {"W1": dW1, "b1": db1, "W2": dW2, "b2": db2}
eps, worst, count = 1e-6, 0.0, 0
for name, p in params.items():
    for idx in np.ndindex(p.shape):
        old = p[idx]
        p[idx] = old + eps
        up = forward(W1, b1, W2, b2)[3]
        p[idx] = old - eps
        down = forward(W1, b1, W2, b2)[3]
        p[idx] = old                      # put the parameter back
        worst = max(worst, abs((up - down) / (2 * eps) - grads[name][idx]))
        count += 1
print(f"\nchecked {count} parameters; backprop matches finite differences: {bool(worst < 1e-6)}")

# One gradient-descent step: move every parameter a little against its gradient
lr = 0.1
after = forward(W1 - lr * dW1, b1 - lr * db1, W2 - lr * dW2, b2 - lr * db2)[3]
print(f"loss before = {loss:.4f}   after one step = {after:.4f}")
  1. W1 (2, 3) and W2 (3, 1): a network with 2 inputs, 3 hidden ReLU units and 1 output, initialised with small random numbers from a seeded generator.
  2. forward: x @ W1 + b1, ReLU, h @ W2 + b2, then half the squared error. The middle hidden unit's sum is negative, so ReLU outputs 0 for it.
  3. dy = y - t: the derivative of ½(y − t)² with respect to y.
  4. dW2 = np.outer(h, dy): input times error, shape (3, 1) like W2.
  5. dh = W2 @ dy: sends the error back through the weights (the "δWT" step, written for column-shaped W2).
  6. dz1 = dh * (z1 > 0): ReLU's local slope as a mask. The middle column of dW1 is exactly 0 because that unit was inactive.
  7. The gradient check nudges all 13 parameters one at a time and confirms every backprop gradient.
  8. One gradient-descent step drops the loss from 0.6390 to 0.1796.
z1 = [ 0.1678 -0.6017  0.6818]
h  = [0.1678 0.     0.6818]
y  = -0.1305   loss = 0.6390

dW1 shape (2, 3) == W1 shape (2, 3): True
db1 shape (3,) == b1 shape (3,): True
dW2 shape (3, 1) == W2 shape (3, 1): True
db2 shape (1,) == b2 shape (1,): True
dW1 =
[[-0.7371  0.      0.3978]
 [-1.4742  0.      0.7956]]

checked 13 parameters; backprop matches finite differences: True
loss before = 0.6390   after one step = 0.1796

Module 3 turns this into a full training loop with many examples, batches and optimisers (lesson 3.4).

Why reverse mode, what it costs, and how frameworks do it

Reverse versus forward mode. You could also push derivatives forwards, from one input towards the output. That gives the derivative of every output with respect to one input per pass. Training has millions of inputs (the parameters) and one output (the loss), so reverse mode, which gives the derivative of one output with respect to all inputs in one backward pass, is enormously cheaper. Its cost is a small constant multiple of the forward pass, roughly two to three times, regardless of the number of parameters.

Memory. The backward pass needs the intermediate values of the forward pass (our back functions read self.data and other.data). Storing all those activations for a large model with long sequences takes a lot of accelerator memory. A common trade-off, activation checkpointing, stores only some of them and recomputes the rest during the backward pass.

Vanishing and exploding gradients. The chain rule multiplies many local slopes. If they are mostly below 1 (saturated sigmoids, dead ReLUs) the product shrinks towards 0 in deep networks; if mostly above 1 it blows up. Careful initialisation, normalisation layers and residual connections, where each block adds its output to its input so a slope-1 path always exists, are the main reasons very deep transformers train at all (lesson 4.8).

In PyTorch. The same graph is written with tensors created with requires_grad=True; after computing the loss, loss.backward() fills each tensor's .grad, and an optimiser's step() applies the update. Our Value class mirrors that design on single numbers. PyTorch is not used or run by this module's tests; it appears from module 10.

Common mistakes and debugging tips

Forgetting to reset gradients between steps

Gradients accumulate with +=, so without a reset each step uses the sum of all previous gradients and training goes haywire.

Fix: zero every parameter's gradient before each backward pass (w.grad = 0.0 here, optimizer.zero_grad() in PyTorch).

Overwriting instead of accumulating gradients

Writing self.grad = ... in a backward function loses the contribution from every other place the value was used. Results are wrong only when a value is reused, which makes the bug hard to spot.

Fix: always accumulate with +=, and test with an expression that uses a variable twice (such as u * u).

Gradient shapes that don't match parameter shapes

In matrix code a transposed or swapped product can still run thanks to broadcasting and silently give a gradient of the wrong shape or meaning.

Fix: assert grad.shape == param.shape for every parameter, as tiny_network.py prints, and run a numerical gradient check on a small network.

Dead ReLUs

If a unit's input is negative for every example, its gradient is always 0 and it never recovers. A large learning rate can push many units into this state at once.

Fix: use a smaller learning rate, sensible initialisation, or a smooth activation such as GELU; monitor the fraction of units that are always zero.

Key takeaways

  • A neuron is activation(w·x + b); a layer is activation(X @ W + b); non-linear activations stop layers collapsing into one matrix.
  • Backpropagation is the chain rule applied in reverse topological order; each node only needs its local derivative.
  • Gradients from several uses of a value add up, and must be reset before each step.
  • For a linear layer: dW = xᵀδ, db = δ, dx = δWᵀ; every gradient has its parameter's shape.

Exercise: add a sigmoid to the autograd engine

Add a sigmoid method to Value in autograd.py. The sigmoid is σ(a) = 1 / (1 + e−a) and its derivative is σ(a)(1 − σ(a)). Then test it with the expression f = u.sigmoid() * u at u = 0.5, comparing the backprop gradient with a numerical one. Note that u is used twice, so your test also exercises gradient accumulation.

Hint

Copy the shape of tanh: compute the output value once, create out = Value(s, (self,), "sigmoid"), and in back add s * (1 - s) * out.grad to self.grad.

Show a solution
def sigmoid(self):
    s = 1.0 / (1.0 + math.exp(-self.data))
    out = Value(s, (self,), "sigmoid")
    def back():
        self.grad += s * (1.0 - s) * out.grad
    out._back = back
    return out
Value.sigmoid = sigmoid        # or put the method inside the class

u = Value(0.5)
f = u.sigmoid() * u
f.backward()
g = lambda q: q / (1 + math.exp(-q))
h = 1e-6
print(f"backprop {u.grad:.6f}  numeric {(g(0.5 + h) - g(0.5 - h)) / (2 * h):.6f}")
backprop 0.739961  numeric 0.739961

The gradient has two parts, one through each use of u: σ(u) from the multiplication (0.6225) plus u·σ(u)(1 − σ(u)) through the sigmoid (0.1175). The += adds them.

Check your understanding

Why do neural networks need a non-linear activation between layers?

  1. To make training faster on GPUs
  2. Without it, any stack of linear layers equals a single linear layer
  3. To keep the outputs between 0 and 1
The product of matrices is a matrix, so linear layers alone collapse into one and can only represent linear functions. Activations don't speed things up, and many (ReLU, GELU) don't limit outputs to [0, 1].

In c = a * b with a = 2 and b = 5, the upstream gradient dL/dc is 3. What is dL/da?

  1. 15
  2. 6
  3. 3
The local slope of a·b with respect to a is b = 5; multiply by the upstream gradient: 5 × 3 = 15. 6 would be a × 3 (that's dL/db), and 3 ignores the local slope.

A value u is used in two places in a computation. How is its gradient computed?

  1. Only the first use counts
  2. The two contributions are multiplied
  3. The contributions from both uses are added
This is the multivariable chain rule: total sensitivity is the sum over every path from u to the loss. That's why backward functions use +=.

Lesson 2.6Module 2: Mathematics and foundations

Practical Python demonstrations

  • ⏱ 17 min read
  • Intermediate

Learning objectives

  • Train a complete model (logistic regression) with NumPy: forward pass, loss, gradients, update, repeated.
  • Write that loop vectorised over a whole dataset, with every shape accounted for.
  • Recognise five NumPy pitfalls that silently break machine-learning code, and the one-line checks that catch them.
  • Fit a line by gradient descent and confirm it against the exact least-squares answer (the mini-project).

This lesson puts the previous five together in working code. Vectors and matrices (lessons 2.1 and 2.2) hold the data and parameters; probability (2.3) turns scores into predictions; a loss and its gradient (2.4) say how to improve; the chain rule (2.5) gives those gradients. The result is the training loop, the same four steps that train every neural network including the largest language models: forward (predict), loss (measure), backward (compute gradients), update (step downhill). Here it fits on one screen and runs in well under a second.

Simplified, on purpose

The models in this lesson have 2 or 3 parameters and train on 60 to 100 made-up points. A frontier LLM has billions of parameters and trains on trillions of tokens across thousands of accelerators. The loop is the same; everything around it (data pipelines, parallelism, optimisers, monitoring) is a very large engineering effort that later modules describe.

Analogy: tuning a recipe by tasting

A cook adjusting a soup follows a loop: taste it (forward pass), judge how far it is from what they want (loss), work out which ingredient is responsible and in which direction (gradient), add a little of the right thing (update), and taste again. They don't change everything at once and they don't dump in a whole cup of salt; small, informed corrections repeated many times get there. A training loop is that cook, tasting thousands of times per second.

Logistic regression: the smallest classifier

Logistic regression answers a yes/no question from a few numbers. Each example is a vector x (here a point with 2 coordinates), and the model computes a score z=w·x+b, then squashes it into a probability with the sigmoid function. It is a single neuron with a sigmoid activation, or equivalently, softmax with two classes.

p=σ(z)=11+e−z,L=−1N∑i=1N[yilogpi+(1−yi)log(1−pi)]

In words: the sigmoid maps any score to a probability between 0 and 1 (score 0 gives 0.5). The loss is binary cross-entropy: for each example, minus the log of the probability the model gave to the true label (p if the label is 1, 1 − p if it is 0), averaged over all N examples.

Just like softmax with cross-entropy, the gradient of this loss with respect to each score is wonderfully simple: p−y. By the chain rule through z=w·x+b, and averaged over the batch, that gives the two gradients we need, both computed for all examples at once with a matrix product:

∂L∂w=1NXT(p−y),∂L∂b=1N∑i=1N(pi−yi)

In words: each weight's gradient is the average, over all examples, of "that example's error times that example's input feature"; the bias gradient is just the average error. Xᵀ does all the "error times feature" products in one matrix multiplication.

The training loop in NumPy

# @run
# Lesson 2.6: logistic regression on a tiny 2-D dataset with NumPy only.
# Forward pass -> loss -> gradients -> update, repeated. The same loop trains every neural network.
import numpy as np

rng = np.random.default_rng(0)

# 1. Data: two clouds of 2-D points. Class 0 around (-1, -1), class 1 around (+1, +1).
n = 50                                               # points per class
X0 = rng.normal(loc=[-1.0, -1.0], scale=0.8, size=(n, 2))
X1 = rng.normal(loc=[1.0, 1.0], scale=0.8, size=(n, 2))
X = np.vstack([X0, X1])                              # shape (100, 2)
y = np.concatenate([np.zeros(n), np.ones(n)])        # shape (100,)
print("X:", X.shape, " y:", y.shape, " class balance:", int(y.sum()), "of", len(y))

def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))

def bce(p, y, eps=1e-12):
    """Binary cross-entropy: average surprise at the true labels."""
    p = np.clip(p, eps, 1 - eps)                     # never take log(0)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

# 2. Parameters: one weight per input feature plus a bias, all starting at zero
w = np.zeros(2)
b = 0.0
lr = 0.5

for step in range(301):
    z = X @ w + b                    # (100, 2) @ (2,) -> (100,): one score per point
    p = sigmoid(z)                   # probability of class 1 for each point
    loss = bce(p, y)
    err = p - y                      # dLoss/dz for every point (same p - y as softmax + cross-entropy)
    grad_w = X.T @ err / len(y)      # (2, 100) @ (100,) -> (2,)
    grad_b = err.mean()
    w -= lr * grad_w                 # step downhill
    b -= lr * grad_b
    if step % 50 == 0:
        acc = np.mean((p >= 0.5) == y)
        print(f"step {step:3d}  loss {loss:.4f}  accuracy {acc:.2f}")

# 3. Use the trained model
p = sigmoid(X @ w + b)
print(f"\nweights = [{w[0]:.3f}, {w[1]:.3f}]  bias = {b:.3f}")
print(f"final accuracy = {np.mean((p >= 0.5) == y):.2f}")
for point in ([-2.0, -1.5], [0.0, 0.0], [1.5, 2.0]):
    q = sigmoid(np.dot(point, w) + b)
    print(f"P(class 1 | x = {point}) = {q:.4f}")
  1. rng.normal(loc=[-1, -1], scale=0.8, size=(n, 2)): 50 points scattered around (−1, −1) for class 0, and 50 around (+1, +1) for class 1. The clouds overlap a little, so a perfect score is impossible.
  2. np.vstack and np.concatenate: stack them into X of shape (100, 2) and labels y of shape (100,). The first print checks the shapes and the class balance.
  3. bce: binary cross-entropy. np.clip(p, eps, 1 - eps) keeps probabilities away from exactly 0 and 1 so log never sees 0.
  4. w = np.zeros(2), b = 0.0: start knowing nothing. Every score is 0, every probability 0.5, and the loss is log 2 ≈ 0.6931.
  5. z = X @ w + b: the forward pass for all 100 points in one line; p = sigmoid(z) turns scores into probabilities.
  6. err = p - y: the gradient of the loss with respect to each score.
  7. grad_w = X.T @ err / len(y): (2, 100) @ (100,) → (2,), one gradient per weight, exactly the equation above.
  8. w -= lr * grad_w: the update. The loop prints loss and accuracy every 50 steps.
  9. The last lines use the trained model on three new points: far on the class-0 side, exactly in the middle, and far on the class-1 side.
X: (100, 2)  y: (100,)  class balance: 50 of 100
step   0  loss 0.6931  accuracy 0.50
step  50  loss 0.1510  accuracy 0.95
step 100  loss 0.1407  accuracy 0.95
step 150  loss 0.1378  accuracy 0.95
step 200  loss 0.1367  accuracy 0.95
step 250  loss 0.1362  accuracy 0.95
step 300  loss 0.1359  accuracy 0.95

weights = [2.495, 2.641]  bias = -0.230
final accuracy = 0.95
P(class 1 | x = [-2.0, -1.5]) = 0.0001
P(class 1 | x = [0.0, 0.0]) = 0.4429
P(class 1 | x = [1.5, 2.0]) = 0.9998

The loss drops quickly from 0.6931 and then levels off around 0.136 while accuracy stays at 0.95: the 5 misclassified points sit in the overlap of the two clouds, and no straight line can separate them. That is an important lesson about models in general: a model can only be as good as its form allows. Logistic regression draws a straight boundary (where w·x+b=0); a neural network with hidden layers (lesson 3.6) can draw curved ones. The point (0, 0) gets 0.4429, close to 0.5, because it sits near the boundary.

Five NumPy pitfalls that silently break ML code

The most expensive bugs in ML code don't crash. They produce numbers that look plausible, and the model trains a bit worse, or not at all, with no error message. These five cause a large share of them.

# @run
# Lesson 2.6: five NumPy pitfalls that silently break ML code, and how to catch them.
import numpy as np

# 1. Shape (n,) versus (n, 1): broadcasting turns a subtraction into a 3 x 3 matrix
pred = np.array([0.9, 0.2, 0.7])              # shape (3,)
target = np.array([[1.0], [0.0], [1.0]])      # shape (3, 1), e.g. sliced from a 2-D table
diff = pred - target
print("1. pred", pred.shape, "- target", target.shape, "->", diff.shape, " (expected (3,))")
print("   wrong MSE:", f"{np.mean(diff ** 2):.4f}", "  right MSE:", f"{np.mean((pred - target.ravel()) ** 2):.4f}")
assert (pred - target.reshape(-1)).shape == pred.shape   # a one-line shape check catches it

# 2. Integer arrays stay integer: writing floats into them truncates silently
counts = np.array([3, 1, 4])                  # an integer dtype (int64 on most machines)
counts[0] = 2.9
print("2. after counts[0] = 2.9 ->", counts.tolist(), " integer dtype:", bool(np.issubdtype(counts.dtype, np.integer)))
try:
    counts *= 0.5                             # in-place multiply cannot store 1.5 in an int array
except TypeError:
    print("   counts *= 0.5 raises a TypeError (cannot cast float results into int)")
print("   counts / 2 makes a new float array:", (counts / 2).tolist(), "  counts // 2:", (counts // 2).tolist())

# 3. Slices are views: changing the slice changes the original
weights = np.array([1.0, 2.0, 3.0, 4.0])
first_two = weights[:2]                       # a view, not a copy
first_two[0] = 100.0
print("3. weights after editing the slice:", weights.tolist())
safe = weights[:2].copy()
safe[0] = -1.0
print("   after editing a .copy(), weights is unchanged:", weights.tolist())

# 4. In-place updates on an array that something else still refers to
old = np.array([0.5, 0.5])
w = old                                       # NOT a copy: two names, one array
w -= 0.1                                      # in-place: old changes too
print("4. old after w -= 0.1:", old.tolist(), "  (use w = w - 0.1 or old.copy())")

# 5. Seeds: a Generator with the same seed gives the same numbers; different seeds differ
a = np.random.default_rng(42).normal(size=3)
b = np.random.default_rng(42).normal(size=3)
c = np.random.default_rng(7).normal(size=3)
print("5. same seed equal:", bool(np.array_equal(a, b)), "  different seed equal:", bool(np.array_equal(a, c)))

# Bonus: the axis argument decides what you average over
batch = np.array([[1.0, 2.0, 3.0],
                  [4.0, 5.0, 6.0]])          # 2 examples x 3 features
print("   mean over axis 0 (per feature):", batch.mean(axis=0).tolist())
print("   mean over axis 1 (per example):", batch.mean(axis=1).tolist())
  1. Shape (n,) versus (n, 1). Subtracting a (3, 1) column from a (3,) vector broadcasts to a (3, 3) matrix: every prediction is compared with every target. The "MSE" is computed without complaint and is wrong (0.3133 instead of 0.0467). The assert line shows the cheap guard: check that the result has the shape you expect.
  2. Integer arrays stay integer. np.array([3, 1, 4]) has an integer dtype, so assigning 2.9 stores 2, and an in-place *= 0.5 raises a TypeError. Create float arrays (np.array([3.0, 1.0, 4.0]) or dtype=float) for anything you will do maths on.
  3. Slices are views. weights[:2] doesn't copy; changing the slice changes the original. Use .copy() when you need an independent array.
  4. Two names, one array. w = old doesn't copy either, and w -= 0.1 modifies the array in place, so old changes too. This bites when you "save the best weights so far" by plain assignment.
  5. Seeds. Generators made with the same seed give the same numbers; different seeds give different ones. Seed your experiments so you can tell a real improvement from luck.
  6. Bonus, axes. mean(axis=0) averages down the rows (one result per feature), axis=1 across the columns (one per example). Normalising over the wrong axis is another silent bug.
1. pred (3,) - target (3, 1) -> (3, 3)  (expected (3,))
   wrong MSE: 0.3133   right MSE: 0.0467
2. after counts[0] = 2.9 -> [2, 1, 4]  integer dtype: True
   counts *= 0.5 raises a TypeError (cannot cast float results into int)
   counts / 2 makes a new float array: [1.0, 0.5, 2.0]   counts // 2: [1, 0, 2]
3. weights after editing the slice: [100.0, 2.0, 3.0, 4.0]
   after editing a .copy(), weights is unchanged: [100.0, 2.0, 3.0, 4.0]
4. old after w -= 0.1: [0.4, 0.4]   (use w = w - 0.1 or old.copy())
5. same seed equal: True   different seed equal: False
   mean over axis 0 (per feature): [2.5, 3.5, 4.5]
   mean over axis 1 (per example): [2.0, 5.0]

Watch gradient descent fit a line

The mini-project below fits a straight line y = m·x + c to noisy points by gradient descent on the mean squared error. Try it here first. Step a few times and watch the line swing into place; then try a learning rate that is too large and watch it blow up.

Fitting a line by gradient descentInteractive

The demo generates its own random points in JavaScript (true slope 3, intercept 2, as in the Python file), so its numbers differ slightly from the file's output below.

Vectorisation, closed-form solutions and when not to use gradient descent

Vectorise. Every loop in this lesson runs over training steps, never over individual examples or features: X @ w computes all 100 scores in one call into optimised compiled code. A Python loop over examples would give identical numbers and run tens to hundreds of times slower. Deep-learning frameworks push the same idea further onto GPUs; "write it as array operations" is the habit that makes model code fast.

Closed forms. Fitting a line with squared error has an exact answer: set both partial derivatives to zero and solve the two linear equations, the normal equations (ATA)θ=ATy, where each row of A is [x, 1]. The mini-project checks gradient descent against that answer and against np.linalg.lstsq, which solves the same problem more robustly. Logistic regression and neural networks have no closed form, which is why we need iterative methods at all.

Feature scaling. Our x values run from 0 to 10, so the slope's gradient is about ten times larger than the intercept's and the learning rate has to suit the steeper direction. That's why the intercept converges more slowly than the slope in the output. Standardising inputs (lesson 2.3) makes all directions similar and lets one learning rate work well for every parameter, one of the jobs normalisation layers do inside transformers.

Common mistakes and debugging tips

The loss doesn't go down at all

Usual suspects, in order: the update has the wrong sign; gradients are computed but never applied (for example updating a copy); the learning rate is far too small; or the labels don't line up with the inputs.

Fix: print the loss for the first 5 steps; check with a single example that one step lowers the loss; check the gradient numerically.

The loss becomes nan or inf

A learning rate that is too large makes parameters explode, then exp overflows or log(0) appears.

Fix: lower the learning rate, clip probabilities before taking logs, and use stable softmax/log-sum-exp.

Accuracy looks great but means nothing

On a dataset that is 95% class 0, always answering 0 scores 95% accuracy. And measuring on the training data rewards memorisation.

Fix: print the class balance (as the logistic file does), compare against a trivial baseline, and evaluate on held-out data the model never trained on (lesson 10.8).

Silent broadcasting in the loss

A (n, 1) target minus a (n,) prediction becomes (n, n) and the training "works" on a nonsense loss.

Fix: flatten targets with .reshape(-1) and assert the shape of the difference before averaging it.

Key takeaways

  • Every model trains with the same loop: forward, loss, backward, update.
  • Logistic regression is one sigmoid neuron trained with binary cross-entropy; its gradient is Xᵀ(p − y)/N.
  • Check shapes, dtypes, views and seeds: the worst ML bugs don't raise errors.
  • When an exact answer exists, use it to check your gradient-descent code.

Exercise: move the boundary

In logistic_regression.py, the decision boundary is where w·x+b=0. (a) Using the trained weights printed in the output (w = [2.495, 2.641], b = −0.230), work out by hand whether the point (0.5, −0.3) is predicted as class 1. (b) Change the class-1 cloud's centre from (1, 1) to (2, 2), run it, and explain what happens to the final accuracy and why.

Hint

(a) Compute z = 2.495 × 0.5 + 2.641 × (−0.3) − 0.230 and look at its sign: positive means p > 0.5. (b) Think about how much the two clouds overlap when their centres are further apart.

Show a solution

(a) z = 1.2475 − 0.7923 − 0.230 = 0.2252 > 0, so p = σ(0.2252) ≈ 0.556 and the prediction is class 1, though not confidently: the point is near the boundary.

(b) With centres at (−1, −1) and (2, 2), the clouds barely overlap, so a straight line separates every point and the final accuracy rises to 1.00 (with seed 0). The loss also falls lower, because the model can afford to be more confident. Data that is easier to separate gives a better model with no change to the code: the data matters at least as much as the algorithm.

Mini-project: fit a line two ways

Build, from scratch with NumPy, a program that fits a straight line to noisy data by gradient descent, then proves it found the right answer by comparing with the exact least-squares solution. It uses every idea in this module: vectors and dot products, a matrix for the closed form, a loss, derivatives, and the training loop.

  1. Make data. With rng = np.random.default_rng(0), draw 60 values of x uniformly between 0 and 10 and set y = 3x + 2 plus Gaussian noise with standard deviation 1.5.
  2. Loss. Write mse(m, c), the mean of (m·x + c − y)².
  3. Gradients by hand. Differentiate: dMSE/dm = 2·mean(err·x) and dMSE/dc = 2·mean(err), where err = m·x + c − y. Check them numerically once with a central difference.
  4. Train. Start from m = c = 0 and run gradient descent with learning rate 0.01 for 5,000 steps, printing m, c and the MSE at a few steps.
  5. Exact answer. Build A with rows [x, 1] (np.column_stack) and solve the normal equations np.linalg.solve(A.T @ A, A.T @ y). Also try np.linalg.lstsq.
  6. Compare. Print both answers and whether they agree to 3 decimals. Then explain why neither equals exactly (3, 2).
  7. Stretch. Try learning rates 0.001 and 0.03 and describe what happens; then standardise x first and see how many steps you need now.
Hints / reference solution

Keep all the arithmetic vectorised: err is a (60,) array and every gradient is one np.mean. If the MSE grows, your learning rate is too large or a sign is flipped. Here is a reference solution and its output:

# @run
# Lesson 2.6 mini-project (reference solution): fit a line y = m*x + c with gradient descent,
# then compare with the exact closed-form least-squares answer.
import numpy as np

rng = np.random.default_rng(0)
x = rng.uniform(0.0, 10.0, size=60)
y = 3.0 * x + 2.0 + rng.normal(0.0, 1.5, size=60)      # true slope 3, intercept 2, plus noise

def mse(m, c):
    return np.mean((m * x + c - y) ** 2)

# 1. Gradient descent on the mean squared error
m, c = 0.0, 0.0
lr = 0.01
for step in range(5001):
    err = m * x + c - y                  # prediction minus target, shape (60,)
    grad_m = 2.0 * np.mean(err * x)      # dMSE/dm
    grad_c = 2.0 * np.mean(err)          # dMSE/dc
    m -= lr * grad_m
    c -= lr * grad_c
    if step in (0, 10, 100, 1000, 5000):
        print(f"step {step:4d}  m = {m:.4f}  c = {c:.4f}  MSE = {mse(m, c):.4f}")

# 2. Closed form: solve the normal equations (A^T A) theta = A^T y with A = [x, 1]
A = np.column_stack([x, np.ones_like(x)])               # shape (60, 2)
m_exact, c_exact = np.linalg.solve(A.T @ A, A.T @ y)
print(f"\nclosed form    m = {m_exact:.4f}  c = {c_exact:.4f}  MSE = {mse(m_exact, c_exact):.4f}")
print(f"gradient desc. m = {m:.4f}  c = {c:.4f}  MSE = {mse(m, c):.4f}")
print("agree to 3 decimals:", bool(abs(m - m_exact) < 1e-3 and abs(c - c_exact) < 1e-3))

# 3. Same answer from NumPy's least-squares solver
theta, *_ = np.linalg.lstsq(A, y, rcond=None)
print(f"np.linalg.lstsq m = {theta[0]:.4f}  c = {theta[1]:.4f}")
step    0  m = 2.2735  c = 0.3457  MSE = 36.5476
step   10  m = 3.2281  c = 0.5719  MSE = 2.9516
step  100  m = 3.1415  c = 1.1567  MSE = 2.5577
step 1000  m = 2.9917  c = 2.1668  MSE = 2.2904
step 5000  m = 2.9901  c = 2.1779  MSE = 2.2903

closed form    m = 2.9901  c = 2.1779  MSE = 2.2903
gradient desc. m = 2.9901  c = 2.1779  MSE = 2.2903
agree to 3 decimals: True
np.linalg.lstsq m = 2.9901  c = 2.1779

Both methods give m = 2.9901, c = 2.1779. They don't equal (3, 2) because the noise in 60 points shifts the best-fitting line slightly; with more data the estimates would move closer to the true values. Notice that the intercept is still noticeably off after 100 steps while the slope is already close: with unscaled x, the two directions have very different steepness. With learning rate 0.03 the updates overshoot and the MSE explodes; with 0.001 the slope is close after 5,000 steps but the intercept is still about 2.04 instead of 2.18, because the flat intercept direction converges very slowly.

Check your understanding

What are the four steps of a training loop, in order?

  1. Update, forward, loss, backward
  2. Forward, loss, backward, update
  3. Backward, forward, update, loss
You must predict (forward) before you can measure the error (loss), need the loss before computing gradients (backward), and need gradients before stepping (update).

pred has shape (4,) and target has shape (4, 1). What is the shape of pred - target?

  1. (4,)
  2. (4, 1)
  3. (4, 4)
Broadcasting lines shapes up from the right: (4,) acts like (1, 4), and (4, 1) − (1, 4) expands to (4, 4). That's the silent bug from pitfall 1; flatten the target first.

Logistic regression on two overlapping clouds stops improving at 95% accuracy. Why?

  1. It can only draw a straight boundary, and some points lie on the wrong side of any straight line
  2. The learning rate is too small
  3. The sigmoid function saturates at 95%
The loss has levelled off, so training has converged; the limit is the model's form, not the optimiser. Sigmoid outputs can approach 1 but that has nothing to do with accuracy reaching 95%.