TExcelTAD
Home › Math for Deep Learning & LLMs › Math for Deep Learning Intro

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 d\sqrt{d}, 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:

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.

python · try it yourself
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 p−y\mathbf{p} - \mathbf{y} (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 (∇θL\nabla_{\boldsymbol{\theta}}\mathcal{L}, softmax⁡(QKT/dk)V\operatorname{softmax}(QK^T/\sqrt{d_k})V, E[⋅]\mathbb{E}[\cdot]), 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

100 480100\,480.

Solution

The weight matrix is 128×784=100 352128 \times 784 = 100\,352 numbers, plus 128 biases: 100 352+128=100 480100\,352 + 128 = 100\,480.

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

ln⁡10≈2.303\ln 10 \approx 2.303.

Solution

The true class gets probability 110\frac{1}{10} and the loss is −ln⁡110=ln⁡10-\ln\frac{1}{10} = \ln 10. 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 W1∈R4×3W_1 \in \mathbb{R}^{4 \times 3}. Compute the hidden activations with rows as examples and print the shape.

Answer

(32,4)(32, 4), computed as XW1TXW_1^T.

Solution

With examples as rows, the layer is H=XW1TH = XW_1^T: (32×3)(3×4)=32×4(32 \times 3)(3 \times 4) = 32 \times 4.

python · try it yourself
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…

  1. solving a linear system once
  2. gradient-based optimization with gradients from backpropagation
  3. random search over weights
  4. 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…

  1. p\mathbf{p}
  2. p−y\mathbf{p} - \mathbf{y}
  3. log⁡p\log\mathbf{p}
  4. y\mathbf{y}

Which part of Goodfellow, Bengio and Courville's book does the start of this course follow?

  1. Part I: applied math and machine-learning basics
  2. Part III: research topics only
  3. the appendix only
  4. none