Stochastic Calculus & SDEs (Advanced)
After this lesson, you will be able to:
- Read Brownian motion, Itô's lemma, SDEs and the Fokker-Planck PDE (partial differential equation), and see (dW)² ≈ dt in numbers
- Test numerically whether a candidate density is stationary for an SDE by checking that its probability current is zero
- Write DDPM as the variance-preserving SDE with its reverse-time sampler
Before you start
#Where Part 1 Left Off
q(x_t | x_0), the score, denoising score matching with the Tweedie line, and a reverse chain that turned pure noise into two bumps. None of it needed stochastic calculus. This lesson takes the same story to continuous time. Each small step becomes an instant, the noise becomes Brownian motion, and the chain becomes a stochastic differential equation. It is advanced and optional, and it assumes you have met the score and the discrete reverse chain.#From Discrete Steps to Continuous Time
dW_t like a Gaussian random variable with variance dt" gets you most of the way, and this lesson teaches that heuristic, shows it in numbers, and ends by writing DDPM as one of these equations.#From Random Walks to Brownian Motion
You already know random walks from the Markov chain lesson. Here is the punch line of stochastic calculus: take a random walk, shrink the step size, speed up time, and you get Brownian motion.
dW_t engine produce everything from pure noise to drifting random walks to Geometric Brownian Motion (GBM), a multiplicative version used in finance, for instance behind the Black-Scholes option-pricing formula, which you do not need here.#Three Defining Properties
W_t satisfies:W_0 = 0(start at the origin)- Gaussian independent increments: for any
s < t,W_t − W_s ~ N(0, t − s), and increments over disjoint time intervals are independent - Continuous paths (almost surely), but
W_tis nowhere differentiable
W_t, you see more wiggles, not a tangent line. The path has fractal-like structure all the way down. This is why ordinary calculus fails: there is no dW_t/dt to take a derivative of.A standard Brownian motion W_t has Var(W_t) = t. You simulate W_T over the interval [0, 4] and over [0, 16]. How does the typical magnitude of W_T compare between the two simulations?
#The Heuristic Stochastic Integral
f(t) against the noise dW_t. Discretise time into steps t_0 < t_1 < ... < t_n = T and define:f(t_i) independent of W_{t_{i+1}} − W_{t_i}. That independence yields clean martingale theory. (A martingale is a process with no predictable trend: your best forecast of its future value is its value now, like the running total in a fair coin-toss game.) Using the midpoint gives you the Stratonovich integral, which obeys ordinary chain-rule calculus but loses some of Itô's nice properties. ML almost universally uses Itô.dW_t live in different function spaces), but the discrete heuristic above is the only thing you need for ML papers.Why does the sum of squared increments settle at T instead of shrinking to zero? Open the derivation to see that its average is T and its spread dies out.
The lesson used the fact that the fourth moment of a standard Gaussian is 3. Open the derivation to see it come out of one integration by parts.
#Itô's Lemma (Informally)
X_t evolves according to dX_t = μ dt + σ dW_t, and you want to track Y_t = g(t, X_t), some smooth function of time and the noisy state. In ordinary calculus the chain rule gives dY = (∂g/∂t) dt + (∂g/∂x) dX. In stochastic calculus you get an extra term:(dW_t)² ≈ dt (their variance is dt), not zero. In a Taylor expansion of g(X + dX) around X, the (dX)² term, which would normally be discarded as "higher order", contributes a non-negligible σ² dt. That is the Itô correction.The same two ideas, the Taylor expansion and the rule (dW)^2 = dt, give the general lemma. Open the derivation for the one-dimensional version.
#Seeing the Itô correction in numbers
(dW)² ≈ dt is a claim. Test it on the simplest case, Y = W². The ordinary chain rule says d(W²) = 2W dW. Itô says d(W²) = 2W dW + dt. Adding up both sides from time 0 to T (and W_0 = 0) gives W_T² = 2 ∫ W dW + T.∫ W dW has average zero, so E[W_T²] = T. This agrees with Var(W_T) = T. The ordinary chain rule would predict E[W_T²] = 0, which contradicts it. The extra dt is exactly what fixes the books.dt = 0.25 and let each jump be ±√dt = ±0.5, the coin-flip walk from earlier. Jumps +0.5, −0.5, +0.5, +0.5 give the path W = 0, 0.5, 0, 0.5, 1.0.0.25, so Σ(dW)² = 1.0 = T. The left-endpoint sum is Σ W·dW = 0·0.5 + 0.5·(−0.5) + 0·0.5 + 0.5·0.5 = 0. Then W_T² = 1 = 2 × 0 + 1, exactly the identity.−0.5 four times: W = 0, −0.5, −1, −1.5, −2. Now Σ W·dW = 1.5 and W_T² = 4 = 2 × 1.5 + 1. The squares still add to 1, because they cannot cancel.1, not 0. The two conventions differ by exactly Σ(dW)² = T.(0 + 1) / 2 = 0.5. That equals W_T² / 2 = 0.5, the answer ordinary calculus gives for ∫ W dW. This is Stratonovich. Itô's left endpoint gives 0 = (W_T² − T) / 2. Same path, different integral, so an SDE is only defined once you say which convention it uses.Add the steps and flip the jumps yourself to see the identity hold every time.
This is the cleanest place to see the Itô correction. Open the derivation to build the identity for W squared from one line of algebra.
The cell simulates 20,000 Brownian paths with 1,000 steps each and prints every piece.
E[W_T²] = 0.9960 against the theory 1, an average of the Itô integral term E[2 ∫ W dW] = −0.0035 (standard error 0.0101, so consistent with 0), and an average of the squared increments E[Σ(dW)²] = 0.9995. So −0.0035 + 0.9995 = 0.9960: the whole of E[W_T²] comes from the squared increments, not from the "chain rule" term. The pathwise identity W_T² = 2 ∫ W dW + Σ(dW)² holds to 3.8e-14 on every path. And the sum of squared increments hardly varies from path to path (standard deviation 0.0449 around 1), which is why replacing (dW)² by its average dt is a sound move: it is almost not random at all.(Stratonovich calculus does obey the ordinary chain rule, at the cost of the integrand and the noise becoming statistically dependent. Some physics literature uses it; ML almost never does.)
What is the practical difference between the Itô and Stratonovich interpretations of a stochastic integral for ML purposes?
#Stochastic Differential Equations
g(t, x) was any smooth function you apply to the state. In the SDE below, g(t) is the noise strength. They are unrelated. Part 1 used q(x_t | x_0) for the forward noising and p_t for the marginal density, and this lesson keeps both.dx = -θ x dt + σ dW. It is the "spring plus random kick" model used in physics, neuroscience and finance. Watch the path get yanked back to zero whenever the noise sends it too far.Where does the stationary variance sigma squared over 2 theta come from? Open the derivation to solve the OU equation exactly with Itô's lemma.
Now run the same Euler-Maruyama update yourself: switch between the four models, drag the time cursor, and watch the histogram of X_t beside the paths settle onto the exact density. The diffusion forward process is the one from Part 1: it melts a two-bump "data" distribution into N(0, 1).
U(x) (a landscape in which a small U means a good place to be):β = 1 and U = −log p. Then the drift is ∇log p(x), the score, and the noise is √2 dW. Keep that picture in mind: following the score plus a steady jitter is the Langevin SDE.#Geometric Brownian motion: the Itô correction at work
Geometric Brownian motion (GBM) is the SDE dX = mu X dt + sigma X dW. The noise is proportional to the current size, so X stays positive. It is the cleanest place to see the Itô correction change a number you can measure: the mean of X_T and its median are different.
#The Fokker-Planck Equation
p_t(x) of the state at time t. For an SDE dx = f(x,t) dt + g(t) dW, the density evolves according to the Fokker-Planck equation:Where does this equation come from? Open the derivation for the full argument in one dimension. It uses a test function, a smooth bump that probes the density, and it is a derivation under smoothness assumptions: p_t must be differentiable twice and must decay at infinity.
dx = ∇log p(x) dt + √2 dW, the stationary distribution (the t → ∞ limit of p_t) is exactly p(x). This is the foundation of Langevin sampling. Here is the check, in one dimension, step by step.#Checking stationarity by hand
∂p/∂t = −∂(f p)/∂x + (g²/2) ∂²p/∂x². Group the two terms as one: ∂p/∂t = −∂J/∂x, where J = f p − (g²/2) ∂p/∂x is the probability current, the net flow of probability mass past the point x. If J = 0 everywhere, nothing flows, ∂p/∂t = 0, and the density is stationary.x = −1, 0, +1 holding 0.25, 0.50, 0.25. Use the pull f = −x and write D = g²/2. There are two pipes, at x = −0.5 and x = +0.5.f = +0.5 and the average level is 0.375, so the pump moves 0.5 × 0.375 = 0.1875 to the right. Levelling moves mass from the middle bin to the left bin, D × (0.50 − 0.25) = 0.25 D. So J = 0.1875 − 0.25 D, and the right pipe mirrors it.D = 0.75 both currents are 0, so nothing changes. At D = 1.5 (too much noise) the currents are −0.1875 and +0.1875, and each bin changes at the rate inflow minus outflow: +0.1875, −0.375, +0.1875. After a time of 0.1 the bins read 0.26875, 0.4625, 0.26875. The total stays 1.Slide D to see the pump and the levelling trade off.
f = p′/p and g² = 2 give J = p′ − p′ = 0 for any p. For Ornstein-Uhlenbeck the same condition gives a Gaussian with variance σ²/(2θ): the drift pulls mass inward at rate θ x p, and diffusion pushes it outward at exactly the same rate. Open the derivation to solve J = 0 instead of guessing.J on a grid for the claimed stationary variance and for a wrong one, so you can see that a zero current is a real test.max |J| = 4.59e-06 for the claimed variance 0.32 (zero up to finite-difference error, against a drift flow of size 0.242), and max |J| = 8.07e-02 for the wrong variance 0.48. Only the right variance balances drift against diffusion.Consider the SDE dx = μ dt + σ dW (constant drift, constant diffusion). What kind of process is this?
#Langevin Dynamics: Sampling From p(x)
dx = ∇log p(x) dt + √2 dW has stationary distribution p(x). Discretising this SDE with step size ε gives Langevin dynamics, the universal sampler:#The Reverse SDE: Sampling From Random Noise
f = 0) and noise g = 1, in steps of Δ = 0.1. Start with data of variance 1. Each step adds g²Δ = 0.1 of variance, so the variance reads 1, 1.1, 1.2.x = 1.2, where the variance is 1.2. The score is −x / variance = −1.0. Step one moves it by g² × score × Δ, from 1.2 to 1.1. The variance is now 1.1, so the score is −1.0 again and step two lands on 1.0. This is the average path, with the fresh noise set aside.1.2, 1.108, 1.016, back toward the original 1. A 2,000,000-sample run gives 1.015. With noise only and no score, it goes 1.2, 1.3, 1.4 and keeps spreading.f, the bracket f − g² × score below would contain it too, and stepping backward subtracts the bracket.dx = f(x, t) dt + g(t) dW, the reverse-time SDE is:Why does the score appear in the reverse drift with a g squared in front? Open the derivation to see it fall out of Bayes' rule over one tiny step.
Anderson's formula can also be reached through the Fokker-Planck equation instead of one Bayes step. Open the second derivation. Like the first, it is a derivation under smoothness assumptions: p_t is smooth and positive, and the forward and reversed equations have unique solutions.
#DDPM as the Variance-Preserving SDE
x_t = √(1 − β_t) x_{t-1} + √β_t ε. For a small β_t, √(1 − β_t) ≈ 1 − β_t/2, sox_t ≈ x_{t-1} − ½ β_t x_{t-1} + √β_t εThat is one Euler-Maruyama step of the SDE
(x_t + β_t s)/√α_t + √β_t z ≈ x_t + ½ β_t x_t + β_t s + √β_t z, is one Euler-Maruyama step of the reverse SDE with this f and g: the drift f − g² s = −½ β x − β s is applied backward in time. So DDPM is a discretisation of the variance-preserving SDE, and DDPM sampling is a discretisation of its reverse. Reopen the SDE simulator above, pick the diffusion forward process, and you are watching the forward half of this equation.Why is DDPM this particular SDE, and where does the marginal coefficient a(t) in the code come from? Open the derivation for both.
β(t) rising from 0.1 to 20 over t in [0, 1], 1000 reverse steps and 100,000 samples.a(1) = 0.0066, 50.1% of samples on the right, a right bump with mean 2.003 and standard deviation 0.503, and a left bump with mean −2.001 and standard deviation 0.502. The continuous-time sampler recovers the same two bumps as the discrete one in Part 1, from pure noise.This is the unifying view: DDPM, score-based models, EDM and latent diffusion are all discretisations of the reverse SDE, with some way of parameterising the score. The architecture (U-Net, DiT) is implementation detail; the math is the same.
#Flow Matching: The Deterministic Cousin
v_θ(x, t) such that integrating dx/dt = v_θ(x, t) from noise to data produces samples. It is the same idea (transport mass from a known distribution to data) with less stochasticity and often faster sampling. See the Flow Matching lesson in the Generative AI track for implementation details. The math primitives are the same as in this lesson, minus the dW term.#Bridges to Modern AI
Score-Based Generative Modeling Through Stochastic Differential Equations
Yang Song, Jascha Sohl-Dickstein, Diederik P. Kingma, Abhishek Kumar, Stefano Ermon, Ben Poole (2021)
Denoising Diffusion Probabilistic Models
Jonathan Ho, Ajay Jain, Pieter Abbeel (2020)
#Try It Yourself
Reading about Euler-Maruyama is not the same as writing it. Here you build the solver yourself and point it at the Ornstein-Uhlenbeck process from earlier. Then you measure the discretisation error two ways, so that it shows up clearly instead of drowning in sampling noise. First you compute the error of the Euler scheme exactly, with no randomness at all, by recursion. Then you run a large simulation and check that it lands on the Euler number rather than on the exact one.
Tests: Verify euler_maruyama returns shape (n_paths, n_steps + 1); the Euler-recursion mean error at t = 1 and variance error at T = 6 both shrink steadily as dt falls through 0.2, 0.1, 0.01, 0.001; the dt = 0.1 sample variance lies within a few standard errors of the Euler recursion value 0.2306 but many standard errors from the exact 0.2133; the GBM mean is near 1.105 and its median near 1.057.
t = 1 is 0.4463 and the exact stationary variance is 0.2133. The Euler recursion has no sampling noise, so its errors show the discretisation error alone. The mean error falls from 0.1101 at dt = 0.2 to 0.0525 at 0.1, 0.0050 at 0.01 and 0.0005 at 0.001. The variance error falls from 0.0376 to 0.0173, 0.0016 and 0.0002. Cutting dt by ten cuts the error by about ten: the error is first order in dt. At dt = 0.1 the Euler scheme settles on a variance of 0.2306, about 8% too large, because each step slightly over-counts the noise.dt = 0.1 (seed 42) the sample variance is 0.2323 with a standard error of 0.0015. That is only 1.1 standard errors from the Euler recursion value 0.2306 but 12.9 standard errors from the exact 0.2133. So the simulation reproduces the scheme faithfully, and the scheme itself is biased by the step size. This is the fair way to separate bias from noise: noise shrinks with more paths, bias shrinks with a smaller dt.For geometric Brownian motion over T = 1, one run printed a mean of 1.1018 against the exact 1.1052, and a median of 1.0550 against the exact 1.0565. The mean tracks exp(0.1) while the median sits lower by exp(-0.045), because the volatility drag pulls the typical path below the average one.
#A Final Recap
Part 1 told the whole diffusion story with discrete steps, Gaussians and a gradient, and it needed no stochastic calculus. This lesson rewrote the same story in continuous time:
- Brownian motion is the limit of an infinitely fine random walk: Gaussian independent increments, continuous but nowhere differentiable paths, and quadratic variation equal to T.
- Itô's lemma adds the correction term
½σ² ∂²g/∂x²because (dW)² behaves like dt. Numerically, E[W_T²] = T while E[2 ∫ W dW] = 0. - An SDE is drift plus diffusion,
dx = f dt + g dW, simulated by Euler-Maruyama. Ornstein-Uhlenbeck and geometric Brownian motion are the two examples to remember. - Fokker-Planck tracks the density, and a zero probability current shows that the SDE
dx = ∇log p dt + √2 dWhas stationary density p, which is why Langevin dynamics samples. - DDPM is the variance-preserving SDE, and its sampler is Euler-Maruyama on the reverse-time SDE
dx = [f − g² score] dt + g dW̄.
dx_t.#Quick Check
What is the defining property of Brownian motion that makes it different from a smooth function?