Lesson overview | Lesson overview | Next part
Stochastic Processes: Part 1: Intuition and Overview to 10. Common Mistakes
1. Intuition and Overview
1.1 What Is a Stochastic Process?
A stochastic process is a family of random variables defined on a common probability space , indexed by a set called the index set or time set. For each fixed outcome , the mapping is called a sample path or realisation of the process.
The key conceptual shift from classical probability: rather than asking "what is the distribution of ?", we ask "how does the random system evolve over time?" This trajectory-level view captures phenomena that static distributions cannot: memory, feedback, path dependence, and accumulation of information.
Informal classification: The simplest stochastic process is a sequence of iid random variables - no memory, no dependence. More interesting processes have memory (the present depends on the past), structure (the conditional distributions have a specific form), or continuity (sample paths are almost surely continuous). The richest models - Brownian motion, diffusion processes - have all three.
For AI: Almost every quantity that evolves during training or inference is a stochastic process. The parameter vector after steps of SGD is a stochastic process. The hidden state of an RNN at position is a stochastic process. The sequence of tokens sampled from an LLM is a stochastic process. The noise level in a diffusion model forward pass is a stochastic process. Stochastic process theory gives us the mathematical language to reason about all of these rigorously.
1.2 The Central Examples
The five canonical stochastic processes appear throughout mathematics and AI:
-
Simple Random Walk (SRW): where . Discrete time, discrete state space. Models fair gambling, particle diffusion in discrete space, and gradient noise accumulation.
-
Poisson Process: = number of events in , with independent of the past. Continuous time, discrete (integer) state space. Models arrival streams, request queues, neuron spike trains.
-
Brownian Motion (Wiener Process): with , continuous paths, independent of the past. Continuous time, continuous state space. The fundamental building block of continuous-time stochastic processes, and the forward process in diffusion models.
-
Gaussian Process: A process where every finite collection is jointly Gaussian. Fully specified by its mean function and covariance kernel . Foundation of Gaussian process regression (Bayesian nonparametrics) and closely related to neural network functions in the infinite-width limit.
-
Markov Chain: where - the past matters only through the present. Discrete time, arbitrary state space. The backbone of MCMC, reinforcement learning, and language model token generation. Full treatment: Section07 Markov Chains.
1.3 Why Processes Matter for AI
Stochastic process theory provides the theoretical foundation for several pillar areas of modern AI:
Diffusion models (DDPM, DDIM, Score SDE) define a forward process that progressively corrupts data with Gaussian noise - this is literally a discrete-time approximation to the Ornstein-Uhlenbeck SDE. The reverse process learned by the neural network is a time-reversed SDE, and training minimises a score-matching objective derived from Ito calculus.
SGD dynamics can be approximated by a continuous-time diffusion SDE: where is the effective noise temperature proportional to the learning rate divided by batch size. This approximation (Mandt et al., 2017; Li et al., 2017) explains why SGD finds flat minima: the stationary distribution of the SDE concentrates in regions of low curvature.
Reinforcement learning uses the discounted return , which is a function of the trajectory - a stochastic process. The temporal difference error forms a martingale difference sequence under the optimal value function, and TD-learning is an online martingale approximation algorithm.
Gaussian processes are used as priors over functions in Bayesian optimisation (tuning LLM hyperparameters), and the neural tangent kernel theory shows that infinite-width neural networks converge to GPs. RoPE (Rotary Position Embedding) encodes relative position using a stationary kernel - exploiting the wide-sense stationarity machinery developed in Section7.
1.4 Historical Timeline
| Year | Contributor | Result |
|---|---|---|
| 1900 | Louis Bachelier | Modelled stock prices as random walk (Brownian motion) in doctoral thesis |
| 1905 | Albert Einstein | Derived diffusion equation from random molecular motion |
| 1923 | Norbert Wiener | Constructed Brownian motion rigorously on path space |
| 1933 | Andrei Kolmogorov | Axiomatic probability; forward/backward equations for Markov processes |
| 1940 | Paul Levy | Characterised Levy processes; Levy-Khinchin representation |
| 1944 | Kiyosi Ito | Developed stochastic calculus (Ito integral, Ito's lemma) |
| 1953 | Joseph Doob | Martingale theory; optional stopping; convergence theorems |
| 1964 | Skorokhod | Embedding theorem; functional CLT (Donsker's theorem) |
| 1991 | Brockwell & Davis | Time series analysis unified with stochastic process theory |
| 2015 | Ho, Jain & Abbeel | Denoising diffusion probabilistic models (DDPM) |
| 2021 | Song et al. | Score-based generative models via SDEs |
| 2022 | Su et al. | RoPE: positional encoding as stationary kernel |
2. Formal Framework
2.1 Probability Spaces and Filtrations
The rigorous foundation of stochastic processes builds on probability spaces enhanced with a filtration - a formal model of accumulating information.
Definition (Filtered Probability Space). A filtered probability space is a quadruple where:
- is a probability space
- is a filtration: an increasing family of sub--algebras, for all
Intuitively, represents the information available at time - everything that has been observed up to and including time . The filtration captures how information accumulates: knowing more over time means larger -algebras.
Definition (Adapted Process). A stochastic process is adapted to the filtration if is -measurable for each . Intuitively: the value of the process at time is determined by information available at time (not the future).
The natural filtration: Given a process , the natural filtration is - the -algebra generated by the process up to time . Every process is adapted to its natural filtration.
For AI: In online learning, represents the set of training examples seen up to step . The model parameters are -measurable (they depend only on past data). A look-ahead bias - where depends on future data - violates adaptedness and invalidates PAC bounds.
In a causal language model, the token at position is sampled conditioned on all previous tokens - this is precisely the adaptedness condition. Non-causal (bidirectional) models like BERT use a different filtration where includes information from both past and future.
Standard conditions (usual conditions): A filtration satisfies the usual conditions if:
- is right-continuous:
- contains all -null sets (completeness)
These technical conditions ensure stopping times and martingales behave as expected. All filtrations in this section are assumed to satisfy the usual conditions.
2.2 Classification of Stochastic Processes
Processes are classified by the structure of their time set and state space :
TAXONOMY OF STOCHASTIC PROCESSES
========================================================================
State Space S
---------------------------------
Discrete Continuous
---------------------------------
Time Discrete | Markov chains Random walk |
Set T | | HMMs AR(p) models |
| | Galton-Watson trees |
+----------+----------------------------------+
Continuous | Poisson process Brownian mot |
| Birth-death proc OU process |
| Counting processes Diffusion SDE|
---------------------------------
========================================================================
Discrete time, discrete state: Markov chains, hidden Markov models (HMMs used in speech recognition), random walks on graphs. The transition dynamics are described by a stochastic matrix.
Discrete time, continuous state: Random walks in , AR/ARMA time series models, recurrent neural network hidden states. State space is for some dimension .
Continuous time, discrete state: Poisson processes, birth-death processes, queueing models. Transitions happen at random times; between transitions the state is constant.
Continuous time, continuous state: Brownian motion, Ornstein-Uhlenbeck process, general diffusion SDEs. These are the most mathematically sophisticated and most relevant to diffusion models and SGD dynamics.
2.3 Stopping Times
A stopping time (or optional time) formalises the idea of a "decision made using only available information."
Definition (Stopping Time). A random variable is a stopping time with respect to filtration if for all . Equivalently, the decision "stop now" can be made using only information available at the current time.
Examples:
- : constant time - trivially a stopping time
- (first passage time): stopping time (the event is -measurable)
- (last time above level): not a stopping time (requires future knowledge)
The -algebra : For a stopping time , the -algebra at is . This represents "information available at the random time ."
For AI: Early stopping in neural network training is a stopping time: the rule "stop when validation loss hasn't improved for steps" depends only on past validation losses - it is -measurable. In contrast, "stop at the training step that achieves minimum test loss" is NOT a stopping time - it requires knowing future test losses.
In RL, = "the first time the agent reaches the goal state" is a stopping time. Doob's Optional Stopping Theorem (Section3.3) characterises the distribution of - the martingale value at this random time.
2.4 Sample Paths and Almost-Sure Properties
For each fixed , the sample path is an ordinary function of time. The regularity of sample paths (continuity, measurability, boundedness) is crucial for the applicability of theorems.
Path properties:
- Continuous paths: is continuous for a.e. . Example: Brownian motion.
- Cadlag paths (right-continuous with left limits): is right-continuous with left limits for a.e. . Example: Poisson process. Pronounced "cadlag" from French continu a droite, limite a gauche.
- Caglad paths: left-continuous with right limits. Useful in predictable integrands.
Why continuity matters: A process with continuous paths can be approximated by discrete-time processes as the mesh goes to zero - this is the content of Donsker's invariance principle (Section6.3) and justifies the SDE approximation of SGD. A process with only cadlag paths (like Poisson) has discontinuities that cannot be approximated this way.
Almost-sure properties: Properties that hold with probability one (a.s.) are the gold standard. For example, Brownian motion is a.s. nowhere differentiable - every sample path is continuous but has infinite variation everywhere. This non-differentiability is responsible for the scaling of noise in SDEs (Ito's formula) and explains why diffusion model noise scales as rather than linearly in time.
3. Martingales
3.1 Definition and Intuition
The word martingale comes from a gambling strategy: double your bet after each loss. Mathematically, a martingale captures the notion of a "fair game" - the best prediction of the future value is the current value, given everything known so far.
Definition (Martingale). An adapted process with for all is a martingale with respect to filtration if:
The condition says: given all information up to time , the best prediction of is . The process neither drifts up nor down in conditional expectation.
Three types:
- Martingale: - fair game
- Submartingale: - tends upward on average (e.g., convex functions of martingales via Jensen)
- Supermartingale: - tends downward on average
Discrete-time discrete version: is a martingale if for all . This is equivalent to the martingale difference condition: .
Immediate consequence (tower property): For any , . So the mean of a martingale is constant: for all .
3.2 Examples of Martingales
Example 1: Partial Sums of Zero-Mean iid. Let be iid with . Then is a martingale:
Example 2: Products of Unit-Mean iid. Let be iid with , . Then is a martingale:
This is the likelihood ratio (Radon-Nikodym derivative) martingale - fundamental to sequential hypothesis testing and importance sampling.
Example 3: Conditional Expectations. For any integrable and filtration , the process is a martingale (the Doob martingale). This follows directly from the tower property: .
Example 4: Polya Urn. An urn contains red and blue balls. At each step, draw a ball, record its colour, return it with one extra ball of the same colour. Let = fraction of red balls after step . Then is a martingale. The limiting fraction .
Example 5: Squared SRW minus time. The simple random walk satisfies is a martingale (when ):
For AI: The gradient of the expected loss minus the mini-batch gradient estimate is a martingale difference - the fundamental quantity that makes SGD unbiased. The accumulation of these martingale differences over training steps determines the SGD trajectory.
3.3 Doob's Optional Stopping Theorem
Doob's Optional Stopping Theorem (OST) is perhaps the most useful result in martingale theory. It answers: "what is the expected value of a martingale at a stopping time?"
Naively: Since for all , one might expect for any stopping time . This is false in general (e.g., the doubling strategy in gambling can exploit martingale properties without bounded stopping times).
Theorem (Doob's Optional Stopping Theorem). Let be a martingale and a stopping time. Then provided at least one of the following holds:
- is bounded: a.s. for some constant
- and a.s. for some constant
- (uniformly integrable)
Proof sketch (bounded case). . Write , use adaptedness of , and the martingale property . Each cross term vanishes, leaving .
Application: Gambler's Ruin. Symmetric random walk on with absorbing barriers. Start at . Let .
Since is a martingale and is bounded by Wald's identity (it can be shown ):
Also: is a martingale, so , giving .
3.4 Doob's Martingale Inequalities
Beyond Optional Stopping, Doob proved several fundamental inequalities that control the maximum of a martingale.
Theorem (Doob's Maximal Inequality). For a non-negative submartingale and :
Corollary (Doob's Inequality). For a martingale with :
Theorem (Martingale Convergence Theorem, Doob 1953). Every -bounded martingale (i.e., ) converges almost surely to a finite limit .
This convergence theorem is the rigorous foundation for why TD-learning and Q-learning converge under appropriate conditions - the value function updates form a bounded supermartingale under the optimal policy.
3.5 The Doob Martingale Construction
Definition. For a function of independent random variables, define:
Then , , and is a martingale (by tower property). This is the Doob martingale for .
Connection to McDiarmid: The martingale differences are . If has bounded differences , then a.s. Applying Azuma's inequality to the martingale :
This is exactly McDiarmid's inequality - it is Azuma applied to the Doob martingale. The Doob construction thus unifies martingale theory with the concentration inequalities of Section05.
For AI: The empirical risk is a function of independent training examples, each contributing bounded difference. The Doob martingale converges from to , and Azuma gives the McDiarmid generalisation bound .
3.6 Supermartingales and Submartingales
Supermartingales () model processes that decrease in conditional expectation - losing bets, damped oscillators, optimisation algorithms.
Key example: For a Lyapunov function in optimisation, if , then is a "noisy supermartingale." Under appropriate noise control, the Martingale Convergence Theorem guarantees a.s., implying convergence to a critical point.
Submartingales () arise as convex functions of martingales (by Jensen's inequality: convex, martingale submartingale). Examples: , , (for ).
For AI: The training loss trajectory is typically a supermartingale in the early phases of training (decreasing in expectation per step). Plateau phases correspond to near-martingale behaviour. The Doob decomposition theorem guarantees any submartingale can be written as where is a martingale and is a predictable increasing process - this decomposition underlies variance reduction in stochastic optimisation.
3.7 ML: SGD as a Near-Martingale
Consider the SGD update: where is the mini-batch loss. Define = gradient noise.
Since each mini-batch is sampled iid, - the gradient noise is a martingale difference sequence. The noise accumulation forms a martingale.
The diffusion approximation (continuous-time limit): As step size with and fixed, the SGD trajectory converges in distribution to the SDE:
where is the gradient covariance matrix and is a Brownian motion in parameter space. The noise temperature (learning rate / batch size) controls the diffusion coefficient.
Variance reduction methods: SVRG (Stochastic Variance Reduced Gradient) and SAG (Stochastic Average Gradient) reduce to make SGD closer to a true gradient descent. They convert the martingale noise from variance to variance by periodically computing the full gradient. The convergence improvement from (SGD) to (linear convergence of SVRG) directly reflects this martingale variance reduction.
4. Discrete-Time Random Walks
4.1 Simple Random Walk
Definition. The simple random walk (SRW) on is , where (so ).
Distribution: for . By CLT: .
Key identity (Reflection Principle): The number of paths from to that touch or cross the -axis equals the number of all paths from to . This gives:
for integers - approximately for large .
The arc-sine law: The last time the SRW is at 0 before time has a distribution that concentrates near 0 and , not at as intuition suggests. Formally: if , then .
Biased random walk: With , , the walk has drift . It is a submartingale if , supermartingale if , martingale if . The exponential tilting is a martingale for any .
4.2 Recurrence and Transience
Definition. A random walk is recurrent if it returns to its starting point with probability 1; transient if it escapes to infinity with positive probability.
Polya's Theorem (1921). The SRW on is:
- Recurrent for and (probability 1 of returning to origin)
- Transient for (positive probability of never returning)
Proof idea for : The expected number of returns to 0 is by Stirling. Since the expected number of returns is infinite, the walk must return infinitely often (Borel-Cantelli).
Proof idea for : by Stirling, so by Borel-Cantelli the walk returns only finitely many times.
For AI: In gradient descent on a loss landscape with one flat direction (rank deficiency), the gradient is zero in that direction - the component of the iterate in the flat direction performs a random walk. In 2D, this walk is recurrent: training can drift arbitrarily far in the flat direction, explaining parameter growth and the need for weight decay (which adds a restoring force, converting the walk from recurrent to transient).
4.3 Gambler's Ruin
Setup: A gambler starts with dollars, plays a fair game (win/lose \1$N$0$ (ruin).
Result (via OST): Using the martingales and :
- ,
- (expected duration)
Biased gambler (): Use the exponential martingale :
For AI: Gambler's ruin models early stopping in training: the training loss random-walks around a local minimum, and we stop when it either reaches a "good" threshold (success) or explodes (ruin). The expected stopping time motivates why learning rate schedules that reduce the step size as training progresses can reduce expected convergence time.
4.4 ML: Token Sequences as Random Walks
A language model generates tokens sequentially. Conditional on the context, each token selection is a draw from a distribution - making the sequence a stochastic process. The log-probability of a sequence:
is a sum of log-probabilities - a random walk in log-space. The perplexity is the geometric mean of the inverse probabilities, and concentrates around where is the true entropy rate of the language.
Surprise accumulation: The cumulative surprise for a well-calibrated model is a martingale (under the true distribution). If the model is miscalibrated, the surprise process is either a submartingale (model too confident -> underestimates entropy) or supermartingale (model too diffuse). This connects language model calibration to martingale theory.
5. Poisson Processes
5.1 Definition and Characterisation
The Poisson process is the canonical continuous-time counting process - it counts the number of events in an interval.
Definition (Poisson Process). A right-continuous process with is a Poisson process with rate if:
- Independent increments: For any , the increments are mutually independent
- Stationary increments: for all
- Poisson distribution of increments: for
Equivalent characterisation via inter-arrivals: If are the inter-arrival times between successive events, then is a Poisson process iff .
The limit: A Poisson process can be approximated by a Bernoulli process: divide into intervals of length . Place an event in interval with probability independently. As with fixed, this converges to a Poisson process.
Martingale structure: is a martingale (compensated Poisson process). Its quadratic variation is also , so is also a martingale.
5.2 Properties: Superposition and Thinning
Superposition: If and are independent, then . The superposition of independent Poisson processes is Poisson with rate .
Thinning (Coloring): Start with a Poisson process . Independently colour each arrival red with probability and blue with probability . Then the red and blue counting processes are independent Poisson processes with rates and .
Conditioning (uniform order statistics): Given , the arrival times are distributed as the order statistics of iid Uniform random variables. This is the conditional uniformity property - conditioning on the count makes the arrival times maximally spread.
Non-homogeneous Poisson process: Generalise by allowing a time-varying rate : with independent increments. The compensator is (the integrated intensity).
5.3 Compound Poisson Process
Definition. Let be a Poisson process with rate and iid random variables (independent of ). The compound Poisson process is:
Key moments:
- MGF:
For AI: The total compute consumed by serving an LLM API follows a compound Poisson model: requests arrive as a Poisson process, and each request requires a random amount of compute (the "jump size" ). Capacity planning uses compound Poisson theory to compute the required buffer size to handle peak demand with high probability.
5.4 ML: Event Streams and Token Timing
LLM inference event streams: In deployed LLMs, user requests arrive as a Poisson process with rate (requests/second). Under heavy load, the inter-arrival distribution determines queueing behaviour. If token generation takes seconds on average, the system is stable when (arrival rate < service rate) - an M/M/1 queue analysis using Poisson process theory.
KV-cache access patterns: In multi-head attention with prefix caching, the pattern of cache hits/misses follows a complex point process. Poisson approximation applies when individual hit probabilities are small and requests are approximately independent.
Continuous batching: Modern LLM serving (vLLM, TensorRT-LLM) uses continuous batching: new requests join an existing batch as others complete. The batch size at time is a birth-death process - a continuous-time Markov chain with Poisson arrivals and Exponential service times.
6. Brownian Motion
6.1 Definition and Wiener's Axioms
Brownian motion (the Wiener process) is the fundamental continuous-time continuous-path stochastic process. It is simultaneously the limit of rescaled random walks (Donsker's theorem) and the building block for all diffusion processes in modern AI.
Definition (Standard Brownian Motion). A stochastic process is a standard Brownian motion (or Wiener process) if:
- a.s.
- Independent increments: For , the increments are mutually independent
- Gaussian increments: for all
- Continuous paths: is continuous a.s.
Existence: Wiener (1923) proved that such a process exists by constructing it on the space of continuous functions with the Wiener measure. The construction uses Levy's Haar wavelet representation and is one of the foundational results of modern probability.
Finite-dimensional distributions: For , the joint density of is:
with .
Martingale properties: The following are all martingales:
- (mean zero, no drift)
- (variance process)
- for any (exponential martingale / Doleans-Dade)
6.2 Key Properties and Quadratic Variation
Self-similarity: for any . The process "looks the same" at any scale - it is fractal.
Time inversion: (with ).
Non-differentiability: Brownian motion is a.s. nowhere differentiable. Formally: for almost every , the function is not differentiable at any point. This is why stochastic calculus requires the Ito integral - the standard Riemann-Stieltjes integral does not apply.
Quadratic variation: The key property distinguishing Brownian motion from ordinary functions is its quadratic variation:
where the limit is over partitions as the mesh . Informally: . This is the foundation of Ito's lemma and the scaling of stochastic noise.
The Levy characterisation: A continuous martingale with and quadratic variation is a standard Brownian motion. This characterises BM among all continuous martingales.
For AI: The quadratic variation formula explains why diffusion model noise at timestep scales as , not . In DDPM, the forward process adds noise scaled by , where - a discretisation of BM's variance accumulation.
6.3 Brownian Motion as a Limit
Theorem (Donsker's Invariance Principle, 1951). Let be iid with and . Define the continuous interpolation:
Then (convergence in distribution on with the uniform topology), where is standard Brownian motion.
This is the functional central limit theorem - it upgrades the CLT from convergence of individual random variables to convergence of entire paths. The SRW path, rescaled by in space and in time, converges to Brownian motion.
Implications: Any result proved for Brownian motion has a discrete-time analogue for random walks. This transfers insights between the continuous-time theory (SDEs, Ito calculus) and the discrete-time practice (mini-batch SGD, RL).
6.4 Geometric Brownian Motion
Definition. A process satisfies geometric Brownian motion if:
By Ito's lemma applied to :
So .
For AI: GBM models multiplicative noise, which appears in layer-normalisation dynamics. When a transformer residual stream is updated as where , the norm approximately follows GBM, explaining the norm growth observed in deep transformers without proper initialisation.
6.5 Ornstein-Uhlenbeck Process
The Ornstein-Uhlenbeck (OU) process is the unique stationary Gaussian Markov process - and the theoretical foundation for diffusion model forward processes.
Definition (OU SDE). The OU process satisfies:
The drift is a mean-reverting force pulling the process toward .
Solution (via Ito's formula):
Distributions:
- Stationary distribution:
- Autocorrelation: - exponential decay
For AI: The DDPM forward process is , which matches the OU solution with , , (after time reparametrisation). The variance-preserving SDE (VP-SDE) of Song et al. (2021) makes this correspondence exact:
with . The OU process provides the continuous-time foundation for all modern diffusion models.
L2 regularisation as OU: L2 regularisation in gradient descent adds a restoring force to the update, giving a discrete-time OU process for the parameters. The stationary distribution concentrates around with variance (noise / regularisation), explaining why stronger L2 keeps parameters smaller.
6.6 ML: Diffusion Models
The forward process (data -> noise): Given clean data , DDPM defines:
The marginal is where . This forward process is a discretised OU process.
The reverse process (noise -> data): By Bayes' theorem and the Gaussian Markov property:
The network learns to predict the score (or equivalently, the noise ), enabling the reverse process to denoise step by step.
Score matching: The training objective minimises:
This is equivalent to minimising Fisher divergence between and , connecting to information-geometric stochastic process theory.
Continuous-time perspective (Score SDE, Song et al. 2021): The continuous limit is:
- Forward SDE:
- Reverse SDE:
The neural network approximates - the score function - enabling the SDE to run backward from noise to data. This is the unified framework behind DDPM (discrete VP-SDE), DDIM (deterministic ODE), and Consistency Models.
7. Stationary Processes and Ergodicity
7.1 Strict and Wide-Sense Stationarity
Definition (Strict Stationarity). A stochastic process is strictly stationary if for any , any times , and any shift :
The finite-dimensional distributions are invariant under time shifts.
Definition (Wide-Sense Stationarity, WSS). A process is wide-sense stationary (or second-order stationary) if:
- (constant mean)
- depends only on the lag
Examples:
- Strictly stationary but not WSS: -distributed noise with 1 DOF (undefined variance)
- WSS but not strictly stationary: with iid - WSS with ; not strictly stationary since is perfectly periodic with a random phase
- Both: Gaussian processes with stationary kernels; iid sequences
The autocovariance function for a WSS process satisfies:
- Symmetry: (real process)
- Positive semidefiniteness: for all finite sequences
For AI: A WSS process is fully characterised by and - enormously parsimonious compared to the general joint distribution. This is why WSS is the right model for relative position encodings in transformers.
7.2 Ergodicity and the Ergodic Theorem
Intuition: A process is ergodic if "time averages equal ensemble averages" - a single long trajectory captures the full statistical behaviour of the process.
Theorem (Birkhoff's Ergodic Theorem, 1931). For a stationary ergodic process with :
For discrete time: .
What "ergodic" means formally: A stationary process is ergodic if the only time-invariant events have probability 0 or 1 (the -algebra of invariant events is trivial). Equivalently, correlations decay: .
Non-ergodic example: for all , where is fixed once and for all. This is stationary (distribution constant) but not ergodic (time average for any realisation).
For AI: SGD convergence analysis assumes that the gradient noise process is ergodic - the time average of gradient variance equals the ensemble average. If the data distribution shifts during training (non-stationarity), this fails. Continual learning methods address the resulting catastrophic forgetting, which is fundamentally a violation of the stationarity assumption.
7.3 Autocorrelation and Power Spectral Density
Definition. The autocovariance function (ACVF) is . The autocorrelation function (ACF) is , normalised to .
Examples of ACFs:
- iid white noise:
- AR(1) process (, ): - geometric decay
- OU process: - continuous-time geometric decay
- Seasonal process: periodic ACF
Theorem (Wiener-Khinchin, 1934). For a WSS process with absolutely summable autocovariance:
The power spectral density (PSD) is the Fourier transform of and is non-negative: for all .
Conversely, any non-negative integrable function is the PSD of some WSS process (Bochner's theorem). PSD decomposes the variance of a process by frequency: low-frequency components explain slow variation, high-frequency components explain rapid fluctuation.
For AI: The attention mechanism computes . For a stationary input sequence, and , so the attention score between positions and depends (via the input autocorrelation) only on - the relative position. This is the stationarity condition that relative position encodings (ALiBi, T5 bias, RoPE) exploit.
7.4 Gaussian Processes
Definition. A stochastic process is a Gaussian process (GP) if every finite collection is jointly Gaussian. A GP is fully specified by:
- Mean function:
- Covariance kernel:
Notation: .
The kernel determines everything: Properties of the GP sample paths are determined by :
- Smoothness: Matern- kernel controls differentiability ( times differentiable paths)
- Length scale: (RBF/squared-exponential) has length scale
- Periodicity: for periodic processes
Common kernels:
| Kernel | Formula | Properties |
|---|---|---|
| RBF (squared-exponential) | Infinitely differentiable | |
| Matern-1/2 | Continuous but not diff. (= OU) | |
| Matern-3/2 | Once differentiable | |
| Periodic | Exactly periodic | |
| Linear | Bayesian linear regression |
GP Posterior (Bayesian inference): Given observations , :
This is exact Bayesian inference in time (from the Cholesky decomposition of the kernel matrix).
For AI: Bayesian optimisation for hyperparameter search uses a GP prior over the loss surface. The acquisition function (UCB, EI) determines where to evaluate next, and the GP posterior updates after each observation. This is the principled method for tuning LLM training hyperparameters (, , , etc.) when each evaluation is expensive.
Neural tangent kernel (NTK): An infinite-width neural network at initialisation is a GP with kernel determined by the architecture. During gradient descent with small learning rate, the network stays approximately GP (lazy training regime). The NTK determines the learning dynamics via the Gram matrix .
7.5 ML: RoPE and Stationarity in Attention
Wide-sense stationarity of attention: For a sequence of token embeddings , the attention matrix can be made to depend only on the relative position if we choose position encoding appropriately. This is equivalent to making the - inner product a stationary kernel.
RoPE (Rotary Position Embedding, Su et al. 2022): RoPE encodes position by rotating the query and key vectors:
The inner product satisfies:
which depends only on - exactly the stationarity condition! RoPE makes attention score a stationary kernel in position, enabling efficient relative position encoding.
ALiBi and linear bias: ALiBi (Press et al., 2022) adds to each attention logit where is a per-head slope. The resulting attention scores are of the form , where the term is a stationary (translation-invariant) bias. This enables extrapolation to longer sequences - a key advantage when the training distribution has stationarity structure.
8. Preview: Markov Chains
8.1 The Markov Property
A stochastic process satisfies the Markov property if:
The past is irrelevant - the present state is a sufficient statistic for the future. Markov chains are the simplest non-trivial stochastic processes with memory.
Markov chains fit within the stochastic process framework developed here:
- They are adapted to their natural filtration
- The transition function defines a stochastic matrix
- Many Markov chains are martingale transforms: is a martingale if is harmonic for the transition operator
8.2 Forward Reference
Full treatment: Section07 Markov Chains
That section covers: transition matrices, invariant/stationary distributions, detailed balance, recurrence/transience (Markov chain version), mixing times, spectral gap, Perron-Frobenius theorem, reversibility, MCMC (Metropolis-Hastings, Gibbs), and ML applications in language model generation, RL policy evaluation, and PageRank.
9. ML Deep Dive
9.1 SGD Trajectory as Stochastic Process
The parameter sequence produced by SGD is a discrete-time stochastic process with values in . Understanding its properties as a process - not just its endpoint - reveals why deep learning generalises.
The update rule as a random dynamical system:
where is a random mini-batch drawn at step .
Key stochastic process properties:
- is adapted to
- - unbiasedness means the noise is a martingale difference
- is a martingale difference sequence
The diffusion approximation (Mandt et al., 2017): Under small step size and local quadratic approximation , the SGD dynamics converge to:
This is a multivariate OU process with mean-reversion matrix and noise . The stationary distribution is:
Lower learning rate -> smaller stationary variance -> SGD concentrates more tightly around . The ratio determines the noise temperature.
Flat minima and generalisation: The stationary distribution of the SGD SDE concentrates in regions of small Hessian (flat minima). Fisher-Rao information connects to the curvature, and the entropy of the stationary distribution is large for flat minima. This provides a stochastic process explanation for why SGD with large learning rates prefers flat minima that generalise well.
9.2 RL Value Functions as Martingales
In reinforcement learning, the agent at time is in state , takes action , receives reward , and transitions to . The discounted return is:
The Bellman equation: Under a fixed policy , the value function satisfies:
Martingale characterisation: Define . Under the true :
So is a martingale! The TD error is a martingale difference: . TD-learning converges because it performs online martingale approximation - stochastic approximation theory guarantees convergence of martingale difference algorithms under Robbins-Monro conditions.
REINFORCE gradient: The policy gradient estimator is an unbiased estimator of - it is a martingale difference. The baseline reduces variance without introducing bias: since .
9.3 Attention over Sequences
Attention can be viewed as a stochastic process operating over the token sequence:
Token sequence as discrete-time process: with embedding . The attention mechanism at layer computes:
The hidden state is a weighted average of all positions - a generalisation of the conditional expectation .
Causal attention as filtration: In autoregressive generation, causal masking ensures depends only on - maintaining the adaptedness condition to the natural filtration of the sequence. Bidirectional attention (BERT) uses a "global" -algebra that is not filtered.
KV-cache as path memory: The key-value cache stores - the full path of the process up to position . This is the computational realisation of the filtration : at each new token, the model has access to the complete history.
9.4 Diffusion Model Schedules
Different noise schedules in diffusion models correspond to different continuous-time SDEs:
| Schedule | SDE | Marginal |
|---|---|---|
| Linear (DDPM) | ||
| Cosine | Same SDE, different | Smoother transition |
| VE-SDE | ||
| SubVP-SDE | Tighter bounds |
The reverse SDE (Anderson, 1982) is:
where is a backward Brownian motion. The neural network is trained to estimate the score function, enabling the reverse process to convert noise into data.
Consistency Models (Song et al., 2023) learn to map any point on the reverse SDE trajectory directly to the final sample, bypassing the iterative nature of full diffusion. The key insight uses probability flow ODE theory - replacing the stochastic reverse SDE with a deterministic ODE that has the same marginals.
10. Common Mistakes
| # | Mistake | Why It's Wrong | Fix |
|---|---|---|---|
| 1 | "Any increasing family of sets is a filtration" | Filtration requires -algebras, not just sets. A family of sets with has no algebraic structure. | Verify each is a -algebra (closed under complements and countable unions) and for . |
| 2 | "If for all , then is a martingale" | Constant mean is necessary but not sufficient. Non-martingale with constant mean: with Rademacher steps (mean 0, but $\mathbb{E}[M_{n+1} | M_n] = -M_n \neq M_n$). |
| 3 | "OST applies to any stopping time" | Without boundedness or uniform integrability, . The doubling strategy ( = "first win") has and violates OST. | Verify one of the three OST conditions: bounded, + bounded differences, or UI. |
| 4 | "Brownian motion is differentiable since it's continuous" | Continuity does not imply differentiability. BM is a.s. nowhere differentiable (Wiener 1923). Its paths have infinite variation on any interval. | Use Ito calculus () for BM integrals, not classical Riemann-Stieltjes. |
| 5 | "The Poisson process has stationary paths" | Stationarity of increments \neq stationarity of the process itself. - the marginal distribution changes with ; is not stationary. | The compensated process is a martingale; stationarity applies to increments, not levels. |
| 6 | "Strict stationarity implies WSS" | Strict stationarity only implies WSS if the second moment exists. A process with at all times (iid) is strictly stationary but , so WSS is undefined. | Always verify second moment existence before claiming WSS from strict stationarity. |
| 7 | "WSS implies strict stationarity" | WSS is a second-moment condition. Higher-order moments may not be stationary. Example: an AR(1) with non-Gaussian innovations has the same ACVF regardless of the innovation distribution, but higher moments differ with time if innovations have time-varying skewness. | WSS -> strict stationarity ONLY for Gaussian processes (since Gaussians are determined by first two moments). |
| 8 | "The OU process converges to its mean" | The OU process converges to its stationary distribution , not to the constant . It fluctuates around with variance in steady state. | Distinguish convergence of the distribution (to stationary distribution) from convergence of the paths (which remain stochastic). |
| 9 | "Ergodicity means the process repeats" | Ergodicity means time averages equal ensemble averages. An ergodic process does not repeat its paths - it explores the full distribution over time. | Ergodic = time average converges to ensemble average. Periodicity (repeating paths) is a different and usually violated property. |
| 10 | "A GP with RBF kernel can model any function" | RBF GPs have infinitely smooth sample paths. Functions with discontinuities or kinks (like ReLU activations) cannot be well-approximated by RBF GPs. Matern-1/2 (OU) or Matern-3/2 kernels are better for rough functions. | Match kernel smoothness to the smoothness of the function being modelled. Use Matern family for non-smooth functions. |
| 11 | "DDPM forward process is Brownian motion" | DDPM uses a discretised, time-reversed, variance-preserving process. True BM has no mean reversion and linearly growing variance; DDPM's forward process is a discrete OU approximation with . | DDPM forward process \approx discrete VP-SDE (OU); the connection to BM is via Donsker's theorem in the limit , . |