CONTENTS
CHAPTER 3

The Math and ML Foundations You Actually Need

6 MIN READ

Let’s settle the anxiety first: you do not need a math degree to be an excellent applied AI engineer. You do need intuition for a handful of concepts, and the deeper you go toward training and research, the more you’ll need fluency. This chapter gives you the intuitions and a realistic map of how far to go.

3.1 How much math, for which role?

Role Math needed
AI Product Engineer Intuition: vectors, similarity, probability. Enough to read a model card.
Applied AI Engineer Above, plus statistics for evals (variance, confidence intervals, significance).
ML / Fine-tuning Engineer Above, plus working linear algebra, gradients, loss functions, optimization.
Research Engineer Fluent linear algebra, calculus, probability; numerical stability; distributed training math.
Research Scientist All of the above, deeply, plus whatever your subfield needs (information theory, RL theory, statistics).

The good news: the core ideas are few and they recur everywhere.

3.2 Linear algebra: the language of neural networks

Vectors are lists of numbers, and you can think of them as points or arrows in space. A token embedding is a vector. An image is a (big) vector.

Dot product measures alignment: a⋅b=∑iaibia \cdot b = \sum_{i}a_{i}b_{i}. Large and positive means pointing the same way; zero means unrelated (orthogonal); negative means opposite. Cosine similarity is the dot product of normalized vectors, the workhorse of semantic search. Attention scores are dot products between queries and keys.

Matrices are transformations. Multiplying a vector by a matrix rotates, scales, projects, or mixes its dimensions. A neural network layer is essentially output = activation(W @ input + b). Learning means finding good values for WW.

Matrix multiplication is the whole game. Nearly all LLM compute is matrix multiplication. GPUs are fast at it. When people talk about FLOPs, tensor cores, and “memory-bound vs. compute-bound,” they’re talking about how fast you can multiply matrices and move them in and out of memory.

import numpy as np

# A tiny "layer": 4 input features → 3 output features
W = np.random.randn(3, 4)       # weights
b = np.zeros(3)                 # bias
x = np.array([1.0, 0.5, -0.2, 0.8])

h = np.maximum(0, W @ x + b)    # ReLU(Wx + b) — that's a neural network layer

Shapes are everything. The most common bug in ML code is a shape mismatch. Get into the habit of annotating tensor shapes in comments (# (batch, seq_len, d_model)), the same way you annotate types in TypeScript.

What to learn: vectors, dot products, matrix multiplication, transpose, the idea of a basis and of dimensionality reduction. Optional but valuable: eigenvectors and SVD, which underpin LoRA (Chapter 10) and many interpretability methods.

Best resource: 3Blue1Brown’s Essence of Linear Algebra (YouTube). Visual, intuitive, about three hours total.

3.3 Calculus: how models learn

You need exactly one idea from calculus, deeply: the gradient.

The derivative tells you how much the output changes when you nudge the input. The gradient is the multi-dimensional version: for a function of many variables (like a loss that depends on a billion weights), it’s a vector pointing in the direction of steepest increase.

Gradient descent: to minimize the loss, repeatedly step against the gradient:

w←w−η⋅∇wL\left. w\leftarrow w - \eta \cdot \nabla_{w}L \right.

where η\eta is the learning rate (step size). Too large and you overshoot and diverge. Too small and training takes forever.

Backpropagation is how you compute the gradient efficiently for a network with billions of parameters. It’s the chain rule applied systematically from the output back to the input. If LL depends on yy, which depends on ww, then ∂L∂w=∂L∂y⋅∂y∂w\frac{\partial L}{\partial w} = \frac{\partial L}{\partial y} \cdot \frac{\partial y}{\partial w}. The network is a computation graph; backprop walks it in reverse, multiplying local derivatives.

Here’s backprop for a single neuron, written out by hand:

# Forward:  y = w*x + b ;  loss = (y - target)^2
x, target = 2.0, 10.0
w, b = 1.0, 0.0
lr = 0.05

for step in range(50):
    y = w * x + b
    loss = (y - target) ** 2

    # Backward (chain rule):
    dloss_dy = 2 * (y - target)
    dloss_dw = dloss_dy * x      # dy/dw = x
    dloss_db = dloss_dy * 1      # dy/db = 1

    w -= lr * dloss_dw
    b -= lr * dloss_db

print(w * x + b)  # ≈ 10.0

Frameworks like PyTorch do this automatically (autograd): you write the forward pass, call loss.backward(), and every parameter gets its .grad. But building it by hand once, as in Karpathy’s micrograd video, makes it click permanently.

Variants you’ll hear about: SGD, momentum, Adam/AdamW (the default optimizer for transformers, which adapts the step size per parameter), learning-rate warmup and cosine decay, gradient clipping.

3.4 Probability and statistics: the language of uncertainty

LLMs are probability machines, and evals are statistics. Two areas matter.

Probability for understanding models

  • Probability distributions: The model outputs a categorical distribution over the vocabulary.
  • Softmax turns arbitrary scores (logits) into probabilities: pi=ezi∑jezjp_{i} = \frac{e^{z_{i}}}{\sum_{j}e^{z_{j}}}. Temperature divides the logits before softmax.
  • Cross-entropy loss: −log⁡p(correct token)- \log p\left( \text{correct token} \right). If the model gave the right token probability 0.9, the loss is about 0.1. If 0.01, about 4.6. Training minimizes the average over trillions of tokens.
  • Perplexity is elosse^{\text{loss}}: roughly, “how many tokens the model is choosing between, on average.” Lower is better.
  • Conditional probability: p(next∣previous)p\left( \text{next} \mid \text{previous} \right) is literally what an LLM computes.
  • Log probabilities (logprobs): Some APIs expose them. They’re useful for confidence estimation, classification, and detecting uncertainty.

Statistics for evals (more important than people think)

When you change a prompt and accuracy goes from 82% to 85% on 100 examples, is that real? Probably not. With n = 100, the 95% confidence interval for a proportion around 0.83 is roughly ±7.5 percentage points.

import math
def ci95(p, n):
    se = math.sqrt(p * (1 - p) / n)
    return (p - 1.96 * se, p + 1.96 * se)

ci95(0.83, 100)   # → (0.756, 0.904)
ci95(0.83, 1000)  # → (0.807, 0.853)

Learn: sample size and confidence intervals, variance across repeated runs (run each eval several times), paired comparisons (compare two systems on the same examples), and the base-rate fallacy. This alone puts you ahead of many teams shipping AI.

3.5 Core ML concepts in one place

These terms will come up constantly:

  • Model / parameters / weights: The learned numbers.
  • Training / validation / test split: Train on one set, tune on another, report on a held-out third. Never tune on your test set. The same principle applies to eval sets for prompts.
  • Overfitting: Memorizing training data instead of learning general patterns. The model looks great on training data and bad on new data. This applies to prompts too: a prompt over-tuned to 20 examples often fails on example 21.
  • Generalization: Performance on unseen data, which is the thing you actually care about.
  • Batch, epoch, step: A batch is a group of examples processed together; a step is one gradient update; an epoch is one pass over the dataset.
  • Hyperparameters: Settings you choose rather than learn (learning rate, batch size, number of layers).
  • Inference: Running a trained model to get predictions.
  • Fine-tuning: Continuing to train a pretrained model on new data.
  • Scaling laws: Empirical power-law relationships showing that loss falls predictably as you scale parameters, data, and compute (Kaplan et al. 2020; Hoffmann et al. 2022, the “Chinchilla” paper). They’re why labs could confidently invest in ever-larger training runs.

3.6 PyTorch in fifteen lines

PyTorch is the dominant framework for research and most training. If you understand this snippet, you understand the skeleton of every training loop, from MNIST to frontier LLMs:

import torch, torch.nn as nn

model = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()

for epoch in range(5):
    for x, y in train_loader:          # x: (batch, 784), y: (batch,)
        logits = model(x)               # forward pass  → (batch, 10)
        loss = loss_fn(logits, y)       # how wrong are we?
        opt.zero_grad()                 # clear old gradients
        loss.backward()                 # backprop: compute gradients
        opt.step()                      # update weights

Forward, loss, backward, step. Frontier-scale training adds data parallelism, model sharding, mixed precision, checkpointing, and a great deal of engineering, but the loop is the same.

3.7 A study plan that respects your time

If you’re targeting applied AI engineering (2–4 weeks, a few hours a week):

  1. 3Blue1Brown, Essence of Linear Algebra (chapters 1–4, 9).
  2. 3Blue1Brown, Neural Networks series (all of it, including the transformer and attention episodes).
  3. Karpathy, micrograd video (build backprop from scratch).
  4. A refresher on confidence intervals and hypothesis testing (any intro stats resource).

If you’re targeting ML engineering or research engineering (3–6 months), add:

  1. Karpathy’s full Neural Networks: Zero to Hero series (makemore → GPT → tokenizer).
  2. Mathematics for Machine Learning (Deisenroth, Faisal, Ong). Free online; do chapters 2–6.
  3. Deep Learning (Goodfellow, Bengio, Courville), chapters 6–8, or the more modern Understanding Deep Learning (Simon Prince, free online).
  4. fast.ai Practical Deep Learning for Coders: top-down and code-first, which suits engineers well.

Learning tip: As a developer, learn math through code. Every time you meet a formula, implement it in NumPy and test it on small numbers. Formulas that look intimidating are usually three lines of code.

Key takeaways

  • Applied AI needs intuition; training and research need fluency. Calibrate your study to your target role.
  • Linear algebra: vectors as meaning, dot products as similarity, matrix multiplication as computation.
  • Calculus: gradients and the chain rule are how every network learns.
  • Probability: softmax, cross-entropy, and logprobs explain model outputs. Statistics (confidence intervals, variance) make your evals trustworthy.
  • The training loop (forward, loss, backward, step) is universal.

Exercises

  1. Implement softmax, cross-entropy, and cosine similarity in NumPy. Check softmax against torch.softmax.
  2. Extend the single-neuron backprop example to two inputs and a hidden layer of two ReLU neurons. Verify your gradients against PyTorch autograd.
  3. Take an eval you might run (e.g., “classify 200 support tickets”). Compute how many examples you’d need to detect a 3-point accuracy improvement with reasonable confidence.
  4. Train the 15-line PyTorch model on MNIST. Then make the learning rate 100× bigger and watch it diverge. Make it 100× smaller and watch it crawl. Feel the hyperparameter.