Part 2Math for LLMs

Stochastic Processes: Part 2 - Exercises To Appendix U Continuous Time Martingales

Probability Theory / Stochastic Processes

Private notes
0/8000

Notes stay private to your browser until account sync is configured.

Part 2
29 min read18 headingsSplit lesson page

Lesson overview | Previous part | Next part

Stochastic Processes: Part 11: Exercises to Appendix U: Continuous-Time Martingales

11. Exercises

Exercise 1 * - Martingale Verification Let X1,X2,X_1, X_2, \ldots be iid with E[Xi]=0\mathbb{E}[X_i] = 0, Var(Xi)=σ2\text{Var}(X_i) = \sigma^2. Define Sn=k=1nXkS_n = \sum_{k=1}^n X_k and Vn=Sn2nσ2V_n = S_n^2 - n\sigma^2.

(a) Prove {Sn}\{S_n\} is a martingale with respect to its natural filtration. (b) Prove {Vn}\{V_n\} is a martingale. What does E[Vτ]=E[V0]\mathbb{E}[V_\tau] = \mathbb{E}[V_0] imply for a bounded stopping time τ\tau? (c) For XkUniform{1,+1}X_k \sim \text{Uniform}\{-1,+1\}, verify (a) and (b) numerically with n=100n=100 and 10510^5 simulations. Check E[Sn]0\mathbb{E}[S_n] \approx 0 and E[Vn]0\mathbb{E}[V_n] \approx 0. (d) Let τ=min(n,50)\tau = \min(n, 50) for a fixed n=100n=100 simulation. Verify E[Sτ]0\mathbb{E}[S_\tau] \approx 0 and E[Vτ]0\mathbb{E}[V_\tau] \approx 0 empirically.

Exercise 2 * - Doob's OST: Gambler's Ruin A fair gambler starts with k=30k = 30 dollars and plays until reaching N=100N = 100 or going broke.

(a) Use OST applied to SnS_n to derive P(win)=k/NP(\text{win}) = k/N. Compute numerically for k=30k=30, N=100N=100. (b) Use OST applied to Sn2nS_n^2 - n to derive E[τ]=k(Nk)\mathbb{E}[\tau] = k(N-k). Compute for the given values. (c) Simulate 10510^5 games and verify both P(win)P(\text{win}) and E[τ]\mathbb{E}[\tau] empirically. (d) For a biased game with p=0.6p=0.6, use the exponential martingale Mn=((1p)/p)SnM_n = ((1-p)/p)^{S_n} to derive P(win)P(\text{win}). Verify numerically.

Exercise 3 * - Poisson Process Properties Let N(t)Poisson(λ=2)N(t) \sim \text{Poisson}(\lambda=2).

(a) Compute P(N(3)5)P(N(3) \geq 5) exactly and via simulation (10510^5 trials). (b) Show that M(t)=N(t)λtM(t) = N(t) - \lambda t is a martingale (verify E[M(t)]=0\mathbb{E}[M(t)] = 0 and E[M(t)N(s),sr]=M(r)\mathbb{E}[M(t)|N(s), s \leq r] = M(r) for r<tr < t). (c) Thinning: Generate a Poisson process with rate λ=5\lambda=5. Thin independently with p=0.4p=0.4. Verify the thinned process is Poisson(22) by checking its inter-arrival distribution. (d) Superposition: Show that the superposition of Poisson(1)\text{Poisson}(1) and Poisson(2)\text{Poisson}(2) is Poisson(3)\text{Poisson}(3) empirically.

Exercise 4 ** - Doob Martingale and McDiarmid Let f(x1,,xn)=max1knxkf(x_1,\ldots,x_n) = \max_{1 \leq k \leq n} x_k on [0,1]n[0,1]^n with XiiidUniform[0,1]X_i \stackrel{iid}{\sim}\text{Uniform}[0,1].

(a) Show ff has bounded differences: supf(,xk,)f(,xk,)1\sup |f(\ldots,x_k,\ldots) - f(\ldots,x_k',\ldots)| \leq 1 for each kk, so ck=1c_k = 1. (b) Construct the Doob martingale Mk=E[maxXX1,,Xk]M_k = \mathbb{E}[\max X | X_1,\ldots,X_k] and compute M0M_0 and MnM_n analytically. (c) Apply Azuma's inequality to bound P(fE[f]t)P(f - \mathbb{E}[f] \geq t) and compare to McDiarmid's bound. (d) Verify both bounds numerically for n=100n=100, t=0.05t=0.05. Compute the empirical tail probability and compare to the bound.

Exercise 5 ** - Brownian Motion Properties Simulate BtB_t on [0,1][0,1] using n=1000n=1000 steps.

(a) Verify the increment distribution: check that BtBsN(0,ts)B_t - B_s \sim \mathcal{N}(0, t-s) holds for several (s,t)(s,t) pairs using KS test. (b) Verify quadratic variation: compute QVn=k=1n(Bk/nB(k1)/n)2QV_n = \sum_{k=1}^n (B_{k/n} - B_{(k-1)/n})^2 for n=10,100,1000,10000n = 10, 100, 1000, 10000 and show QVn1QV_n \to 1. (c) Verify non-differentiability heuristically: compute finite differences ΔB/Δt\Delta B / \Delta t for Δt=101,102,103\Delta t = 10^{-1}, 10^{-2}, 10^{-3} and observe they grow as 1/Δt1/\sqrt{\Delta t}. (d) Simulate the OU process dX=Xdt+2dBtdX = -X\,dt + \sqrt{2}\,dB_t with Euler-Maruyama. Verify the stationary distribution is N(0,1)\mathcal{N}(0,1).

Exercise 6 ** - Gaussian Process Posterior Let fGP(0,kRBF)f \sim \mathcal{GP}(0, k_{\text{RBF}}) with kRBF(x,x)=exp(xx2/(22))k_{\text{RBF}}(x,x') = \exp(-|x-x'|^2/(2\ell^2)), =0.5\ell = 0.5.

(a) Draw 5 sample paths from the GP prior on [0,5][0,5] using the covariance matrix. (b) Given observations yi=f(xi)+ϵiy_i = f(x_i) + \epsilon_i at x={0.5,1.5,2.5,3.5}x = \{0.5, 1.5, 2.5, 3.5\} with ϵiN(0,0.01)\epsilon_i \sim \mathcal{N}(0, 0.01), compute the GP posterior mean and variance. (c) Plot the posterior mean ±2\pm 2 standard deviations and verify that all observation points are covered. (d) Compare the posterior using RBF kernel vs Matern-1/2 kernel. Which has smoother interpolation? Which has faster uncertainty growth away from observations?

Exercise 7 *** - SGD as Diffusion Process Minimise L(θ)=θ2/2L(\theta) = \theta^2/2 (quadratic, H=1H=1, θ=0\theta^* = 0) using SGD with g~(θ)=θ+ϵ\tilde{g}(\theta) = \theta + \epsilon, ϵN(0,σ2)\epsilon \sim \mathcal{N}(0, \sigma^2).

(a) Show that the SGD iterates satisfy θn+1=(1η)θnηϵn\theta_{n+1} = (1-\eta)\theta_n - \eta\epsilon_n. Find the stationary distribution of θn\theta_n. (b) Verify analytically that Var(θ)=ησ2/(2η)ησ2/2\text{Var}(\theta_\infty) = \eta\sigma^2/(2-\eta) \approx \eta\sigma^2/2 for small η\eta. (c) Simulate for η{0.01,0.1,0.3}\eta \in \{0.01, 0.1, 0.3\}, σ2=1\sigma^2 = 1, n=10000n = 10000 steps. Plot the stationary distribution and compare to the analytical prediction. (d) Verify the diffusion approximation: the continuous-time SDE dθ=θdt+ησdBtd\theta = -\theta\,dt + \sqrt{\eta}\sigma\,dB_t has stationary distribution N(0,ησ2/2)\mathcal{N}(0, \eta\sigma^2/2). Compare to part (b).

Exercise 8 *** - RL TD-Error as Martingale Consider a Markov reward process: states {1,2,3}\{1, 2, 3\}, transition matrix P=[[0.5,0.3,0.2],[0.4,0.4,0.2],[0.3,0.3,0.4]]P = [[0.5,0.3,0.2],[0.4,0.4,0.2],[0.3,0.3,0.4]], rewards r=[1,2,3]r = [1, 2, 3], discount γ=0.9\gamma = 0.9.

(a) Compute the true value function V=(IγP)1rV = (I - \gamma P)^{-1}r exactly. (b) Implement TD(0) to estimate VV: run 10410^4 episodes of length 50, update V(st)V(st)+α(rt+γV(st+1)V(st))V(s_t) \leftarrow V(s_t) + \alpha(r_t + \gamma V(s_{t+1}) - V(s_t)) with α=0.01\alpha = 0.01. Compare to exact VV. (c) Verify the martingale property of the TD error: under the true VV^*, the TD error δt=rt+γV(st+1)V(st)\delta_t = r_t + \gamma V^*(s_{t+1}) - V^*(s_t) has E[δtst]=0\mathbb{E}[\delta_t | s_t] = 0. Verify numerically. (d) Implement variance-reduced version using baseline b(s)=rˉb(s) = \bar{r} (mean reward). Show this reduces the variance of the gradient estimate without introducing bias.


12. Why This Matters for AI (2026 Perspective)

ConceptAI/ML Impact
Filtrations and adaptednessCausal vs. bidirectional attention; early stopping as stopping time; data leakage detection
MartingalesTD-learning convergence; REINFORCE gradient estimators; unbiased gradient noise in SGD
Optional Stopping TheoremEarly stopping criteria; gambler's ruin models of gradient explosion; RL episode termination
Doob MartingaleUnified proof of McDiarmid/Azuma; online learning regret bounds; generalisation theory
Poisson ProcessLLM inference request queues; KV-cache hit modelling; continuous batching server design
Brownian MotionForward process in diffusion models; SGD noise continuous-time approximation; random feature maps
OU ProcessDDPM/Score-SDE forward processes; L2 regularisation as mean reversion; Adam momentum as filtering
Geometric Brownian MotionResidual stream norm growth; multiplicative noise in LoRA fine-tuning
Donsker's TheoremJustifies SDE approximation of SGD; random walk -> BM limit for CLT on paths
Wide-Sense StationarityRoPE relative position encoding; ALiBi attention bias; translation-invariant kernels
Ergodic TheoremTime-average = ensemble average in training; failure mode in continual learning
Gaussian ProcessesBayesian hyperparameter search; neural tangent kernel in infinite-width limit; GAN discriminator theory
GP PosteriorUncertainty quantification in Bayesian deep learning; active learning for LLM fine-tuning data selection
Score SDEUnified framework for DDPM, DDIM, consistency models, flow matching
Martingale CLTAsymptotic normality of SGD parameter estimates; statistical inference on trained models

13. Conceptual Bridge

Looking backward: This section builds directly on the static probability of Section01-Section05. Filtrations formalise conditional expectations (Section04) over time; the Doob martingale makes McDiarmid's inequality (Section05) a consequence of Azuma applied to a martingale; the Gaussian process is the stochastic-process version of the multivariate Gaussian (Section03). Every concept here has a static probability antecedent.

Looking forward: Stochastic processes enable the dynamic probability of Section07 and beyond. Markov chains (Section07) are stochastic processes satisfying the Markov property - the specialisation of the general framework to memoryless dynamics. Statistics (Section07-Statistics) uses time series models (AR, MA, ARIMA) which are stationary stochastic processes analysed via the autocorrelation and spectral density tools developed here. Optimisation (Section08) uses the SDE/martingale formalism to analyse SGD convergence and diffusion-based sampling.

The martingale as a unifying concept: The martingale is arguably the most powerful single concept in probability theory. It appears in: (a) concentration inequalities as the Doob/Azuma construction, (b) SGD as a near-martingale gradient process, (c) RL value functions as martingale transforms, (d) diffusion model reverse processes as time-reversed SDEs with martingale driving noise, (e) sequential hypothesis testing (SPRT) as a martingale stopping problem. Understanding martingales is understanding the probabilistic structure that makes machine learning algorithms work.

STOCHASTIC PROCESSES: POSITION IN CURRICULUM
========================================================================

  STATIC PROBABILITY (Section01-Section05)
  ---------------------------------------------
  Section01 Random Variables  ->  Section02 Distributions
  Section03 Joint Dist.       ->  Section04 Expectation/MGF
  Section05 Concentration     ->  Azuma = Doob + Azuma
  ---------------------------------------------
                | filtrations, martingales, paths
                v
  +---------------------------------------------+
  |  Section06 STOCHASTIC PROCESSES (THIS SECTION)    |
  |  -----------------------------------------  |
  |  Filtrations    Martingales   OST           |
  |  Random Walks   Poisson       BM/OU         |
  |  Stationarity   GPs           SGD/RL/Diff   |
  +---------------------------------------------+
                |
       +--------+--------+
       v                 v
  Section07 Markov Chains   Section07-Stat/05 Time Series
  (Markov property,   (AR/MA/ARIMA, spectral
  MCMC, PageRank,     analysis, forecasting,
  RL policy eval)     seasonal decomposition)
       |
       v
  Section08 Optimisation (SDE/martingale-based
  convergence of SGD, Langevin dynamics,
  diffusion-based sampling)

========================================================================

The AI synthesis: In 2026, the stochastic process framework permeates every major AI subfield. Diffusion models are explicit SDE constructions. RL convergence relies on martingale theory. LLM evaluation uses Hoeffding/CLT on sequences of i.i.d. samples (Poisson processes of test cases). Bayesian optimisation uses GP posteriors. Continual learning grapples with non-stationarity. The practitioner who understands stochastic processes sees the probabilistic skeleton underlying methods that otherwise appear unrelated.


This completes Section06 Stochastic Processes. The framework built here - filtrations, martingales, the canonical processes - is the common language of probability theory in motion.

<- Back to Chapter 6: Probability Theory | Next: Markov Chains ->


Appendix A: Stochastic Calculus Primer

A.1 The Ito Integral

Classical calculus integrates smooth functions. The Ito integral extends integration to Brownian motion, where the integrand is a stochastic process.

Why ordinary integrals fail: Define 0TBtdBt\int_0^T B_t\,dB_t using Riemann sums. Two natural choices:

  • Left-endpoint (Ito): k=0n1Btk(Btk+1Btk)\sum_{k=0}^{n-1} B_{t_k}(B_{t_{k+1}} - B_{t_k})
  • Midpoint (Stratonovich): k=0n1Btk+Btk+12(Btk+1Btk)\sum_{k=0}^{n-1} \frac{B_{t_k}+B_{t_{k+1}}}{2}(B_{t_{k+1}} - B_{t_k})

These give different limits as nn \to \infty! This is unique to stochastic integration - in classical calculus all Riemann sums give the same limit.

Computation:

Ito: 0TBtdBt=BT2T2\text{Ito: } \int_0^T B_t\,dB_t = \frac{B_T^2 - T}{2} Stratonovich: 0TBtdBt=BT22\text{Stratonovich: } \int_0^T B_t \circ dB_t = \frac{B_T^2}{2}

The Ito integral gives an extra T/2-T/2 term from the quadratic variation [B]T=T[B]_T = T. This is the source of Ito's lemma.

The Ito integral is a martingale: For any adapted square-integrable integrand HtH_t:

MT=0THtdBtis a martingaleM_T = \int_0^T H_t\,dB_t \quad \text{is a martingale}

with E[MT2]=0TE[Ht2]dt\mathbb{E}[M_T^2] = \int_0^T \mathbb{E}[H_t^2]\,dt (Ito isometry).

A.2 Ito's Lemma

Theorem (Ito's Lemma). Let XtX_t satisfy the SDE dXt=μtdt+σtdBtdX_t = \mu_t\,dt + \sigma_t\,dB_t. For any C2C^2 function ff:

df(Xt)=f(Xt)dXt+12f(Xt)σt2dtdf(X_t) = f'(X_t)\,dX_t + \frac{1}{2}f''(X_t)\sigma_t^2\,dt =(μtf(Xt)+σt22f(Xt))dt+σtf(Xt)dBt= \left(\mu_t f'(X_t) + \frac{\sigma_t^2}{2}f''(X_t)\right)dt + \sigma_t f'(X_t)\,dB_t

The extra term 12f(Xt)σt2dt\frac{1}{2}f''(X_t)\sigma_t^2\,dt (the Ito correction) arises from the quadratic variation (dBt)2=dt(dB_t)^2 = dt. It has no classical analogue.

Example: GBM. dS=μSdt+σSdBdS = \mu S\,dt + \sigma S\,dB. Apply Ito to f(S)=logSf(S) = \log S:

dlogS=1SμSdt+1SσSdB121S2σ2S2dt=(μσ22)dt+σdBd\log S = \frac{1}{S}\mu S\,dt + \frac{1}{S}\sigma S\,dB - \frac{1}{2}\frac{1}{S^2}\sigma^2 S^2\,dt = \left(\mu - \frac{\sigma^2}{2}\right)dt + \sigma\,dB

The σ2/2-\sigma^2/2 Ito correction converts the arithmetic drift μ\mu to the geometric/log drift μσ2/2\mu - \sigma^2/2.

For AI: DDPM noise levels satisfy dαˉtβtαˉtdtd\bar\alpha_t \approx -\beta_t\bar\alpha_t\,dt (linear SDE for logαˉ\log\bar\alpha). The Ito correction explains why the SNR αˉt/(1αˉt)\bar\alpha_t/(1-\bar\alpha_t) does not decrease linearly even for linear schedules - the correction term shifts the effective noise profile.

A.3 Stochastic Differential Equations

General Ito SDE:

dXt=b(Xt,t)dt+σ(Xt,t)dBt,X0=x0dX_t = b(X_t, t)\,dt + \sigma(X_t, t)\,dB_t, \quad X_0 = x_0
  • b(x,t)b(x,t): drift (deterministic tendency)
  • σ(x,t)\sigma(x,t): diffusion coefficient (noise strength)

Existence and uniqueness (Lipschitz conditions): If bb and σ\sigma are Lipschitz in xx uniformly in tt and have linear growth, the SDE has a unique strong solution (Picard-Lindelof for SDEs).

Important SDEs in ML:

ProcessSDENotes
BMdX=dBdX = dBb=0b=0, σ=1\sigma=1
OUdX=θXdt+σdBdX = -\theta X\,dt + \sigma\,dBMean-reverting
GBMdX=μXdt+σXdBdX = \mu X\,dt + \sigma X\,dBMultiplicative noise
LangevindX=U(X)dt+2dBdX = -\nabla U(X)\,dt + \sqrt{2}\,dBStationary eU\propto e^{-U}
SGD-SDEdθ=L(θ)dt+ηΣdBd\theta = -\nabla L(\theta)\,dt + \sqrt{\eta\Sigma}\,dBSGD diffusion approx.
DDPM fwddX=β2Xdt+βdBdX = -\frac{\beta}{2}X\,dt + \sqrt{\beta}\,dBVP-SDE for diffusion

Langevin dynamics and MCMC: The Langevin SDE dXt=U(Xt)dt+2dBtdX_t = -\nabla U(X_t)\,dt + \sqrt{2}\,dB_t has stationary distribution π(x)eU(x)\pi(x) \propto e^{-U(x)}. This is the continuous-time version of Langevin MCMC, used for sampling from complex posteriors (e.g., Bayesian neural networks, energy-based models).


Appendix B: Convergence Theorems for Martingales

B.1 Martingale Convergence

Theorem (Doob's Martingale Convergence, 1953). If {Mn}\{M_n\} is a martingale and supnE[Mn]<\sup_n \mathbb{E}[|M_n|] < \infty (L1L^1 bounded), then M=limnMnM_\infty = \lim_{n\to\infty} M_n exists a.s. and E[M]<\mathbb{E}[|M_\infty|] < \infty.

This theorem is foundational for proving convergence of:

  • Bayesian posterior updates (likelihood ratio martingales)
  • Online learning algorithms (regret bounds via bounded martingales)
  • Stochastic approximation algorithms (Robbins-Monro)

The L2L^2 version: If supnE[Mn2]<\sup_n \mathbb{E}[M_n^2] < \infty, then MnMM_n \to M_\infty both a.s. and in L2L^2.

B.2 Upcrossing Inequality

The proof of martingale convergence uses the upcrossing inequality: the number of times a martingale upcrosses an interval [a,b][a,b] (goes from below aa to above bb) satisfies:

E[Un[a,b]]E[(Mna)+]ba\mathbb{E}[U_n[a,b]] \leq \frac{\mathbb{E}[(M_n - a)^+]}{b - a}

If MnM_n is L1L^1 bounded, then E[U[a,b]]<\mathbb{E}[U_\infty[a,b]] < \infty, so upcrossings are finite for every rational interval [a,b][a,b]. This means oscillation in the limit is impossible, forcing convergence.

B.3 Uniform Integrability and L1L^1 Convergence

Definition. A family {Mt}\{M_t\} is uniformly integrable (UI) if:

suptE[Mt1Mt>K]0as K\sup_t \mathbb{E}[|M_t|\mathbf{1}_{|M_t| > K}] \to 0 \quad \text{as } K \to \infty

UI is the condition needed for E[M]=limnE[Mn]\mathbb{E}[M_\infty] = \lim_n \mathbb{E}[M_n] (exchange of limit and expectation). Without UI, a.s. convergence does not imply L1L^1 convergence.

Sufficient condition for UI: supnE[Mnp]<\sup_n \mathbb{E}[|M_n|^p] < \infty for any p>1p > 1.

For AI: Uniform integrability is implicitly required for most SGD convergence proofs that need E[L(θN)]L\mathbb{E}[L(\theta_N)] \to L^* (expectation of limit = limit of expectations). When gradient clipping is used, it ensures the gradient process is UI, validating the convergence proofs.


Appendix C: Gaussian Process Details

C.1 Kernel Properties

A function k:X×XRk: \mathcal{X} \times \mathcal{X} \to \mathbb{R} is a valid kernel (positive semidefinite / Mercer kernel) iff:

i,j=1ncicjk(xi,xj)0n,x1,,xnX,ciR\sum_{i,j=1}^n c_i c_j k(x_i, x_j) \geq 0 \quad \forall n, x_1,\ldots,x_n \in \mathcal{X}, c_i \in \mathbb{R}

Operations preserving PSD kernels:

  • Sum: k1+k2k_1 + k_2 (sum of two valid kernels is valid)
  • Product: k1k2k_1 \cdot k_2 (product of two valid kernels is valid)
  • Scaling: αk\alpha k for α>0\alpha > 0
  • Composition: k(x,x)=k1(ϕ(x),ϕ(x))k(x,x') = k_1(\phi(x), \phi(x')) for any feature map ϕ\phi

Bochner's theorem (characterisation of stationary kernels): A continuous function k(τ)k(\tau) is the covariance of a stationary process iff:

k(τ)=eiωτdF(ω)k(\tau) = \int e^{i\omega\tau}\,dF(\omega)

for some non-decreasing bounded measure FF (the spectral measure). The PSD is S(ω)=dF/dωS(\omega) = dF/d\omega.

C.2 Sparse GP Approximations

Exact GP inference costs O(n3)O(n^3) for nn training points. For large nn (e.g., n=105n = 10^5), this is intractable. Sparse GP approximations use mnm \ll n inducing points u=f(z)\mathbf{u} = f(\mathbf{z}):

p(f)q(f)=p(fu)q(u)dup(f) \approx q(f) = \int p(f|\mathbf{u})q(\mathbf{u})\,d\mathbf{u}

The most common is the SVGP (Sparse Variational GP) which optimises a variational lower bound (ELBO), reducing cost to O(nm2+m3)O(nm^2 + m^3).

For AI: Sparse GPs enable scalable Bayesian optimisation for LLM hyperparameter tuning with n>1000n > 1000 evaluations. The inducing points act as a compressed representation of the observations, analogous to the key-value cache in attention.

C.3 Deep Kernel Learning

Neural-network kernels: Replace the input xx with a neural network representation ϕθ(x)\phi_\theta(x) and use:

kθ(x,x)=kbase(ϕθ(x),ϕθ(x))k_\theta(x,x') = k_{\text{base}}(\phi_\theta(x), \phi_\theta(x'))

This is deep kernel learning (DKL): train θ\theta by maximising the GP marginal likelihood. DKL combines the flexibility of deep representations with the uncertainty quantification of GPs, and is used in scalable Bayesian optimisation for AutoML.


Appendix D: Extended ML Applications

D.1 Diffusion Models: Mathematical Details

The probability flow ODE for the VP-SDE is:

dxdt=f(x,t)12g(t)2xlogpt(x)\frac{dx}{dt} = f(x,t) - \frac{1}{2}g(t)^2\nabla_x\log p_t(x)

This ODE has the same marginal distributions as the reverse SDE but is deterministic. It enables:

  • DDIM sampling: Solve the ODE with large step sizes (fewer function evaluations)
  • Latent space interpolation: Deterministic ODE gives unique encoding of each data point
  • Consistency models: Learn direct xtx0x_t \to x_0 mapping that is consistent along ODE trajectories

The score function sθ(xt,t)xtlogpt(xt)s_\theta(x_t, t) \approx \nabla_{x_t}\log p_t(x_t) is the neural network that drives both the SDE and ODE. At optimum:

sθ(xt,t)=E ⁣[x0αˉtxt1αˉtxt]11αˉts_\theta^*(x_t, t) = \mathbb{E}\!\left[\frac{x_0 - \sqrt{\bar\alpha_t}x_t}{1-\bar\alpha_t}\,\Big|\,x_t\right] \cdot \frac{-1}{\sqrt{1-\bar\alpha_t}}

This is a conditional expectation - directly connecting score learning to the Doob martingale construction.

D.2 Online Learning and Martingale Regret Bounds

In online learning, at each round tt the learner predicts y^t\hat{y}_t, suffers loss t(y^t)\ell_t(\hat{y}_t), and observes true outcome yty_t. The regret against best fixed action aa^* is:

RegretT=t=1Tt(y^t)minat=1Tt(a)\text{Regret}_T = \sum_{t=1}^T \ell_t(\hat{y}_t) - \min_{a}\sum_{t=1}^T \ell_t(a)

Martingale structure: In Follow-the-Regularised-Leader (FTRL) algorithms, the loss differences t(y^t)E[t(y^t)Ft1]\ell_t(\hat{y}_t) - \mathbb{E}[\ell_t(\hat{y}_t)|\mathcal{F}_{t-1}] form a martingale difference sequence. Applying Azuma's inequality:

P ⁣(RegretTE[RegretT]+tT)e2t2P\!\left(\text{Regret}_T \geq \mathbb{E}[\text{Regret}_T] + t\sqrt{T}\right) \leq e^{-2t^2}

This gives high-probability regret bounds - the stochastic process framework converts expected regret into individual-run guarantees.

Bandit algorithms (Thompson Sampling): In multi-armed bandits with KK arms, at each round the agent samples parameters from the posterior and plays the arm with highest reward. The number of plays of suboptimal arms is bounded using stopping time arguments on the likelihood ratio martingale.

D.3 RLHF and Reward Models as Stochastic Processes

RLHF (Reinforcement Learning from Human Feedback) trains a language model πθ\pi_\theta to maximise a learned reward model rϕ(x,y)r_\phi(x,y) subject to a KL penalty:

maxπExD,yπ[rϕ(x,y)]βKL(ππref)\max_\pi \mathbb{E}_{x\sim\mathcal{D}, y\sim\pi}[r_\phi(x,y)] - \beta\text{KL}(\pi \| \pi_{\text{ref}})

This is a stochastic control problem: the policy π\pi is a controller, the generation trajectory (y1,,yT)(y_1,\ldots,y_T) is the controlled stochastic process, and the reward rϕ(x,y1:T)r_\phi(x, y_{1:T}) is a terminal cost.

The RLHF policy update (PPO) as a martingale: The policy gradient estimator in PPO is:

g^=Et ⁣[πθ(atst)πθold(atst)At]\hat{g} = \mathbb{E}_t\!\left[\frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_\text{old}}(a_t|s_t)}A_t\right]

where AtA_t is the advantage estimate. Under the true advantage function, At=Qπ(st,at)Vπ(st)A_t = Q^\pi(s_t,a_t) - V^\pi(s_t) has E[Atst]=0\mathbb{E}[A_t | s_t] = 0 - it is a martingale difference. PPO clips the ratio to prevent large updates, maintaining stability of the martingale approximation.

D.4 Stochastic Processes in LLM Interpretability

Mechanistic interpretability (Elhage et al., Nanda et al.) studies circuits in transformer weights. The token sequence flowing through a transformer layers can be modelled as a stochastic process evolving through residual stream updates:

xt(+1)=xt()+Attn()(x1:t())+MLP()(xt())x_t^{(\ell+1)} = x_t^{(\ell)} + \text{Attn}^{(\ell)}(x_{1:t}^{(\ell)}) + \text{MLP}^{(\ell)}(x_t^{(\ell)})

Each residual update is a perturbation to the current state - the trajectory through layers is a discrete-time process indexed by layer depth \ell, not token position tt. Understanding this process (what information is stored/retrieved at each layer) is the central question of interpretability.

Induction heads are attention heads that implement the operation "if A appeared before B at some position, predict B will appear after the current A." This is a pattern-matching stopping time: the head activates when it detects that the current context matches a past pattern. Formalising this as a stopping time over the layer-depth stochastic process is an active research direction.


Appendix E: The Functional CLT (Donsker's Theorem)

E.1 Weak Convergence on Function Spaces

Donsker's theorem states convergence in distribution on the function space C([0,1])C([0,1]) - the space of continuous functions equipped with the supremum norm f=suptf(t)\|f\|_\infty = \sup_t |f(t)|.

Theorem (Donsker, 1951). Let X1,X2,X_1, X_2, \ldots be iid with E[Xi]=0\mathbb{E}[X_i]=0, σ2=E[Xi2]<\sigma^2 = \mathbb{E}[X_i^2] < \infty. Define:

Wn(t)=1σnSnt,t[0,1]W_n(t) = \frac{1}{\sigma\sqrt{n}}S_{\lfloor nt \rfloor}, \quad t \in [0,1]

Then WnBW_n \Rightarrow B weakly in (C([0,1]),)(C([0,1]), \|\cdot\|_\infty), where BB is standard Brownian motion.

Continuous mapping theorem: If WnBW_n \Rightarrow B and g:C([0,1])Rg: C([0,1]) \to \mathbb{R} is continuous, then g(Wn)g(B)g(W_n) \Rightarrow g(B). This gives:

  • max0knSk/(σn)max0t1Bt\max_{0 \leq k \leq n} S_k / (\sigma\sqrt{n}) \Rightarrow \max_{0 \leq t \leq 1} B_t - reflection principle for random walks
  • n1k=1nSk2/σ201Bt2dtn^{-1}\sum_{k=1}^n S_k^2 / \sigma^2 \Rightarrow \int_0^1 B_t^2\,dt - law of Brownian local time

E.2 Applications to SGD Analysis

Donsker's theorem justifies the SDE approximation of SGD: as step size η0\eta \to 0, the piecewise-constant SGD interpolation converges (in distribution, as a path) to the SDE dθ=Ldt+ηΣdBd\theta = -\nabla L\,dt + \sqrt{\eta\Sigma}\,dB. This means:

  • Convergence results for the SDE (e.g., mixing time to stationary distribution) translate to discrete-time SGD results
  • The stationary distribution of SGD approximates N(θ,η2H1Σ)\mathcal{N}(\theta^*, \frac{\eta}{2}H^{-1}\Sigma) near a minimum θ\theta^*
  • The escape rate from a local minimum scales as exp(ΔL/(η/B))\exp(-\Delta L / (\eta/B)) - the Kramers escape rate formula

This is why practitioners observe that increasing batch size BB by factor kk requires proportionally increasing learning rate η\eta by kk to maintain the same noise temperature η/B\eta/B and thus the same optimisation dynamics.


Appendix F: Notation Summary

SymbolMeaning
(Ω,F,P)(\Omega, \mathcal{F}, P)Probability space
(Ft)t0(\mathcal{F}_t)_{t \geq 0}Filtration (increasing family of σ\sigma-algebras)
{Xt}tT\{X_t\}_{t \in T}Stochastic process indexed by TT
MnM_nMartingale
τ\tauStopping time
Fτ\mathcal{F}_\tauσ\sigma-algebra at stopping time τ\tau
[X]t[X]_tQuadratic variation of process XX up to time tt
BtB_tStandard Brownian motion (Wiener process)
N(t)N(t)Poisson process with rate λ\lambda
k(s,t)k(s,t)Covariance kernel (for GPs)
GP(m,k)\mathcal{GP}(m, k)Gaussian process with mean mm and kernel kk
dBtdB_tWiener increment (stochastic differential)
0THtdBt\int_0^T H_t\,dB_tIto integral
[B]T=T[B]_T = TQuadratic variation of BM
αˉt\bar\alpha_tDDPM cumulative noise schedule
sθ(x,t)s_\theta(x,t)Score function approximation
VP-SDEVariance-Preserving SDE (DDPM continuum)
VE-SDEVariance-Exploding SDE
OSTOptional Stopping Theorem (Doob)
UIUniformly Integrable
WSSWide-Sense Stationary
ACVFAutocovariance function
PSDPower Spectral Density
NTKNeural Tangent Kernel
OUOrnstein-Uhlenbeck process
GBMGeometric Brownian Motion
SRWSimple Random Walk

Appendix G: Worked Examples

G.1 Symmetric Random Walk: Hitting Probabilities

Problem. A particle starts at position x=3x = 3 on the integer line. At each step it moves +1+1 or 1-1 with equal probability. Find: (a) The probability it hits 0 before hitting 10 (b) The expected number of steps to hit {0,10}\{0, 10\} (c) The probability it ever returns to 3 starting from 3

Solution.

(a) By the gambler's ruin result, P(hit 0 before 10)=13/10=7/10P(\text{hit 0 before 10}) = 1 - 3/10 = 7/10.

(b) E[τ]=k(Nk)=3×7=21\mathbb{E}[\tau] = k(N-k) = 3 \times 7 = 21 steps.

(c) For a symmetric walk starting at x=3x=3 on Z\mathbb{Z}, the probability of ever returning to 3 equals 1 (by Polya's theorem, d=1d=1 recurrence). However, the expected return time is \infty (the walk is null-recurrent).

Numerical verification:

import numpy as np
np.random.seed(42)
N_trials = 100_000

# (a) Gambler's ruin simulation
hits_zero = 0
for _ in range(N_trials):
    x = 3
    while 0 < x < 10:
        x += np.random.choice([-1, 1])
    hits_zero += (x == 0)
print(f"P(hit 0) \\approx {hits_zero/N_trials:.4f}, theory: 0.7000")  # -> 0.7000

# (b) Expected steps
total_steps = 0
for _ in range(N_trials):
    x, steps = 3, 0
    while 0 < x < 10:
        x += np.random.choice([-1, 1])
        steps += 1
    total_steps += steps
print(f"E[\\tau] \\approx {total_steps/N_trials:.2f}, theory: 21.00")  # -> 21.00

G.2 Poisson Process: Conditional Uniformity

Problem. Events arrive as a Poisson process with rate λ\lambda. Given that exactly 5 events occurred in [0,3][0,3], what is the distribution of the first event time T1T_1?

Solution. By the conditional uniformity property, given N(3)=5N(3) = 5, the 5 event times are the order statistics of 5 iid Uniform[0,3][0,3] random variables. Therefore T1N(3)=5Beta(1,5)T_1 | N(3)=5 \sim \text{Beta}(1,5) scaled to [0,3][0,3]:

T1N(3)=53Beta(1,5)1=36Uniform[0,3] in distributionT_1 | N(3)=5 \sim \frac{3 \cdot \text{Beta}(1,5)}{1} = \frac{3}{6}\text{Uniform}[0,3] \text{ in distribution}

More precisely: P(T1>tN(3)=5)=(1t/3)5P(T_1 > t | N(3)=5) = (1-t/3)^5 for t[0,3]t \in [0,3].

Verification: Simulate 5 Uniform[0,3][0,3] random variables, take the minimum. Compare to conditional Poisson process simulation.

G.3 Brownian Motion: The Arc-Sine Distribution

Problem. Let L1=sup{t[0,1]:Bt=0}L_1 = \sup\{t \in [0,1]: B_t = 0\} be the last zero of Brownian motion before time 1. Find P(L1t)P(L_1 \leq t).

Solution. By Levy's arc-sine law:

P(L1t)=2πarcsin(t)P(L_1 \leq t) = \frac{2}{\pi}\arcsin(\sqrt{t})

This is the CDF of the arc-sine distribution on [0,1][0,1]. The density p(t)=1/(πt(1t))p(t) = 1/(\pi\sqrt{t(1-t)}) concentrates near 0 and 1 - the last zero before time 1 is most likely to be near 0 or near 1, and least likely to be near 1/21/2. This violates the naive intuition that "the last zero should be somewhere in the middle."

Implication for AI: The arc-sine law suggests that in a long random walk (or SRW approximation of SGD noise), the trajectory spends most of its time on one side of zero - the noise process can have long "runs" of the same sign. This persistent structure in gradient noise is why momentum-based optimisers (Adam, SGD with momentum) perform better than pure SGD for certain problem structures.

G.4 OU Process: Analytical vs Numerical

Problem. Solve dX=2(X1)dt+3dBdX = -2(X-1)\,dt + \sqrt{3}\,dB, X0=5X_0 = 5.

Solution. This is OU with θ=2\theta=2, μ=1\mu=1, σ=3\sigma=\sqrt{3}.

  • Solution: Xt=1+(51)e2t+30te2(ts)dBsX_t = 1 + (5-1)e^{-2t} + \sqrt{3}\int_0^t e^{-2(t-s)}\,dB_s
  • Mean: E[Xt]=1+4e2t\mathbb{E}[X_t] = 1 + 4e^{-2t}
  • Variance: Var(Xt)=34(1e4t)\text{Var}(X_t) = \frac{3}{4}(1 - e^{-4t})
  • Stationary distribution: XN(1,3/4)X_\infty \sim \mathcal{N}(1, 3/4)

The process decays exponentially from X0=5X_0=5 toward the mean μ=1\mu=1 with decay rate θ=2\theta=2, while accumulating noise that saturates at σ2/(2θ)=3/4\sigma^2/(2\theta) = 3/4.

For diffusion models: This corresponds to DDPM with βt=4Δt\beta_t = 4\Delta t (time-discretised) and the signal-to-noise ratio at time TT approaching E[XT]=1+4e2T\mathbb{E}[X_T] = 1 + 4e^{-2T} for TT \to \infty - which is the "pure noise" terminal condition when XTN(1,3/4)X_T \approx \mathcal{N}(1, 3/4).

G.5 Gaussian Process: Prior vs Posterior

Problem. Fit a GP to three observations (x1,y1)=(0,1)(x_1, y_1) = (0, 1), (x2,y2)=(1,0.5)(x_2, y_2) = (1, -0.5), (x3,y3)=(2,0.8)(x_3, y_3) = (2, 0.8) with RBF kernel k(x,x)=e(xx)2k(x,x') = e^{-(x-x')^2} and noise σn2=0.01\sigma_n^2 = 0.01.

Solution. Build the 3×33 \times 3 kernel matrix KK:

Kij=e(xixj)2+0.01δijK_{ij} = e^{-(x_i-x_j)^2} + 0.01\,\delta_{ij}

Posterior at test point x=1.5x_* = 1.5:

  • Compute k=[k(x,x1),k(x,x2),k(x,x3)]k_* = [k(x_*, x_1), k(x_*, x_2), k(x_*, x_3)]
  • μ=k(K)1y\mu_* = k_*^\top(K)^{-1}\mathbf{y}
  • σ2=k(x,x)kK1k\sigma_*^2 = k(x_*,x_*) - k_*^\top K^{-1} k_*

The posterior mean interpolates between the observations, and the posterior variance is small near observations (where the kernel provides strong correlation) and large away from them.


Appendix H: Self-Assessment Checklist

After completing this section, verify you can:

  • State the definition of a stochastic process and give 3 examples of each combination of (discrete/continuous) x (time/state space)
  • Define a filtration and explain what "adapted" means in ML context
  • Verify the martingale property for a new process by computing E[Mn+1Fn]\mathbb{E}[M_{n+1}|\mathcal{F}_n]
  • State all three conditions of Doob's OST and identify which applies to a given problem
  • Apply OST to compute expected stopping times and boundary hitting probabilities
  • Construct the Doob martingale for a given function ff and derive McDiarmid from Azuma
  • State the three defining properties of a Poisson process and derive the superposition/thinning results
  • State Wiener's four axioms for Brownian motion and compute P(Bta)P(B_t \geq a)
  • Compute the quadratic variation [B]T=T[B]_T = T and state Ito's lemma
  • Solve the OU SDE and state its stationary distribution
  • Connect the DDPM forward process to the VP-SDE and OU process
  • Define WSS and ergodicity, and state the Wiener-Khinchin theorem
  • Specify a GP by its mean function and kernel, and compute the posterior given observations
  • Explain why RoPE makes attention a stationary kernel in position
  • Model SGD as a near-martingale and state the diffusion SDE approximation

Appendix I: Connections to Other Areas

I.1 Information Theory (Section09)

  • The log-likelihood ratio process klog(p/q)(Xk)\sum_k \log(p/q)(X_k) is a supermartingale under QQ and a submartingale under PP
  • The sequential probability ratio test (SPRT) is an optimal stopping time for hypothesis testing, derived using the likelihood ratio martingale
  • Renyi entropy rates and the entropy rate Hˉ=limnH(XnXn1,,X1)/1\bar{H} = \lim_n H(X_n|X_{n-1},\ldots,X_1)/1 of a stationary process are central concepts at the intersection of stochastic processes and information theory

I.2 Functional Analysis (Section12)

  • The space C([0,1])C([0,1]) of continuous functions is a Banach space; weak convergence on this space is Donsker's theorem
  • Gaussian processes are infinite-dimensional Gaussian distributions on function spaces (Hilbert spaces)
  • Reproducing Kernel Hilbert Spaces (RKHS): For each valid kernel kk, there is a unique RKHS Hk\mathcal{H}_k with the reproducing property f(x)=f,k(,x)Hkf(x) = \langle f, k(\cdot,x)\rangle_{\mathcal{H}_k}. GP regression in Hk\mathcal{H}_k is equivalent to minimising a regularised empirical risk in the RKHS

I.3 Optimisation (Section08)

  • Stochastic approximation (Robbins-Monro, 1951): The original framework for SGD convergence uses martingale theory. Under step sizes tηt=\sum_t \eta_t = \infty, tηt2<\sum_t \eta_t^2 < \infty and bounded variance, the iterates converge a.s.
  • Lyapunov methods: Proving convergence of SGD amounts to constructing a Lyapunov function V(θ)V(\theta) that is a (noisy) supermartingale, then applying martingale convergence
  • Langevin MCMC: The Langevin SDE dθ=U(θ)dt+2dBtd\theta = -\nabla U(\theta)\,dt + \sqrt{2}\,dB_t is used for posterior sampling in Bayesian DL, connecting optimisation and stochastic process theory

I.4 Statistics (Section07-Statistics)

  • Time series analysis (ARIMA, state-space models) is the statistical estimation side of stochastic processes: given observed data X1,,XnX_1,\ldots,X_n, estimate the model parameters of an assumed process
  • Spectral analysis uses the Wiener-Khinchin theorem to estimate the PSD from data via the periodogram
  • Hypothesis testing for stationarity (Augmented Dickey-Fuller test, KPSS test) checks whether an observed time series is consistent with a stationary process

Appendix J: Advanced Topics

J.1 Levy Processes

A Levy process generalises both Brownian motion (continuous paths) and Poisson process (jumps) to arbitrary combinations of drift, diffusion, and jumps.

Levy-Khinchin representation: Every Levy process XtX_t has characteristic function:

E[eiθXt]=exp ⁣(t[iμθσ2θ22+R{0}(eiθx1iθx1x<1)ν(dx)])\mathbb{E}[e^{i\theta X_t}] = \exp\!\left(t\left[i\mu\theta - \frac{\sigma^2\theta^2}{2} + \int_{\mathbb{R}\setminus\{0\}} (e^{i\theta x} - 1 - i\theta x\mathbf{1}_{|x|<1})\,\nu(dx)\right]\right)

where μR\mu \in \mathbb{R} (drift), σ20\sigma^2 \geq 0 (diffusion), and ν\nu is the Levy measure (jump intensity).

For AI: Heavy-tailed gradient distributions in neural network training are better modelled by Levy processes (with large jumps) than by Brownian motion (Gaussian, no jumps). The Levy stable distribution family includes the Gaussian (index α=2\alpha=2) and Cauchy (α=1\alpha=1) as special cases. Empirical studies of gradient statistics in transformers show heavy tails (Student-tt with low degrees of freedom), suggesting Levy process models may be more appropriate than the Gaussian SDE approximation.

J.2 Malliavin Calculus

Malliavin calculus is a variational calculus on Wiener space - it provides derivatives of random variables with respect to the underlying Brownian motion.

The Malliavin derivative DsF\mathcal{D}_s F measures the sensitivity of FF to the Brownian increment at time ss. It satisfies:

DsF=limε0F(B+ε1[s,))F(B)ε\mathcal{D}_s F = \lim_{\varepsilon\to 0}\frac{F(B + \varepsilon\mathbf{1}_{[s,\infty)}) - F(B)}{\varepsilon}

Clark-Ocone formula: For FL2F \in L^2 with E[F]=0\mathbb{E}[F]=0:

F=0TE[DsFFs]dBsF = \int_0^T \mathbb{E}[\mathcal{D}_s F | \mathcal{F}_s]\,dB_s

This represents any square-integrable random variable as a stochastic integral - connecting Malliavin calculus to the martingale representation theorem.

For AI: Malliavin calculus provides pathwise gradients for diffusion models, enabling gradient computation through the stochastic sampling process. This is used in score-based generative model training with more stable gradient estimates than the standard score-matching loss.

J.3 Stochastic Control and HJB Equation

A stochastic control problem seeks to find a policy ut(ω)u_t(\omega) (adapted to Ft\mathcal{F}_t) minimising:

J(u)=E ⁣[0TL(Xt,ut)dt+g(XT)]J(u) = \mathbb{E}\!\left[\int_0^T \mathcal{L}(X_t, u_t)\,dt + g(X_T)\right]

subject to dXt=b(Xt,ut)dt+σ(Xt,ut)dBtdX_t = b(X_t, u_t)\,dt + \sigma(X_t, u_t)\,dB_t.

The Hamilton-Jacobi-Bellman (HJB) equation gives the optimal value function V(x,t)=infuJ(u;x,t)V(x,t) = \inf_u J(u; x,t):

tV=minu ⁣[L(x,u)+b(x,u)xV+12tr(σσx2V)]-\partial_t V = \min_u\!\left[\mathcal{L}(x,u) + b(x,u)^\top\nabla_x V + \frac{1}{2}\text{tr}(\sigma\sigma^\top \nabla^2_x V)\right]

For AI: RLHF can be formulated as a stochastic control problem where the LLM generates tokens sequentially (the SDE), the reward is the RLHF reward model (the cost), and the KL penalty is a regularisation term. The HJB equation characterises the optimal RLHF policy, and PPO approximately solves it using neural network approximations of VV.


Appendix K: Python Recipes for Stochastic Processes

K.1 Simulating Stochastic Processes

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)

# Simple Random Walk
def simulate_srw(n_steps, n_paths=5):
    steps = np.random.choice([-1, 1], size=(n_paths, n_steps))
    return np.hstack([np.zeros((n_paths,1)), steps.cumsum(axis=1)])

# Brownian Motion (via SRW limit)
def simulate_bm(T=1.0, n_steps=1000, n_paths=5):
    dt = T / n_steps
    increments = np.random.normal(0, np.sqrt(dt), (n_paths, n_steps))
    return np.hstack([np.zeros((n_paths,1)), increments.cumsum(axis=1)])

# Ornstein-Uhlenbeck (Euler-Maruyama)
def simulate_ou(theta=1.0, mu=0.0, sigma=1.0, T=10.0, n_steps=1000, n_paths=5):
    dt = T / n_steps
    X = np.zeros((n_paths, n_steps+1))
    X[:,0] = 2.0  # initial condition
    for t in range(n_steps):
        dB = np.random.normal(0, np.sqrt(dt), n_paths)
        X[:,t+1] = X[:,t] + theta*(mu - X[:,t])*dt + sigma*dB
    return X

# Poisson Process
def simulate_poisson(lam=1.0, T=10.0, n_paths=5):
    paths = []
    for _ in range(n_paths):
        t, events = 0, [0]
        while t < T:
            t += np.random.exponential(1/lam)
            events.append(min(t, T))
        paths.append(events)
    return paths

# Geometric Brownian Motion
def simulate_gbm(mu=0.1, sigma=0.3, S0=100.0, T=1.0, n_steps=252, n_paths=5):
    dt = T / n_steps
    log_S = np.zeros((n_paths, n_steps+1))
    log_S[:,0] = np.log(S0)
    for t in range(n_steps):
        log_S[:,t+1] = log_S[:,t] + (mu - sigma**2/2)*dt + sigma*np.random.normal(0, np.sqrt(dt), n_paths)
    return np.exp(log_S)

K.2 Gaussian Process Posterior

import numpy as np
from scipy.linalg import cho_factor, cho_solve

def rbf_kernel(X1, X2, length_scale=1.0, variance=1.0):
    """Squared-exponential (RBF) kernel."""
    dists = ((X1[:,None] - X2[None,:])**2).sum(-1)
    return variance * np.exp(-dists / (2 * length_scale**2))

def gp_posterior(X_train, y_train, X_test, kernel_fn, noise_var=1e-3):
    """Compute GP posterior mean and variance."""
    K_tt = kernel_fn(X_train, X_train) + noise_var * np.eye(len(X_train))
    K_ts = kernel_fn(X_train, X_test)
    K_ss = kernel_fn(X_test, X_test)

    # Solve K_tt @ alpha = y_train using Cholesky
    cho = cho_factor(K_tt)
    alpha = cho_solve(cho, y_train)
    v = cho_solve(cho, K_ts)

    mu_post = K_ts.T @ alpha
    var_post = np.diag(K_ss) - (K_ts * v).sum(0)
    return mu_post, np.sqrt(np.maximum(var_post, 0))

# Usage:
# X_train = np.array([0., 1., 2.])
# y_train = np.array([1., -0.5, 0.8])
# X_test = np.linspace(-0.5, 2.5, 100)
# mu, std = gp_posterior(X_train, y_train, X_test, rbf_kernel)

K.3 Martingale Verification

import numpy as np

def verify_martingale(process_fn, n_steps=100, n_paths=10000, tol=0.05):
    """
    Verify martingale property: E[M_{n+1} | M_n] \\approx M_n.
    process_fn: callable that generates (n_paths, n_steps+1) array.
    """
    paths = process_fn(n_steps, n_paths)
    # Check: mean at step n equals mean at step 0
    means = paths.mean(axis=0)
    assert np.allclose(means, means[0], atol=tol), f"Mean not constant: {means[:5]}"
    # Check: E[M_{n+1}^2] - E[M_n^2] = variance increment
    print(f"Mean at all steps: {means[0]:.4f} +/- {means.std():.4f} (should be ~0)")
    print(f"PASS: Martingale mean constant within tolerance {tol}")

def simulate_srw_paths(n_steps, n_paths):
    steps = np.random.choice([-1., 1.], size=(n_paths, n_steps))
    return np.hstack([np.zeros((n_paths,1)), steps.cumsum(axis=1)])

np.random.seed(42)
verify_martingale(simulate_srw_paths)

K.4 Diffusion Model Forward Process

import numpy as np

def ddpm_forward_process(x0, T=1000, beta_start=1e-4, beta_end=0.02):
    """
    DDPM forward process: q(x_t | x_0) = N(sqrt(alpha_bar_t)*x0, (1-alpha_bar_t)*I)
    Returns: {t: (x_t, alpha_bar_t)} for t = 0, 1, ..., T
    """
    betas = np.linspace(beta_start, beta_end, T)
    alphas = 1 - betas
    alpha_bars = np.cumprod(alphas)

    trajectory = {0: (x0, 1.0)}
    x0_arr = np.array(x0, dtype=float)

    for t in range(1, T+1):
        ab = alpha_bars[t-1]
        eps = np.random.randn(*x0_arr.shape)
        x_t = np.sqrt(ab) * x0_arr + np.sqrt(1 - ab) * eps
        trajectory[t] = (x_t, ab)
    return trajectory, alpha_bars

def snr(alpha_bar):
    """Signal-to-noise ratio: alpha_bar / (1 - alpha_bar)."""
    return alpha_bar / (1 - alpha_bar + 1e-9)

# Example:
# x0 = np.array([1.0, 0.0, -1.0])
# traj, alpha_bars = ddpm_forward_process(x0, T=1000)
# For t=500: SNR \\approx 1 (equal signal and noise)
# For t=1000: SNR \\approx 0 (pure noise)

K.5 DDPM Schedule Comparison

import numpy as np

def linear_schedule(T=1000, beta_start=1e-4, beta_end=0.02):
    return np.linspace(beta_start, beta_end, T)

def cosine_schedule(T=1000, s=0.008):
    t = np.arange(T+1) / T
    f = np.cos((t + s)/(1+s) * np.pi/2)**2
    alpha_bars = f / f[0]
    betas = 1 - alpha_bars[1:] / alpha_bars[:-1]
    return np.clip(betas, 0, 0.999)

T = 1000
betas_linear = linear_schedule(T)
betas_cosine = cosine_schedule(T)

ab_linear = np.cumprod(1 - betas_linear)
ab_cosine = np.cumprod(1 - betas_cosine)

print("Signal preserved at t=T/4, T/2, 3T/4, T:")
for name, ab in [("Linear", ab_linear), ("Cosine", ab_cosine)]:
    vals = [ab[T//4-1], ab[T//2-1], ab[3*T//4-1], ab[-1]]
    print(f"  {name}: {[f'{v:.4f}' for v in vals]}")
# Cosine schedule destroys signal more uniformly across timesteps

Appendix L: Theory Problems (Advanced)

L.1 Optional Stopping and Wald's Identity

Problem. Let X1,X2,X_1, X_2, \ldots be iid with E[Xi]=μ\mathbb{E}[X_i] = \mu and E[Xi2]=σ2+μ2\mathbb{E}[X_i^2] = \sigma^2 + \mu^2. Let τ\tau be a stopping time with E[τ]<\mathbb{E}[\tau] < \infty. Prove Wald's Identity:

E[Sτ]=μE[τ],E[Sτ2]=σ2E[τ]+μ2E[τ]2\mathbb{E}[S_\tau] = \mu \cdot \mathbb{E}[\tau], \quad \mathbb{E}[S_\tau^2] = \sigma^2\mathbb{E}[\tau] + \mu^2\mathbb{E}[\tau]^2

Hint: SnnμS_n - n\mu is a martingale. Apply OST. For the second moment, use (Snnμ)2nσ2(S_n - n\mu)^2 - n\sigma^2.

L.2 The Optional Stopping Theorem: Necessary Conditions

Problem. Show that the condition E[τ]<\mathbb{E}[\tau] < \infty alone does NOT suffice for OST. Construct a martingale {Mn}\{M_n\} and stopping time τ\tau with E[τ]<\mathbb{E}[\tau] < \infty but E[Mτ]E[M0]\mathbb{E}[M_\tau] \neq \mathbb{E}[M_0].

Hint: Let Mn=M_n = SRW and τ=min(T,hitting time of level n)\tau = \min(T, \text{hitting time of level } n) for appropriate TT depending on nn...

L.3 Levy Characterisation of BM

Problem. Prove that if {Mt}\{M_t\} is a continuous local martingale starting at 0 with quadratic variation [M]t=t[M]_t = t, then MtM_t is a standard Brownian motion.

Hint: Use the exponential martingale eiθMt+θ2t/2e^{i\theta M_t + \theta^2 t/2} and show it is a martingale. Then compute the characteristic function of (Mt1,,Mtn)(M_{t_1},\ldots,M_{t_n}).

L.4 GP Posterior as Hilbert Space Projection

Problem. Show that the GP posterior mean μ(x)=kK1y\mu_*(x) = k_*^\top K^{-1}\mathbf{y} is the orthogonal projection of ff onto the span of {k(,x1),,k(,xn)}\{k(\cdot, x_1),\ldots,k(\cdot, x_n)\} in the RKHS Hk\mathcal{H}_k.

Hint: Use the reproducing property f(xi)=f,k(,xi)Hkf(x_i) = \langle f, k(\cdot,x_i)\rangle_{\mathcal{H}_k} to express the GP as a Hilbert space problem.


Appendix M: References and Further Reading

Textbooks

  1. Karatzas & Shreve, Brownian Motion and Stochastic Calculus (1991) - The standard reference for rigorous continuous-time stochastic processes, Ito calculus, and SDEs. Graduate-level.

  2. Durrett, Probability: Theory and Examples (5th ed., 2019) - Comprehensive coverage including martingales, stopping times, ergodic theory, Brownian motion. Excellent exercises.

  3. Williams, Probability with Martingales (1991) - Elegant, concise introduction to martingale theory. The clearest proof of martingale convergence. Highly recommended.

  4. Oksendal, Stochastic Differential Equations (7th ed., 2014) - Standard SDEs reference. Accessible treatment of Ito calculus and applications.

  5. Rasmussen & Williams, Gaussian Processes for Machine Learning (2006) - The canonical GP reference. Available free online.

  6. Doob, Stochastic Processes (1953) - The original monograph. Still valuable for historical context.

Papers for AI Connections

  1. Song et al. (2021), Score-Based Generative Modeling through Stochastic Differential Equations - Score SDE framework unifying DDPM, SMLD.

  2. Mandt, Hoffman & Blei (2017), Stochastic Gradient Descent as Approximate Bayesian Inference - SDE approximation of SGD.

  3. Su et al. (2022), RoFormer: Enhanced Transformer with Rotary Position Embedding - RoPE as stationary kernel.

  4. Ho, Jain & Abbeel (2020), Denoising Diffusion Probabilistic Models - DDPM.

  5. Li et al. (2017), Stochastic Modified Equations and Adaptive Stochastic Gradient Algorithms - SDE theory for SGD.

  6. Song et al. (2023), Consistency Models - Distillation of diffusion models via probability flow ODE.

  7. Tropp (2015), An Introduction to Matrix Concentration Inequalities - Matrix Bernstein, extends scalar martingale results.

  8. Williams (1997), Reinforcement Learning: An Introduction (Sutton & Barto) - RL value functions as martingales; Chapter 6 on TD-learning.


Appendix N: Extended Proofs

N.1 Proof of Doob's Maximal Inequality

Theorem. For a non-negative submartingale {Mk}k=0n\{M_k\}_{k=0}^n and λ>0\lambda > 0:

λP ⁣(max0knMkλ)E[Mn]\lambda \cdot P\!\left(\max_{0 \leq k \leq n} M_k \geq \lambda\right) \leq \mathbb{E}[M_n]

Proof. Let τ=min{k:Mkλ}\tau = \min\{k : M_k \geq \lambda\} (first time the process crosses λ\lambda), with τ=n\tau = n if no crossing occurs. Then τ\tau is a stopping time (the crossing event is Fk\mathcal{F}_k-measurable).

Decompose the expectation E[Mn]\mathbb{E}[M_n]:

E[Mn]=E[Mn1τn]+E[Mn1τ>n]\mathbb{E}[M_n] = \mathbb{E}[M_n \mathbf{1}_{\tau \leq n}] + \mathbb{E}[M_n \mathbf{1}_{\tau > n}]

For the first term: since {Mk}\{M_k\} is a submartingale, E[MnFτ]Mτλ\mathbb{E}[M_n | \mathcal{F}_\tau] \geq M_\tau \geq \lambda on {τn}\{\tau \leq n\}:

E[Mn1τn]=E[E[MnFτ]1τn]λP(τn)=λP ⁣(maxkMkλ)\mathbb{E}[M_n \mathbf{1}_{\tau \leq n}] = \mathbb{E}[\mathbb{E}[M_n|\mathcal{F}_\tau]\mathbf{1}_{\tau \leq n}] \geq \lambda \cdot P(\tau \leq n) = \lambda \cdot P\!\left(\max_k M_k \geq \lambda\right)

Since E[Mn1τ>n]0\mathbb{E}[M_n \mathbf{1}_{\tau > n}] \geq 0:

E[Mn]λP ⁣(maxkMkλ)\mathbb{E}[M_n] \geq \lambda P\!\left(\max_k M_k \geq \lambda\right)

\square

Corollary. Applying to {Mk}\{|M_k|\} (non-negative submartingale since f(x)=xf(x)=|x| is convex):

P ⁣(max0knMkλ)E[Mn]λP\!\left(\max_{0 \leq k \leq n}|M_k| \geq \lambda\right) \leq \frac{\mathbb{E}[|M_n|]}{\lambda}

N.2 Proof of Azuma's Inequality

Theorem (Azuma-Hoeffding). Let {Mk}k=0n\{M_k\}_{k=0}^n be a martingale with MkMk1ck|M_k - M_{k-1}| \leq c_k a.s. Then:

P(MnM0t)exp ⁣(t22kck2)P(M_n - M_0 \geq t) \leq \exp\!\left(\frac{-t^2}{2\sum_k c_k^2}\right)

Proof. Let Dk=MkMk1D_k = M_k - M_{k-1} be the martingale differences. Since E[DkFk1]=0\mathbb{E}[D_k|\mathcal{F}_{k-1}] = 0 and Dkck|D_k| \leq c_k, by Hoeffding's lemma:

E[esDkFk1]es2ck2/2\mathbb{E}[e^{sD_k}|\mathcal{F}_{k-1}] \leq e^{s^2c_k^2/2}

By the Markov inequality for es(MnM0)e^{s(M_n - M_0)} (for any s>0s > 0):

P(MnM0t)estE[es(MnM0)]P(M_n - M_0 \geq t) \leq e^{-st}\mathbb{E}[e^{s(M_n-M_0)}]

Factor the MGF using conditional independence:

E[eskDk]=E ⁣[kesDk]=E ⁣[k=1n1esDkE[esDnFn1]]E ⁣[k=1n1esDk]es2cn2/2\mathbb{E}[e^{s\sum_k D_k}] = \mathbb{E}\!\left[\prod_k e^{sD_k}\right] = \mathbb{E}\!\left[\prod_{k=1}^{n-1}e^{sD_k}\mathbb{E}[e^{sD_n}|\mathcal{F}_{n-1}]\right] \leq \mathbb{E}\!\left[\prod_{k=1}^{n-1}e^{sD_k}\right] \cdot e^{s^2c_n^2/2}

Iterating: E[es(MnM0)]es2kck2/2\mathbb{E}[e^{s(M_n-M_0)}] \leq e^{s^2\sum_k c_k^2/2}.

Combining:

P(MnM0t)est+s2ck2/2P(M_n - M_0 \geq t) \leq e^{-st + s^2\sum c_k^2/2}

Optimise over s>0s > 0: set s=t/ck2s = t/\sum c_k^2 to get:

P(MnM0t)exp ⁣(t22ck2)P(M_n - M_0 \geq t) \leq \exp\!\left(\frac{-t^2}{2\sum c_k^2}\right)

\square

N.3 Proof of Polya's Theorem (d=1d=1: Recurrence)

Theorem. The SRW on Z\mathbb{Z} is recurrent.

Proof. It suffices to show the expected number of returns to 0 is infinite: n=1P(S2n=0)=\sum_{n=1}^\infty P(S_{2n}=0) = \infty.

By Stirling's approximation (2nn)4n/πn\binom{2n}{n} \sim 4^n/\sqrt{\pi n}:

P(S2n=0)=(2nn)4n1πnP(S_{2n}=0) = \binom{2n}{n}4^{-n} \sim \frac{1}{\sqrt{\pi n}}

Therefore n=1P(S2n=0)n=11πn=\sum_{n=1}^\infty P(S_{2n}=0) \sim \sum_{n=1}^\infty \frac{1}{\sqrt{\pi n}} = \infty.

By the second Borel-Cantelli lemma (the events {S2n=0}\{S_{2n}=0\} are independent since each depends on distinct steps): P(return to 0 infinitely often)=1P(\text{return to 0 infinitely often}) = 1.

Note: In d3d \geq 3, P(S2n=0)Cd/nd/2P(S_{2n}=0) \sim C_d/n^{d/2} by CLT in Rd\mathbb{R}^d, and Cd/nd/2<\sum C_d/n^{d/2} < \infty for d3d \geq 3 (since d/2>1d/2 > 1). By Borel-Cantelli (first lemma): returns occur finitely often, so the walk is transient. \square

N.4 Proof that the OU Process Has the Correct Stationary Distribution

Theorem. The stationary distribution of dX=θXdt+σdBdX = -\theta X\,dt + \sigma\,dB (μ=0\mu=0) is N(0,σ2/(2θ))\mathcal{N}(0, \sigma^2/(2\theta)).

Proof via Fokker-Planck equation. The probability density p(x,t)p(x,t) satisfies:

tp=x((θx)p)+σ22x2p=θx(xp)+σ22x2p\partial_t p = -\partial_x((-\theta x)p) + \frac{\sigma^2}{2}\partial_x^2 p = \theta\partial_x(xp) + \frac{\sigma^2}{2}\partial_x^2 p

At stationarity tp=0\partial_t p = 0:

0=θx(xp)+σ22x2p0 = \theta\partial_x(xp) + \frac{\sigma^2}{2}\partial_x^2 p 0=θ(p+xxp)+σ22x2p0 = \theta(p + x\partial_x p) + \frac{\sigma^2}{2}\partial_x^2 p

Try p(x)=Z1exp(θx2/σ2)p(x) = Z^{-1}\exp(-\theta x^2/\sigma^2):

xp=2θxσ2p,x2p=(2θσ2+4θ2x2σ4)p\partial_x p = -\frac{2\theta x}{\sigma^2}p, \quad \partial_x^2 p = \left(-\frac{2\theta}{\sigma^2} + \frac{4\theta^2 x^2}{\sigma^4}\right)p

Substituting: θ(12θx2/σ2)p+σ22(2θ/σ2+4θ2x2/σ4)p=[θ2θ2x2/σ2θ+2θ2x2/σ2]p=0\theta(1 - 2\theta x^2/\sigma^2)p + \frac{\sigma^2}{2}(-2\theta/\sigma^2 + 4\theta^2x^2/\sigma^4)p = [\theta - 2\theta^2x^2/\sigma^2 - \theta + 2\theta^2x^2/\sigma^2]p = 0 [ok]

The normalisation gives p(x)=N(0,σ2/(2θ))p_\infty(x) = \mathcal{N}(0, \sigma^2/(2\theta)). \square


Appendix O: Spectral Theory of Stochastic Processes

O.1 Spectral Representation

Every WSS process {Xt}\{X_t\} with absolutely integrable ACVF admits the spectral representation:

Xt=eiωtdZ(ω)X_t = \int_{-\infty}^\infty e^{i\omega t}\,dZ(\omega)

where Z(ω)Z(\omega) is an orthogonal increment process (the spectral process) satisfying E[dZ(ω)dZ(ω)]=S(ω)δ(ωω)dω\mathbb{E}[dZ(\omega)\overline{dZ(\omega')}] = S(\omega)\delta(\omega-\omega')\,d\omega.

This is the stochastic analogue of the Fourier transform: a stationary process decomposes into uncorrelated frequency components, each contributing variance S(ω)dωS(\omega)\,d\omega in the frequency band [ω,ω+dω][\omega, \omega+d\omega].

For AI: The power spectral density of a token sequence determines how information is distributed across "frequencies" (temporal scales). A language model with strong long-range dependencies (like GPT-4 modelling coherent long documents) will have a PSD with high power at low frequencies. Attention head specialisation can be viewed as learning frequency-selective filters - heads that attend to nearby tokens (high frequency) vs. distant tokens (low frequency).

O.2 Spectral Gap and Mixing

For a stationary Markov chain with transition operator PP, the spectral gap γ=1λ2\gamma = 1 - |\lambda_2| (where λ2\lambda_2 is the second-largest eigenvalue of PP) determines the mixing time tmix1/γt_{\text{mix}} \sim 1/\gamma.

  • Large spectral gap -> fast mixing -> samples become independent quickly
  • Small spectral gap -> slow mixing -> long-range correlations persist

For transformers: The attention pattern at each layer can be viewed as a stochastic matrix ART×TA \in \mathbb{R}^{T\times T} (for sequence length TT). The spectral gap of AA determines how quickly information "mixes" across the sequence. Heads with nearly uniform attention (large spectral gap) aggregate globally; heads with peaked attention (small spectral gap) attend locally.


Appendix P: Decision Framework for Choosing Process Models

CHOOSE THE RIGHT STOCHASTIC PROCESS MODEL
========================================================================

  Is the system evolving over time?
  +-- No  -> Use static probability (Section01-Section05)
  +-- Yes ->
        Does the state space have a natural structure?
        +-- Countable (e.g., integer counts, categories)
        |   +-- Discrete time -> Markov chain (Section07)
        |   +-- Continuous time -> Poisson or birth-death process
        +-- Continuous (e.g., parameter vector, embedding)
            +-- Does it have independent increments?
            |   +-- Yes, with Gaussian increments -> Brownian motion
            |   +-- Yes, with jump structure -> Poisson / Levy
            |   +-- No, but stationary -> ARMA or OU process
            +-- Does it decrease toward an attractor?
            |   +-- Yes -> OU process or SDE with drift
            +-- Does it only depend on the current state?
                +-- Yes -> Markov process (continuous time)
                +-- No, depends on full history -> GP or ARIMA

========================================================================

  AI Application -> Recommended Model
  ---------------------------------------------------------------------
  SGD parameter trajectory     -> OU SDE (diffusion approx)
  Mini-batch gradient noise    -> Martingale difference sequence
  Diffusion model forward      -> VP-SDE (discrete OU)
  LLM token generation         -> Markov chain (Section07)
  Request arrivals             -> Poisson process
  Hyperparameter optimisation  -> Gaussian process (Bayesian opt)
  RL value function            -> Martingale transform
  Training loss trajectory     -> Supermartingale
  NTK / infinite-width NN      -> Gaussian process
  Residual stream updates      -> Additive noise SDE
  ---------------------------------------------------------------------

Appendix Q: Connections to Measure Theory

Q.1 Stochastic Processes as Measurable Functions

A stochastic process {Xt}tT\{X_t\}_{t \in T} on (Ω,F,P)(\Omega, \mathcal{F}, P) can be viewed as a measurable function from Ω\Omega to the path space RT\mathbb{R}^T. The probabilistic properties of the process are encoded in the pushforward measure PX1P \circ X^{-1} on RT\mathbb{R}^T.

For Brownian motion: The path space is C([0,))C([0,\infty)) (continuous functions). The Wiener measure WW is the unique probability measure on C([0,))C([0,\infty)) such that Bt(ω)=ω(t)B_t(\omega) = \omega(t) (coordinate process) satisfies the four BM axioms. Constructing WW rigorously is Wiener's 1923 achievement.

Q.2 The Radon-Nikodym Theorem and Change of Measure

If PP and QQ are probability measures on (Ω,F)(\Omega, \mathcal{F}) with QPQ \ll P (Q is absolutely continuous wrt P), then there exists the Radon-Nikodym derivative dQ/dP=ZdQ/dP = Z such that Q(A)=EP[Z1A]Q(A) = \mathbb{E}^P[Z\mathbf{1}_A] for all AA.

Girsanov's theorem: Under mild conditions, if BtB_t is a BM under PP and θt\theta_t is adapted, then:

B~t=Bt+0tθsds\tilde{B}_t = B_t + \int_0^t \theta_s\,ds

is a BM under QQ where dQ/dP=exp(0TθtdBt120Tθt2dt)dQ/dP = \exp(-\int_0^T \theta_t\,dB_t - \frac{1}{2}\int_0^T\theta_t^2\,dt) (the Girsanov kernel).

For diffusion models: Girsanov's theorem is the mathematical basis for the reverse diffusion process. The reverse SDE under the data distribution PP corresponds to a change of measure from the noise distribution QQ (standard BM), with the Radon-Nikodym derivative involving the score function logpt\nabla\log p_t. This makes the score-matching objective the likelihood maximisation objective under the reverse measure.


Appendix R: Supplementary: Concentration and Martingales Revisited

R.1 The Azuma-McDiarmid Connection - Full Detail

In Section3.5 we introduced the Doob martingale construction as the proof of McDiarmid's inequality. Here we make the connection fully explicit.

Setup. Let X1,,XnX_1, \ldots, X_n be independent random variables and f:XnRf: \mathcal{X}^n \to \mathbb{R} satisfy the bounded differences condition: for each kk,

supx1,,xn,xkf(x1,,xk,,xn)f(x1,,xk,,xn)ck\sup_{x_1,\ldots,x_n, x_k'} |f(x_1,\ldots,x_k,\ldots,x_n) - f(x_1,\ldots,x_k',\ldots,x_n)| \leq c_k

Step 1: Doob martingale. Define Mk=E[fX1,,Xk]M_k = \mathbb{E}[f | X_1,\ldots,X_k] for k=0,,nk=0,\ldots,n. Then M0=E[f]M_0 = \mathbb{E}[f], Mn=fM_n = f, and {Mk}\{M_k\} is a martingale.

Step 2: Bounded differences. The martingale difference Dk=MkMk1D_k = M_k - M_{k-1} satisfies Dkck|D_k| \leq c_k a.s. because:

MkMk1=E[fX1,,Xk]E[fX1,,Xk1]supxk,xkE[f(,xk,)f(,xk,)X1:k1]ck|M_k - M_{k-1}| = |\mathbb{E}[f|X_1,\ldots,X_k] - \mathbb{E}[f|X_1,\ldots,X_{k-1}]| \leq \sup_{x_k, x_k'} |\mathbb{E}[f(\ldots,x_k,\ldots) - f(\ldots,x_k',\ldots)|X_{1:k-1}]| \leq c_k

Step 3: Azuma. Apply Azuma's inequality (proved in SectionN.2) to the martingale {Mk}\{M_k\}:

P(fE[f]t)=P(MnM0t)exp ⁣(t22ck2)P(f - \mathbb{E}[f] \geq t) = P(M_n - M_0 \geq t) \leq \exp\!\left(\frac{-t^2}{2\sum c_k^2}\right)

This IS McDiarmid's inequality. The concentration inequality Section05 is a consequence of martingale theory.

R.2 The Freedman Inequality

Azuma's inequality uses only the almost-sure bound Dkck|D_k| \leq c_k. Freedman's inequality (1975) also uses conditional variances, giving a Bernstein-type improvement:

Theorem (Freedman, 1975). Let {Mn}\{M_n\} be a martingale with DkM|D_k| \leq M a.s. Define Wn=k=1nE[Dk2Fk1]W_n = \sum_{k=1}^n \mathbb{E}[D_k^2|\mathcal{F}_{k-1}] (total conditional variance). Then for t,v>0t, v > 0:

P(MnM0t,Wnv)exp ⁣(t2/2v+Mt/3)P(M_n - M_0 \geq t, W_n \leq v) \leq \exp\!\left(\frac{-t^2/2}{v + Mt/3}\right)

This is a martingale version of Bernstein's inequality. The event WnvW_n \leq v restricts to "low variance" trajectories. Unconditionally:

P(MnM0t)exp ⁣(t2/2V+Mt/3) where V=supωWn(ω)P(M_n - M_0 \geq t) \leq \exp\!\left(\frac{-t^2/2}{V + Mt/3}\right) \text{ where } V = \sup_\omega W_n(\omega)

For AI: Freedman's inequality gives tighter bounds for SGD convergence when the gradient variance is small. In the low-variance early-training phase (when the model is near initialisation and gradients are large but consistent), Freedman gives et2/(2v)e^{-t^2/(2v)} bounds tighter than Azuma's et2/(2nM2)e^{-t^2/(2nM^2)}.


Appendix S: Practice Problems (All Levels)

Level * (Computation)

S.1. Let Mn=2SnM_n = 2^{S_n} where SnS_n is the SRW. For what value of pp in the biased walk (P(+1)=pP(+1)=p) is Mn=2SnM_n = 2^{S_n} a martingale?

Answer: E[2Sn+1Sn]=2Sn(2p+(1p)/2)\mathbb{E}[2^{S_{n+1}}|S_n] = 2^{S_n}(2p + (1-p)/2). Set equal to 2Sn2^{S_n}: 2p+(1p)/2=12p + (1-p)/2 = 1, so p=1/3p = 1/3.

S.2. A Poisson process has rate λ=3\lambda = 3 (events per hour). Find P(N(2)5)P(N(2) \geq 5) and the expected time to the 4th event.

Answer: N(2)Poisson(6)N(2) \sim \text{Poisson}(6), so P(N(2)5)=1k=04e66k/k!0.715P(N(2)\geq 5) = 1 - \sum_{k=0}^4 e^{-6}6^k/k! \approx 0.715. Time to 4th event: T4Gamma(4,1/3)T_4 \sim \text{Gamma}(4, 1/3), E[T4]=4/3\mathbb{E}[T_4] = 4/3 hours.

S.3. For the OU process with θ=1\theta=1, μ=2\mu=2, σ=2\sigma=\sqrt{2}, X0=0X_0=0: compute E[X3]\mathbb{E}[X_3] and Var(X3)\text{Var}(X_3).

Answer: E[X3]=2+(02)e3=22e31.9\mathbb{E}[X_3] = 2 + (0-2)e^{-3} = 2 - 2e^{-3} \approx 1.9. Var(X3)=22(1e6)=1e60.9975\text{Var}(X_3) = \frac{2}{2}(1-e^{-6}) = 1-e^{-6} \approx 0.9975.

Level ** (Theory)

S.4. Show that for a martingale {Mn}\{M_n\}, the sequence Mn2[M]nM_n^2 - [M]_n is also a martingale, where [M]n=k=1nE[Dk2Fk1][M]_n = \sum_{k=1}^n \mathbb{E}[D_k^2|\mathcal{F}_{k-1}] is the predictable quadratic variation.

S.5. Prove that if ff is convex and {Mn}\{M_n\} is a martingale, then {f(Mn)}\{f(M_n)\} is a submartingale (using Jensen's inequality).

S.6. For the compound Poisson process X(t)=k=1N(t)YkX(t) = \sum_{k=1}^{N(t)} Y_k with λ=2\lambda = 2, YkExp(3)Y_k \sim \text{Exp}(3): compute the MGF MX(t)(s)M_{X(t)}(s) and use it to find E[X(t)]\mathbb{E}[X(t)] and Var(X(t))\text{Var}(X(t)).

Level *** (AI Applications)

S.7. (Diffusion model noise schedule design) You want a noise schedule βt\beta_t for the DDPM forward process such that the SNR αt/(1αt)\alpha_t/(1-\alpha_t) decreases linearly from SNR0=100\text{SNR}_0 = 100 to SNRT=0.01\text{SNR}_T = 0.01 over T=1000T=1000 steps. Derive the required βt\beta_t and compare to the linear schedule.

S.8. (SGD stationary distribution) In a 2D quadratic loss L(θ)=12θHθL(\theta) = \frac{1}{2}\theta^\top H\theta with H=diag(1,10)H = \text{diag}(1, 10), SGD with step η\eta and gradient noise Σ=I\Sigma = I has stationary distribution N(0,η2H1)\mathcal{N}(0, \frac{\eta}{2}H^{-1}). Show that the ratio of the standard deviations in the two directions is 10\sqrt{10}, and interpret this for optimisation.

S.9. (Martingale in RLHF) In PPO with KL-regularised reward rθ(s,a)=rϕ(s,a)βlog(πθ(as)/πref(as))r_\theta(s,a) = r_\phi(s,a) - \beta\log(\pi_\theta(a|s)/\pi_{\text{ref}}(a|s)), show that the KL penalty term creates a non-martingale perturbation to the policy gradient estimator. Under what conditions on β\beta does the perturbation become negligible?


Appendix T: Theorem Index

TheoremStatementSection
Doob's OSTE[Mτ]=E[M0]\mathbb{E}[M_\tau]=\mathbb{E}[M_0] under UI or bounded conditionsSection3.3
Doob's Maximal InequalityλP(maxMkλ)E[Mn]\lambda P(\max M_k \geq \lambda) \leq \mathbb{E}[M_n]Section3.4, App. N
Martingale ConvergenceL1L^1-bounded martingale converges a.s.Section3.4
Azuma's InequalityBounded differences -> et2/2ck2e^{-t^2/2\sum c_k^2}App. N
McDiarmid's InequalityBounded differences function -> Azuma on Doob martingaleSection3.5
Freedman's InequalityMartingale Bernstein with conditional varianceApp. R
Polya's TheoremSRW on Zd\mathbb{Z}^d: recurrent iff d2d \leq 2Section4.2, App. N
Donsker's TheoremSRW \Rightarrow BM in C([0,1])C([0,1])Section6.3, App. E
Levy CharacterisationContinuous martingale + QV =t= t \Rightarrow BMSection6.2
Ito's Lemmadf(Xt)=fdX+12f(dX)2df(X_t) = f'dX + \frac{1}{2}f''(dX)^2App. A
Wiener-KhinchinACVF \leftrightarrow PSD via FourierSection7.3
Bochner's TheoremPSD is valid iff non-negative definiteSection7.3
Birkhoff ErgodicTime average = ensemble average a.s.Section7.2
Girsanov's TheoremChange of drift = change of measureApp. Q
Fokker-PlanckPDE for density of SDEApp. N
Anderson's Reverse SDEReverse SDE = forward SDE + scoreSection6.6
Clark-Ocone FormulaMalliavin representation on Wiener spaceApp. J
Wald's IdentityE[Sτ]=μE[τ]\mathbb{E}[S_\tau] = \mu\mathbb{E}[\tau]App. L

Appendix U: Continuous-Time Martingales

U.1 Local Martingales

In continuous time, the natural generalisation of a martingale is a local martingale: a process {Mt}\{M_t\} such that there exist stopping times τn\tau_n \uparrow \infty and each stopped process MtτnM_{t \wedge \tau_n} is a martingale.

Every continuous local martingale with M0=0M_0 = 0 can be written as a time-changed Brownian motion (by the Dambis-Dubins-Schwarz theorem):

Mt=B[M]tM_t = B_{[M]_t}

where BB is a standard BM and [M]t[M]_t is the quadratic variation of MM.

The Ito integral 0tHsdBs\int_0^t H_s\,dB_s is a local martingale (and a true martingale when E[0THs2ds]<\mathbb{E}[\int_0^T H_s^2\,ds] < \infty).

U.2 The Martingale Representation Theorem

Theorem (Martingale Representation). Every square-integrable martingale {Mt}\{M_t\} adapted to the Brownian filtration can be written as:

Mt=M0+0tHsdBsM_t = M_0 + \int_0^t H_s\,dB_s

for some adapted process HsH_s with E[0THs2ds]<\mathbb{E}[\int_0^T H_s^2\,ds] < \infty.

For AI: In score-based diffusion model training, the training loss can be expressed as an Ito integral against the Wiener process of the forward noise. The neural network effectively learns the integrand Hs(xs)H_s(x_s) that represents the reverse process. The martingale representation theorem guarantees that such a representation exists - it is the theoretical justification for why neural networks can learn to "undo" Brownian noise.

U.3 Feynman-Kac Formula

For the SDE dXt=b(Xt)dt+σ(Xt)dBtdX_t = b(X_t)\,dt + \sigma(X_t)\,dB_t and function ff, the Feynman-Kac formula relates the SDE to a PDE:

u(x,t)=E ⁣[f(XT)exp ⁣(tTr(Xs)ds)Xt=x]u(x,t) = \mathbb{E}\!\left[f(X_T)\exp\!\left(-\int_t^T r(X_s)\,ds\right)\,\Big|\, X_t = x\right]

satisfies the PDE tu=bxu+σ22xxuru-\partial_t u = b\partial_x u + \frac{\sigma^2}{2}\partial_{xx}u - ru with terminal condition u(x,T)=f(x)u(x,T) = f(x).

For AI: The score function in diffusion models satisfies a backward Kolmogorov equation (the PDE form of the reverse SDE). Feynman-Kac connects this PDE to the expectation form logpt(xt)=E[x0αˉtxt1αˉtxt]\nabla\log p_t(x_t) = \mathbb{E}[\frac{x_0 - \sqrt{\bar\alpha_t}x_t}{1-\bar\alpha_t}|x_t], which is directly implemented by the neural denoiser.


Skill Check

Test this lesson

Answer 4 quick questions to lock in the lesson and feed your adaptive practice queue.

--
Score
0/4
Answered
Not attempted
Status
1

Which module does this lesson belong to?

2

Which section is covered in this lesson content?

3

Which term is most central to this lesson?

4

What is the best way to use this lesson for real learning?

Your answers save locally first, then sync when account storage is available.
Practice queue