Skip to content
Sajith JeewanthaSoftware Engineer

Track 01 · Foundation

Math & Physics Foundations for ML

The math that deep learning actually uses — linear algebra, multivariable calculus, probability, optimisation, information theory — plus the physics ideas (energy, statistical mechanics, diffusion) behind modern generative models.

Last updated
Total effort
630 h · ≈ 63 weeks
Your progress

Overview

Every ML system is a few mathematical ideas wearing engineering clothes. A neural network is a chain of matrix multiplications (linear algebra), trained by following gradients (calculus) of a loss that is really a negative log-likelihood (probability), using an optimiser whose behaviour depends on curvature (optimisation), and judged by quantities like cross-entropy and KL divergence (information theory). Diffusion models, Hopfield networks and Boltzmann machines borrow directly from statistical physics. This track teaches that math in service of ML: each topic is paired with the exact place it appears in a model you'll build, so you learn it once, for a reason, and it sticks.

Why it matters heading into 2027

As AI tools write more of the routine code, the scarce skill is understanding — reading a new paper, debugging a training run, judging whether an eval result is real. All three depend on math. Research-heavy roles (training, post-training, inference optimisation, interpretability) explicitly screen for it, and the 2024 Nobel Prize in Physics, awarded to Hopfield and Hinton, recognised how deeply ML is rooted in physics. You don't need a math degree; you need fluent, working intuition for about a dozen ideas, and the ability to follow a derivation in a paper.

Prerequisites

  • High-school algebra and functions. Comfort with summation notation is not needed yet — we build it.
  • Python and NumPy, so every idea can be checked numerically.
  • Patience: work problems with pen and paper, then verify them in code.

Learning path

How the stages build on each other, and where this track hands off to others.

flowchart TB
  P["Prereqs: algebra · Python · NumPy"] --> B
  subgraph B["1 · Beginner — the working toolkit"]
    direction LR
    B1["vectors & matrices"] --> B2["derivatives & chain rule"] --> B3["probability basics"]
  end
  subgraph I["2 · Intermediate — math of training"]
    direction LR
    I1["gradients & Jacobians"] --> I2["MLE · MAP · Bayes"] --> I3["SVD & eigenvalues"] --> I4["gradient descent"]
  end
  subgraph A["3 · Advanced — reading papers"]
    direction LR
    A1["entropy · KL"] --> A2["convexity & curvature"] --> A3["matrix calculus"] --> A4["sampling & Monte Carlo"]
  end
  subgraph E["4 · Expert — physics of generative models"]
    direction LR
    E1["energy-based models"] --> E2["statistical mechanics"] --> E3["SDEs & diffusion"] --> E4["flow matching"]
  end
  B --> I --> A --> E
  I -.-> ML["ML Engineering"]
  A -.-> DL["Deep Learning"]
  E -.-> DL

Stages

Tick items as you go — progress is saved in this browser only. Times are focused hours (reading + building); the week estimates follow the study time you pick above.

01Beginner110 h · ≈ 11 weeksBuild a working toolkit: vectors, matrices, derivatives and basic probability — always connected to a line of NumPy you can run.

Key concepts

Build these

Ready for the next stage when…

02Intermediate150 h · ≈ 15 weeksThe math of training: gradients of vector functions, likelihood-based losses, matrix decompositions and gradient descent.

Key concepts

Build these

Ready for the next stage when…

03Advanced170 h · ≈ 17 weeksRead ML papers comfortably: information theory, convexity and curvature, matrix calculus, and sampling.

Key concepts

Build these

Ready for the next stage when…

04Expert200 h · ≈ 20 weeksThe physics behind modern generative models: energy-based models, statistical mechanics, stochastic differential equations and diffusion.

Key concepts

Build these

Ready for the next stage when…

Field guide

The ideas behind the checklist, with diagrams and the math where it helps.

The concept map

You don’t need all of mathematics. You need these ideas, and you need to see where each one lives in a model. Read the map left to right: each box is something you learn, and the arrow points to where it shows up in ML.

flowchart LR
  subgraph LA["Linear algebra"]
    direction TB
    la1["dot product · norms"]
    la2["matrix multiply"]
    la3["eigen · SVD · rank"]
  end
  subgraph CA["Calculus"]
    direction TB
    ca1["chain rule"]
    ca2["gradients · Jacobians"]
    ca3["Hessian · curvature"]
  end
  subgraph PR["Probability & stats"]
    direction TB
    pr1["distributions · expectation"]
    pr2["MLE · MAP · Bayes"]
    pr3["sampling · Monte Carlo"]
  end
  subgraph IT["Information theory"]
    direction TB
    it1["entropy · cross-entropy"]
    it2["KL divergence"]
  end
  subgraph PH["Physics"]
    direction TB
    ph1["energy · Boltzmann"]
    ph2["Langevin · SDEs"]
  end
  la1 --> E1["embeddings · attention scores"]
  la2 --> E2["every layer of a network"]
  la3 --> E3["LoRA · PCA · conditioning"]
  ca1 --> E4["backpropagation"]
  ca3 --> E5["optimisers · learning rates"]
  pr2 --> E6["loss functions · weight decay"]
  pr3 --> E7["VAEs · RL policy gradients"]
  it1 --> E8["LM training loss · perplexity"]
  it2 --> E9["RLHF · DPO · distillation"]
  ph1 --> E10["softmax · temperature · Hopfield"]
  ph2 --> E11["diffusion models"]

Linear algebra: the language of layers

A dense layer is a matrix–vector product plus a bias:

h=σ(Wx+b),W∈Rdout×dinh = \sigma(Wx + b), \qquad W \in \mathbb{R}^{d_\text{out} \times d_\text{in}}

Why it matters — embeddings and attention. An embedding is a vector, and “similar meaning” is measured with the dot product or cosine similarity:

cos⁡(u,v)=u⊤v∥u∥ ∥v∥\cos(u, v) = \frac{u^\top v}{\lVert u \rVert\, \lVert v \rVert}

That is the whole of vector search in AI Engineering, and attention scores QK⊤QK^\top are just a matrix of dot products between queries and keys.

Why it matters — SVD and LoRA. Any matrix factorises as W=UΣV⊤W = U \Sigma V^\top, where the singular values in Σ\Sigma say how much each direction matters. Keeping only the top rr gives the best rank-rr approximation (Eckart–Young). LoRA bets that the change needed to fine-tune a model is low-rank too:

W′=W+ΔW=W+BA,B∈Rd×r, A∈Rr×k, r≪min⁡(d,k)W' = W + \Delta W = W + BA, \qquad B \in \mathbb{R}^{d \times r},\ A \in \mathbb{R}^{r \times k},\ r \ll \min(d, k)

For a 4096×40964096 \times 4096 matrix and r=16r = 16, that’s about 131k131\text{k} trainable numbers instead of 16.8M16.8\text{M}, a 128× reduction.

Why it matters — eigenvalues and conditioning. For a symmetric matrix, the eigen-decomposition A=QΛQ⊤A = Q\Lambda Q^\top tells you how it stretches space. The condition number κ=λmax/λmin\kappa = \lambda_\text{max} / \lambda_\text{min} of a loss surface’s curvature decides how fast gradient descent converges: high κ\kappa means a long, narrow valley and zig-zagging steps. This is why normalisation layers and adaptive optimisers like Adam exist.

Calculus: the chain rule is backpropagation

For a composition L=f(g(h(x)))L = f(g(h(x))) the chain rule says

∂L∂x=∂f∂g⋅∂g∂h⋅∂h∂x\frac{\partial L}{\partial x} = \frac{\partial f}{\partial g}\cdot\frac{\partial g}{\partial h}\cdot\frac{\partial h}{\partial x}

A neural network is a long composition of layers, so the gradient of the loss with respect to any weight is a product of local derivatives. Backpropagation is just computing that product right to left, reusing intermediate results. That’s why it costs about as much as one forward pass, rather than one pass per parameter.

With vectors, each local derivative becomes a Jacobian matrix Jij=∂yi/∂xjJ_{ij} = \partial y_i / \partial x_j, and backprop multiplies vectors by Jacobians (“vector–Jacobian products”). The single most useful result to derive yourself is the softmax cross-entropy gradient. With logits zz, probabilities p=softmax⁡(z)p = \operatorname{softmax}(z) and one-hot target yy:

∂∂z(−∑kyklog⁡pk)=p−y\frac{\partial}{\partial z}\left(-\sum_k y_k \log p_k\right) = p - y

It’s beautifully simple, and it’s the gradient at the top of every language model.

Second order. The Hessian H=∇2LH = \nabla^2 L describes curvature. Near a minimum, L(θ+δ)≈L(θ)+12δ⊤HδL(\theta + \delta) \approx L(\theta) + \tfrac12 \delta^\top H \delta; the largest eigenvalue of HH caps the stable learning rate at about 2/λmax2/\lambda_\text{max}. Learning-rate warmup and “edge of stability” effects are about this number.

Probability: every loss is a likelihood

Maximum likelihood. Given data {xi}\{x_i\} and a model pθp_\theta, MLE picks

θ⋆=arg⁡max⁡θ∑ilog⁡pθ(xi)=arg⁡min⁡θ−1n∑ilog⁡pθ(xi)⏟negative log-likelihood\theta^\star = \arg\max_\theta \sum_i \log p_\theta(x_i) = \arg\min_\theta \underbrace{-\frac1n \sum_i \log p_\theta(x_i)}_{\text{negative log-likelihood}}

Why it matters. If the model outputs a categorical distribution, the NLL is cross-entropy, the loss of every classifier and language model. If it outputs a Gaussian mean with fixed variance, the NLL is (up to constants) mean-squared error. Choosing a loss means choosing a noise model.

MAP and weight decay. Adding a prior p(θ)p(\theta) and maximising the posterior gives MAP:

arg⁡max⁡θ[log⁡p(data∣θ)+log⁡p(θ)]\arg\max_\theta \left[\log p(\text{data}\mid\theta) + \log p(\theta)\right]

With a Gaussian prior θ∼N(0,σ2I)\theta \sim \mathcal{N}(0, \sigma^2 I), log⁡p(θ)=−12σ2∥θ∥2+const\log p(\theta) = -\frac{1}{2\sigma^2}\lVert\theta\rVert^2 + \text{const}, which is exactly L2 weight decay. A Laplace prior gives L1 (sparsity).

Statistics for evals. A benchmark score is an estimate. With nn questions and accuracy p^\hat p, the standard error is p^(1−p^)/n\sqrt{\hat p(1-\hat p)/n}; on 500 questions at 70%, that’s about ±2 points (95% interval ≈ ±4). Many “improvements” on small eval sets are noise.

Optimisation: from gradient descent to Adam

Plain gradient descent is θt+1=θt−η∇L(θt)\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t). Stochastic gradient descent uses a mini-batch estimate of ∇L\nabla L, which is noisy but cheap and, helpfully, acts as a regulariser.

Adam keeps running averages of the gradient and its square:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,θt+1=θt−η m^tv^t+ϵm_t = \beta_1 m_{t-1} + (1-\beta_1) g_t,\quad v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2,\quad \theta_{t+1} = \theta_t - \eta\,\frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon}

Dividing by vt\sqrt{v_t} rescales each coordinate. It’s a cheap, diagonal stand-in for curvature, which helps on the ill-conditioned surfaces from the linear algebra section.

Convexity. For convex problems (linear and logistic regression, SVMs) every local minimum is global, and theory guarantees convergence. Deep networks aren’t convex, but convex ideas still guide practice: Lagrange multipliers explain constrained objectives like the KL-constrained RLHF problem, and duality explains why some losses have closed-form optima.

Information theory: entropy, cross-entropy and KL

The entropy of a distribution is its average surprise, H(p)=−∑xp(x)log⁡p(x)H(p) = -\sum_x p(x)\log p(x). The cross-entropy of model qq under true distribution pp is H(p,q)=−∑xp(x)log⁡q(x)H(p, q) = -\sum_x p(x)\log q(x), and the gap between them is the KL divergence:

KL(p ∥ q)=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p) ≥0\mathrm{KL}(p\,\|\,q) = \sum_x p(x)\log\frac{p(x)}{q(x)} = H(p, q) - H(p) \ \ge 0

Why it matters — three places you’ll meet KL:

  1. Language-model training. H(p)H(p) of the data is fixed, so minimising cross-entropy minimises KL(pdata ∥ pθ)\mathrm{KL}(p_\text{data}\,\|\,p_\theta). Perplexity =eH= e^{H} is “how many tokens the model is effectively choosing between”.
  2. RLHF and DPO. The objective E[r(x,y)]−β KL(πθ ∥ πref)\mathbb{E}[r(x,y)] - \beta\,\mathrm{KL}(\pi_\theta\,\|\,\pi_\text{ref}) rewards good answers but charges for drifting from the reference model. DPO’s loss comes straight from the closed-form optimum of this objective (see Deep Learning).
  3. Distillation and VAEs. Knowledge distillation minimises KL between teacher and student distributions; a VAE’s ELBO contains a KL term that keeps the latent code close to a prior.

KL is asymmetric. KL(p∥q)\mathrm{KL}(p\|q) (“forward”, mass-covering) punishes qq for missing modes of pp; KL(q∥p)\mathrm{KL}(q\|p) (“reverse”, mode-seeking) punishes qq for putting mass where pp has none. The direction you choose changes the behaviour you get.

Physics I: energy, temperature and the Boltzmann distribution

Statistical mechanics says a system in equilibrium at temperature TT occupies state xx with probability

p(x)=e−E(x)/TZ,Z=∑x′e−E(x′)/Tp(x) = \frac{e^{-E(x)/T}}{Z}, \qquad Z = \sum_{x'} e^{-E(x')/T}

Why it matters — softmax is a Boltzmann distribution. Set the energy to the negative logit, Ek=−zkE_k = -z_k, and you get pk=ezk/T/∑jezj/Tp_k = e^{z_k/T} / \sum_j e^{z_j/T}: softmax with temperature. That’s why sampling “temperature” behaves like physical temperature. T→0T \to 0 freezes into the single lowest-energy (highest-logit) token; large TT melts toward uniform randomness.

Energy-based models define pθ(x)∝e−Eθ(x)p_\theta(x) \propto e^{-E_\theta(x)} with a learned energy. The hard part is always the partition function ZZ, a sum over every possible xx. Much of generative modelling is clever ways to avoid computing it: contrastive losses, score matching, and diffusion.

Physics II: Hopfield networks and attention

A Hopfield network stores patterns as low points of an energy function over binary states ss:

E(s)=−12∑i,jwij sisj,wij=∑μξiμξjμE(s) = -\tfrac12 \sum_{i,j} w_{ij}\, s_i s_j, \qquad w_{ij} = \sum_\mu \xi_i^\mu \xi_j^\mu

Updating each neuron to lower EE slides the state downhill into the nearest stored memory ξμ\xi^\mu. That is associative memory, and it’s part of why Hopfield shared the 2024 Nobel Prize in Physics.

Modern Hopfield networks (Ramsauer et al., 2020) use an exponential energy with continuous states, and their one-step update for a query ξ\xi against stored patterns XX is

ξnew=X softmax⁡ ⁣(βX⊤ξ)\xi^\text{new} = X\,\operatorname{softmax}\!\left(\beta X^\top \xi\right)

which is exactly Transformer attention with β=1/dk\beta = 1/\sqrt{d_k}. Attention can be read as one step of energy minimisation that retrieves the stored pattern best matching the query.

Physics III: diffusion as a stochastic process

Brownian motion adds Gaussian noise continuously. A diffusion model defines a forward process that gradually turns data into noise, in discrete form (DDPM):

q(xt∣xt−1)=N ⁣(xt; 1−βt xt−1, βtI)q(x_t \mid x_{t-1}) = \mathcal{N}\!\left(x_t;\ \sqrt{1-\beta_t}\,x_{t-1},\ \beta_t I\right)

or in continuous time as a stochastic differential equation, dx=f(x,t) dt+g(t) dwdx = f(x,t)\,dt + g(t)\,dw. Remarkably, the process has a reverse-time SDE that turns noise back into data, and it needs only the score ∇xlog⁡pt(x)\nabla_x \log p_t(x):

dx=[f(x,t)−g(t)2 ∇xlog⁡pt(x)]dt+g(t) dwˉdx = \left[f(x,t) - g(t)^2\,\nabla_x \log p_t(x)\right]dt + g(t)\,d\bar w

A neural network learns that score, which in practice is the same as predicting the added noise. DDPM’s training loss is then strikingly simple:

L=Et, x0, ϵ[∥ϵ−ϵθ(αˉt x0+1−αˉt ϵ, t)∥2]\mathcal{L} = \mathbb{E}_{t,\,x_0,\,\epsilon}\left[\lVert \epsilon - \epsilon_\theta(\sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\epsilon,\ t)\rVert^2\right]

Langevin dynamics is the physics behind sampling. Follow the score uphill while adding noise,

xk+1=xk+η2∇xlog⁡p(xk)+η zk,zk∼N(0,I)x_{k+1} = x_k + \frac{\eta}{2}\nabla_x \log p(x_k) + \sqrt{\eta}\,z_k, \qquad z_k \sim \mathcal{N}(0, I)

and the particles end up distributed according to pp. Flow matching (2022) learns a deterministic velocity field instead, so generation becomes solving an ODE with fewer steps.

flowchart LR
  X0["data x₀"] -- "add noise (forward SDE)" --> XT["pure noise x_T"]
  XT -- "denoise with learned score (reverse SDE)" --> XS["new sample"]
  NN["network ε_θ(x_t, t)<br/>≈ −σ·score"] -.-> XS

How to study this track

  1. Intuition, then formalism, then code. Watch the 3Blue1Brown video, read the MML chapter, then verify the result numerically in NumPy.
  2. Derive the six workhorse results yourself: softmax cross-entropy gradient, MSE as Gaussian NLL, L2 as a Gaussian prior, the DPO loss, the ELBO, and the DDPM loss.
  3. Interleave with building. Study Beginner math alongside the Deep Learning Beginner stage, so each idea has a model to live in.
  4. Keep a “math I used this week” log in your notes. Retrieval practice beats rereading.

How this track connects

References

Original sources first: arXiv, official docs, university courses and lab blogs. Every link was checked on 7 Nov 2026.

Foundational & seminal papers(12)

  1. Neural networks and physical systems with emergent collective computational abilities

    J. J. Hopfield · 1982 · doi.org

    Memory as minima of an energy function — the start of physics-inspired neural nets.

  2. A Learning Algorithm for Boltzmann Machines

    Ackley, Hinton & Sejnowski · 1985 · doi.org

    Learning with the Boltzmann distribution; statistical mechanics meets neural networks.

  3. A Tutorial on Energy-Based Learning

    LeCun et al. · 2006 · yann.lecun.com

    One framework that covers many losses as shaping an energy landscape.

  4. Deep Unsupervised Learning using Nonequilibrium Thermodynamics

    Sohl-Dickstein et al. · 2015 · arxiv.org

    The origin of diffusion models, explicitly built on non-equilibrium physics.

  5. The Matrix Calculus You Need For Deep Learning

    Parr & Howard · 2018 · arxiv.org

    Gradients of vector and matrix functions, explained for practitioners.

  6. Generative Modeling by Estimating Gradients of the Data Distribution

    Song & Ermon · 2019 · arxiv.org

    Score matching plus Langevin dynamics as a generative model.

  7. Denoising Diffusion Probabilistic Models

    Ho et al. · 2020 · arxiv.org

    DDPM — the simple noise-prediction loss behind modern image models.

  8. Hopfield Networks is All You Need

    Ramsauer et al. · 2020 · arxiv.org

    Modern Hopfield networks' update rule is the Transformer's attention.

  9. Score-Based Generative Modeling through Stochastic Differential Equations

    Song et al. · 2020 · arxiv.org

    Unifies diffusion and score models as forward and reverse-time SDEs.

  10. Statistical Mechanics of Deep Learning

    Bahri et al. · 2020 · doi.org

    Survey of what physics says about loss landscapes, generalisation and dynamics.

  11. Flow Matching for Generative Modeling

    Lipman et al. · 2022 · arxiv.org

    Simulation-free training of continuous flows; the successor to diffusion in many systems.

  12. Direct Preference Optimization: Your Language Model is Secretly a Reward Model

    Rafailov et al. · 2023 · arxiv.org

    A clean, readable derivation that uses KL, Bradley–Terry and a closed-form optimum — great Advanced-stage practice.

Courses & videos(6)

  1. Essence of Linear Algebra

    3Blue1Brown · youtube.com

    Geometric intuition first. Watch before any textbook.

  2. Essence of Calculus

    3Blue1Brown · youtube.com

    Derivatives and the chain rule as pictures.

  3. Neural Networks

    3Blue1Brown · youtube.com

    Backprop and Transformers visualised — the bridge from math to models.

  4. MIT 18.06 Linear Algebra

    Gilbert Strang, MIT OpenCourseWare · 2010 · ocw.mit.edu

    The classic course; do the problem sets for the Intermediate stage.

  5. MIT 18.02SC Multivariable Calculus

    MIT OpenCourseWare · 2010 · ocw.mit.edu

    Partial derivatives, gradients, Jacobians and Lagrange multipliers.

  6. Stat 110: Probability

    Joe Blitzstein, Harvard · stat110.hsites.harvard.edu

    The best introductory probability course, with a free textbook.

Books(9)

  1. Mathematics for Machine Learning

    Deisenroth, Faisal & Ong · 2020 · mml-book.github.io

    The core text for this track — free, and written exactly for ML.

  2. Linear Algebra and Learning from Data

    Gilbert Strang · 2019 · math.mit.edu

    SVD, low-rank approximation and optimisation aimed at deep learning.

  3. Convex Optimization

    Boyd & Vandenberghe · 2004 · web.stanford.edu

    Chapters 2–5 for convexity, duality and Lagrange multipliers; free PDF.

  4. Elements of Information Theory (2nd ed.)

    Cover & Thomas · 2006 · wiley.com

    The standard reference on entropy, KL divergence and coding.

  5. Information Theory, Inference, and Learning Algorithms

    David MacKay · 2003 · inference.org.uk

    Information theory and Bayesian inference together, with wit; free.

  6. Pattern Recognition and Machine Learning

    Christopher Bishop · 2006 · microsoft.com

    The probabilistic view of ML: MLE, MAP, Bayesian models; free PDF.

  7. Probabilistic Machine Learning (Introduction and Advanced Topics)

    Kevin Murphy · 2022 · probml.github.io

    Comprehensive modern reference, including diffusion and EBMs; free.

  8. Understanding Deep Learning

    Simon J. D. Prince · 2023 · udlbook.github.io

    Clear chapters on diffusion, flows and VAEs with just the math you need.

  9. The Matrix Cookbook

    Petersen & Pedersen · math.uwaterloo.ca

    A lookup table of matrix identities and derivatives — keep it open.

Articles, blogs & official docs(5)

  1. Calculus on Computational Graphs: Backpropagation

    Chris Olah · 2015 · colah.github.io

    Why reverse-mode autodiff is efficient, in one short read.

  2. The Matrix Calculus You Need For Deep Learning (HTML)

    Terence Parr & Jeremy Howard · explained.ai

    The readable web version of the paper above.

  3. Generative Modeling by Estimating Gradients of the Data Distribution (blog)

    Yang Song · 2021 · yang-song.net

    The clearest introduction to score-based models and SDEs.

  4. What are Diffusion Models?

    Lilian Weng · 2021 · lilianweng.github.io

    Diffusion math derived step by step, with all the notation in one place.

  5. The Nobel Prize in Physics 2024 — press release

    The Royal Swedish Academy of Sciences · 2024 · nobelprize.org

    A short, accessible account of how Hopfield networks and Boltzmann machines came from physics.