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) X ∼ N ( μ , σ 2 ) has density:
p ( x ) = 1 2 π σ 2 exp ( − ( x − μ ) 2 2 σ 2 ) p(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right) p ( x ) = 2 π σ 2 1 exp ( − 2 σ 2 ( x − μ ) 2 ) μ \mu μ : mean (centre of the bell curve)σ 2 \sigma^2 σ 2 : variance (spread); σ \sigma σ is the standard deviationMultivariate Gaussian x ∼ N ( μ , Σ ) \mathbf{x} \sim \mathcal{N}(\boldsymbol{\mu}, \Sigma) x ∼ N ( μ , Σ ) , Σ ∈ R d × d \Sigma \in \mathbb{R}^{d\times d} Σ ∈ R d × d covariance matrix:
p ( x ) = 1 ( 2 π ) d / 2 ∣ Σ ∣ 1 / 2 exp ( − 1 2 ( 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) p ( x ) = ( 2 π ) d /2 ∣Σ ∣ 1/2 1 exp ( − 2 1 ( x − μ ) ⊤ Σ − 1 ( x − μ ) ) Expectation & Variance# E [ X ] = ∫ x p ( x ) d x , E [ f ( X ) ] = ∫ f ( x ) p ( x ) d x \mathbb{E}[X] = \int x\, p(x)\, dx, \qquad \mathbb{E}[f(X)] = \int f(x)\, p(x)\, dx E [ X ] = ∫ x p ( x ) d x , E [ f ( X )] = ∫ f ( x ) p ( x ) d x Var ( X ) = E [ ( X − E [ X ] ) 2 ] = E [ X 2 ] − ( E [ X ] ) 2 \text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2 Var ( X ) = E [( X − E [ X ] ) 2 ] = E [ X 2 ] − ( E [ X ] ) 2 Entropy & KL Divergence# Entropy — measures uncertainty of distribution p p p :
H ( p ) = − ∑ x p ( x ) log p ( x ) ( discrete ) , H ( p ) = − ∫ p ( x ) log p ( x ) d x ( 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}) H ( p ) = − x ∑ p ( x ) log p ( x ) ( discrete ) , H ( p ) = − ∫ p ( x ) log p ( x ) d x ( continuous ) KL Divergence — measures how much q q q differs from p p p (not a distance — asymmetric):
D KL ( p ∥ q ) = ∑ x p ( x ) log p ( x ) q ( x ) ≥ 0 , = 0 ⟺ p = q D_{\text{KL}}(p \| q) = \sum_x p(x)\log\frac{p(x)}{q(x)} \geq 0, \quad = 0 \iff p = q D KL ( p ∥ q ) = x ∑ p ( x ) log q ( x ) p ( x ) ≥ 0 , = 0 ⟺ p = q Cross-entropy loss is directly related: L CE = H ( p ) + D KL ( p ∥ q ) \mathcal{L}_{\text{CE}} = H(p) + D_{\text{KL}}(p\|q) L CE = H ( p ) + D KL ( p ∥ q ) where p p p 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 ( θ ∣ D ) = P ( D ) P ( D ∣ θ ) P ( θ ) P ( θ ) P(\theta) P ( θ ) : prior — belief about parameters before seeing dataP ( D ∣ θ ) P(\mathcal{D}\mid\theta) P ( D ∣ θ ) : likelihood — how well θ \theta θ explains dataP ( θ ∣ D ) P(\theta\mid\mathcal{D}) P ( θ ∣ D ) : posterior — updated belief after dataP ( D ) P(\mathcal{D}) P ( D ) : evidence — normalisation constantMLE (Maximum Likelihood Estimation) maximises P ( D ∣ θ ) P(\mathcal{D}\mid\theta) P ( D ∣ θ ) ; MAP adds a prior regulariser.
Core ML Concepts, Mathematically# Linear Regression (LR)# f ( x ) = w ⊤ x + b = ∑ j = 1 d w j x j + b f(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b = \sum_{j=1}^{d} w_j x_j + b f ( x ) = w ⊤ x + b = j = 1 ∑ d w j x j + b In matrix form over n n n samples: y ^ = X w + b 1 , X ∈ R n × d \hat{\mathbf{y}} = X\mathbf{w} + b\mathbf{1},\quad X \in \mathbb{R}^{n \times d} y ^ = X w + b 1 , X ∈ R n × d
Squared Error (SE)# SE ( y ^ , y ) = ( y ^ − y ) 2 \text{SE}(\hat{y}, y) = (\hat{y} - y)^2 SE ( y ^ , y ) = ( y ^ − y ) 2 Mean Squared Error (MSE)# L MSE ( θ ) = 1 n ∑ i = 1 n ( 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 L MSE ( θ ) = n 1 i = 1 ∑ n ( f θ ( x ( i ) ) − y ( i ) ) 2 Cross-Entropy Loss (CE)# Used for classification. For a one-hot label y ∈ { 0 , 1 } K \mathbf{y} \in \{0,1\}^K y ∈ { 0 , 1 } K over K K K classes and predicted probability vector p ^ = softmax ( z ) \hat{\mathbf{p}} = \text{softmax}(\mathbf{z}) p ^ = softmax ( z ) :
L CE = − ∑ k = 1 K y k log p ^ k \mathcal{L}_{\text{CE}} = -\sum_{k=1}^{K} y_k \log \hat{p}_k L CE = − k = 1 ∑ K y k log p ^ k For binary classification (K = 2 K=2 K = 2 ):
L BCE = − [ y log p ^ + ( 1 − y ) log ( 1 − p ^ ) ] \mathcal{L}_{\text{BCE}} = -\left[y \log \hat{p} + (1-y)\log(1-\hat{p})\right] L BCE = − [ y log p ^ + ( 1 − y ) log ( 1 − p ^ ) ] Over n n n samples (multiclass):
L CE ( θ ) = − 1 n ∑ i = 1 n log p ^ y ( i ) ( i ) \mathcal{L}_{\text{CE}}(\theta) = -\frac{1}{n}\sum_{i=1}^{n} \log \hat{p}_{y^{(i)}}^{(i)} L CE ( θ ) = − n 1 i = 1 ∑ n log p ^ y ( i ) ( i ) Derivatives# Derivative — instantaneous rate of change:
f ′ ( x ) = d f d x = lim h → 0 f ( x + h ) − f ( x ) h f'(x) = \frac{df}{dx} = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} f ′ ( x ) = d x df = h → 0 lim h f ( x + h ) − f ( x ) Gradient — multivariate generalisation f : R d → R f : \mathbb{R}^d \to \mathbb{R} f : R d → R :
∇ θ L = [ ∂ L / ∂ θ 1 ⋮ ∂ L / ∂ θ d ] ∈ R d \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 ∇ θ L = ∂ L / ∂ θ 1 ⋮ ∂ L / ∂ θ d ∈ R d Chain Rule — for z = g ( f ( x ) ) z = g(f(x)) z = g ( f ( x )) :
d z d x = d z d f ⋅ d f d x \frac{dz}{dx} = \frac{dz}{df} \cdot \frac{df}{dx} d x d z = df d z ⋅ d x df For deep compositions z = h ( g ( f ( x ) ) ) z = h(g(f(\mathbf{x}))) z = h ( g ( f ( 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}} ∂ x ∂ z = ∂ g ∂ z ⋅ ∂ f ∂ g ⋅ ∂ x ∂ f Gradient Descent — minimise L ( θ ) \mathcal{L}(\theta) L ( θ ) by stepping opposite the gradient:
θ t + 1 = θ t − η ⋅ ∇ θ L ( θ t ) \theta_{t+1} = \theta_t - \eta \cdot \nabla_\theta \mathcal{L}(\theta_t) θ t + 1 = θ t − η ⋅ ∇ θ L ( θ t ) The Four-Step Recipe of Machine Learning# Collect the data Define the model's structure Define the loss function Minimise the loss Vectors Are All You Need# A vector x ∈ R d \mathbf{x} \in \mathbb{R}^d x ∈ R d encodes a data point with d d d features.
Operations:
Add: ( u + v ) i = u i + v i (\mathbf{u} + \mathbf{v})_i = u_i + v_i ( u + v ) i = u i + v i Dot product: u ⋅ v = u ⊤ v = ∑ i u i v i \mathbf{u} \cdot \mathbf{v} = \mathbf{u}^\top \mathbf{v} = \sum_i u_i v_i u ⋅ v = u ⊤ v = ∑ i u i v i ℓ 2 \ell_2 ℓ 2 Norm: ∥ x ∥ 2 = ∑ i x i 2 \|\mathbf{x}\|_2 = \sqrt{\sum_i x_i^2} ∥ x ∥ 2 = ∑ 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}\|} cos ( u , v ) = ∥ u ∥∥ v ∥ u ⊤ v Matrices# A matrix W ∈ R m × n W \in \mathbb{R}^{m \times n} W ∈ R m × n represents a linear transformation R n → R m \mathbb{R}^n \to \mathbb{R}^m R n → R m .
Operations:
Add: ( A + B ) i j = A i j + B i j (A+B)_{ij} = A_{ij}+B_{ij} ( A + B ) ij = A ij + B ij Mul (matrix product): ( A B ) i j = ∑ k A i k B k j (AB)_{ij} = \sum_k A_{ik}B_{kj} ( A B ) ij = ∑ k A ik B kj Broadcast: scalar/vector ops extend across batch dimensionsTranspose: ( A ⊤ ) i j = A j i (A^\top)_{ij} = A_{ji} ( A ⊤ ) ij = A ji Neural Networks# Single neuron:
a = ϕ ( w ⊤ x + b ) a = \phi(\mathbf{w}^\top \mathbf{x} + b) a = ϕ ( w ⊤ 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) z ( ℓ ) = W ( ℓ ) a ( ℓ − 1 ) + b ( ℓ ) , a ( ℓ ) = ϕ ( z ( ℓ ) ) 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) δ ( ℓ ) = ( W ( ℓ + 1 ) ⊤ δ ( ℓ + 1 ) ) ⊙ ϕ ′ ( z ( ℓ ) ) ∂ L ∂ W ( ℓ ) = δ ( ℓ ) a ( ℓ − 1 ) ⊤ \frac{\partial \mathcal{L}}{\partial W^{(\ell)}} = \boldsymbol{\delta}^{(\ell)}\mathbf{a}^{(\ell-1)\top} ∂ W ( ℓ ) ∂ L = δ ( ℓ ) a ( ℓ − 1 ) ⊤ 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] ReLU ( x ) = max ( 0 , x ) , ReLU ′ ( x ) = 1 [ x > 0 ] Sigmoid:
σ ( x ) = 1 1 + e − x , σ ′ ( x ) = σ ( x ) ( 1 − σ ( x ) ) \sigma(x) = \frac{1}{1+e^{-x}}, \qquad \sigma'(x) = \sigma(x)(1-\sigma(x)) σ ( x ) = 1 + e − x 1 , σ ′ ( x ) = σ ( x ) ( 1 − σ ( x )) Tanh:
tanh ( x ) = e x − e − x e x + 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) tanh ( x ) = e x + e − x e x − e − x , tanh ′ ( x ) = 1 − tanh 2 ( x ) Softmax:
softmax ( z ) k = e z k ∑ j e z j \text{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_j e^{z_j}} softmax ( z ) k = ∑ j e z j e z k GELU (Gaussian Error Linear Unit) — used in BERT, GPT-2, and many modern Transformers:
GELU ( x ) = x ⋅ Φ ( x ) = x ⋅ 1 2 [ 1 + erf ( x 2 ) ] \text{GELU}(x) = x \cdot \Phi(x) = x \cdot \frac{1}{2}\left[1 + \text{erf}\!\left(\frac{x}{\sqrt{2}}\right)\right] GELU ( x ) = x ⋅ Φ ( x ) = x ⋅ 2 1 [ 1 + erf ( 2 x ) ] where Φ ( x ) \Phi(x) Φ ( x ) is the standard Gaussian CDF. Practical approximation:
GELU ( x ) ≈ 0.5 x ( 1 + tanh ( 2 π ( x + 0.044715 x 3 ) ) ) \text{GELU}(x) \approx 0.5x\left(1 + \tanh\!\left(\sqrt{\frac{2}{\pi}}\,(x + 0.044715\,x^3)\right)\right) GELU ( x ) ≈ 0.5 x ( 1 + tanh ( π 2 ( x + 0.044715 x 3 ) ) ) Unlike ReLU, GELU is smooth everywhere and lets small negative values through for x < 0 x < 0 x < 0 , which helps gradient flow.
Training Details# Parameters θ = { W ( ℓ ) , b ( ℓ ) } \theta = \{W^{(\ell)}, \mathbf{b}^{(\ell)}\} θ = { W ( ℓ ) , b ( ℓ ) } : learned by gradient descent.Hyperparameters : learning rate η \eta η , batch size B B B , layers L L L , hidden dim d d d — set before training.ℓ 2 \ell_2 ℓ 2 Regularisation (weight decay):
L reg ( θ ) = L ( θ ) + λ 2 ∥ θ ∥ 2 2 \mathcal{L}_{\text{reg}}(\theta) = \mathcal{L}(\theta) + \frac{\lambda}{2}\|\theta\|_2^2 L reg ( θ ) = L ( θ ) + 2 λ ∥ θ ∥ 2 2 Dropout — randomly zero out neurons during training with probability p p p :
a ~ = m ⊙ a ⋅ 1 1 − p , m i ∼ 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) a ~ = m ⊙ a ⋅ 1 − p 1 , m i ∼ Bernoulli ( 1 − p ) At inference, no dropout is applied: activations were already scaled by 1 / ( 1 − p ) 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 = x i − μ B σ B 2 + ϵ , y i = γ 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 x ^ i = σ B 2 + ϵ x i − μ B , y i = γ x ^ i + β where μ B , σ B 2 \mu_\mathcal{B}, \sigma_\mathcal{B}^2 μ B , σ 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 σ x 2 + ϵ ⋅ γ + β , μ x = 1 d ∑ j x j \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 x ^ = σ x 2 + ϵ x − μ x ⋅ γ + β , μ x = d 1 j ∑ x j Adam optimiser — bias-corrected moment estimates:
m t = β 1 m t − 1 + ( 1 − β 1 ) g t , v t = β 2 v t − 1 + ( 1 − β 2 ) g t 2 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 m t = β 1 m t − 1 + ( 1 − β 1 ) g t , v t = β 2 v t − 1 + ( 1 − β 2 ) g t 2 θ t + 1 = θ t − η m ^ t v ^ t + ϵ , m ^ t = m t 1 − β 1 t , v ^ t = v t 1 − β 2 t \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} θ t + 1 = θ t − η v ^ t + ϵ m ^ t , m ^ t = 1 − β 1 t m t , v ^ t = 1 − β 2 t v t Vanishing & Exploding Gradients# In a deep network with L L L 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)}} ∂ a ( ℓ ) ∂ L = ∂ a ( L ) ∂ L k = ℓ ∏ L − 1 ∂ a ( k ) ∂ a ( k + 1 ) Each factor ≈ W ( k ) ⋅ diag ( ϕ ′ ( z ( k ) ) ) \approx W^{(k)} \cdot \text{diag}(\phi'(\mathbf{z}^{(k)})) ≈ W ( k ) ⋅ diag ( ϕ ′ ( z ( k ) )) . If the spectral norm ∥ W ∥ < 1 \|W\| < 1 ∥ W ∥ < 1 repeatedly, gradients vanish exponentially; if ∥ W ∥ > 1 \|W\| > 1 ∥ W ∥ > 1 , they explode .
Vanishing : gradients → 0 \to 0 → 0 , early layers learn nothing. Caused by sigmoid/tanh saturation (σ ′ ≤ 0.25 \sigma' \leq 0.25 σ ′ ≤ 0.25 ) + many layers.Exploding : parameter updates become huge, training diverges.Fixes : ReLU (gradient = 1 in positive region), residual connections, LayerNorm, gradient clipping:
g t ← g t ⋅ min ( 1 , τ ∥ g t ∥ ) , τ is the clip threshold g_t \leftarrow g_t \cdot \min\!\left(1,\; \frac{\tau}{\|g_t\|}\right), \quad \tau \text{ is the clip threshold} g t ← g t ⋅ min ( 1 , ∥ g t ∥ τ ) , τ 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)}} θ t + 1 ( i ) = θ t ( i ) − η ∂ θ ( i ) ∂ L 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:
v t + 1 = γ v t + η ∇ θ L , θ t + 1 = θ t − v t + 1 \mathbf{v}_{t+1} = \gamma \mathbf{v}_t + \eta \nabla_\theta \mathcal{L}, \qquad \theta_{t+1} = \theta_t - \mathbf{v}_{t+1} v t + 1 = γ v t + η ∇ θ L , θ t + 1 = θ t − 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 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 , { W i } ) + x \mathbf{y} = \mathcal{F}(\mathbf{x},\,\{W_i\}) + \mathbf{x} y = F ( x , { W i }) + x F ( x ) \mathcal{F}(\mathbf{x}) F ( x ) : the residual to learn (e.g. two conv layers)x \mathbf{x} x : identity shortcutWhy it works: the gradient through the skip path is exactly 1 1 1 — 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 ∂ x ∂ y = ∂ x ∂ F + I . This prevents vanishing gradients in very deep networks (ResNet-152, Transformers).
CNN# 2D convolution — kernel K ∈ R k × k K \in \mathbb{R}^{k\times k} K ∈ R k × k slides over image X ∈ R H × W X \in \mathbb{R}^{H\times W} X ∈ R H × W :
( X ∗ K ) i , j = ∑ m = 0 k − 1 ∑ n = 0 k − 1 K m , n ⋅ X i + 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} ( X ∗ K ) i , j = m = 0 ∑ k − 1 n = 0 ∑ k − 1 K m , n ⋅ X i + m , j + n Each layer applies C out C_{\text{out}} C out kernels → feature map ∈ R C out × H ′ × W ′ \in \mathbb{R}^{C_{\text{out}}\times H'\times W'} ∈ R C out × H ′ × W ′ .
Pooling — downsample spatial dimensions to reduce computation and add translation invariance:
MaxPool ( X ) i , j = max ( m , n ) ∈ window X i ⋅ 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} MaxPool ( X ) i , j = ( m , n ) ∈ window max X i ⋅ s + m , j ⋅ s + n AvgPool ( X ) i , j = 1 k 2 ∑ ( m , n ) ∈ window X i ⋅ 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} AvgPool ( X ) i , j = k 2 1 ( m , n ) ∈ window ∑ X i ⋅ s + m , j ⋅ s + n where k k k is the pool size and s s s is the stride.
RNN# Vanilla RNN — hidden state recurrence:
h t = tanh ( W h h t − 1 + W x x t + b ) \mathbf{h}_t = \tanh(W_h \mathbf{h}_{t-1} + W_x \mathbf{x}_t + \mathbf{b}) h t = tanh ( W h h t − 1 + W x x t + b ) LSTM — gated memory cell ( i , f , o (i,f,o ( i , f , o : input/forget/output gates) ) ) :
f t = σ ( W f [ h t − 1 ; x t ] + b f ) , i t = σ ( W i [ h t − 1 ; x t ] + b i ) \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) f t = σ ( W f [ h t − 1 ; x t ] + b f ) , i t = σ ( W i [ h t − 1 ; x t ] + b i ) c t = f t ⊙ c t − 1 + i t ⊙ tanh ( W c [ h t − 1 ; x t ] + b c ) \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) c t = f t ⊙ c t − 1 + i t ⊙ tanh ( W c [ h t − 1 ; x t ] + b c ) o t = σ ( W o [ h t − 1 ; x t ] + b o ) , h t = o t ⊙ tanh ( c t ) \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) o t = σ ( W o [ h t − 1 ; x t ] + b o ) , h t = o t ⊙ tanh ( c t ) GRU — simplified gating (reset r t \mathbf{r}_t r t , update z t \mathbf{z}_t z t ):
z t = σ ( W z [ h t − 1 ; x t ] ) , r t = σ ( W r [ h t − 1 ; x t ] ) \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]) z t = σ ( W z [ h t − 1 ; x t ]) , r t = σ ( W r [ h t − 1 ; x t ]) h t = ( 1 − z t ) ⊙ h t − 1 + z t ⊙ tanh ( W h [ r t ⊙ h t − 1 ; x t ] ) \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]) h t = ( 1 − z t ) ⊙ h t − 1 + z t ⊙ tanh ( W h [ r t ⊙ h t − 1 ; x t ]) Attention# Scaled Dot-Product Attention — Q , K , V ∈ R n × d k Q,K,V \in \mathbb{R}^{n\times d_k} Q , K , V ∈ R n × d k :
Attention ( Q , K , V ) = softmax ( Q K ⊤ d k ) V \text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V Attention ( Q , K , V ) = softmax ( d k Q K ⊤ ) V Multi-Head Attention — h h h parallel heads, then project:
head i = Attention ( Q W i Q , K W i K , V W i V ) \text{head}_i = \text{Attention}(QW_i^Q,\,KW_i^K,\,VW_i^V) head i = Attention ( Q W i Q , K W i K , V W i V ) MultiHead ( Q , K , V ) = Concat ( head 1 , … , head h ) W O \text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1,\ldots,\text{head}_h)\,W^O MultiHead ( Q , K , V ) = Concat ( head 1 , … , head h ) W O Positional Encoding (sinusoidal):
PE ( p o s , 2 i ) = sin ( p o s 10000 2 i / d ) , PE ( p o s , 2 i + 1 ) = cos ( p o s 10000 2 i / 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) PE ( p os , 2 i ) = sin ( 1000 0 2 i / d p os ) , PE ( p os , 2 i + 1 ) = cos ( 1000 0 2 i / d p os ) 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 + MultiHead ( h , h , h )) h ′ ′ = LayerNorm ( h ′ + FFN ( h ′ ) ) , FFN ( x ) = W 2 ReLU ( W 1 x + b 1 ) + b 2 \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 h ′′ = LayerNorm ( h ′ + FFN ( h ′ )) , FFN ( x ) = W 2 ReLU ( W 1 x + b 1 ) + b 2 Language Modelling Objective — minimise the negative log-likelihood of the token sequence:
L = − 1 T ∑ t = 1 T log P θ ( t t ∣ t < t ) \mathcal{L} = -\frac{1}{T}\sum_{t=1}^T \log P_\theta(t_t \mid t_{\lt t}) L = − T 1 t = 1 ∑ T log P θ ( t t ∣ t < t ) ViT — split image into N N N patches p i ∈ R P 2 C \mathbf{p}_i \in \mathbb{R}^{P^2 C} p i ∈ R P 2 C , linearly project to token embeddings, then apply Transformer encoder:
z 0 = [ x cls ; E p 1 ; … ; E p N ] + E pos \mathbf{z}_0 = [\mathbf{x}_{\text{cls}};\, E\mathbf{p}_1;\,\ldots;\,E\mathbf{p}_N] + \mathbf{E}_{\text{pos}} z 0 = [ x cls ; E p 1 ; … ; E p N ] + E 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:
head i cross = Attention ( Q dec W i Q , K enc W i K , V enc W i V ) \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) head i cross = Attention ( Q dec W i Q , K enc W i K , V 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:
L MLM = − ∑ i ∈ M log P θ ( t i ∣ t \ M ) \mathcal{L}_{\text{MLM}} = -\sum_{i \in \mathcal{M}} \log P_\theta(t_i \mid \mathbf{t}_{\backslash \mathcal{M}}) L MLM = − i ∈ M ∑ log P θ ( t i ∣ t \ M ) M \mathcal{M} M : set of masked positionst \ M \mathbf{t}_{\backslash \mathcal{M}} t \ M : all tokens except the masked onesBecause 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?
L NSP = − log P θ ( IsNext ∣ [ CLS ] ) \mathcal{L}_{\text{NSP}} = -\log P_\theta(\text{IsNext} \mid [\text{CLS}]) L NSP = − log P θ ( IsNext ∣ [ CLS ]) GPT vs BERT comparison:
GPT (decoder-only) BERT (encoder-only) Attention Causal (left-to-right) Bidirectional (full) Pre-training Next-token prediction MLM + NSP Strength Generation Understanding / Classification Representation h i \mathbf{h}_i h i sees only t 1 , … , t i t_1,\ldots,t_i t 1 , … , t i h i \mathbf{h}_i h i sees all tokens
Transfer Learning# Pre-train on large corpus D pre \mathcal{D}_{\text{pre}} D pre to get θ ∗ \theta^* θ ∗ , then fine-tune on target task D ft \mathcal{D}_{\text{ft}} D ft :
θ ft = arg min θ L ft ( θ ; D ft ) , θ ← θ ∗ (initialised) \theta_{\text{ft}} = \arg\min_\theta \mathcal{L}_{\text{ft}}(\theta;\,\mathcal{D}_{\text{ft}}), \quad \theta \leftarrow \theta^* \text{ (initialised)} θ ft = arg θ min L ft ( θ ; D ft ) , θ ← θ ∗ (initialised) LoRA — freeze W 0 W_0 W 0 , inject low-rank update Δ W = B A \Delta W = BA Δ W = B A (B ∈ R d × r , A ∈ R r × k , r ≪ min ( d , k ) B\in\mathbb{R}^{d\times r},\,A\in\mathbb{R}^{r\times k},\,r\ll\min(d,k) B ∈ R d × r , A ∈ R r × k , r ≪ min ( d , k ) ):
W = W 0 + Δ W = W 0 + B A W = W_0 + \Delta W = W_0 + BA W = W 0 + Δ W = W 0 + B A Generative AI# Generative models learn the data distribution p ( x ) p(\mathbf{x}) p ( x ) and can sample new data from it.
The core distinction from discriminative models:
Discriminative Generative Goal p ( y ∥ x ) p(y\|\mathbf{x}) p ( y ∥ x ) p ( x ) p(\mathbf{x}) p ( x ) or p ( x , y ) p(\mathbf{x},y) p ( x , y ) Output Label / decision New data sample Examples Classifier, Regression VAE, GAN, Diffusion, LLM
Variational Autoencoder (VAE)# Encode data x \mathbf{x} x into a latent variable z \mathbf{z} 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}) q ϕ ( z ∣ x ) ≈ p ( z ∣ 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}))) q ϕ ( z ∣ x ) = N ( z ; μ ϕ ( x ) , diag ( σ ϕ 2 ( x ))) Decoder — likelihood p θ ( x ∣ z ) p_\theta(\mathbf{x}|\mathbf{z}) p θ ( x ∣ z ) .
ELBO objective (Evidence Lower Bound, maximise):
L VAE ( θ , ϕ ) = E q ϕ ( z ∣ x ) [ log p θ ( x ∣ z ) ] − D KL ( 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) L VAE ( θ , ϕ ) = E q ϕ ( z ∣ x ) [ log p θ ( x ∣ z ) ] − D KL ( q ϕ ( z ∣ x ) ∥ p ( z ) ) KL divergence between two Gaussians:
D KL ( N ( μ , σ 2 ) ∥ N ( 0 , I ) ) = 1 2 ∑ j ( σ j 2 + μ j 2 − 1 − log σ j 2 ) 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) D KL ( N ( μ , σ 2 ) ∥ N ( 0 , I )) = 2 1 j ∑ ( σ j 2 + μ j 2 − 1 − log σ j 2 ) 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) z = μ ϕ ( x ) + σ ϕ ( x ) ⊙ ϵ , ϵ ∼ N ( 0 , I ) Generative Adversarial Network (GAN)# Two networks compete: Generator G θ G_\theta G θ tries to fool Discriminator D ϕ D_\phi D ϕ .
min θ max ϕ E x ∼ p data [ log D ϕ ( x ) ] + E z ∼ 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] θ min ϕ max E x ∼ p data [ log D ϕ ( x ) ] + E z ∼ p ( z ) [ log ( 1 − D ϕ ( G θ ( z ))) ] G θ ( z ) G_\theta(\mathbf{z}) G θ ( z ) : maps noise z ∼ N ( 0 , I ) \mathbf{z}\sim\mathcal{N}(\mathbf{0},I) z ∼ N ( 0 , I ) to fake samples.D ϕ ( x ) ∈ ( 0 , 1 ) D_\phi(\mathbf{x})\in(0,1) D ϕ ( x ) ∈ ( 0 , 1 ) : probability that x \mathbf{x} x is real.At equilibrium: D ϕ ( x ) = 1 2 D_\phi(\mathbf{x}) = \tfrac{1}{2} D ϕ ( x ) = 2 1 everywhere — generator perfectly mimics data. Diffusion Models (DDPM)# Gradually add Gaussian noise over T T T steps (forward process ), then learn to reverse it (reverse process ).
Forward process — fixed Markov chain:
q ( x t ∣ x t − 1 ) = N ( x t ; 1 − β t x t − 1 , β t I ) 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) q ( x t ∣ x t − 1 ) = N ( x t ; 1 − β t x t − 1 , β t I ) Closed-form sampling at any step t t t (let α ˉ t = ∏ s = 1 t ( 1 − β s ) \bar\alpha_t = \prod_{s=1}^t(1-\beta_s) α ˉ t = ∏ s = 1 t ( 1 − β s ) ):
x t = α ˉ t x 0 + 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) x t = α ˉ t x 0 + 1 − α ˉ t ϵ , ϵ ∼ N ( 0 , I ) Reverse process — learned denoiser ϵ θ ( x t , t ) \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t) ϵ θ ( x t , t ) :
p θ ( x t − 1 ∣ x t ) = N ( x t − 1 ; μ θ ( x t , t ) , β ~ t I ) 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) p θ ( x t − 1 ∣ x t ) = N ( x t − 1 ; μ θ ( x t , t ) , β ~ t I ) μ θ ( x t , t ) = 1 α t ( x t − β t 1 − α ˉ t ϵ θ ( x t , 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) μ θ ( x t , t ) = α t 1 ( x t − 1 − α ˉ t β t ϵ θ ( x t , t ) ) Training objective — predict the noise:
L DDPM = E t , x 0 , ϵ [ ∥ ϵ − ϵ θ ( x t , 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] L DDPM = E t , x 0 , ϵ [ ∥ ϵ − ϵ θ ( x t , t ) ∥ 2 ] Autoregressive Generation (LLM Decoding)# Given a prompt ( t 1 , … , t k ) (t_1,\ldots,t_k) ( t 1 , … , t k ) , generate token-by-token:
t k + i ∼ P θ ( ⋅ ∣ t 1 , … , t k + i − 1 ) t_{k+i} \sim P_\theta(\cdot \mid t_1,\ldots,t_{k+i-1}) t k + i ∼ P θ ( ⋅ ∣ t 1 , … , t k + i − 1 ) Temperature scaling — control sharpness of distribution:
P τ ( t ) = exp ( z t / τ ) ∑ j exp ( z j / τ ) P_\tau(t) = \frac{\exp(z_t / \tau)}{\sum_j \exp(z_j / \tau)} P τ ( t ) = ∑ j exp ( z j / τ ) exp ( z t / τ ) τ → 0 \tau \to 0 τ → 0 : greedy (deterministic); τ = 1 \tau = 1 τ = 1 : standard softmax; τ > 1 \tau > 1 τ > 1 : more random.Top-p p p (nucleus) sampling — sample from smallest set V \mathcal{V} V s.t.:
∑ t ∈ V P ( t ) ≥ p \sum_{t \in \mathcal{V}} P(t) \geq p t ∈ V ∑ P ( t ) ≥ 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}) r ϕ ( x , y ) from preference pairs ( y w ≻ y l ) (y_w \succ y_l) ( y w ≻ y l ) :
L RM = − E ( x , y w , y l ) [ log σ ( r ϕ ( x , y w ) − r ϕ ( x , y l ) ) ] \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] L RM = − E ( x , y w , y l ) [ log σ ( r ϕ ( x , y w ) − r ϕ ( x , y l ) ) ] Step 3 — PPO fine-tuning — maximise reward while staying close to SFT policy π ref \pi_{\text{ref}} π ref :
L RLHF ( θ ) = E x ∼ D , y ∼ π θ [ r ϕ ( x , y ) ] − β D KL ( π θ ( ⋅ ∣ 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) L RLHF ( θ ) = E x ∼ D , y ∼ π θ [ r ϕ ( x , y ) ] − β D KL ( π θ ( ⋅ ∣ x ) ∥ π ref ( ⋅ ∣ x ) ) DPO (Direct Preference Optimisation) — skips reward model, optimise preferences directly:
L DPO ( θ ) = − E ( x , y w , y l ) [ log σ ( β log π θ ( y w ∣ x ) π ref ( y w ∣ x ) − β log π θ ( y l ∣ x ) π ref ( y l ∣ 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] L DPO ( θ ) = − E ( x , y w , y l ) [ log σ ( β log π ref ( y w ∣ x ) π θ ( y w ∣ x ) − β log π ref ( y l ∣ x ) π θ ( y l ∣ x ) ) ] Large Language Models (LLM)# Architecture Overview# A decoder-only Transformer stacks L L L blocks. Given token sequence ( t 1 , … , t n ) (t_1,\ldots,t_n) ( t 1 , … , t n ) :
Tokenisation — map text to integer IDs via vocabulary V \mathcal{V} V , ∣ V ∣ ∼ 50 k |\mathcal{V}|\sim 50\text{k} ∣ V ∣ ∼ 50 k –200 k 200\text{k} 200 k .Embedding — E ∈ R ∣ V ∣ × d \mathbf{E} \in \mathbb{R}^{|\mathcal{V}|\times d} E ∈ R ∣ V ∣ × d , look up row t i t_i t i : h i ( 0 ) = E t i + P E i \mathbf{h}_i^{(0)} = \mathbf{E}_{t_i} + \mathbf{PE}_i h i ( 0 ) = E t i + PE i L L L Transformer blocks (causal masked attention + FFN).Unembedding — project to logits and apply softmax: l i = E h i ( L ) ∈ R ∣ V ∣ \mathbf{l}_i = \mathbf{E}\,\mathbf{h}_i^{(L)} \in \mathbb{R}^{|\mathcal{V}|} l i = E h i ( L ) ∈ R ∣ V ∣ Causal (masked) self-attention — token i i i can only attend to positions j ≤ i j \leq i j ≤ i :
Attention ( Q , K , V ) = softmax ( Q K ⊤ d k + M ) V , M i j = { 0 j ≤ 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} Attention ( Q , K , V ) = softmax ( d k Q K ⊤ + M ) V , M ij = { 0 − ∞ j ≤ i j > i Tokenisation & Embedding# Byte-Pair Encoding (BPE) — iteratively merge the most frequent adjacent pair until vocabulary size ∣ V ∣ |\mathcal{V}| ∣ V ∣ is reached.
Token embedding + positional encoding → input representation:
h i = E t i + P E i ∈ R d \mathbf{h}_i = \mathbf{E}_{t_i} + \mathbf{PE}_i \in \mathbb{R}^d h i = E t i + PE i ∈ R d RoPE (Rotary Positional Embedding) — encode position by rotating query/key vectors:
q m = R m q , k n = R n k , q m ⊤ k n = q ⊤ R n − m k \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} q m = R m q , k n = R n k , q m ⊤ k n = q ⊤ R n − m k where R m R_m R m is a block-diagonal rotation matrix at angle m θ i m\theta_i m θ i .
Perplexity (PPL)# The standard intrinsic evaluation metric for language models — how "surprised" the model is by the test set:
PPL ( T ) = exp ( − 1 T ∑ t = 1 T log P θ ( t t ∣ 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}) PPL ( T ) = exp ( − T 1 t = 1 ∑ T log P θ ( t t ∣ t < t ) ) = exp ( L ) Lower PPL = model assigns higher probability to real text = better. PPL is simply the exponential of the cross-entropy loss L \mathcal{L} L . PPL = k = k = k means the model is as uncertain as choosing uniformly among k k k 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 = L ln 2 \text{BPC} = \frac{\mathcal{L}}{\ln 2} BPC = ln 2 L Scaling Laws# Model performance scales predictably with compute C C C , data D D D , and parameters N N N (Chinchilla):
L ( N , D ) = A N α + B D β + L ∞ \mathcal{L}(N, D) = \frac{A}{N^\alpha} + \frac{B}{D^\beta} + \mathcal{L}_\infty L ( N , D ) = N α A + D β B + L ∞ Optimal allocation for a compute budget C = 6 N D C = 6ND C = 6 N D :
N opt ∝ C 0.5 , D opt ∝ C 0.5 N_{\text{opt}} \propto C^{0.5}, \qquad D_{\text{opt}} \propto C^{0.5} N opt ∝ C 0.5 , D opt ∝ 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 .
k k k -shot prompting — prepend k k k (input, output) examples:
P θ ( y ∣ x , ( x 1 , y 1 ) , … , ( x k , y k ) ) P_\theta(y \mid x, (x_1,y_1),\ldots,(x_k,y_k)) P θ ( y ∣ x , ( x 1 , y 1 ) , … , ( x k , y k )) Chain-of-Thought (CoT) — include reasoning steps r r r before answer a a a :
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) P θ ( r , a ∣ x ) = P θ ( r ∣ x ) ⋅ P θ ( a ∣ x , r ) Self-consistency — sample M M M reasoning paths, take majority vote:
a ^ = arg max a ∑ m = 1 M 1 [ a m = a ] \hat{a} = \arg\max_a \sum_{m=1}^{M} \mathbf{1}[a_m = a] a ^ = arg a max m = 1 ∑ M 1 [ a m = a ] Retrieval-Augmented Generation (RAG)# Augment generation with retrieved documents D r \mathcal{D}_r D r from an external knowledge base:
P θ ( y ∣ x ) = ∑ d ∈ D r P θ ( y ∣ x , d ) P ret ( 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) P θ ( y ∣ x ) = d ∈ D r ∑ P θ ( y ∣ x , d ) P ret ( d ∣ x ) Retrieval — encode query and documents, fetch top-k k k 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)\|} score ( x , d ) = ∥ f ( x ) ∥∥ 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 = [ k 1 , … , k t ] , V ≤ t = [ v 1 , … , v t ] K_{\leq t} = [k_1,\ldots,k_t], \quad V_{\leq t} = [v_1,\ldots,v_t] K ≤ t = [ k 1 , … , k t ] , V ≤ t = [ v 1 , … , v t ] New token t + 1 t+1 t + 1 only computes q t + 1 q_{t+1} q t + 1 , then attends over cached K ≤ t , V ≤ t K_{\leq t}, V_{\leq t} K ≤ t , V ≤ t . Reduces per-step cost from O ( t 2 d ) \mathcal{O}(t^2 d) O ( t 2 d ) to O ( t d ) \mathcal{O}(t d) O ( t d ) ; memory grows linearly with sequence length.
Mixture of Experts (MoE)# Replace the dense FFN in each Transformer block with E E E expert FFNs. A learned router selects top-k k k experts per token:
MoE ( x ) = ∑ i = 1 k g i ( x ) FFN i ( x ) \text{MoE}(\mathbf{x}) = \sum_{i=1}^{k} g_i(\mathbf{x})\; \text{FFN}_i(\mathbf{x}) MoE ( x ) = i = 1 ∑ k g i ( x ) FFN i ( x ) g i ( x ) = softmax ( TopK ( W g x , k ) ) i g_i(\mathbf{x}) = \text{softmax}\!\left(\text{TopK}\!\left(W_g\mathbf{x},\; k\right)\right)_i g i ( x ) = softmax ( TopK ( W g x , k ) ) i Activated params per token: ∼ k / E \sim k/E ∼ k / E of total params → same inference cost as a smaller dense model.Load balancing loss encourages uniform expert utilisation: L bal = E ∑ i f i ⋅ p i \mathcal{L}_{\text{bal}} = E \sum_i f_i \cdot p_i L bal = E ∑ i f i ⋅ p i where f i f_i f i is fraction of tokens routed to expert i i i and p i p_i p i is mean router probability.Used in Switch Transformer , Mixtral , and DeepSeek-V3 .
Key LLM Concepts Summary# Concept What it does Key formula / idea Tokenisation (BPE) Text → integer IDs Merge most-frequent pairs Causal Attention Each token sees only past Mask M i j = − ∞ M_{ij}=-\infty M ij = − ∞ for j > i j>i j > i Scaling Law Predict loss from N , D , C N,D,C N , D , C L ∝ N − α + D − β \mathcal{L} \propto N^{-\alpha} + D^{-\beta} L ∝ N − α + D − β SFT Align model to instructions Cross-entropy on demonstrations RLHF / DPO Align to human preferences Reward signal or preference pairs CoT Prompting Elicit step-by-step reasoning P ( r , a ∥ x ) = P ( r ∥ x ) P ( a ∥ x , r ) P(r,a\|x) = P(r\|x)P(a\|x,r) P ( r , a ∥ x ) = P ( r ∥ x ) P ( a ∥ x , r ) RAG Ground generation in facts Retrieve then generate LoRA Parameter-efficient fine-tuning W = W 0 + B A W = W_0 + BA W = W 0 + B A , r ≪ d r \ll d r ≪ d
Multimodal AI# Multimodal models process and generate more than one modality (text, image, audio, video) within a unified framework.
f θ : M 1 × M 2 × ⋯ → Y f_\theta : \mathcal{M}_1 \times \mathcal{M}_2 \times \cdots \to \mathcal{Y} f θ : M 1 × M 2 × ⋯ → Y Modality Encoding# Each modality is first encoded into a shared embedding space R d \mathbb{R}^d R d :
Modality Encoder Output Text Tokeniser + Embedding h t ∈ R L × d \mathbf{h}_t \in \mathbb{R}^{L\times d} h t ∈ R L × d Image ViT / CNN patch encoder h v ∈ R N × d \mathbf{h}_v \in \mathbb{R}^{N\times d} h v ∈ R N × d Audio Spectrogram + Conv / Whisper h a ∈ R S × d \mathbf{h}_a \in \mathbb{R}^{S\times d} h a ∈ R S × d Video Frame-level ViT + temporal attention h f ∈ R T × N × d \mathbf{h}_f \in \mathbb{R}^{T\times N\times d} h f ∈ R T × N × d
CLIP — Contrastive Vision-Language Pre-training# Learn aligned image and text embeddings by maximising agreement between matched pairs.
Given a batch of N N N (image v i \mathbf{v}_i v i , text t i \mathbf{t}_i t i ) pairs, compute cosine similarities:
s i j = f ( v i ) ⊤ g ( t j ) ∥ f ( v i ) ∥ ∥ g ( t j ) ∥ ⋅ exp ( τ ) s_{ij} = \frac{f(\mathbf{v}_i)^\top g(\mathbf{t}_j)}{\|f(\mathbf{v}_i)\|\|g(\mathbf{t}_j)\|} \cdot \exp(\tau) s ij = ∥ f ( v i ) ∥∥ g ( t j ) ∥ f ( v i ) ⊤ g ( t j ) ⋅ exp ( τ ) Symmetric InfoNCE loss (maximise diagonal, minimise off-diagonal):
L CLIP = − 1 2 N ∑ i = 1 N [ log e s i i ∑ j e s i j + log e s i i ∑ j e s j i ] \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] L CLIP = − 2 N 1 i = 1 ∑ N [ log ∑ j e s ij e s ii + log ∑ j e s ji e s ii ] 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:
h v = VisualEncoder ( I ) ∈ R N × d v \mathbf{h}_v = \text{VisualEncoder}(\mathbf{I}) \in \mathbb{R}^{N\times d_v} h v = VisualEncoder ( I ) ∈ R N × d v h ~ v = W proj h v ∈ R N × d , W proj ∈ R d × d v \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} h ~ v = W proj h v ∈ R N × d , W proj ∈ R d × d v Visual tokens h ~ v \tilde{\mathbf{h}}_v h ~ v are prepended (or interleaved) with text tokens and fed into the LLM:
input = [ h ~ v ; h text ] \text{input} = [\tilde{\mathbf{h}}_v;\, \mathbf{h}_{\text{text}}] input = [ h ~ v ; h text ] LLaVA-style training — two stages:
Pre-train projection only (freeze encoder + LLM): learn W proj W_{\text{proj}} W proj Instruction fine-tuning: unfreeze LLM, train on (image, instruction, response) triplets Objective — standard next-token prediction on response tokens only:
L = − ∑ t log P θ ( y t ∣ I , x , y < t ) \mathcal{L} = -\sum_{t} \log P_\theta(y_t \mid \mathbf{I},\, \mathbf{x},\, y_{\lt t}) L = − t ∑ log P θ ( y t ∣ I , x , y < t ) Cross-Modal Attention# Allow one modality to attend over another. Text queries attend to visual keys/values:
h text ′ = Attention ( Q text , K vision , V vision ) \mathbf{h}'_{\text{text}} = \text{Attention}(Q_{\text{text}},\; K_{\text{vision}},\; V_{\text{vision}}) h text ′ = Attention ( Q text , K vision , V vision ) = softmax ( Q text K vision ⊤ d k ) V vision = \text{softmax}\!\left(\frac{Q_{\text{text}} K_{\text{vision}}^\top}{\sqrt{d_k}}\right) V_{\text{vision}} = softmax ( d k Q text K vision ⊤ ) V 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}) c = g ϕ ( prompt ) .
Classifier-Free Guidance (CFG) — blend conditional and unconditional score:
ϵ ~ θ ( x t , c ) = ϵ θ ( x t , ∅ ) + w ( ϵ θ ( x t , c ) − ϵ θ ( x t , ∅ ) ) \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) ϵ ~ θ ( x t , c ) = ϵ θ ( x t , ∅ ) + w ( ϵ θ ( x t , c ) − ϵ θ ( x t , ∅ ) ) w > 1 w > 1 w > 1 : stronger text conditioning (higher fidelity to prompt, less diversity).w = 1 w = 1 w = 1 : standard conditional generation.w = 0 w = 0 w = 0 : unconditional generation.Latent Diffusion (Stable Diffusion) — run diffusion in a compressed latent space:
z = E ( x ) , x ^ = D ( z ) , L = E t , z 0 , ϵ [ ∥ ϵ − ϵ θ ( z t , 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] z = E ( x ) , x ^ = D ( z ) , L = E t , z 0 , ϵ [ ∥ ϵ − ϵ θ ( z t , t , c ) ∥ 2 ] Multimodal Summary# Model / Concept Modalities Key idea CLIP Image + Text Contrastive alignment, InfoNCE LLaVA / InternVL Image + Text Visual tokens → LLM via projection Flamingo Image + Text Cross-modal attention layers Stable Diffusion Text → Image Latent diffusion + CFG Whisper Audio → Text Spectrogram encoder + decoder GPT-4o Image/Audio/Text Unified multimodal autoregressive LLM