Library
Core
30 min read
Every key equation on this site, on one page, grouped by track, with each symbol named and a link to the page that derives it. Use it for revision and for decoding papers. The equations are few in kind: maximum likelihood, the chain rule, the Bellman equation and a KL penalty account for most of what follows.
10,000 ft
Modern AI rests on a small number of equations that recur in many disguises. Maximum
likelihood becomes the cross-entropy loss of every classifier and language model. The chain
rule becomes backpropagation. Gradient descent, with momentum and adaptive scaling, becomes
Adam. The Bellman equation becomes TD learning, Q-learning and the critic in PPO . The
evidence lower bound becomes VAEs and diffusion. A reward maximised under a KL leash becomes
RLHF , and solving that objective in closed form becomes DPO . This sheet lists the forms you
will meet, track by track, in one notation. It does not derive them: each row links the page
that does. For words rather than symbols, see the glossary .
Five equations generate most of the sheet
Notation
Symbol
Meaning
\(\mathbf{x}\) , \(W\) , \(\mathbf{x}^\top\)
Vector (bold lower-case), matrix (upper-case), transpose
\(\boldsymbol\theta\)
All trainable parameters
\(L\) , \(\ell\)
Loss averaged over data; loss on one example
\(\eta\)
Learning rate
\(p\) , \(q\) , \(\pi\)
Distributions; \(\pi_\theta\) is a policy or language model with parameters \(\theta\)
\(\sigma(z)\)
Sigmoid \(1/(1+e^{-z})\)
\(\odot\)
Element-wise product
\(n\) , \(d\) , \(d_k\) , \(d_h\)
Sequence length, model width, key width, head width
\(N\) , \(D\) , \(C\)
Parameters, training tokens, training FLOPs
\(\gamma\) , \(\beta\)
Discount factor (RL ); KL -penalty strength (post-training)
How to use this sheet
Cover the formula column and write each equation from its name; then check the symbols
column. Anything you cannot reproduce, follow the link and redo the derivation on paper.
The Check the sheet numerically section verifies several
identities in NumPy so you can see them hold.
Mathematics
Linear algebra
Name
Formula
Symbols and notes
Page
Dot product
\(\mathbf{a}^\top\mathbf{b} = \sum_i a_ib_i = \lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert\cos\theta\)
\(\theta\) is the angle between the vectors
Vectors
Cosine similarity
\(\cos\theta = \dfrac{\mathbf{a}^\top\mathbf{b}}{\lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert}\)
For unit vectors, \(\lVert\hat{\mathbf a}-\hat{\mathbf b}\rVert^2 = 2-2\cos\theta\)
Vectors
Projection
\(\operatorname{proj}_{\mathbf b}\mathbf a = \dfrac{\mathbf a^\top\mathbf b}{\mathbf b^\top\mathbf b}\,\mathbf b\)
Component of \(\mathbf a\) along \(\mathbf b\)
Vectors
Cauchy–Schwarz
\(\lvert\mathbf a^\top\mathbf b\rvert \le \lVert\mathbf a\rVert\lVert\mathbf b\rVert\)
Why cosine lies in \([-1,1]\)
Vectors
Matrix product
\((AB)_{ij} = \sum_k A_{ik}B_{kj}\)
\((m\times n)(n\times p)\to(m\times p)\) ; costs \(2mnp\) FLOPs
Matrices
Rank–nullity
\(\operatorname{rank}(A) + \dim\operatorname{null}(A) = n\)
\(n\) = number of columns
Matrices
2×2 determinant and inverse
\(\det = ad-bc\) , \(\;A^{-1} = \frac{1}{ad-bc}\begin{pmatrix}d&-b\\-c&a\end{pmatrix}\)
Invertible iff \(\det \ne 0\)
Matrices
Gradients of a linear layer
\(\mathbf y = W\mathbf x\) : \(\;\partial L/\partial\mathbf x = W^\top\mathbf g\) , \(\;\partial L/\partial W = \mathbf g\mathbf x^\top\)
\(\mathbf g = \partial L/\partial\mathbf y\)
Matrices
Eigen-decomposition
\(A\mathbf v = \lambda\mathbf v\) ; \(\;A = Q\Lambda Q^\top\) for symmetric \(A\)
\(Q\) orthogonal, \(\Lambda\) diagonal
Eigen, SVD , PCA
Characteristic equation
\(\det(A-\lambda I) = 0\)
Roots are the eigenvalues
Eigen, SVD , PCA
SVD
\(A = U\Sigma V^\top = \sum_{i=1}^r\sigma_i\mathbf u_i\mathbf v_i^\top\)
\(\sigma_1\ge\sigma_2\ge\dots\ge 0\)
Eigen, SVD , PCA
Eckart–Young
\(\lVert A - A_k\rVert_F = \sqrt{\sigma_{k+1}^2+\dots+\sigma_r^2}\)
\(A_k\) = top-\(k\) SVD terms is the best rank-\(k\) approximation
Eigen, SVD , PCA
PCA
\(C = \frac1n X^\top X\) (centred \(X\) ), principal axes = top eigenvectors of \(C\)
Variance along \(\mathbf v_i\) is \(\lambda_i\)
Eigen, SVD , PCA
Calculus
Name
Formula
Symbols and notes
Page
Derivative
\(f'(x) = \lim_{h\to0}\frac{f(x+h)-f(x)}{h}\)
Slope of the best linear approximation
Derivatives
Central difference
\(\frac{f(x+h)-f(x-h)}{2h} = f'(x) + O(h^2)\)
Use it for gradient checks
Derivatives
Gradient
\(\nabla f = \left(\frac{\partial f}{\partial x_1},\dots,\frac{\partial f}{\partial x_n}\right)\)
Points uphill; \(D_{\mathbf u}f = \nabla f\cdot\mathbf u\)
Derivatives
Second-order Taylor
\(f(\mathbf x+\mathbf h) \approx f(\mathbf x) + \nabla f^\top\mathbf h + \tfrac12\mathbf h^\top H\mathbf h\)
\(H_{ij} = \partial^2 f/\partial x_i\partial x_j\)
Derivatives
Chain rule
\(\frac{dz}{dx} = f'(g(x))\,g'(x)\)
\(z = f(g(x))\)
Chain rule
Multivariable chain rule
\(J_{f\circ g}(\mathbf x) = J_f(g(\mathbf x))\,J_g(\mathbf x)\)
Shapes \((m\times k)(k\times n)\)
Chain rule
Softmax Jacobian
\(\frac{\partial p_i}{\partial z_j} = p_i(\delta_{ij} - p_j)\) , \(\;J = \operatorname{diag}(\mathbf p) - \mathbf p\mathbf p^\top\)
\(\delta_{ij}\) = 1 if \(i=j\)
Chain rule
Change of variables
\(\log p_X(\mathbf x) = \log p_Z(\mathbf z) - \log\lvert\det J_f(\mathbf z)\rvert\)
\(\mathbf x = f(\mathbf z)\) , \(f\) invertible; the basis of normalising flows
Chain rule
Probability and estimation
Name
Formula
Symbols and notes
Page
Chain rule of probability
\(p(x_1,\dots,x_T) = \prod_{t=1}^T p(x_t\mid x_{<t})\)
Exact; the factorisation every LLM uses
Probability
Bayes' rule
\(p(a\mid b) = \dfrac{p(b\mid a)\,p(a)}{\sum_{a'}p(b\mid a')\,p(a')}\)
Posterior ∝ likelihood × prior
Probability
Linearity of expectation
\(\mathbb E[X+Y] = \mathbb E[X] + \mathbb E[Y]\)
Holds even when \(X\) , \(Y\) are dependent
Probability
Variance
\(\operatorname{Var}(X) = \mathbb E[X^2] - \mathbb E[X]^2\)
\(\operatorname{Var}(aX+b) = a^2\operatorname{Var}(X)\)
Probability
Chebyshev / weak LLN
\(P(\lvert\bar X-\mu\rvert\ge\varepsilon) \le \dfrac{\sigma^2}{n\varepsilon^2}\)
Averages concentrate as \(1/\sqrt n\)
Probability
Risk
\(R(\theta) = \mathbb E_{(\mathbf x,y)\sim\mathcal D}\,\ell(f_\theta(\mathbf x),y)\)
What training estimates with an average
Probability
Gaussian
\(\mathcal N(x;\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}e^{-(x-\mu)^2/2\sigma^2}\)
Multivariate: \(\propto\exp(-\frac12(\mathbf x-\boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x-\boldsymbol\mu))\)
Distributions
Beta
\(\operatorname{Beta}(p;\alpha,\beta)\propto p^{\alpha-1}(1-p)^{\beta-1}\) , \(\;\mathbb E[p] = \frac{\alpha}{\alpha+\beta}\)
Conjugate to Bernoulli: add successes to \(\alpha\) , failures to \(\beta\)
Distributions
Gumbel-max trick
\(\arg\max_k(z_k+g_k)\sim\operatorname{softmax}(\mathbf z)\)
\(g_k\) i.i.d. standard Gumbel
Distributions
Log-likelihood
\(\ell(\theta) = \sum_{i=1}^n\log p(x_i\mid\theta)\)
MLE maximises it
Estimation
MAP
\(\hat\theta_{\text{MAP}} = \arg\max_\theta[\log p(D\mid\theta) + \log p(\theta)]\)
Gaussian prior ⇒ L2 penalty
Estimation
Posterior predictive
\(p(y\mid\mathbf x,D) = \int p(y\mid\mathbf x,\theta)\,p(\theta\mid D)\,d\theta\)
Average over parameter uncertainty
Estimation
Estimator MSE
\(\mathbb E[(\hat\theta-\theta)^2] = \operatorname{bias}^2 + \operatorname{Var}(\hat\theta)\)
The bias–variance split for estimators
Estimation
Bayesian linear regression
\(S = (\alpha I + \beta\Phi^\top\Phi)^{-1}\) , \(\;\mathbf m = \beta S\Phi^\top\mathbf y\)
Prior precision \(\alpha\) , noise precision \(\beta\)
Estimation
Name
Formula
Symbols and notes
Page
Information content
\(I(x) = -\log p(x)\)
Surprise; bits for \(\log_2\) , nats for \(\ln\)
Entropy and KL
Entropy
\(H(p) = -\sum_x p(x)\log p(x)\)
Max \(\log K\) for uniform over \(K\) outcomes
Entropy and KL
Cross-entropy
\(H(p,q) = -\sum_x p(x)\log q(x)\)
The training loss with \(p\) = data, \(q\) = model
Entropy and KL
KL divergence
\(\operatorname{KL}(p\Vert q) = \sum_x p(x)\log\frac{p(x)}{q(x)} = H(p,q)-H(p) \ge 0\)
Asymmetric; zero iff \(p=q\)
Entropy and KL
Mutual information
\(I(X;Y) = H(X)-H(X\mid Y) = \operatorname{KL}(p(x,y)\Vert p(x)p(y))\)
Zero iff independent
Entropy and KL
Softmax
\(\operatorname{softmax}(\mathbf z)_i = e^{z_i}/\sum_j e^{z_j}\)
Invariant to adding a constant to all \(z_i\)
Entropy and KL
Softmax-CE gradient
\(\frac{\partial}{\partial z_k}\left(-\log\operatorname{softmax}(\mathbf z)_y\right) = p_k - y_k\)
\(\mathbf y\) one-hot
Entropy and KL
KL of Gaussians
\(\operatorname{KL}(\mathcal N_1\Vert\mathcal N_2) = \log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2} - \frac12\)
The VAE 's KL term uses this with \(\mathcal N_2 = \mathcal N(0,1)\)
Entropy and KL
Optimisation, numerics and statistics
Name
Formula
Symbols and notes
Page
Gradient descent
\(\boldsymbol\theta_{t+1} = \boldsymbol\theta_t - \eta\nabla L(\boldsymbol\theta_t)\)
On a quadratic, each eigen-direction shrinks by \((1-\eta\lambda_i)\)
Optimisation
Stability condition
converges on a quadratic iff \(0 < \eta < 2/\lambda_{\max}\)
\(\lambda_{\max}\) = largest Hessian eigenvalue
Optimisation
Descent lemma
\(f(\mathbf b) \le f(\mathbf a) - \eta(1 - \frac{L\eta}{2})\lVert\nabla f(\mathbf a)\rVert^2\)
\(L\) -smooth \(f\) , \(\mathbf b = \mathbf a - \eta\nabla f\)
Optimisation
Lagrange condition
\(\nabla f(\theta^*) = \lambda\nabla g(\theta^*)\)
Optimum of \(f\) subject to \(g = 0\)
Optimisation
Floating-point number
\(x = (-1)^s\times 1.m\times 2^{e-\text{bias}}\) ; \(\;\operatorname{fl}(a\circ b) = (a\circ b)(1+\delta)\) , \(\lvert\delta\rvert\le u\)
\(u\) = unit roundoff
Floating point
Log-sum-exp
\(\operatorname{LSE}(\mathbf z) = m + \log\sum_j e^{z_j-m}\) , \(\;m = \max_j z_j\)
\(\max_j z_j \le \operatorname{LSE} \le \max_j z_j + \log n\)
Floating point
Online softmax
\(\ell_{t+1} = \ell_t e^{m_t-m_{t+1}} + \sum_{z\in B_{t+1}}e^{z-m_{t+1}}\)
Running max \(m\) and sum \(\ell\) ; the core of FlashAttention
Floating point
Standard error of accuracy
\(\operatorname{SE} = \sqrt{\hat p(1-\hat p)/n}\)
95% CI ≈ \(\hat p \pm 1.96\,\operatorname{SE}\)
Statistics
Paired difference
\(\operatorname{Var}(d) = \operatorname{Var}(a)+\operatorname{Var}(b)-2\operatorname{Cov}(a,b)\)
Comparing two models on the same items cuts variance
Statistics
Sample size for power
\(n = \dfrac{(z_{1-\alpha/2}+z_{1-\beta})^2\sigma_d^2}{\delta^2}\)
≈ \(7.85\sigma_d^2/\delta^2\) for 5% level, 80% power
Statistics
Bradley–Terry
\(P(i \text{ beats } j) = \sigma(s_i - s_j)\)
Arena ratings and reward models
Statistics
Classical machine learning
Name
Formula
Symbols and notes
Page
Least squares
\(\hat{\mathbf w} = (X^\top X)^{-1}X^\top\mathbf y\)
From the normal equations \(X^\top X\hat{\mathbf w} = X^\top\mathbf y\)
Linear regression
Simple regression slope
\(\hat w_1 = \frac{\sum(x_i-\bar x)(y_i-\bar y)}{\sum(x_i-\bar x)^2}\) , \(\;\hat w_0 = \bar y - \hat w_1\bar x\)
Linear regression
MSE gradient
\(\nabla L = \frac1n X^\top(X\mathbf w - \mathbf y)\)
Hessian \(\frac1n X^\top X\) (convex)
Linear regression
Logistic model
\(p = \sigma(\mathbf w^\top\mathbf x + b)\) , \(\;\log\frac{p}{1-p} = \mathbf w^\top\mathbf x + b\)
Linear in log-odds
Logistic regression
Binary cross-entropy
\(L = -\frac1n\sum_i[y_i\log p_i + (1-y_i)\log(1-p_i)]\)
Gradient \(\frac1n X^\top(\mathbf p-\mathbf y)\)
Logistic regression
Cost-optimal threshold
\(p > t^* = \dfrac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}}\)
For calibrated probabilities
Logistic regression
Ridge
\(\hat{\mathbf w}_{\text{ridge}} = (X^\top X + \lambda I)^{-1}X^\top\mathbf y\)
Shrinks along small singular directions by \(d_j^2/(d_j^2+\lambda)\)
Bias, variance
Lasso (orthonormal case)
\(\hat w_j = \operatorname{sign}(\hat w_j)(\lvert\hat w_j\rvert - \lambda)_+\)
Soft-thresholding: exact zeros
Bias, variance
Bias–variance decomposition
\(\mathbb E[(y-\hat f)^2] = \sigma^2 + (f-\bar f)^2 + \mathbb E[(\hat f-\bar f)^2]\)
Noise + bias² + variance
Bias, variance
Precision, recall, F1
\(P = \frac{TP}{TP+FP}\) , \(\;R = \frac{TP}{TP+FN}\) , \(\;F_1 = \frac{2PR}{P+R}\)
Metrics
Precision from base rate
\(P = \dfrac{\pi\,\mathrm{TPR}}{\pi\,\mathrm{TPR} + (1-\pi)\,\mathrm{FPR}}\)
\(\pi\) = prevalence; why rare classes are hard
Metrics
AUC
\(\mathrm{AUC} = P(S_1 > S_0)\)
Score of a random positive beats a random negative
Metrics
Smoothed target encoding
\(\operatorname{enc}(c) = \dfrac{\sum_{i\in c}y_i + m\,p_0}{n_c + m}\)
Shrinks rare categories to the prior \(p_0\)
Features
Gini and entropy impurity
\(\text{Gini} = 1-\sum_k p_k^2\) , \(\;H = -\sum_k p_k\log_2 p_k\)
Tree split criteria
Trees
Variance of an average of trees
\(\rho\sigma^2 + \frac{1-\rho}{B}\sigma^2\)
Random forests lower \(\rho\) by feature subsampling
Trees
Boosting pseudo-residual
\(r_i = -\left.\partial L(y_i,F)/\partial F\right\rvert_{F=F_{m-1}(\mathbf x_i)}\)
Each new tree fits these
Trees
Hard-margin SVM
\(\min\frac12\lVert\mathbf w\rVert^2\) s.t. \(y_i(\mathbf w^\top\mathbf x_i+b)\ge1\)
Margin \(= 2/\lVert\mathbf w\rVert\)
Kernels and SVMs
Soft-margin SVM
\(\min\frac1n\sum_i\max(0,1-y_if(\mathbf x_i)) + \frac\lambda2\lVert\mathbf w\rVert^2\)
Hinge loss + L2
Kernels and SVMs
Kernel prediction
\(f(\mathbf x) = \sum_i\alpha_iy_i\,k(\mathbf x_i,\mathbf x) + b\)
e.g. RBF \(k = \exp(-\gamma\lVert\mathbf x-\mathbf x'\rVert^2)\)
Kernels and SVMs
k-means objective
\(J = \sum_i\lVert\mathbf x_i - \boldsymbol\mu_{z_i}\rVert^2\)
Lloyd's algorithm decreases it monotonically
Clustering
GMM responsibilities (E-step)
\(r_{ij} = \dfrac{\pi_j\mathcal N(\mathbf x_i\mid\boldsymbol\mu_j,\Sigma_j)}{\sum_l\pi_l\mathcal N(\mathbf x_i\mid\boldsymbol\mu_l,\Sigma_l)}\)
M-step: \(\pi_j = N_j/n\) , \(\boldsymbol\mu_j = \frac1{N_j}\sum_ir_{ij}\mathbf x_i\)
Clustering
Finite-class PAC bound
\(R(h) \le \hat R_S(h) + \sqrt{\dfrac{\ln\lvert\mathcal H\rvert + \ln(2/\delta)}{2m}}\)
With probability \(\ge 1-\delta\)
Learning theory
VC bound
\(R(h) \le \hat R_S(h) + O\!\left(\sqrt{\frac{d\ln(m/d)+\ln(1/\delta)}{m}}\right)\)
\(d\) = VC dimension
Learning theory
Bayesian network factorisation
\(p(x_1,\dots,x_n) = \prod_i p(x_i\mid\operatorname{pa}(x_i))\)
Graphical models
HMM forward recursion
\(\boldsymbol\alpha_t = (A^\top\boldsymbol\alpha_{t-1})\odot\mathbf b_t\)
\(A\) transitions, \(\mathbf b_t\) emission likelihoods
Graphical models
Deep learning
Name
Formula
Symbols and notes
Page
Neuron and layer
\(\mathbf h = \phi(W\mathbf x + \mathbf b)\)
\(\phi\) = activation
Neurons and MLPs
Perceptron update
if \(y_n\mathbf w^\top\mathbf x_n \le 0\) : \(\mathbf w \leftarrow \mathbf w + y_n\mathbf x_n\)
\(y_n\in\{-1,+1\}\)
Neurons and MLPs
Backprop (four equations)
\(\boldsymbol\delta_L = \nabla_{\mathbf z_L}L\) ; \(\;\boldsymbol\delta_\ell = (W_{\ell+1}^\top\boldsymbol\delta_{\ell+1})\odot\phi'(\mathbf z_\ell)\) ; \(\;\frac{\partial L}{\partial W_\ell} = \boldsymbol\delta_\ell\mathbf h_{\ell-1}^\top\) ; \(\;\frac{\partial L}{\partial\mathbf b_\ell} = \boldsymbol\delta_\ell\)
\(\boldsymbol\delta_\ell = \partial L/\partial\mathbf z_\ell\)
Backpropagation
Reverse-mode adjoint
\(\bar v_i = \sum_{j:\,i\in\operatorname{pa}(j)}\bar v_j\,\frac{\partial v_j}{\partial v_i}\)
\(\bar v = \partial L/\partial v\)
Autodiff
JVP and VJP
\(\operatorname{jvp} = J\mathbf v\) , \(\;\operatorname{vjp} = \mathbf u^\top J\)
Forward mode computes JVPs, reverse mode VJPs
Autodiff
Dual numbers
\(f(a+b\varepsilon) = f(a) + f'(a)\,b\,\varepsilon\) , \(\;\varepsilon^2 = 0\)
Forward-mode autodiff in one line
Autodiff
GELU , SiLU
\(\operatorname{GELU}(x) = x\,\Phi(x)\) , \(\;\operatorname{SiLU}(x) = x\,\sigma(x)\)
\(\Phi\) = standard normal CDF
Activations
Sigmoid derivative
\(\sigma'(z) = \sigma(z)(1-\sigma(z)) \le \tfrac14\)
Why deep sigmoid nets vanish
Activations
Variance propagation
\(\operatorname{Var}(z_j) = n\,\sigma_w^2\,\mathbb E[h^2]\)
\(n\) = fan-in
Initialisation
Xavier / He init
\(\sigma_w^2 = \dfrac{2}{n_{\text{in}}+n_{\text{out}}}\) ; \(\;\sigma_w^2 = \dfrac{2}{n_{\text{in}}}\)
He for ReLU
Initialisation
LayerNorm
\(\operatorname{LN}(\mathbf x) = \boldsymbol\gamma\odot\frac{\mathbf x-\mu}{\sqrt{\sigma^2+\epsilon}} + \boldsymbol\beta\)
Statistics over features of one token
Initialisation
RMSNorm
\(\operatorname{RMSNorm}(\mathbf x) = \boldsymbol\gamma\odot\mathbf x/\sqrt{\frac1d\sum_ix_i^2+\epsilon}\)
No mean subtraction, no \(\boldsymbol\beta\)
Initialisation
SGD with momentum
\(\mathbf v_t = \beta\mathbf v_{t-1} + \mathbf g_t\) , \(\;\boldsymbol\theta_{t+1} = \boldsymbol\theta_t - \eta\mathbf v_t\)
\(\beta\approx0.9\)
Optimisers
Adam
\(\mathbf m_t = \beta_1\mathbf m_{t-1} + (1-\beta_1)\mathbf g_t\) , \(\;\mathbf v_t = \beta_2\mathbf v_{t-1} + (1-\beta_2)\mathbf g_t^2\) , \(\;\hat{\mathbf m}_t = \frac{\mathbf m_t}{1-\beta_1^t}\) , \(\;\hat{\mathbf v}_t = \frac{\mathbf v_t}{1-\beta_2^t}\)
Defaults \(\beta_1 = 0.9\) , \(\beta_2 = 0.999\) (often 0.95 for LLMs )
Optimisers
AdamW step
\(\boldsymbol\theta_{t+1} = \boldsymbol\theta_t - \eta_t\left(\hat{\mathbf m}_t/(\sqrt{\hat{\mathbf v}_t}+\epsilon) + \lambda\boldsymbol\theta_t\right)\)
Decoupled weight decay \(\lambda\)
Optimisers
Cosine schedule
\(\eta_t = \eta_{\min} + \frac12(\eta_{\max}-\eta_{\min})\left(1+\cos\frac{\pi t}{T}\right)\)
After linear warm-up
Optimisers
Weight decay as L2
\(w \leftarrow (1-\eta\lambda)\,w\) per step
Gaussian prior on weights, MAP view
Regularisation
Dropout (inverted)
\(\tilde{\mathbf h} = \mathbf m\odot\mathbf h/(1-p)\) , \(\;m_i\sim\operatorname{Bernoulli}(1-p)\)
Expected activation unchanged
Regularisation
2-D convolution
\(Y_{o,i,j} = b_o + \sum_c\sum_{u,v}w_{o,c,u,v}X_{c,\,si+u,\,sj+v}\)
Cross-correlation in practice
CNNs
Output size
\(H_{\text{out}} = \left\lfloor\frac{H+2P-K}{S}\right\rfloor + 1\)
Kernel \(K\) , padding \(P\) , stride \(S\)
CNNs
Simple RNN
\(\mathbf h_t = \tanh(W_{hh}\mathbf h_{t-1} + W_{xh}\mathbf x_t + \mathbf b)\)
Gradient is a product of \(T\) Jacobians
RNNs and LSTMs
LSTM cell
\(\mathbf c_t = \mathbf f_t\odot\mathbf c_{t-1} + \mathbf i_t\odot\tilde{\mathbf c}_t\) , \(\;\mathbf h_t = \mathbf o_t\odot\tanh(\mathbf c_t)\)
Gates \(\mathbf f,\mathbf i,\mathbf o = \sigma(\cdot)\)
RNNs and LSTMs
Additive attention (2014)
\(\alpha_{ij} = \operatorname{softmax}_j(e_{ij})\) , \(\;\mathbf c_i = \sum_j\alpha_{ij}\mathbf h_j\)
\(e_{ij} = \operatorname{score}(\mathbf s_{i-1},\mathbf h_j)\)
RNNs and LSTMs
Skip-gram with negative sampling
\(\ell = -\log\sigma(\mathbf w^\top\mathbf c) - \sum_{j=1}^k\log\sigma(-\mathbf w^\top\mathbf c_j^-)\)
Optimum: \(\mathbf w^\top\mathbf c = \operatorname{PMI}(w,c) - \log k\)
Embeddings
InfoNCE
\(\mathcal L_i = -\log\dfrac{\exp(s(\mathbf a_i,\mathbf b_i)/\tau)}{\sum_j\exp(s(\mathbf a_i,\mathbf b_j)/\tau)}\)
Contrastive loss of CLIP and embedding models
Embeddings
Residual block
\(\mathbf y = \mathbf x + F(\mathbf x)\) ; \(\;\frac{\partial\mathbf x_L}{\partial\mathbf x_l} = \prod_{i=l}^{L-1}(I+J_i)\)
The identity term keeps gradients alive
Residual networks
Name
Formula
Symbols and notes
Page
BPE merge
\((a^*,b^*) = \arg\max_{(a,b)}c(a,b)\)
Most frequent adjacent pair
Tokenisation
Bits per byte
\(\text{BPB} = \dfrac{T\cdot L_{\text{tok}}}{B\ln 2}\)
\(T\) tokens, \(B\) bytes, \(L_{\text{tok}}\) nats per token
Tokenisation
Projections
\(Q = XW_Q\) , \(K = XW_K\) , \(V = XW_V\)
\(X\in\mathbb R^{n\times d}\) , \(Q,K\in\mathbb R^{n\times d_k}\)
Attention
Scaled dot-product attention
\(\operatorname{Attn}(Q,K,V) = \operatorname{softmax}\!\left(\dfrac{QK^\top}{\sqrt{d_k}} + M\right)V\)
\(M_{ij} = -\infty\) for \(j>i\) (causal mask)
Attention
Why \(\sqrt{d_k}\)
\(\operatorname{Var}(\mathbf q^\top\mathbf k) = d_k\) for unit-variance entries
Dividing restores variance 1
Attention
Attention backward
\(\bar V = A^\top\bar O\) , \(\;\bar A = \bar OV^\top\) , \(\;\bar S_{ij} = A_{ij}(\bar A_{ij} - \sum_\ell\bar A_{i\ell}A_{i\ell})\)
\(A\) = attention weights
Attention
Multi-head attention
\(\operatorname{MHA}(X) = \operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)W_O\)
\(d_h = d/h\)
Multi-head attention
Pre-norm block
\(H = X + \operatorname{MHA}(\operatorname{Norm}_1(X))\) , \(\;Y = H + \operatorname{MLP}(\operatorname{Norm}_2(H))\)
Transformer block
SwiGLU FFN
\(\operatorname{SwiGLU}(\mathbf u) = (\operatorname{SiLU}(\mathbf uW_1)\odot\mathbf uW_3)W_2\)
Hidden width ≈ \(\frac83 d\)
Transformer block
Residual stream
\(\mathbf x_L = \mathbf x_0 + \sum_{\ell=1}^L(\text{attn}_\ell + \text{mlp}_\ell)\)
Every layer writes to one shared vector
Transformer block
Sinusoidal PE
\(\mathrm{PE}(p,2i) = \sin(p\,\omega_i)\) , \(\;\mathrm{PE}(p,2i+1) = \cos(p\,\omega_i)\) , \(\;\omega_i = 10000^{-2i/d}\)
Positional encoding
RoPE
\((R_{m\theta}\mathbf q)^\top(R_{n\theta}\mathbf k) = \mathbf q^\top R_{(n-m)\theta}\mathbf k\) , \(\;\theta_i = b^{-2i/d_h}\)
Depends only on relative position
Positional encoding
ALiBi
\(s_{ij} = \frac{\mathbf q_i^\top\mathbf k_j}{\sqrt{d_h}} - m_h(i-j)\)
Head-specific slope \(m_h\)
Positional encoding
LM objective
\(L(\theta) = -\frac1N\sum_t\log p_\theta(x_{t+1}\mid x_{\le t})\)
Cross-entropy on next tokens
Language modelling
Perplexity
\(\operatorname{PPL} = \exp(L)\)
\(L\) in nats per token
Language modelling
Loss decomposition
\(\mathbb E[-\log p_\theta] = H(p_{\text{data}}) + \operatorname{KL}(p_{\text{data}}\Vert p_\theta)\)
The entropy floor cannot be beaten
Language modelling
MinHash
\(\Pr[\min h(A) = \min h(B)] = J(A,B) = \frac{\lvert A\cap B\rvert}{\lvert A\cup B\rvert}\)
Near-duplicate detection
Pre-training data
LSH banding
\(\Pr[\text{flagged}] = 1-(1-s^r)^b\)
\(b\) bands of \(r\) rows
Pre-training data
Training compute
\(C \approx 6ND\)
2 FLOPs /param/token forward, 4 backward
Scaling laws
Kaplan scaling
\(L(N) = (N_c/N)^{\alpha_N}\) , \(\alpha_N\approx0.076\)
Loss vs parameters at ample data
Scaling laws
Chinchilla fit
\(L(N,D) = 1.69 + \dfrac{406.4}{N^{0.34}} + \dfrac{410.7}{D^{0.28}}\)
Optimum ≈ 20 tokens per parameter
Scaling laws
Parameter count
\(N \approx 12Ld^2 + Vd\)
\(L\) layers, width \(d\) , vocab \(V\) (GPT -2-style MLP )
GPT from scratch
Temperature
\(p_i^{(T)} = \dfrac{\exp(z_i/T)}{\sum_j\exp(z_j/T)} \propto p_i^{1/T}\)
Entropy falls monotonically as \(1/T\) grows
Decoding
Top-p set
smallest \(m\) with \(\sum_{j\le m}p_{(j)}\ge p\)
\(p_{(j)}\) sorted descending
Decoding
KV cache size
\(2\times n_{\text{layers}}\times h_{kv}\times d_h\times b\) bytes per token
\(b\) bytes per number; GQA shrinks \(h_{kv}\)
KV cache
Decode step time
\(t \approx \dfrac{\text{weight bytes} + B\times\text{cache bytes}}{\text{HBM bandwidth}}\)
Memory-bound regime
KV cache
RoPE wavelength
\(\lambda_i = 2\pi b^{2i/d_h}\)
Dimensions with \(\lambda_i > L\) never complete a turn in training
Long context
Needle attention weight
\(a = \dfrac{e^\Delta}{e^\Delta + n-1}\)
Required margin grows as \(\ln n\)
Long context
MoE output
\(\mathbf y = \sum_{i\in\operatorname{TopK}(\mathbf g)}g_i\,\operatorname{FFN}_i(\mathbf x)\)
Router \(\mathbf g = \operatorname{softmax}(W_r\mathbf x)\)
Mixture of experts
Load-balancing loss
\(\mathcal L_{\text{aux}} = \alpha E\sum_{i=1}^E f_iP_i\)
\(f_i\) fraction routed, \(P_i\) mean router prob
Mixture of experts
Expert capacity
\(\dfrac{\text{tokens}\times k}{E}\times\text{capacity factor}\)
Mixture of experts
Linear attention
\(\mathbf o_t = \dfrac{\phi(\mathbf q_t)^\top S_t}{\phi(\mathbf q_t)^\top\mathbf z_t}\) , \(\;S_t = S_{t-1} + \phi(\mathbf k_t)\mathbf v_t^\top\)
Constant-size state
Beyond transformers
Discretised SSM
\(h_t = \bar Ah_{t-1} + \bar Bx_t\) , \(\;y_t = Ch_t\) , \(\;\bar A = e^{\Delta A}\)
Mamba makes \(\Delta,B,C\) input-dependent
Beyond transformers
pass@k (unbiased)
\(1 - \binom{n-c}{k}\big/\binom{n}{k}\)
\(n\) samples, \(c\) correct
Reasoning models
GRPO advantage
\(\hat A_i = \dfrac{r_i - \operatorname{mean}(r_{1..G})}{\operatorname{std}(r_{1..G})}\)
Group of \(G\) samples per prompt
Reasoning models
Post-training
Name
Formula
Symbols and notes
Page
SFT loss
\(L_{\text{SFT}} = -\mathbb E\sum_t\log\pi_\theta(y_t\mid x,y_{<t})\)
Loss on response tokens only
Instruction tuning
Reward-model loss
\(L = -\mathbb E[\log\sigma(r_\phi(x,y_w) - r_\phi(x,y_l))]\)
Bradley–Terry on preference pairs
Reward models
KL -regularised objective
\(\max_\pi\ \mathbb E_{y\sim\pi}[r(x,y)] - \beta\operatorname{KL}(\pi(\cdot\mid x)\Vert\pi_{\text{ref}}(\cdot\mid x))\)
The RLHF objective
RLHF with PPO
Its optimum
\(\pi^*(y\mid x) = \frac{1}{Z(x)}\pi_{\text{ref}}(y\mid x)\exp(r(x,y)/\beta)\)
Starting point for DPO
DPO
Per-token RLHF reward
\(r_t = -\beta\log\frac{\pi_\theta(y_t\mid\cdot)}{\pi_{\text{ref}}(y_t\mid\cdot)}\) , plus \(r_\phi(x,y)\) at the last token
How the KL enters PPO
RLHF with PPO
DPO loss
\(L_{\text{DPO}} = -\mathbb E\left[\log\sigma\!\left(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\right)\right]\)
No reward model, no sampling
DPO
Implicit reward
\(r(x,y) = \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta\log Z(x)\)
\(Z(x)\) cancels in pairwise comparisons
DPO
GRPO objective
\(\frac1G\sum_i\frac{1}{\lvert o_i\rvert}\sum_t\min\left(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1\pm\epsilon)\hat A_i\right) - \beta\operatorname{KL}\)
\(\rho\) = new/old token probability ratio
RL with verifiable rewards
LoRA
\(W' = W_0 + \frac{\alpha}{r}BA\) , \(\;B\in\mathbb R^{d\times r}\) , \(A\in\mathbb R^{r\times k}\)
Trainable params \(r(d+k)\) vs \(dk\) ; \(B\) initialised to 0
LoRA
Distillation loss
\(L_{\text{KD}} = (1-\lambda)\operatorname{CE}(y,q^S) + \lambda T^2\operatorname{KL}(q^{T}_{\tau}\Vert q^{S}_{\tau})\)
Softened by temperature; \(T^2\) keeps gradient scale
Distillation
Task arithmetic
\(\boldsymbol\theta = \boldsymbol\theta_0 + \sum_k\lambda_k\boldsymbol\tau_k\) , \(\;\boldsymbol\tau_k = \boldsymbol\theta_k - \boldsymbol\theta_0\)
Model merging
Merging
Reinforcement learning
Name
Formula
Symbols and notes
Page
Incremental mean
\(Q_{n+1} = Q_n + \frac1n(R_n - Q_n)\)
Template for every RL update
Bandits
UCB1
\(a_t = \arg\max_a\left[Q_a + c\sqrt{\frac{\ln t}{N_a}}\right]\)
Optimism under uncertainty
Bandits
Regret
\(R_T = T\mu^* - \mathbb E\sum_{t=1}^T r_t\)
Logarithmic for UCB and Thompson
Bandits
Return
\(G_t = \sum_{k\ge0}\gamma^kr_{t+k+1}\)
Effective horizon \(1/(1-\gamma)\)
MDPs and Bellman
Bellman expectation
\(V^\pi(s) = \sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)[r + \gamma V^\pi(s')]\)
Linear: \(V = (I-\gamma P^\pi)^{-1}R^\pi\)
MDPs and Bellman
Bellman optimality
\(Q^*(s,a) = \mathbb E[r + \gamma\max_{a'}Q^*(s',a')]\)
A \(\gamma\) -contraction in sup norm
MDPs and Bellman
Value iteration
\(V_{k+1}(s) = \max_a\sum_{s'}P(s'\mid s,a)[r + \gamma V_k(s')]\)
Error shrinks by \(\gamma\) per sweep
Dynamic programming
TD (0)
\(V(s) \leftarrow V(s) + \alpha[r + \gamma V(s') - V(s)]\)
Bracket = TD error \(\delta\)
Monte Carlo and TD
λ-return
\(G_t^\lambda = (1-\lambda)\sum_{n\ge1}\lambda^{n-1}G_t^{(n)}\)
Interpolates TD (\(\lambda=0\) ) and MC (\(\lambda=1\) )
Monte Carlo and TD
Q-learning
\(Q(s,a) \leftarrow Q(s,a) + \alpha[r + \gamma\max_{a'}Q(s',a') - Q(s,a)]\)
Off-policy
Q-learning and DQN
DQN loss
\(L = \mathbb E[(r + \gamma\max_{a'}Q_{\bar\theta}(s',a') - Q_\theta(s,a))^2]\)
\(\bar\theta\) = target network
Q-learning and DQN
Policy gradient theorem
\(\nabla_\theta J = \mathbb E_\pi[\nabla_\theta\log\pi_\theta(a\mid s)\,Q^\pi(s,a)]\)
REINFORCE uses \(G_t\) for \(Q\)
Policy gradients
Baseline
\(\mathbb E[\nabla\log\pi_\theta(a\mid s)\,b(s)] = 0\)
Subtracting \(b\) adds no bias
Policy gradients
Advantage and GAE
\(A = Q - V\) ; \(\;\hat A_t^{\text{GAE}} = \sum_{l\ge0}(\gamma\lambda)^l\delta_{t+l}\)
\(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\)
Actor-critic and PPO
PPO clipped objective
\(L^{\text{CLIP}} = \mathbb E[\min(\rho_t\hat A_t,\ \operatorname{clip}(\rho_t,1-\epsilon,1+\epsilon)\hat A_t)]\)
\(\rho_t = \pi_\theta(a_t\mid s_t)/\pi_{\text{old}}(a_t\mid s_t)\)
Actor-critic and PPO
PUCT (AlphaZero)
\(a = \arg\max_a\left[Q(s,a) + c\,P(s,a)\frac{\sqrt{N(s)}}{1+N(s,a)}\right]\)
Prior \(P\) from the policy network
Model-based RL
Importance sampling
\(\mathbb E_{\pi}[f] = \mathbb E_{\mu}\left[\frac{\pi(a\mid s)}{\mu(a\mid s)}f\right]\)
Off-policy evaluation from logged data
Offline RL
Generative models
Name
Formula
Symbols and notes
Page
ELBO
\(\log p(\mathbf x) \ge \mathbb E_{q(\mathbf z\mid\mathbf x)}[\log p(\mathbf x\mid\mathbf z)] - \operatorname{KL}(q(\mathbf z\mid\mathbf x)\Vert p(\mathbf z))\)
Gap = \(\operatorname{KL}(q\Vert p(\mathbf z\mid\mathbf x))\)
VAEs
Reparameterisation
\(\mathbf z = \boldsymbol\mu + \boldsymbol\sigma\odot\boldsymbol\epsilon\) , \(\;\boldsymbol\epsilon\sim\mathcal N(0,I)\)
Gradients through sampling
VAEs
GAN minimax
\(\min_G\max_D\ \mathbb E_{\text{data}}[\log D(\mathbf x)] + \mathbb E_{\mathbf z}[\log(1-D(G(\mathbf z)))]\)
Optimal \(D^* = \frac{p_{\text{data}}}{p_{\text{data}}+p_g}\)
GANs
GAN at optimal D
\(C(G) = -\log 4 + 2\operatorname{JSD}(p_{\text{data}}\Vert p_g)\)
Minimised when \(p_g = p_{\text{data}}\)
GANs
Forward diffusion
\(q(\mathbf x_t\mid\mathbf x_0) = \mathcal N(\sqrt{\bar\alpha_t}\mathbf x_0,(1-\bar\alpha_t)I)\)
\(\bar\alpha_t = \prod_{s\le t}(1-\beta_s)\)
Diffusion models
DDPM loss
\(L_{\text{simple}} = \mathbb E_{t,\mathbf x_0,\boldsymbol\epsilon}\lVert\boldsymbol\epsilon - \boldsymbol\epsilon_\theta(\sqrt{\bar\alpha_t}\mathbf x_0 + \sqrt{1-\bar\alpha_t}\boldsymbol\epsilon,\,t)\rVert^2\)
Predict the noise
Diffusion models
Noise ↔ score
\(\nabla_{\mathbf x_t}\log q(\mathbf x_t) \approx -\boldsymbol\epsilon_\theta(\mathbf x_t,t)/\sqrt{1-\bar\alpha_t}\)
Score and flow matching
Denoising score matching
\(\mathbb E\lVert s_\theta(\tilde{\mathbf x}) - \nabla_{\tilde{\mathbf x}}\log q(\tilde{\mathbf x}\mid\mathbf x)\rVert^2\)
Equals score matching up to a constant
Score and flow matching
Langevin step
\(\mathbf x \leftarrow \mathbf x + \frac\epsilon2\nabla\log p(\mathbf x) + \sqrt\epsilon\,\mathbf z\)
Score and flow matching
Flow matching (straight path)
\(\mathbf x_t = (1-t)\mathbf x_0 + t\mathbf x_1\) , \(\;L = \mathbb E\lVert v_\theta(\mathbf x_t,t) - (\mathbf x_1-\mathbf x_0)\rVert^2\)
Sample by integrating \(d\mathbf x/dt = v_\theta\)
Score and flow matching
Classifier-free guidance
\(\hat{\boldsymbol\epsilon} = \boldsymbol\epsilon_\emptyset + w(\boldsymbol\epsilon_c - \boldsymbol\epsilon_\emptyset)\)
\(w > 1\) strengthens the condition
Latent diffusion
ViT tokens
\(n = \frac{HW}{P^2}\) patches of dimension \(P^2C\)
224×224 with \(P = 16\) gives 196
ViT and CLIP
CLIP loss
symmetric InfoNCE over the \(N\times N\) image–text similarity matrix, temperature \(\tau\)
Diagonal = matching pairs
ViT and CLIP
Systems
Name
Formula
Symbols and notes
Page
Arithmetic intensity
\(I = \dfrac{\text{FLOPs}}{\text{bytes moved}}\)
Compute-bound iff \(I >\) peak FLOP /s ÷ bandwidth
GPU architecture
Roofline
attainable \(= \min(\text{peak FLOP/s},\ I\times\text{bandwidth})\)
GPU architecture
Matmul intensity
\(\dfrac{2mnk}{b(mk + kn + mn)}\)
\(b\) bytes per element
Kernels
BF16 layout
1 sign, 8 exponent, 7 mantissa bits
Same range as FP32
Mixed precision
Training memory (mixed precision, Adam)
≈ 16 bytes per parameter
2 (BF16 weights) + 2 (grads) + 4 (FP32 master) + 8 (Adam \(m\) , \(v\) )
Distributed training
Ring all-reduce traffic
\(2\frac{p-1}{p}S\) bytes per device
\(S\) = gradient size, \(p\) devices
Distributed training
Pipeline bubble
\(\dfrac{p-1}{m+p-1}\)
\(p\) stages, \(m\) micro-batches
Distributed training
Forward FLOPs per token
\(\approx 2N + 2Ln_{\text{ctx}}d\)
Second term = attention
Compute maths
MFU
\(\dfrac{6N\times\text{tokens/s}}{\text{peak FLOP/s}}\)
Compute maths
Symmetric INT8 quantisation
\(q = \operatorname{round}(x/s)\) , \(\;s = \max\lvert x\rvert/127\)
Dequantise \(\hat x = sq\)
Quantisation
Speculative decoding speed-up
expected tokens per verify \(= \dfrac{1-\alpha^{k+1}}{1-\alpha}\)
Acceptance rate \(\alpha\) , draft length \(k\)
Serving LLMs
Little's law
\(L = \lambda W\)
Requests in flight = arrival rate × latency
Serving LLMs
LLM applications, evaluation and data
Name
Formula
Symbols and notes
Page
Cosine retrieval
\(\operatorname{score}(q,d) = \frac{\mathbf e_q^\top\mathbf e_d}{\lVert\mathbf e_q\rVert\lVert\mathbf e_d\rVert}\)
Equals dot product for normalised embeddings
Embeddings and vector search
Recall@k
fraction of relevant items found in the top \(k\)
The retrieval metric RAG depends on
RAG
BM25
\(\sum_{t\in q}\operatorname{IDF}(t)\dfrac{f(t,d)(k_1+1)}{f(t,d) + k_1(1-b+b\frac{\lvert d\rvert}{\text{avgdl}})}\)
\(k_1\approx1.2\) –\(2\) , \(b\approx0.75\)
Advanced RAG
Reciprocal rank fusion
\(\operatorname{RRF}(d) = \sum_{r\in R}\dfrac{1}{k + \operatorname{rank}_r(d)}\)
\(k = 60\) by convention
Advanced RAG
nDCG
\(\operatorname{DCG} = \sum_i\frac{\text{rel}_i}{\log_2(i+1)}\) , \(\;\operatorname{nDCG} = \operatorname{DCG}/\operatorname{IDCG}\)
Graded ranking quality
Advanced RAG
Judge agreement
Cohen's \(\kappa = \dfrac{p_o - p_e}{1 - p_e}\)
Observed vs chance agreement
Evals in practice
Agent success over steps
\(P(\text{success}) = p^k\) for \(k\) independent steps
0.95 per step over 20 steps ≈ 0.36
Agents
Elo expected score
\(E_A = \dfrac{1}{1+10^{(R_B-R_A)/400}}\)
A logistic Bradley–Terry model
Benchmarks
Differential privacy
\(P(M(D)\in S) \le e^\varepsilon P(M(D')\in S) + \delta\)
\(D\) , \(D'\) differ in one record
Robustness, fairness, privacy
Sparse autoencoder
\(\min\lVert\mathbf x - W_d\,\operatorname{ReLU}(W_e\mathbf x + \mathbf b)\rVert^2 + \lambda\lVert\mathbf f\rVert_1\)
\(\mathbf f\) = feature activations
Interpretability
Jaccard similarity
\(J(A,B) = \frac{\lvert A\cap B\rvert}{\lvert A\cup B\rvert}\)
Near-duplicate threshold often 0.7–0.8
Quality and dedup
Population stability index
\(\operatorname{PSI} = \sum_i(a_i - e_i)\ln\frac{a_i}{e_i}\)
Drift between expected and actual bins
Data in production
Check the sheet numerically
A sheet of formulas is only useful if you trust it. This script checks eight of them in NumPy:
the softmax-cross-entropy gradient, KL 's asymmetry, log-sum-exp stability, the \(\sqrt{d_k}\)
scaling, \(6ND\) , the KV -cache formula, the standard error of an eval and a Bellman solution.
import numpy as np
rng = np . random . default_rng ( 0 )
# 1. Softmax + cross-entropy gradient is p - y
z = rng . normal ( size = 5 ); y = np . eye ( 5 )[ 2 ]
p = np . exp ( z - z . max ()); p /= p . sum ()
loss = lambda z : - np . log ( np . exp ( z [ 2 ] - z . max ()) / np . exp ( z - z . max ()) . sum ())
num = np . array ([( loss ( z + h ) - loss ( z - h )) / 2e-5 for h in np . eye ( 5 ) * 1e-5 ])
print ( "softmax-CE grad error:" , np . abs ( num - ( p - y )) . max () . round ( 10 ))
# 2. KL(p||q) = H(p,q) - H(p) >= 0, and it is asymmetric
q = np . array ([ 0.5 , 0.3 , 0.2 ]); r = np . array ([ 0.1 , 0.1 , 0.8 ])
kl = lambda a , b : np . sum ( a * np . log ( a / b ))
print ( "KL(q||r), KL(r||q):" , kl ( q , r ) . round ( 4 ), kl ( r , q ) . round ( 4 ))
# 3. Log-sum-exp: naive overflows, shifted does not
big = np . array ([ 1000.0 , 1001.0 , 1002.0 ])
with np . errstate ( over = "ignore" ):
naive = np . log ( np . exp ( big ) . sum ())
m = big . max (); stable = m + np . log ( np . exp ( big - m ) . sum ())
print ( "naive LSE:" , naive , "| stable LSE:" , stable . round ( 4 ))
# 4. Scaled dot product: var(q.k) = d_k, so divide by sqrt(d_k)
d = 128 ; qk = ( rng . normal ( size = ( 100_000 , d )) * rng . normal ( size = ( 100_000 , d ))) . sum ( 1 )
print ( "var(q.k), var(q.k/sqrt(d)):" , qk . var () . round ( 1 ), ( qk / np . sqrt ( d )) . var () . round ( 3 ))
# 5. Training compute C = 6ND and Chinchilla's ~20 tokens/param
N , D = 7e9 , 2e12
print ( f "6ND for 7B params on 2T tokens: { 6 * N * D : .2e } FLOPs" )
print ( f "Chinchilla 70B x 20 tokens/param: { 70e9 * 20 : .2e } tokens" )
# 6. KV cache bytes per token = 2 * layers * kv_heads * head_dim * bytes
for name , L , hkv in [( "MHA 32 kv heads" , 32 , 32 ), ( "GQA 8 kv heads" , 32 , 8 )]:
b = 2 * L * hkv * 128 * 2
print ( f " { name } : { b : , } bytes/token = { b / 2 ** 20 : .3f } MiB; 32k ctx = { b * 32768 / 2 ** 30 : .1f } GiB" )
# 7. Standard error of an eval accuracy
p_hat , n = 0.80 , 500
print ( "SE of 80 % o n 500 items:" , np . sqrt ( p_hat * ( 1 - p_hat ) / n ) . round ( 4 ))
# 8. Discounted return and Bellman consistency for a 2-state chain
P = np . array ([[ 0.9 , 0.1 ], [ 0.5 , 0.5 ]]); R = np . array ([ 1.0 , 0.0 ]); g = 0.9
V = np . linalg . solve ( np . eye ( 2 ) - g * P , R )
print ( "V =" , V . round ( 4 ), "| Bellman residual:" , np . abs ( R + g * P @ V - V ) . max () . round ( 12 ))
Output (NumPy 2, Python 3.12):
softmax-CE grad error: 0.0
KL(q||r), KL(r||q): 0.857 0.8382
naive LSE: inf | stable LSE: 1002.4076
var(q.k), var(q.k/sqrt(d)): 127.4 0.995
6ND for 7B params on 2T tokens: 8.40e+22 FLOPs
Chinchilla 70B x 20 tokens/param: 1.40e+12 tokens
MHA 32 kv heads: 524,288 bytes/token = 0.500 MiB; 32k ctx = 16.0 GiB
GQA 8 kv heads: 131,072 bytes/token = 0.125 MiB; 32k ctx = 4.0 GiB
SE of 80% on 500 items: 0.0179
V = [8.5938 7.0313] | Bellman residual: 0.0
Read the numbers: the analytic gradient \(\mathbf p - \mathbf y\) matches finite differences to
ten decimal places; \(\operatorname{KL}(q\Vert r) \ne \operatorname{KL}(r\Vert q)\) ; the naive
log-sum-exp overflows to infinity while the shifted one returns 1002.41; \(\mathbf q^\top\mathbf k\)
over 128 dimensions has variance ≈ 128 until divided by \(\sqrt{128}\) ; a 7-billion-parameter
model on 2 trillion tokens costs \(8.4\times10^{22}\) FLOPs ; grouped-query attention with 8
key–value heads cuts a 32k-token cache from 16 GiB to 4 GiB; and an 80% score on 500 items
carries a standard error of 1.8 points, so a 95% interval is about ±3.5 points.
Things to try
Change d in check 4 to 16 and 1024: the variance of \(\mathbf q^\top\mathbf k\) tracks \(d\) exactly.
In check 6, set 64 layers and FP8 (1 byte): how many tokens of cache fit in 80 GB?
In check 7, find \(n\) so that the 95% interval is ±1 point (answer: about 6,150 items).
In check 8, raise \(\gamma\) to 0.99 and watch the values grow towards \(1/(1-\gamma)\) scale.
Conventions differ between papers
Before using any formula from a paper, check four conventions: natural log or \(\log_2\)
(nats or bits); row vectors (\(XW\) , used here for activations) or column vectors (\(W\mathbf x\) );
whether a loss is summed or averaged over tokens and over the batch; and whether \(\beta\)
multiplies the KL (RLHF ) or divides the reward (the DPO derivation). Most "my result does
not match the paper" bugs are one of these.
Where this leads