The Agentic AI Codex
Ch 02 · Math & Statistics for AI
Chapter 02 · Theory + Math

The Math behind every model

Four mini-fields run inside every AI system: linear algebra (geometry of features), calculus (how loss decreases), probability (uncertainty + decoding), and statistics (what we can trust from data). You don’t need to be a mathematician — you need fluent intuition and a working memory of the key formulas.

2.1 · Why these four mini-fields

FieldWhat it gives youUsed in
Linear algebraRepresenting things as vectors and transforming themEmbeddings, attention, weights
CalculusTells the model how to change weightsBackprop, optimization
ProbabilityReasoning under uncertainty, generating samplesDecoding, RAG ranking, RLHF
StatisticsEstimating things from samples, evaluationMetrics, AB tests, eval harnesses

2.2 · Linear algebra — the geometry of features

Scalars, vectors, matrices, tensors

ObjectNotationOrderExample
Scalar$a$0A learning rate 0.001
Vector$\mathbf{v} \in \mathbb{R}^n$1A 1536-dim embedding
Matrix$\mathbf{W} \in \mathbb{R}^{m \times n}$2A weight matrix
Tensor$\mathcal{T}$≥ 3A batch of token embeddings

Dot product — the workhorse

The dot product of two vectors $\mathbf{a}, \mathbf{b} \in \mathbb{R}^n$ is

$\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i = \|\mathbf{a}\|\,\|\mathbf{b}\|\cos\theta$

Why it matters
The dot product measures alignment. Every attention head, every retrieval score, every similarity ranking is — at heart — a dot product.

Cosine similarity

The most-used embedding similarity:

$\cos(\theta) = \dfrac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\|\,\|\mathbf{b}\|} \in [-1, 1]$

  • $+1$ : identical direction (very similar)
  • $0$ : orthogonal (unrelated)
  • $-1$ : opposite (rare in embedding space)

Matrix multiplication

If $\mathbf{C} = \mathbf{A}\mathbf{B}$ with $\mathbf{A} \in \mathbb{R}^{m \times k}$ and $\mathbf{B} \in \mathbb{R}^{k \times n}$, then

$C_{ij} = \sum_{p=1}^{k} A_{ip}\,B_{pj}$

A neural layer is just $\mathbf{y} = \sigma(\mathbf{W}\mathbf{x} + \mathbf{b})$. Master matmul and 80% of model code reads naturally.

Norms, eigenvalues, SVD — intuition only

  • Norm $\|\mathbf{v}\|_2 = \sqrt{\sum v_i^2}$ — “how long is this vector”.
  • Eigenvectors of $\mathbf{A}$ are directions the matrix only stretches (doesn’t rotate). $\mathbf{A}\mathbf{v} = \lambda \mathbf{v}$.
  • SVD decomposes any matrix into rotate–stretch–rotate: $\mathbf{A} = \mathbf{U}\,\mathbf{\Sigma}\,\mathbf{V}^\top$. PCA and modern LoRA fine-tuning both ride on SVD intuition.

Two vectors, three angles

x y a b ≈ a (cos ≈ 0.98) c ⟂ a (cos ≈ 0)

RAG retrieval picks the closest vectors by cosine similarity — it is exactly this picture, in 1536 dimensions.

2.3 · Calculus — how the model learns

Derivative — the local slope

For a function $f : \mathbb{R} \to \mathbb{R}$, the derivative at $x$ is

$f'(x) = \lim_{h \to 0} \dfrac{f(x+h) - f(x)}{h}$

Gradient — derivative in many dimensions

For $f : \mathbb{R}^n \to \mathbb{R}$, the gradient is the vector of partial derivatives:

$\nabla f(\mathbf{x}) = \begin{bmatrix} \partial f / \partial x_1 \\ \vdots \\ \partial f / \partial x_n \end{bmatrix}$

It points in the direction of steepest ascent. Negate it and you have the direction of steepest descent — the basis of all training.

Gradient descent — one line of math, one line of code

$\mathbf{w}_{t+1} = \mathbf{w}_t - \eta \, \nabla_\mathbf{w}\, \mathcal{L}(\mathbf{w}_t)$

  • $\mathbf{w}_t$ : weights at step $t$
  • $\eta$ : learning rate (typically $10^{-5}$ to $10^{-2}$)
  • $\mathcal{L}$ : the loss we’re minimizing
# the universal training loop (any framework, any year)
for batch in data:
    preds = model(batch.x)
    loss  = loss_fn(preds, batch.y)
    loss.backward()           # auto-diff fills in ∂L/∂w for every weight
    optimizer.step()          # w ← w − η ∇L
    optimizer.zero_grad()

The chain rule — backprop’s engine

If $h = f(g(x))$, then $\dfrac{dh}{dx} = f'(g(x)) \cdot g'(x)$.

Stack 96 transformer layers, apply the chain rule layer by layer — that’s backpropagation. Modern autograd tracks this automatically; you write the forward pass, the library does the rest.

Gradient descent — visual

step 1 step 2 step 3 minimum Loss Weight

2.4 · Probability — the language of uncertainty

The big four to memorise

ConceptFormulaUsed in
Conditional$P(A \mid B) = \dfrac{P(A \cap B)}{P(B)}$Language modelling: $P(\text{next} \mid \text{context})$
Bayes' rule$P(A \mid B) = \dfrac{P(B \mid A) P(A)}{P(B)}$Updating beliefs from evidence
Expectation$\mathbb{E}[X] = \sum x_i\,p_i$Expected reward in RL
Variance$\mathrm{Var}(X) = \mathbb{E}[(X - \mu)^2]$Bias–variance tradeoff

Distributions you’ll actually meet

Bernoulli / Binomial

Coin flips. Classification head. Every "is this spam" decision.

Categorical / Softmax

Probabilities over many classes. Output of every LLM is a softmax over the vocab.

$p_i = \dfrac{e^{z_i}}{\sum_j e^{z_j}}$

Gaussian / Normal

Bell curve. Used for noise, initialisations, diffusion models.

$\mathcal{N}(x \mid \mu, \sigma^2)$

Beta & Dirichlet

Distributions over probabilities. Bayesian sampling, A/B test priors.

Sampling from an LLM is a probabilistic act

# logits = model(input)                ← raw scores over vocab
# probs  = softmax(logits / temperature)
# top_k / top_p truncate the tail, then we sample one token.

This is why temperature, top-p, and top-k are not magic dials — they are knobs on the categorical distribution above.

2.5 · Statistics — turning samples into beliefs

Descriptive stats — summary of a dataset

StatisticFormulaWhat it tells you
Mean$\bar{x} = \dfrac{1}{n}\sum x_i$Centre
Medianmiddle value when sortedRobust centre
Std deviation$s = \sqrt{\dfrac{1}{n-1}\sum (x_i - \bar{x})^2}$Spread
Percentilevalue at rank $p$%Latency SLOs (p50, p95, p99)

Inference — estimating from samples

  • Confidence interval: a range that captures the true value with probability $1-\alpha$.
  • Hypothesis test: is the observed difference larger than chance? Reject $H_0$ when $p < \alpha$.
  • Power: the probability you’ll detect a real effect of a given size.

The bias–variance decomposition

$\mathbb{E}\!\left[(y - \hat{f}(x))^2\right] \;=\; \underbrace{\big(\mathbb{E}[\hat{f}(x)] - f(x)\big)^2}_{\text{bias}^2} \;+\; \underbrace{\mathrm{Var}(\hat{f}(x))}_{\text{variance}} \;+\; \underbrace{\sigma^2}_{\text{irreducible noise}}$

Read this twice
The same equation explains underfitting (too much bias) and overfitting (too much variance). Every regularisation trick — dropout, weight decay, early stopping, more data — is an attempt to push one of these terms down without inflating the other.

Classification metrics

MetricFormula
Accuracy$(TP+TN) / (TP+TN+FP+FN)$
Precision$TP / (TP+FP)$ — “of what I flagged, how much was right”
Recall$TP / (TP+FN)$ — “of what was real, how much did I catch”
F1$2 \cdot \dfrac{P \cdot R}{P + R}$
AUC-ROCarea under ROC curve — threshold-agnostic ranking quality

2.6 · Information theory — what models actually minimize

Entropy

$H(p) = -\sum_i p_i \log p_i$

“How surprised am I, on average, by samples from $p$?” Low entropy → predictable distribution.

Cross-entropy — the LLM training loss

$H(p, q) = -\sum_i p_i \log q_i$

For language modelling, $p$ is the true next-token (a one-hot), and $q$ is the model’s predicted distribution. Minimising cross-entropy is equivalent to maximising the likelihood of the data under the model.

KL divergence

$D_{\mathrm{KL}}(p \,\|\, q) = \sum_i p_i \log \dfrac{p_i}{q_i}$

Distance from $p$ to $q$ (not symmetric). Used to keep RLHF and DPO fine-tunes close to the base model.

2.7 · A one-page visual cheat-sheet

Vector & dot product

$\mathbf{a}\cdot \mathbf{b} = \sum a_i b_i$. Powers similarity, attention, retrieval.

Matrix layer

$\mathbf{y} = \sigma(\mathbf{W}\mathbf{x} + \mathbf{b})$. Every neural network.

Gradient step

$\mathbf{w} \leftarrow \mathbf{w} - \eta\,\nabla \mathcal{L}$. All training.

Softmax

$p_i = e^{z_i}/\sum e^{z_j}$. Turns logits into probabilities.

Cross-entropy

$-\sum p_i \log q_i$. The LLM loss.

Bayes

$P(A\mid B) = P(B\mid A) P(A)/P(B)$. Belief updates.

2.8 · Practical notebook — math you can feel

# Tiny cosine similarity — same math as RAG retrieval
import numpy as np

a = np.array([0.2, 0.8, 0.1])
b = np.array([0.3, 0.7, 0.0])
c = np.array([0.9, 0.1, 0.4])

def cos(x, y):
    return np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))

cos(a, b)  # ≈ 0.99  → very similar (e.g. paraphrases)
cos(a, c)  # ≈ 0.46  → less similar (different topic)
# Hand-coded gradient descent on f(w) = (w - 3)^2
w, lr = 0.0, 0.1
for step in range(30):
    grad = 2 * (w - 3)
    w   -= lr * grad
print(w)   # ≈ 3.0 — found the minimum
# Softmax converts arbitrary scores into a probability distribution
import numpy as np

logits = np.array([2.0, 1.0, 0.1])
probs  = np.exp(logits) / np.exp(logits).sum()
# ≈ [0.66, 0.24, 0.10]   — sums to 1.0
# Higher temperature flattens it; lower temperature sharpens it.

2.9 · Self-check

Q1 · The cosine similarity between two perfectly orthogonal vectors is…
1
0
-1
∞
Q2 · Which loss does an LLM minimise during pre-training?
Mean squared error
Cross-entropy
Hinge loss
Accuracy
Q3 · Increasing temperature in softmax sampling…
Sharpens the distribution
Flattens it, increasing diversity
Makes sampling deterministic
Changes the training loss