rumblr Work in progressWIP

● The AI Primer · The symbols reference

Math notation, from zero

This lesson covers Every symbol in an ML formula, as a short loop

Free lesson 27 min5 figures and diagrams12 interactive

What this is

What are these symbols?

The formulas in AI papers and machine learning code are written in a notation of a few dozen symbols, and most of them stand for a short loop over a list of numbers. Σ, for example, means “add up every number in the list”. Each symbol here comes with its loop written out in Python and numbers small enough to check by hand.

Why it matters: You need it when a decision rests on something written in symbols: the spec sheet of an AI model, a training config with β₁ = 0.9 in it, or a paper whose whole claim is one equation. The tell is skipping the equation to read the sentence after it.

At a glance

Key takeaways

  1. Σ is a loop that adds; Π is a loop that multiplies.
  2. A dot product multiplies matching entries and adds them up; it measures how much two vectors agree.
  3. A matrix multiply is a grid of dot products, and it is most of the work a neural network does.
  4. log undoes e, and it turns products into sums, which is why models work with log-probabilities.
  5. The gradient points uphill; training steps the other way.

How it works, from scratch

Each symbol below comes with its parts decoded, the formula read aloud as a sentence, a worked example with small numbers, and the same loop in Python. The Python uses plain loops rather than a fast library, so it can be read as the definition. The loops run over lists and tables of numbers, so those come first.

Chapter 1

Lists and tables of numbers: vectors and matrices

A formula names each number in a table by its row and its column. Click a number below to see its name.

A vector is a list of numbers, like a shopping receipt: (apples 3, bread 1, milk 2). A matrix is a table of numbers, like a spreadsheet with rows and columns.

is a vector with 3 entries. Its entries are written with a small subscript: , , . A matrix with 2 rows and 3 columns has shape , and means "row 2, column 3".

You see Say Python
(lowercase, sometimes bold x) "the vector x" x = [3, 1, 2]
"x sub i": the i-th entry x[i - 1] (maths counts from 1, Python from 0)
(uppercase) "the matrix A" A = [[1, 2, 3], [4, 5, 6]]
or row i, column j A[i - 1][j - 1]
"the set of all lists of d real numbers" any list of d floats
"x is a list of 768 numbers" len(x) == 768
shape: n rows, d columns np.zeros((n, d))

In a language model, a word's embedding is a vector, a batch of embeddings is a matrix with one row per word, and most of the model's weights are matrices.

Chapter 2

Σ (capital sigma): add them all up

The first loop adds a list up, the way you total a receipt:

The formula and its symbols

Symbols

Symbol Meaning
"sum": add up everything that follows
(below) start a counter called at 1
(above) stop after the counter reaches
the thing being added on each step
"and so on, following the same pattern"

In words: "for i from 1 to n, add up x sub i."

With the numbers: .

In Python
x = [1, 2, 3, 4]
total = 0
# Σ: visit each x_i, from i = 1 to n ...
for x_i in x:
    # ... and add it to a running total
    total += x_i
total  # → 10
# Python's built-in sum is the same loop
sum(x)  # → 10

Π (capital pi) is the same idea with multiplication: . It appears wherever independent chances combine: ten steps that each succeed 95% of the time all succeed with probability . Every step an AI agent adds to a task makes finishing it less likely in the same way (see How an AI agent plans a long task).

In Python:

x = [1, 2, 3, 4]
product = 1
# Π: the same loop, multiplying instead of adding
for x_i in x:
    product *= x_i
product  # → 24
# ten steps that each succeed 95% of the time
round(0.95 ** 10, 2)  # → 0.6

In code: product is Π written the same way: a loop with a running product that starts at 1. View source

Press Next i below to run the Σ loop one pass at a time, then switch to Π. Beside it, drag Steps to see the chance that every step of a task succeeds.

Chapter 3

The dot product: how much two lists agree

Two short lists of numbers can be drawn as two arrows. Drag the arrows below and watch their dot product change as they turn towards or away from each other.

Σ can also run over two lists at once. A recipe needs 2 eggs, 3 cups of flour and 1 cup of sugar, and eggs cost $1, flour $0.50 and sugar $2 per unit. The total cost is 2·1 + 3·0.5 + 1·2 = $5.50. Multiplying matching entries and adding the products is called a dot product.

The formula and its symbols

Symbols

Symbol Meaning
two vectors with the same number of entries,
the -th entries multiplied together
"dot": the whole multiply-then-add operation

In words: "multiply the lists position by position and add up the products."

With the numbers: .

In Python
a = [1, 2]
b = [3, 0.5]
# Σ over i of a_i times b_i
sum(a_i * b_i for a_i, b_i in zip(a, b))  # → 4.0

Draw each list as an arrow and the dot product is large when the arrows point the same way, zero when they are at right angles, and negative when they point apart. Attention and embedding search both use it to score how alike two vectors are.

Figure 1 · Diagram

Reading it: follow the arrows from left to right. The first entries of a and b meet in one multiply box and the second entries in the other, and both products flow into one addition. Longer lists add more multiply boxes, all feeding the same sum.

In code: dot is this loop, and it refuses two lists of different lengths. View source

Chapter 4

‖x‖: the length of a vector

Drag the tip of the arrow below and watch Pythagoras give its length, written ‖x‖.

An arrow has a length as well as a direction. Walk 3 blocks east and 4 blocks north and you are 5 blocks from where you started, as the crow flies (Pythagoras). A vector's length is found the same way:

The formula and its symbols

Symbols

Symbol Meaning
the norm (length) of , also written
the -th entry squared ()
square root

In words: "square every entry, add them up, and take the square root."

With the numbers: and .

In Python
import math
def length(x):
    # √ of Σ x_i²
    return math.sqrt(sum(x_i ** 2 for x_i in x))
length([3, 4])  # → 5.0
length([1, 2, 2])  # → 3.0

Dividing a vector by its length gives a unit vector of length 1 that points the same way. Embedding systems do this to their vectors so that a dot product compares direction only (see Similarity).

In code: norm is the square root of a vector's dot product with itself. View source

Chapter 5

Matrix multiply and transpose

Multiplying two matrices fills a new table one cell at a time. Click a cell of the answer below to see which row and which column made it.

A matrix can be read as a stack of vectors: its rows, or its columns. Transpose, written ("A transpose"), flips a table on its diagonal so rows become columns: a matrix becomes .

Matrix multiply, written with nothing in between, is a grid of dot products. The cell in row , column of the answer is row of dotted with column of .

The formula and its symbols

Symbols

Symbol Meaning
an matrix
an matrix; its row count must equal 's column count,
the answer's cell at row , column ; the answer is
the counter that walks along row of and down column of together

In words: "to fill cell (i, j), walk across row i of A and down column j of B at the same pace, multiplying and adding."

With the numbers: .

In Python
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
# A has m columns, B has m rows: they must match
m = len(B)
# (AB)_ij = Σ_k A_ik B_kj
AB = [[sum(A[i][k] * B[k][j] for k in range(m))
       for j in range(len(B[0]))]
      for i in range(len(A))]
AB  # → [[19, 22], [43, 50]]
# the transpose: rows become columns
[list(column) for column in zip(*A)]  # → [[1, 3], [2, 4]]

Figure 2 · Diagram

Reading it: a row of A and a column of B meet in one dot product, which fills one cell of the answer. A matrix multiply repeats this for every (row, column) pair, which is why a row of A and a column of B must be the same length. Most of the arithmetic in a neural network is matrix multiplies, and GPUs are built to do thousands of these multiply-adds at once.

In code: transpose turns columns into rows; matmul transposes B once, then fills each cell with one dot of a row of A and a column of B. View source

Chapter 6

e and log: exponentials and logarithms

So far the loops add and multiply. Two functions turn up wherever a formula deals in probabilities: the exponential and the logarithm that undoes it. Money in an account that compounds continuously at 100% a year grows by a factor of e ≈ 2.718 in one year. is that growth run for years. The natural logarithm (often just in ML papers) answers the reverse question: how many years of that growth turn 1 into ?

You see Say Example
or "e to the x" , , ,
or "log of y" , ,

Two facts about them matter in machine learning:

  1. is always positive and grows fast, which is why softmax uses it.
  2. . Logs turn multiplying into adding. The probability of a whole sentence is a product of thousands of small numbers, which would underflow to 0 on a computer. Its log is a sum of manageable negative numbers. This is why models work with "log-probabilities", and why the usual training loss for a classifier or a language model is (see Loss functions).

Figure 3 · Chart

−2 0 2 4 6 8 −4 −2 0 2 4 6 8 e and its undo button, ln ln 0.9 = -0.11 ln 0.01 = -4.61 e x   ( a l w a y s   >   0 ,   g r o w s   f a s t ) l n x e   ( u n d o e s   ) x mirror line y = x

e to the x stays above zero and climbs steeply; ln x mirrors it across y = x and plunges near 0, so ln 0.01 = -4.61 while ln 0.9 = -0.11

Reading it: the blue curve is always above zero and climbs steeply; every step of 1 to the right multiplies its height by 2.718. The red curve is the same curve mirrored across the dashed diagonal, because it undoes . It only exists for positive inputs, and it dives towards −∞ as its input approaches 0. That dive is why the training loss punishes a confident wrong answer: a model that gave the right answer a chance of 0.01 pays , against for a chance of 0.9.

Multiply a few hundred chances together and the answer becomes too small for a computer to hold. Drag Words below to find where that happens, and watch the sum of the logs stay an ordinary number.

Chapter 7

softmax and argmax

softmax uses to turn a list of scores into shares that are positive and sum to 1 (Attention takes it step by step):

The formula and its symbols

With the numbers: softmax(2.0, 1.0, 0.5) = (0.63, 0.23, 0.14).

In Python
import math
z = [2.0, 1.0, 0.5]
# e^(z_i) for each score
exps = [math.exp(z_i) for z_i in z]
# Σ_j e^(z_j)
total = sum(exps)
# each share of the total
[round(e / total, 2) for e in exps]  # → [0.63, 0.23, 0.14]
# argmax: the position of the largest
max(range(len(z)), key=lambda i: z[i])  # → 0

argmax is simpler. It answers "which position holds the largest value?", not "what is the largest value?". argmax(0.1, 7.0, 3.0) = position 2 (index 1 in Python). "Greedy decoding" in a language model is picking the argmax token every step.

In code: softmax subtracts the largest score before exponentiating, so the exponentials cannot overflow; argmax walks the list and remembers the position of the biggest value. View source

Drag the scores below and watch the shares follow. The crown marks the argmax.

Chapter 8

Mean, variance, standard deviation: the middle and the spread

Eight values sit on the line below. Drag one and watch their middle and their spread move.

A list of numbers, such as a class's test scores or the outputs of a layer, has a middle and a spread. Two classes can both average 70% on a test while in one everyone scored 68 to 72 and in the other scores ran from 30 to 100. The mean is the same, and the spread is not.

The formula and its symbols

Symbols

Symbol Meaning
(mu) the mean: the average
(sigma squared) the variance: the average squared distance from the mean; also written
(sigma) the standard deviation: the typical distance from the mean, in the data's own units
"add them up and divide by how many": an average

In words: "the mean is the average; the variance is the average squared distance from the mean; the standard deviation is its square root."

With the numbers: for (2, 4, 4, 4, 5, 5, 7, 9): μ = 40 / 8 = 5; the squared distances are (9, 1, 1, 1, 0, 0, 4, 16), which sum to 32, so σ² = 32 / 8 = 4 and σ = 2.

In Python
import math
x = [2, 4, 4, 4, 5, 5, 7, 9]
n = len(x)
# μ = (1/n) Σ x_i
mu = sum(x) / n
mu  # → 5.0
# the squared distances from μ
[(x_i - mu) ** 2 for x_i in x]  # → [9.0, 1.0, 1.0, 1.0, 0.0, 0.0, 4.0, 16.0]
# σ² = their average
variance = sum((x_i - mu) ** 2 for x_i in x) / n
# σ is its square root
variance, math.sqrt(variance)  # → (4.0, 2.0)

In a neural network, if the numbers passing from layer to layer spread wider at every layer, training becomes unstable. Normalization layers and careful initialization keep σ near 1 to prevent it (see Training deep neural networks and the √d_k in Attention).

Figure 4 · Chart

−10.0 −7.5 −5.0 −2.5 0.0 2.5 5.0 7.5 10.0 value 0 100 200 300 400 500 how many samples Same mean (μ = 0), different spread σ = 1 σ = 3

Two histograms share the mean 0, but the sigma 1 samples pile up tall and narrow while the sigma 3 samples spread about three times as wide

Reading it: both histograms are centred on the same mean (the dashed line), but the blue one is tall and narrow (σ = 1) while the red one is low and wide (σ = 3). The standard deviation is roughly how far from the dashed line a typical sample lands. About two thirds of samples fall within one σ of the mean.

In code: mean, variance and std are the three formulas above, each a short loop built on summation. View source

Chapter 9

Derivatives and gradients: which way is downhill?

A slope is how fast a curve rises as you move along it. Slide along the curve below to see the slope change, then step down a bowl the way training does.

Training a neural network means adjusting its weights until its errors are small, and derivatives say which way to adjust each one. Picture standing on a hillside in thick fog, trying to reach the valley. You cannot see it, but you can feel the slope under your feet: take a small step in the steepest downhill direction, feel again, and repeat. Neural networks are trained this way, and the method is called gradient descent.

The derivative of a function at a point is its slope there: how much the output changes per tiny nudge of the input.

The formula and its symbols

Symbols

Symbol Meaning
a function: put in, get a number out
or the derivative: the slope of at ("dee f dee x")
a tiny nudge, like 0.00001
"approximately equal": exact as shrinks to 0

In words: "nudge the input a hair up and a hair down, and see how much the output changes per unit of nudge."

With the numbers: for at : (3.00001² − 2.99999²) / 0.00002 = 6. The slope of at 3 is 6 (the rule is ).

In Python
def f(x):
    return x ** 2
h = 0.00001
# rise over run across a tiny step
round((f(3 + h) - f(3 - h)) / (2 * h), 6)  # → 6.0

With many inputs, nudge each one separately. The slope in each direction is a partial derivative, written (the curly ∂ just means "only this input moves, the others stay fixed"). Collect them into a vector and you have the gradient, written ("nabla f" or "grad f"). It points in the steepest uphill direction, so training steps the opposite way:

The formula and its symbols

Symbols

Symbol Meaning
(theta) all the model's adjustable numbers (its parameters or weights)
the loss: one number measuring how wrong the model is
the gradient of the loss: for each weight, how much the loss rises if that weight is nudged up
(eta) the learning rate: how big a step to take, e.g. 0.001

In words: "move every weight a small step in the direction that lowers the loss the fastest."

With the numbers: for the bowl at (1, 2), the gradient is (2, 4), pointing uphill away from the bottom at (0, 0). With η = 0.1, the step goes to (1 − 0.2, 2 − 0.4) = (0.8, 1.6), closer to the bottom.

In Python
# (x, y)
theta = [1.0, 2.0]
# ∇L for L = x² + y²: each slope is 2 times the value
gradient = [2 * theta[0], 2 * theta[1]]
gradient  # → [2.0, 4.0]
eta = 0.1
# θ_new = θ − η ∇L
[t - eta * g for t, g in zip(theta, gradient)]  # → [0.8, 1.6]

Figure 5 · Chart

−2 −1 0 1 2 x −2 −1 0 1 2 y L o s s   :   a r r o w s   p o i n t   d o w n h i l l x y 2 2 + gradient descent from (1, 2)

Arrows on circular contours point straight at the centre, longest on the steep rim; descent from (1, 2) takes big steps first, then ever smaller ones

Reading it: the rings are contour lines, as on a hiking map: every point on a ring has the same loss, and the bottom of the bowl is the centre. The arrows show the negative gradient at several spots. They always cross the rings at right angles, pointing straight downhill, and they are longer where the slope is steeper. The dotted path is gradient descent from (1, 2): big steps on the steep outer slope, shrinking steps as the ground flattens near the bottom.

The chain rule says how slopes combine when functions are chained: if , then . Multiply the slopes along the chain. Backpropagation is the chain rule applied backwards through every layer of a network, reusing work as it goes (see Neural networks).

In code: derivative measures a slope by nudging the input a hair up and a hair down; gradient does that for each input in turn and collects the slopes into one list. View source

Chapter 10

Probability notation

A language model gives every possible next word a probability, and its formulas write probabilities like this:

You see Say Meaning
or "probability of A" a number from 0 (never) to 1 (certain)
"probability of A given B" the chance of A once you know B happened
"probability of word t given the words before it" what a language model computes, one word at a time
"expected value of x" the average you'd get over many tries
"x is drawn from a normal distribution with mean 0 and variance 1" rng.standard_normal()

The bar in P(A | B) says to count only the cases where B happened. Press Given it says “free” below to count that way among a hundred emails.

Chapter 11

Big-O: how cost grows

, "order n squared", describes how cost grows as the input grows, ignoring constant factors. If doubles, an cost doubles and an cost quadruples. Attention is in sequence length, which is why long context is expensive (Attention).

Press Double n below and see what each growth rate does to the cost.

Chapter 12

Greek letters you'll meet

Letter Name Usually means
α alpha a mixing weight, or a learning rate
β beta momentum coefficients in optimizers (β₁, β₂); a strength knob in DPO
γ, β gamma, beta the learned scale and shift in normalization layers
δ delta a small change, or an error signal in backprop
ε epsilon a tiny number added to avoid dividing by zero
η eta the learning rate
θ theta all the model's parameters
λ lambda the strength of a penalty (weight decay)
μ mu a mean
σ sigma a standard deviation, or the sigmoid function
τ tau a temperature (sharpness of softmax)
∇ nabla the gradient
∂ "partial" a partial derivative

Flip the cards below to learn the table, then switch to Quiz me.

Test yourself

5 questions

Answer each one out loud or on paper before you open it.

Question 1Read aloud and evaluate it.Think it through, then reveal

"The sum, for i from 1 to 3, of i squared": 1 + 4 + 9 = 14.

Question 2What is (2, −1, 3) · (1, 4, 0), and what does its sign tell you?Think it through, then reveal

2 − 4 + 0 = −2. It's negative, so the vectors point somewhat apart.

Question 3A is 4 × 3 and B is 3 × 5. What shape is AB? What about BA?Think it through, then reveal

AB is 4 × 5. BA is not defined: B's 5 columns don't match A's 4 rows.

Question 4Why do language models add log-probabilities instead of multiplying probabilities?Think it through, then reveal

A product of thousands of numbers below 1 underflows to 0 in floating point. log(a·b) = log a + log b, so the product becomes a sum of moderate negative numbers.

Question 5What does ∇L tell you, and which way does training move?Think it through, then reveal

For every weight, how fast the loss rises as that weight increases. Training moves each weight the opposite way, scaled by the learning rate η.

Researcher's shelf

Further reading

  • 3Blue1Brown, Essence of Linear Algebra (vectors, matrices, dot products, visually): https://www.3blue1brown.com/topics/linear-algebra
  • 3Blue1Brown, Essence of Calculus (derivatives and the chain rule): https://www.3blue1brown.com/topics/calculus
  • Khan Academy, Linear algebra: https://www.khanacademy.org/math/linear-algebra
  • Deisenroth, Faisal and Ong, Mathematics for Machine Learning (free book): https://mml-book.github.io/
  • NumPy, absolute basics for beginners: https://numpy.org/doc/stable/user/absolute_beginners.html

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.