Math for Deep Learning Intro
A deep network is a long chain of matrix multiplications and simple nonlinear functions, trained by following gradients computed with the chain rule. That one sentence hides a lot of mathematics: why the chain rule is computed backwards, why weights must start at a particular scale, why Adam divides by a square root, why attention scales by , and why a language model's quality is reported as a perplexity. This course derives each of these and computes it in NumPy.
The reference book
The first part of the course follows Part I ("Applied Math and Machine Learning Basics") of Deep Learning by Ian Goodfellow, Yoshua Bengio and Aaron Courville (MIT Press, 2016), which the authors make freely readable online at deeplearningbook.org. The later parts cover the mathematics of modern networks (normalization, Adam, transformers, LLMs) that came after or beyond that book. Thanks to the authors for making it openly available.
The book is used only as a map of topics. All explanations, numbers, code and exercises here are written from scratch for this site, and every example runs in your browser with NumPy alone; no deep-learning framework is needed.
What is in the course
| Part | Topics |
|---|---|
| Foundations refresher | tensors and shapes, broadcasting and einsum, probability, entropy and KL divergence |
| Numerical computation | floating-point formats, overflow and a stable softmax, conditioning, curvature |
| Machine-learning basics | capacity and generalization, maximum likelihood and cross-entropy, losses, regularization |
| Feedforward networks | the perceptron, activations, the forward pass, XOR and depth |
| Backpropagation | computational graphs, backprop through an MLP, softmax-cross-entropy, forward and reverse mode, a tiny autodiff engine, vanishing gradients |
| Initialization and normalization | Xavier and He initialization, batch norm, layer norm and RMSNorm, residual connections |
| Optimizers | mini-batch SGD, momentum, AdaGrad and RMSProp, Adam and AdamW, schedules and clipping |
| Convolutional networks | convolution, padding and stride, pooling and receptive fields, convolution backprop |
| Recurrent networks | RNNs, backpropagation through time, LSTM and GRU gates |
| Attention and transformers | embeddings, scaled dot-product and multi-head attention, causal masks, positional encodings, the transformer block, parameter and FLOP counts |
| LLM math | tokenization (BPE), next-token likelihood, perplexity, temperature and top-p sampling, scaling laws, the KV cache, LoRA |
| Reinforcement learning | Markov decision processes, Bellman equations, policy gradients and RLHF |
What you should know first
This course builds directly on Math for Machine Learning (gradients, Jacobians, probability, optimization). For background it links instead of repeating:
- Linear Algebra & Matrix Theory, especially Neural Network Layers as Matrices and Attention as Matrix Products.
- Calculus Essentials, especially Backpropagation and Automatic Differentiation.
- Generative AI & LLMs for the practical, non-mathematical side of language models.
Here is the whole course in miniature: a one-hidden-layer network's forward pass, its loss, and one gradient step that lowers the loss.
import numpy as np
rng = np.random.default_rng(0)
x, y = np.array([0.5, -1.0, 2.0]), 1 # one input, true class 1 of 3
W1, W2 = rng.normal(0, 0.5, (4, 3)), rng.normal(0, 0.5, (3, 4))
def forward(W1, W2):
h = np.maximum(0, W1 @ x) # ReLU hidden layer
z = W2 @ h # logits
p = np.exp(z - z.max()); p /= p.sum() # softmax
return h, p, -np.log(p[y]) # cross-entropy loss
h, p, loss = forward(W1, W2)
g_z = p.copy(); g_z[y] -= 1 # dLoss/dlogits = p - onehot(y)
g_W2 = np.outer(g_z, h)
g_h = W2.T @ g_z; g_h[h <= 0] = 0
g_W1 = np.outer(g_h, x)
_, _, loss2 = forward(W1 - 0.5 * g_W1, W2 - 0.5 * g_W2)
print("probabilities:", np.round(p, 4))
print(f"loss before {loss:.4f}, after one step {loss2:.4f}")probabilities: [0.1473 0.2844 0.5683]
loss before 1.2575, after one step 0.5656
Every line of this program is a lesson of the course: ReLU (Activation Functions), softmax (Overflow, Underflow and a Stable Softmax), cross-entropy (Maximum Likelihood and Cross-Entropy), the gradient (Softmax and Cross-Entropy Gradient) and backprop (Backpropagation Through an MLP).
How lessons work
Each lesson explains one idea, writes its formulas in math notation (, , ), computes it in NumPy, and ends with an In software note on how PyTorch, JAX or LLM libraries do it, exercises with answers and worked solutions, and a short quiz.
Tip: Shapes are the grammar of deep learning. Before reading any formula, ask what the shape of each symbol is; most bugs in network code are shape bugs.
Learning paths
| Your goal | Suggested route |
|---|---|
| Understand LLMs | Math for ML (parts 1, 4, 5) → this course (backprop, attention, LLM math) → Information Theory → Generative AI & LLMs |
| Train networks well | this course (initialization, normalization, optimizers) → Optimization → Deep Learning (the same ideas in PyTorch) |
| Computer vision | this course (convolutional networks) → Fourier Analysis & Signals |
Exercises
Exercise 1: Count parameters
A dense layer maps 784 inputs to 128 outputs with a bias. How many parameters does it have?
Answer
.
Solution
The weight matrix is numbers, plus 128 biases: .
Exercise 2: Cross-entropy of a guess
A 10-class model outputs the uniform distribution. What is its cross-entropy loss for any example?
Answer
.
Solution
The true class gets probability and the loss is . A freshly initialized classifier usually starts near this value, a useful sanity check.
Exercise 3: Shapes of a batch (code)
A batch of 32 inputs with 3 features passes through . Compute the hidden activations with rows as examples and print the shape.
Answer
, computed as .
Solution
With examples as rows, the layer is : .
import numpy as np
X = np.ones((32, 3)); W1 = np.ones((4, 3))
print((X @ W1.T).shape)(32, 4)
Test yourself
A deep network is trained mainly by…
- solving a linear system once
- gradient-based optimization with gradients from backpropagation
- random search over weights
- sorting the training data
For a classifier with a softmax output and cross-entropy loss, the gradient of the loss with respect to the logits is…
Which part of Goodfellow, Bengio and Courville's book does the start of this course follow?
- Part I: applied math and machine-learning basics
- Part III: research topics only
- the appendix only
- none