Probability & Statistics Foundations

Gaussian Distribution

The most important distribution in deep learning. A random variable X∼N(μ,σ2)X \sim \mathcal{N}(\mu, \sigma^2) has density:

p(x)=12πσ2exp⁡ ⁣(−(x−μ)22σ2)p(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)
  • μ\mu: mean (centre of the bell curve)
  • σ2\sigma^2: variance (spread); σ\sigma is the standard deviation

Multivariate Gaussian x∼N(μ,Σ)\mathbf{x} \sim \mathcal{N}(\boldsymbol{\mu}, \Sigma), Σ∈Rd×d\Sigma \in \mathbb{R}^{d\times d} covariance matrix:

p(x)=1(2π)d/2∣Σ∣1/2exp⁡ ⁣(−12(x−μ)⊤Σ−1(x−μ))p(\mathbf{x}) = \frac{1}{(2\pi)^{d/2}|\Sigma|^{1/2}} \exp\!\left(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^\top \Sigma^{-1}(\mathbf{x}-\boldsymbol{\mu})\right)

Expectation & Variance

E[X]=∫x p(x) dx,E[f(X)]=∫f(x) p(x) dx\mathbb{E}[X] = \int x\, p(x)\, dx, \qquad \mathbb{E}[f(X)] = \int f(x)\, p(x)\, dxVar(X)=E[(X−E[X])2]=E[X2]−(E[X])2\text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2

Entropy & KL Divergence

Entropy — measures uncertainty of distribution pp:

H(p)=−∑xp(x)log⁡p(x)(discrete),H(p)=−∫p(x)log⁡p(x) dx(continuous)H(p) = -\sum_x p(x)\log p(x) \qquad (\text{discrete}), \quad H(p) = -\int p(x)\log p(x)\,dx \quad (\text{continuous})

KL Divergence — measures how much qq differs from pp (not a distance — asymmetric):

DKL(p∥q)=∑xp(x)log⁡p(x)q(x)≥0,=0  ⟺  p=qD_{\text{KL}}(p \| q) = \sum_x p(x)\log\frac{p(x)}{q(x)} \geq 0, \quad = 0 \iff p = q

Cross-entropy loss is directly related: LCE=H(p)+DKL(p∥q)\mathcal{L}_{\text{CE}} = H(p) + D_{\text{KL}}(p\|q) where pp is the true label distribution.

Bayes' Theorem

P(θ∣D)=P(D∣θ)  P(θ)P(D)P(\theta \mid \mathcal{D}) = \frac{P(\mathcal{D} \mid \theta)\; P(\theta)}{P(\mathcal{D})}
  • P(θ)P(\theta): prior — belief about parameters before seeing data
  • P(D∣θ)P(\mathcal{D}\mid\theta): likelihood — how well θ\theta explains data
  • P(θ∣D)P(\theta\mid\mathcal{D}): posterior — updated belief after data
  • P(D)P(\mathcal{D}): evidence — normalisation constant

MLE (Maximum Likelihood Estimation) maximises P(D∣θ)P(\mathcal{D}\mid\theta); MAP adds a prior regulariser.


Core ML Concepts, Mathematically

Linear Regression (LR)

f(x)=w⊤x+b=∑j=1dwjxj+bf(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b = \sum_{j=1}^{d} w_j x_j + b

In matrix form over nn samples: y^=Xw+b1,X∈Rn×d\hat{\mathbf{y}} = X\mathbf{w} + b\mathbf{1},\quad X \in \mathbb{R}^{n \times d}

Squared Error (SE)

SE(y^,y)=(y^−y)2\text{SE}(\hat{y}, y) = (\hat{y} - y)^2

Mean Squared Error (MSE)

LMSE(θ)=1n∑i=1n(fθ(x(i))−y(i))2\mathcal{L}_{\text{MSE}}(\theta) = \frac{1}{n} \sum_{i=1}^{n} \left( f_\theta(\mathbf{x}^{(i)}) - y^{(i)} \right)^2

Cross-Entropy Loss (CE)

Used for classification. For a one-hot label y∈{0,1}K\mathbf{y} \in \{0,1\}^K over KK classes and predicted probability vector p^=softmax(z)\hat{\mathbf{p}} = \text{softmax}(\mathbf{z}):

LCE=−∑k=1Kyklog⁡p^k\mathcal{L}_{\text{CE}} = -\sum_{k=1}^{K} y_k \log \hat{p}_k

For binary classification (K=2K=2):

LBCE=−[ylog⁡p^+(1−y)log⁡(1−p^)]\mathcal{L}_{\text{BCE}} = -\left[y \log \hat{p} + (1-y)\log(1-\hat{p})\right]

Over nn samples (multiclass):

LCE(θ)=−1n∑i=1nlog⁡p^y(i)(i)\mathcal{L}_{\text{CE}}(\theta) = -\frac{1}{n}\sum_{i=1}^{n} \log \hat{p}_{y^{(i)}}^{(i)}

Derivatives

Derivative — instantaneous rate of change:

f′(x)=dfdx=lim⁡h→0f(x+h)−f(x)hf'(x) = \frac{df}{dx} = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}

Gradient — multivariate generalisation f:Rd→Rf : \mathbb{R}^d \to \mathbb{R}:

∇θL=[∂L/∂θ1⋮∂L/∂θd]∈Rd\nabla_\theta \mathcal{L} = \begin{bmatrix} \partial \mathcal{L}/\partial \theta_1 \\ \vdots \\ \partial \mathcal{L}/\partial \theta_d \end{bmatrix} \in \mathbb{R}^d

Chain Rule — for z=g(f(x))z = g(f(x)):

dzdx=dzdf⋅dfdx\frac{dz}{dx} = \frac{dz}{df} \cdot \frac{df}{dx}

For deep compositions z=h(g(f(x)))z = h(g(f(\mathbf{x}))):

∂z∂x=∂z∂g⋅∂g∂f⋅∂f∂x\frac{\partial z}{\partial \mathbf{x}} = \frac{\partial z}{\partial g} \cdot \frac{\partial g}{\partial f} \cdot \frac{\partial f}{\partial \mathbf{x}}

Gradient Descent — minimise L(θ)\mathcal{L}(\theta) by stepping opposite the gradient:

θt+1=θt−η⋅∇θL(θt)\theta_{t+1} = \theta_t - \eta \cdot \nabla_\theta \mathcal{L}(\theta_t)

The Four-Step Recipe of Machine Learning

  1. Collect the data
  2. Define the model's structure
  3. Define the loss function
  4. Minimise the loss

Vectors Are All You Need

A vector x∈Rd\mathbf{x} \in \mathbb{R}^d encodes a data point with dd features.

Operations:

  • Add: (u+v)i=ui+vi(\mathbf{u} + \mathbf{v})_i = u_i + v_i
  • Dot product: u⋅v=u⊤v=∑iuivi\mathbf{u} \cdot \mathbf{v} = \mathbf{u}^\top \mathbf{v} = \sum_i u_i v_i
  • ℓ2\ell_2 Norm: ∥x∥2=∑ixi2\|\mathbf{x}\|_2 = \sqrt{\sum_i x_i^2}
  • Cosine similarity: cos⁡(u,v)=u⊤v∥u∥∥v∥\cos(\mathbf{u},\mathbf{v}) = \dfrac{\mathbf{u}^\top \mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|}

Matrices

A matrix W∈Rm×nW \in \mathbb{R}^{m \times n} represents a linear transformation Rn→Rm\mathbb{R}^n \to \mathbb{R}^m.

Operations:

  • Add: (A+B)ij=Aij+Bij(A+B)_{ij} = A_{ij}+B_{ij}
  • Mul (matrix product): (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik}B_{kj}
  • Broadcast: scalar/vector ops extend across batch dimensions
  • Transpose: (A⊤)ij=Aji(A^\top)_{ij} = A_{ji}

Neural Networks

Single neuron:

a=ϕ(w⊤x+b)a = \phi(\mathbf{w}^\top \mathbf{x} + b)

MLP — layer ℓ\ell forward pass:

z(ℓ)=W(ℓ)a(ℓ−1)+b(ℓ),a(ℓ)=ϕ ⁣(z(ℓ))\mathbf{z}^{(\ell)} = W^{(\ell)}\mathbf{a}^{(\ell-1)} + \mathbf{b}^{(\ell)}, \qquad \mathbf{a}^{(\ell)} = \phi\!\left(\mathbf{z}^{(\ell)}\right)

Backpropagation (chain rule applied layer by layer):

δ(ℓ)=(W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′ ⁣(z(ℓ))\boldsymbol{\delta}^{(\ell)} = \left(W^{(\ell+1)\top}\boldsymbol{\delta}^{(\ell+1)}\right) \odot \phi'\!\left(\mathbf{z}^{(\ell)}\right)∂L∂W(ℓ)=δ(ℓ)a(ℓ−1)⊤\frac{\partial \mathcal{L}}{\partial W^{(\ell)}} = \boldsymbol{\delta}^{(\ell)}\mathbf{a}^{(\ell-1)\top}

Activation functions:

ReLU:

ReLU(x)=max⁡(0,x),ReLU′(x)=1[x>0]\text{ReLU}(x) = \max(0,x), \qquad \text{ReLU}'(x) = \mathbf{1}[x>0]

Sigmoid:

σ(x)=11+e−x,σ′(x)=σ(x)(1−σ(x))\sigma(x) = \frac{1}{1+e^{-x}}, \qquad \sigma'(x) = \sigma(x)(1-\sigma(x))

Tanh:

tanh⁡(x)=ex−e−xex+e−x,tanh⁡′(x)=1−tanh⁡2(x)\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}, \qquad \tanh'(x) = 1 - \tanh^2(x)

Softmax:

softmax(z)k=ezk∑jezj\text{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_j e^{z_j}}

GELU (Gaussian Error Linear Unit) — used in BERT, GPT-2, and many modern Transformers:

GELU(x)=x⋅Φ(x)=x⋅12[1+erf ⁣(x2)]\text{GELU}(x) = x \cdot \Phi(x) = x \cdot \frac{1}{2}\left[1 + \text{erf}\!\left(\frac{x}{\sqrt{2}}\right)\right]

where Φ(x)\Phi(x) is the standard Gaussian CDF. Practical approximation:

GELU(x)≈0.5x(1+tanh⁡ ⁣(2π (x+0.044715 x3)))\text{GELU}(x) \approx 0.5x\left(1 + \tanh\!\left(\sqrt{\frac{2}{\pi}}\,(x + 0.044715\,x^3)\right)\right)

Unlike ReLU, GELU is smooth everywhere and lets small negative values through for x<0x < 0, which helps gradient flow.

Training Details

  • Parameters θ={W(ℓ),b(ℓ)}\theta = \{W^{(\ell)}, \mathbf{b}^{(\ell)}\}: learned by gradient descent.
  • Hyperparameters: learning rate η\eta, batch size BB, layers LL, hidden dim dd — set before training.

ℓ2\ell_2 Regularisation (weight decay):

Lreg(θ)=L(θ)+λ2∥θ∥22\mathcal{L}_{\text{reg}}(\theta) = \mathcal{L}(\theta) + \frac{\lambda}{2}\|\theta\|_2^2

Dropout — randomly zero out neurons during training with probability pp:

a~=m⊙a⋅11−p,mi∼Bernoulli(1−p)\tilde{\mathbf{a}} = \mathbf{m} \odot \mathbf{a} \cdot \frac{1}{1-p}, \quad \mathbf{m}_i \sim \text{Bernoulli}(1-p)

At inference, no dropout is applied: activations were already scaled by 1/(1−p)1/(1-p) during training (inverted dropout), so the expected output matches.

Batch Normalisation (BN) — normalise activations across the batch dimension, then scale and shift:

x^i=xi−μBσB2+ϵ,yi=γx^i+β\hat{x}_i = \frac{x_i - \mu_\mathcal{B}}{\sqrt{\sigma_\mathcal{B}^2 + \epsilon}}, \qquad y_i = \gamma\hat{x}_i + \beta

where μB,σB2\mu_\mathcal{B}, \sigma_\mathcal{B}^2 are batch mean/variance; γ,β\gamma,\beta are learned parameters.

Layer Normalisation (LN) — same formula but normalise across the feature dimension (not batch). Preferred in Transformers because it is batch-size independent:

x^=x−μxσx2+ϵ⋅γ+β,μx=1d∑jxj\hat{\mathbf{x}} = \frac{\mathbf{x} - \mu_\mathbf{x}}{\sqrt{\sigma_\mathbf{x}^2 + \epsilon}} \cdot \boldsymbol{\gamma} + \boldsymbol{\beta}, \quad \mu_\mathbf{x} = \frac{1}{d}\sum_j x_j

Adam optimiser — bias-corrected moment estimates:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2m_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θt+1=θt−ηm^tv^t+ϵ,m^t=mt1−β1t,  v^t=vt1−β2t\theta_{t+1} = \theta_t - \eta\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}, \quad \hat{m}_t = \frac{m_t}{1-\beta_1^t},\; \hat{v}_t = \frac{v_t}{1-\beta_2^t}

Vanishing & Exploding Gradients

In a deep network with LL layers, the gradient flowing back to layer ℓ\ell is a product of Jacobians:

∂L∂a(ℓ)=∂L∂a(L)∏k=ℓL−1∂a(k+1)∂a(k)\frac{\partial \mathcal{L}}{\partial \mathbf{a}^{(\ell)}} = \frac{\partial \mathcal{L}}{\partial \mathbf{a}^{(L)}} \prod_{k=\ell}^{L-1} \frac{\partial \mathbf{a}^{(k+1)}}{\partial \mathbf{a}^{(k)}}

Each factor ≈W(k)⋅diag(ϕ′(z(k)))\approx W^{(k)} \cdot \text{diag}(\phi'(\mathbf{z}^{(k)})). If the spectral norm ∥W∥<1\|W\| < 1 repeatedly, gradients vanish exponentially; if ∥W∥>1\|W\| > 1, they explode.

  • Vanishing: gradients →0\to 0, early layers learn nothing. Caused by sigmoid/tanh saturation (σ′≤0.25\sigma' \leq 0.25) + many layers.
  • Exploding: parameter updates become huge, training diverges.

Fixes: ReLU (gradient = 1 in positive region), residual connections, LayerNorm, gradient clipping:

gt←gt⋅min⁡ ⁣(1,  τ∥gt∥),τ is the clip thresholdg_t \leftarrow g_t \cdot \min\!\left(1,\; \frac{\tau}{\|g_t\|}\right), \quad \tau \text{ is the clip threshold}

Zigzag in Gradient Descent

Vanilla SGD with a fixed learning rate η\eta oscillates (zigzags) when the loss surface has different curvatures along different directions — it overshoots in high-curvature directions and undershoots in low-curvature ones:

θt+1(i)=θt(i)−η ∂L∂θ(i)\theta_{t+1}^{(i)} = \theta_t^{(i)} - \eta\, \frac{\partial \mathcal{L}}{\partial \theta^{(i)}}

If η\eta is large enough to make progress along the flat direction, it overshoots along the steep direction → zigzag trajectory.

Momentum damps oscillations by accumulating a velocity vector:

vt+1=γvt+η∇θL,θt+1=θt−vt+1\mathbf{v}_{t+1} = \gamma \mathbf{v}_t + \eta \nabla_\theta \mathcal{L}, \qquad \theta_{t+1} = \theta_t - \mathbf{v}_{t+1}

The exponential moving average of gradients cancels out oscillating components while reinforcing consistent directions. Adam further applies per-parameter adaptive learning rates via v^t\hat{v}_t (second moment), which is why it often converges faster than plain SGD on non-convex landscapes.

ResNet — Residual Connections

Add a skip connection that bypasses one or more layers, letting gradients flow directly to earlier layers:

y=F(x, {Wi})+x\mathbf{y} = \mathcal{F}(\mathbf{x},\,\{W_i\}) + \mathbf{x}
  • F(x)\mathcal{F}(\mathbf{x}): the residual to learn (e.g. two conv layers)
  • x\mathbf{x}: identity shortcut

Why it works: the gradient through the skip path is exactly 11 — no matter how deep, the chain rule always has a direct path with gradient ∂y∂x=∂F∂x+I\frac{\partial \mathbf{y}}{\partial \mathbf{x}} = \frac{\partial \mathcal{F}}{\partial \mathbf{x}} + I. This prevents vanishing gradients in very deep networks (ResNet-152, Transformers).

CNN

2D convolution — kernel K∈Rk×kK \in \mathbb{R}^{k\times k} slides over image X∈RH×WX \in \mathbb{R}^{H\times W}:

(X∗K)i,j=∑m=0k−1∑n=0k−1Km,n⋅Xi+m, j+n(X * K)_{i,j} = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} K_{m,n} \cdot X_{i+m,\,j+n}

Each layer applies CoutC_{\text{out}} kernels → feature map ∈RCout×H′×W′\in \mathbb{R}^{C_{\text{out}}\times H'\times W'}.

Pooling — downsample spatial dimensions to reduce computation and add translation invariance:

MaxPool(X)i,j=max⁡(m,n)∈windowXi⋅s+m, j⋅s+n\text{MaxPool}(X)_{i,j} = \max_{(m,n)\in\text{window}} X_{i\cdot s+m,\,j\cdot s+n}AvgPool(X)i,j=1k2∑(m,n)∈windowXi⋅s+m, j⋅s+n\text{AvgPool}(X)_{i,j} = \frac{1}{k^2}\sum_{(m,n)\in\text{window}} X_{i\cdot s+m,\,j\cdot s+n}

where kk is the pool size and ss is the stride.

RNN

Vanilla RNN — hidden state recurrence:

ht=tanh⁡(Whht−1+Wxxt+b)\mathbf{h}_t = \tanh(W_h \mathbf{h}_{t-1} + W_x \mathbf{x}_t + \mathbf{b})

LSTM — gated memory cell (i,f,o(i,f,o: input/forget/output gates)):

ft=σ(Wf[ht−1;xt]+bf),it=σ(Wi[ht−1;xt]+bi)\mathbf{f}_t = \sigma(W_f[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_f), \quad \mathbf{i}_t = \sigma(W_i[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_i)ct=ft⊙ct−1+it⊙tanh⁡(Wc[ht−1;xt]+bc)\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tanh(W_c[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_c)ot=σ(Wo[ht−1;xt]+bo),ht=ot⊙tanh⁡(ct)\mathbf{o}_t = \sigma(W_o[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_o), \quad \mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)

GRU — simplified gating (reset rt\mathbf{r}_t, update zt\mathbf{z}_t):

zt=σ(Wz[ht−1;xt]),rt=σ(Wr[ht−1;xt])\mathbf{z}_t = \sigma(W_z[\mathbf{h}_{t-1};\mathbf{x}_t]), \quad \mathbf{r}_t = \sigma(W_r[\mathbf{h}_{t-1};\mathbf{x}_t])ht=(1−zt)⊙ht−1+zt⊙tanh⁡(Wh[rt⊙ht−1;xt])\mathbf{h}_t = (1-\mathbf{z}_t)\odot\mathbf{h}_{t-1} + \mathbf{z}_t\odot\tanh(W_h[\mathbf{r}_t\odot\mathbf{h}_{t-1};\mathbf{x}_t])

Attention

Scaled Dot-Product Attention — Q,K,V∈Rn×dkQ,K,V \in \mathbb{R}^{n\times d_k}:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

Multi-Head Attention — hh parallel heads, then project:

headi=Attention(QWiQ, KWiK, VWiV)\text{head}_i = \text{Attention}(QW_i^Q,\,KW_i^K,\,VW_i^V)MultiHead(Q,K,V)=Concat(head1,…,headh) WO\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1,\ldots,\text{head}_h)\,W^O

Positional Encoding (sinusoidal):

PE(pos,2i)=sin⁡ ⁣(pos100002i/d),PE(pos,2i+1)=cos⁡ ⁣(pos100002i/d)\text{PE}_{(pos,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \quad \text{PE}_{(pos,2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)

Transformer block (with residual + LayerNorm):

h′=LayerNorm(h+MultiHead(h,h,h))\mathbf{h}' = \text{LayerNorm}(\mathbf{h} + \text{MultiHead}(\mathbf{h},\mathbf{h},\mathbf{h}))h′′=LayerNorm(h′+FFN(h′)),FFN(x)=W2 ReLU(W1x+b1)+b2\mathbf{h}'' = \text{LayerNorm}(\mathbf{h}' + \text{FFN}(\mathbf{h}')), \quad \text{FFN}(\mathbf{x})=W_2\,\text{ReLU}(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2

Language Modelling Objective — minimise the negative log-likelihood of the token sequence:

L=−1T∑t=1Tlog⁡Pθ(tt∣t<t)\mathcal{L} = -\frac{1}{T}\sum_{t=1}^T \log P_\theta(t_t \mid t_{\lt t})

ViT — split image into NN patches pi∈RP2C\mathbf{p}_i \in \mathbb{R}^{P^2 C}, linearly project to token embeddings, then apply Transformer encoder:

z0=[xcls; Ep1; …; EpN]+Epos\mathbf{z}_0 = [\mathbf{x}_{\text{cls}};\, E\mathbf{p}_1;\,\ldots;\,E\mathbf{p}_N] + \mathbf{E}_{\text{pos}}

Encoder-Decoder Transformer (original seq2seq, e.g. T5, BART) — encoder processes source sequence bidirectionally; decoder generates target tokens autoregressively with cross-attention over encoder outputs:

headicross=Attention(Qdec WiQ,  Kenc WiK,  Venc WiV)\text{head}_i^{\text{cross}} = \text{Attention}(Q_{\text{dec}}\,W_i^Q,\; K_{\text{enc}}\,W_i^K,\; V_{\text{enc}}\,W_i^V)

Decoder block = (causal self-attention) → (cross-attention to encoder) → (FFN), each with residual + LayerNorm.

BERT — Bidirectional Encoder

BERT uses the encoder-only Transformer and pre-trains on two objectives:

1. Masked Language Model (MLM) — randomly mask 15 % of tokens, predict them from full bidirectional context:

LMLM=−∑i∈Mlog⁡Pθ(ti∣t\M)\mathcal{L}_{\text{MLM}} = -\sum_{i \in \mathcal{M}} \log P_\theta(t_i \mid \mathbf{t}_{\backslash \mathcal{M}})
  • M\mathcal{M}: set of masked positions
  • t\M\mathbf{t}_{\backslash \mathcal{M}}: all tokens except the masked ones

Because attention is bidirectional (no causal mask), every token can attend to every other token — unlike GPT which only sees past context.

2. Next Sentence Prediction (NSP) — binary classification: does sentence B follow sentence A?

LNSP=−log⁡Pθ(IsNext∣[CLS])\mathcal{L}_{\text{NSP}} = -\log P_\theta(\text{IsNext} \mid [\text{CLS}])

GPT vs BERT comparison:

GPT (decoder-only)BERT (encoder-only)
AttentionCausal (left-to-right)Bidirectional (full)
Pre-trainingNext-token predictionMLM + NSP
StrengthGenerationUnderstanding / Classification
Representationhi\mathbf{h}_i sees only t1,…,tit_1,\ldots,t_ihi\mathbf{h}_i sees all tokens

Transfer Learning

Pre-train on large corpus Dpre\mathcal{D}_{\text{pre}} to get θ∗\theta^*, then fine-tune on target task Dft\mathcal{D}_{\text{ft}}:

θft=arg⁡min⁡θLft(θ; Dft),θ←θ∗ (initialised)\theta_{\text{ft}} = \arg\min_\theta \mathcal{L}_{\text{ft}}(\theta;\,\mathcal{D}_{\text{ft}}), \quad \theta \leftarrow \theta^* \text{ (initialised)}

LoRA — freeze W0W_0, inject low-rank update ΔW=BA\Delta W = BA (B∈Rd×r, A∈Rr×k, r≪min⁡(d,k)B\in\mathbb{R}^{d\times r},\,A\in\mathbb{R}^{r\times k},\,r\ll\min(d,k)):

W=W0+ΔW=W0+BAW = W_0 + \Delta W = W_0 + BA

Generative AI

Generative models learn the data distribution p(x)p(\mathbf{x}) and can sample new data from it.

The core distinction from discriminative models:

DiscriminativeGenerative
Goalp(y∥x)p(y\|\mathbf{x})p(x)p(\mathbf{x}) or p(x,y)p(\mathbf{x},y)
OutputLabel / decisionNew data sample
ExamplesClassifier, RegressionVAE, GAN, Diffusion, LLM

Variational Autoencoder (VAE)

Encode data x\mathbf{x} into a latent variable z\mathbf{z}, then decode back.

Encoder — approximate posterior qϕ(z∣x)≈p(z∣x)q_\phi(\mathbf{z}|\mathbf{x}) \approx p(\mathbf{z}|\mathbf{x}), parameterised as Gaussian:

qϕ(z∣x)=N(z; μϕ(x), diag(σϕ2(x)))q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\mathbf{z};\,\boldsymbol{\mu}_\phi(\mathbf{x}),\,\text{diag}(\boldsymbol{\sigma}^2_\phi(\mathbf{x})))

Decoder — likelihood pθ(x∣z)p_\theta(\mathbf{x}|\mathbf{z}).

ELBO objective (Evidence Lower Bound, maximise):

LVAE(θ,ϕ)=Eqϕ(z∣x) ⁣[log⁡pθ(x∣z)]−DKL ⁣(qϕ(z∣x)  ∥  p(z))\mathcal{L}_{\text{VAE}}(\theta,\phi) = \mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})}\!\left[\log p_\theta(\mathbf{x}|\mathbf{z})\right] - D_{\text{KL}}\!\left(q_\phi(\mathbf{z}|\mathbf{x})\;\|\;p(\mathbf{z})\right)

KL divergence between two Gaussians:

DKL(N(μ,σ2)  ∥  N(0,I))=12∑j ⁣(σj2+μj2−1−log⁡σj2)D_{\text{KL}}(\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\sigma}^2)\;\|\;\mathcal{N}(\mathbf{0},I)) = \frac{1}{2}\sum_j\!\left(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2\right)

Reparameterisation trick — make sampling differentiable:

z=μϕ(x)+σϕ(x)⊙ϵ,ϵ∼N(0,I)\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, I)

Generative Adversarial Network (GAN)

Two networks compete: Generator GθG_\theta tries to fool Discriminator DϕD_\phi.

min⁡θmax⁡ϕ  Ex∼pdata ⁣[log⁡Dϕ(x)]+Ez∼p(z) ⁣[log⁡(1−Dϕ(Gθ(z)))]\min_\theta \max_\phi\; \mathbb{E}_{\mathbf{x}\sim p_{\text{data}}}\!\left[\log D_\phi(\mathbf{x})\right] + \mathbb{E}_{\mathbf{z}\sim p(\mathbf{z})}\!\left[\log(1 - D_\phi(G_\theta(\mathbf{z})))\right]
  • Gθ(z)G_\theta(\mathbf{z}): maps noise z∼N(0,I)\mathbf{z}\sim\mathcal{N}(\mathbf{0},I) to fake samples.
  • Dϕ(x)∈(0,1)D_\phi(\mathbf{x})\in(0,1): probability that x\mathbf{x} is real.
  • At equilibrium: Dϕ(x)=12D_\phi(\mathbf{x}) = \tfrac{1}{2} everywhere — generator perfectly mimics data.

Diffusion Models (DDPM)

Gradually add Gaussian noise over TT steps (forward process), then learn to reverse it (reverse process).

Forward process — fixed Markov chain:

q(xt∣xt−1)=N ⁣(xt; 1−βt xt−1, βtI)q(\mathbf{x}_t|\mathbf{x}_{t-1}) = \mathcal{N}\!\left(\mathbf{x}_t;\,\sqrt{1-\beta_t}\,\mathbf{x}_{t-1},\,\beta_t I\right)

Closed-form sampling at any step tt (let αˉt=∏s=1t(1−βs)\bar\alpha_t = \prod_{s=1}^t(1-\beta_s)):

xt=αˉt x0+1−αˉt ϵ,ϵ∼N(0,I)\mathbf{x}_t = \sqrt{\bar\alpha_t}\,\mathbf{x}_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon}\sim\mathcal{N}(\mathbf{0},I)

Reverse process — learned denoiser ϵθ(xt,t)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t):

pθ(xt−1∣xt)=N ⁣(xt−1; μθ(xt,t), β~tI)p_\theta(\mathbf{x}_{t-1}|\mathbf{x}_t) = \mathcal{N}\!\left(\mathbf{x}_{t-1};\,\boldsymbol{\mu}_\theta(\mathbf{x}_t,t),\,\tilde\beta_t I\right)μθ(xt,t)=1αt ⁣(xt−βt1−αˉt ϵθ(xt,t))\boldsymbol{\mu}_\theta(\mathbf{x}_t,t) = \frac{1}{\sqrt{\alpha_t}}\!\left(\mathbf{x}_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\boldsymbol{\epsilon}_\theta(\mathbf{x}_t,t)\right)

Training objective — predict the noise:

LDDPM=Et,x0,ϵ ⁣[∥ϵ−ϵθ(xt,t)∥2]\mathcal{L}_{\text{DDPM}} = \mathbb{E}_{t,\mathbf{x}_0,\boldsymbol{\epsilon}}\!\left[\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)\|^2\right]

Autoregressive Generation (LLM Decoding)

Given a prompt (t1,…,tk)(t_1,\ldots,t_k), generate token-by-token:

tk+i∼Pθ(⋅∣t1,…,tk+i−1)t_{k+i} \sim P_\theta(\cdot \mid t_1,\ldots,t_{k+i-1})

Temperature scaling — control sharpness of distribution:

Pτ(t)=exp⁡(zt/τ)∑jexp⁡(zj/τ)P_\tau(t) = \frac{\exp(z_t / \tau)}{\sum_j \exp(z_j / \tau)}
  • τ→0\tau \to 0: greedy (deterministic); τ=1\tau = 1: standard softmax; τ>1\tau > 1: more random.

Top-pp (nucleus) sampling — sample from smallest set V\mathcal{V} s.t.:

∑t∈VP(t)≥p\sum_{t \in \mathcal{V}} P(t) \geq p

Reinforcement Learning from Human Feedback (RLHF)

Step 1 — Supervised Fine-Tuning (SFT): fine-tune LLM on human demonstrations.

Step 2 — Reward Model: train rϕ(x,y)r_\phi(\mathbf{x}, \mathbf{y}) from preference pairs (yw≻yl)(y_w \succ y_l):

LRM=−E(x,yw,yl) ⁣[log⁡σ ⁣(rϕ(x,yw)−rϕ(x,yl))]\mathcal{L}_{\text{RM}} = -\mathbb{E}_{(x,y_w,y_l)}\!\left[\log\sigma\!\left(r_\phi(x,y_w) - r_\phi(x,y_l)\right)\right]

Step 3 — PPO fine-tuning — maximise reward while staying close to SFT policy πref\pi_{\text{ref}}:

LRLHF(θ)=Ex∼D, y∼πθ ⁣[rϕ(x,y)]−β DKL ⁣(πθ(⋅∣x)  ∥  πref(⋅∣x))\mathcal{L}_{\text{RLHF}}(\theta) = \mathbb{E}_{x\sim\mathcal{D},\,y\sim\pi_\theta}\!\left[r_\phi(x,y)\right] - \beta\,D_{\text{KL}}\!\left(\pi_\theta(\cdot|x)\;\|\;\pi_{\text{ref}}(\cdot|x)\right)

DPO (Direct Preference Optimisation) — skips reward model, optimise preferences directly:

LDPO(θ)=−E(x,yw,yl) ⁣[log⁡σ ⁣(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))]\mathcal{L}_{\text{DPO}}(\theta) = -\mathbb{E}_{(x,y_w,y_l)}\!\left[\log\sigma\!\left(\beta\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \beta\log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\right)\right]

Large Language Models (LLM)

Architecture Overview

A decoder-only Transformer stacks LL blocks. Given token sequence (t1,…,tn)(t_1,\ldots,t_n):

  1. Tokenisation — map text to integer IDs via vocabulary V\mathcal{V}, ∣V∣∼50k|\mathcal{V}|\sim 50\text{k}–200k200\text{k}.
  2. Embedding — E∈R∣V∣×d\mathbf{E} \in \mathbb{R}^{|\mathcal{V}|\times d}, look up row tit_i: hi(0)=Eti+PEi\mathbf{h}_i^{(0)} = \mathbf{E}_{t_i} + \mathbf{PE}_i
  3. LL Transformer blocks (causal masked attention + FFN).
  4. Unembedding — project to logits and apply softmax: li=E hi(L)∈R∣V∣\mathbf{l}_i = \mathbf{E}\,\mathbf{h}_i^{(L)} \in \mathbb{R}^{|\mathcal{V}|}

Causal (masked) self-attention — token ii can only attend to positions j≤ij \leq i:

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V,Mij={0j≤i−∞j>i\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V, \quad M_{ij} = \begin{cases}0 & j\leq i\\-\infty & j>i\end{cases}

Tokenisation & Embedding

Byte-Pair Encoding (BPE) — iteratively merge the most frequent adjacent pair until vocabulary size ∣V∣|\mathcal{V}| is reached.

Token embedding + positional encoding → input representation:

hi=Eti+PEi∈Rd\mathbf{h}_i = \mathbf{E}_{t_i} + \mathbf{PE}_i \in \mathbb{R}^d

RoPE (Rotary Positional Embedding) — encode position by rotating query/key vectors:

qm=Rmq,kn=Rnk,qm⊤kn=q⊤Rn−mk\mathbf{q}_m = R_m \mathbf{q}, \quad \mathbf{k}_n = R_n \mathbf{k}, \quad \mathbf{q}_m^\top \mathbf{k}_n = \mathbf{q}^\top R_{n-m} \mathbf{k}

where RmR_m is a block-diagonal rotation matrix at angle mθim\theta_i.


Perplexity (PPL)

The standard intrinsic evaluation metric for language models — how "surprised" the model is by the test set:

PPL(T)=exp⁡ ⁣(−1T∑t=1Tlog⁡Pθ(tt∣t<t))=exp⁡(L)\text{PPL}(T) = \exp\!\left(-\frac{1}{T}\sum_{t=1}^{T} \log P_\theta(t_t \mid t_{\lt t})\right) = \exp(\mathcal{L})
  • Lower PPL = model assigns higher probability to real text = better.
  • PPL is simply the exponential of the cross-entropy loss L\mathcal{L}.
  • PPL =k= k means the model is as uncertain as choosing uniformly among kk tokens.
  • GPT-2 zero-shot on WikiText-103: PPL ≈ 37.5 (117M) → ≈ 17.5 (1.5B) — scale alone cuts it in half.

Bits-per-character (BPC) — alternative unit used for character-level models:

BPC=Lln⁡2\text{BPC} = \frac{\mathcal{L}}{\ln 2}

Scaling Laws

Model performance scales predictably with compute CC, data DD, and parameters NN (Chinchilla):

L(N,D)=ANα+BDβ+L∞\mathcal{L}(N, D) = \frac{A}{N^\alpha} + \frac{B}{D^\beta} + \mathcal{L}_\infty

Optimal allocation for a compute budget C=6NDC = 6ND:

Nopt∝C0.5,Dopt∝C0.5N_{\text{opt}} \propto C^{0.5}, \qquad D_{\text{opt}} \propto C^{0.5}

i.e. tokens and parameters should scale equally.


In-Context Learning (ICL) & Prompting

LLMs can learn from examples in the prompt without updating weights.

kk-shot prompting — prepend kk (input, output) examples:

Pθ(y∣x,(x1,y1),…,(xk,yk))P_\theta(y \mid x, (x_1,y_1),\ldots,(x_k,y_k))

Chain-of-Thought (CoT) — include reasoning steps rr before answer aa:

Pθ(r,a∣x)=Pθ(r∣x)⋅Pθ(a∣x,r)P_\theta(r, a \mid x) = P_\theta(r \mid x) \cdot P_\theta(a \mid x, r)

Self-consistency — sample MM reasoning paths, take majority vote:

a^=arg⁡max⁡a∑m=1M1[am=a]\hat{a} = \arg\max_a \sum_{m=1}^{M} \mathbf{1}[a_m = a]

Retrieval-Augmented Generation (RAG)

Augment generation with retrieved documents Dr\mathcal{D}_r from an external knowledge base:

Pθ(y∣x)=∑d∈DrPθ(y∣x,d) Pret(d∣x)P_\theta(y \mid x) = \sum_{d \in \mathcal{D}_r} P_\theta(y \mid x, d)\, P_{\text{ret}}(d \mid x)

Retrieval — encode query and documents, fetch top-kk by cosine similarity:

score(x,d)=f(x)⊤g(d)∥f(x)∥∥g(d)∥\text{score}(x, d) = \frac{f(x)^\top g(d)}{\|f(x)\|\|g(d)\|}

KV Cache

During autoregressive inference, keys and values for all past tokens are cached — avoid recomputing on each new token:

K≤t=[k1,…,kt],V≤t=[v1,…,vt]K_{\leq t} = [k_1,\ldots,k_t], \quad V_{\leq t} = [v_1,\ldots,v_t]

New token t+1t+1 only computes qt+1q_{t+1}, then attends over cached K≤t,V≤tK_{\leq t}, V_{\leq t}. Reduces per-step cost from O(t2d)\mathcal{O}(t^2 d) to O(td)\mathcal{O}(t d); memory grows linearly with sequence length.


Mixture of Experts (MoE)

Replace the dense FFN in each Transformer block with EE expert FFNs. A learned router selects top-kk experts per token:

MoE(x)=∑i=1kgi(x)  FFNi(x)\text{MoE}(\mathbf{x}) = \sum_{i=1}^{k} g_i(\mathbf{x})\; \text{FFN}_i(\mathbf{x})gi(x)=softmax ⁣(TopK ⁣(Wgx,  k))ig_i(\mathbf{x}) = \text{softmax}\!\left(\text{TopK}\!\left(W_g\mathbf{x},\; k\right)\right)_i
  • Activated params per token: ∼k/E\sim k/E of total params → same inference cost as a smaller dense model.
  • Load balancing loss encourages uniform expert utilisation: Lbal=E∑ifi⋅pi\mathcal{L}_{\text{bal}} = E \sum_i f_i \cdot p_i where fif_i is fraction of tokens routed to expert ii and pip_i is mean router probability.

Used in Switch Transformer, Mixtral, and DeepSeek-V3.


Key LLM Concepts Summary

ConceptWhat it doesKey formula / idea
Tokenisation (BPE)Text → integer IDsMerge most-frequent pairs
Causal AttentionEach token sees only pastMask Mij=−∞M_{ij}=-\infty for j>ij>i
Scaling LawPredict loss from N,D,CN,D,CL∝N−α+D−β\mathcal{L} \propto N^{-\alpha} + D^{-\beta}
SFTAlign model to instructionsCross-entropy on demonstrations
RLHF / DPOAlign to human preferencesReward signal or preference pairs
CoT PromptingElicit step-by-step reasoningP(r,a∥x)=P(r∥x)P(a∥x,r)P(r,a\|x) = P(r\|x)P(a\|x,r)
RAGGround generation in factsRetrieve then generate
LoRAParameter-efficient fine-tuningW=W0+BAW = W_0 + BA, r≪dr \ll d

Multimodal AI

Multimodal models process and generate more than one modality (text, image, audio, video) within a unified framework.

fθ:M1×M2×⋯→Yf_\theta : \mathcal{M}_1 \times \mathcal{M}_2 \times \cdots \to \mathcal{Y}

Modality Encoding

Each modality is first encoded into a shared embedding space Rd\mathbb{R}^d:

ModalityEncoderOutput
TextTokeniser + Embeddinght∈RL×d\mathbf{h}_t \in \mathbb{R}^{L\times d}
ImageViT / CNN patch encoderhv∈RN×d\mathbf{h}_v \in \mathbb{R}^{N\times d}
AudioSpectrogram + Conv / Whisperha∈RS×d\mathbf{h}_a \in \mathbb{R}^{S\times d}
VideoFrame-level ViT + temporal attentionhf∈RT×N×d\mathbf{h}_f \in \mathbb{R}^{T\times N\times d}

CLIP — Contrastive Vision-Language Pre-training

Learn aligned image and text embeddings by maximising agreement between matched pairs.

Given a batch of NN (image vi\mathbf{v}_i, text ti\mathbf{t}_i) pairs, compute cosine similarities:

sij=f(vi)⊤g(tj)∥f(vi)∥∥g(tj)∥⋅exp⁡(τ)s_{ij} = \frac{f(\mathbf{v}_i)^\top g(\mathbf{t}_j)}{\|f(\mathbf{v}_i)\|\|g(\mathbf{t}_j)\|} \cdot \exp(\tau)

Symmetric InfoNCE loss (maximise diagonal, minimise off-diagonal):

LCLIP=−12N∑i=1N[log⁡esii∑jesij+log⁡esii∑jesji]\mathcal{L}_{\text{CLIP}} = -\frac{1}{2N}\sum_{i=1}^N \left[\log\frac{e^{s_{ii}}}{\sum_j e^{s_{ij}}} + \log\frac{e^{s_{ii}}}{\sum_j e^{s_{ji}}}\right]

At test time: zero-shot classification by picking the text prompt with highest cosine similarity to the image.


Vision-Language Models (VLM)

Connect a vision encoder to an LLM via a projection layer.

Architecture:

hv=VisualEncoder(I)∈RN×dv\mathbf{h}_v = \text{VisualEncoder}(\mathbf{I}) \in \mathbb{R}^{N\times d_v}h~v=Wproj hv∈RN×d,Wproj∈Rd×dv\tilde{\mathbf{h}}_v = W_{\text{proj}}\,\mathbf{h}_v \in \mathbb{R}^{N\times d}, \quad W_{\text{proj}} \in \mathbb{R}^{d\times d_v}

Visual tokens h~v\tilde{\mathbf{h}}_v are prepended (or interleaved) with text tokens and fed into the LLM:

input=[h~v; htext]\text{input} = [\tilde{\mathbf{h}}_v;\, \mathbf{h}_{\text{text}}]

LLaVA-style training — two stages:

  1. Pre-train projection only (freeze encoder + LLM): learn WprojW_{\text{proj}}
  2. Instruction fine-tuning: unfreeze LLM, train on (image, instruction, response) triplets

Objective — standard next-token prediction on response tokens only:

L=−∑tlog⁡Pθ(yt∣I, x, y<t)\mathcal{L} = -\sum_{t} \log P_\theta(y_t \mid \mathbf{I},\, \mathbf{x},\, y_{\lt t})

Cross-Modal Attention

Allow one modality to attend over another. Text queries attend to visual keys/values:

htext′=Attention(Qtext,  Kvision,  Vvision)\mathbf{h}'_{\text{text}} = \text{Attention}(Q_{\text{text}},\; K_{\text{vision}},\; V_{\text{vision}})=softmax ⁣(QtextKvision⊤dk)Vvision= \text{softmax}\!\left(\frac{Q_{\text{text}} K_{\text{vision}}^\top}{\sqrt{d_k}}\right) V_{\text{vision}}

Used in Flamingo, whose gated cross-attention layers read visual tokens from a Perceiver Resampler.


Image Generation — Text-to-Image

Condition a diffusion model on a text embedding c=gϕ(prompt)\mathbf{c} = g_\phi(\text{prompt}).

Classifier-Free Guidance (CFG) — blend conditional and unconditional score:

ϵ~θ(xt,c)=ϵθ(xt,∅)+w ⁣(ϵθ(xt,c)−ϵθ(xt,∅))\tilde{\boldsymbol{\epsilon}}_\theta(\mathbf{x}_t, \mathbf{c}) = \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, \emptyset) + w\!\left(\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, \mathbf{c}) - \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, \emptyset)\right)
  • w>1w > 1: stronger text conditioning (higher fidelity to prompt, less diversity).
  • w=1w = 1: standard conditional generation.
  • w=0w = 0: unconditional generation.

Latent Diffusion (Stable Diffusion) — run diffusion in a compressed latent space:

z=E(x),x^=D(z),L=Et,z0,ϵ ⁣[∥ϵ−ϵθ(zt,t,c)∥2]\mathbf{z} = \mathcal{E}(\mathbf{x}), \quad \hat{\mathbf{x}} = \mathcal{D}(\mathbf{z}), \quad \mathcal{L} = \mathbb{E}_{t,\mathbf{z}_0,\boldsymbol{\epsilon}}\!\left[\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\mathbf{z}_t, t, \mathbf{c})\|^2\right]

Multimodal Summary

Model / ConceptModalitiesKey idea
CLIPImage + TextContrastive alignment, InfoNCE
LLaVA / InternVLImage + TextVisual tokens → LLM via projection
FlamingoImage + TextCross-modal attention layers
Stable DiffusionText → ImageLatent diffusion + CFG
WhisperAudio → TextSpectrogram encoder + decoder
GPT-4oImage/Audio/TextUnified multimodal autoregressive LLM