26.4 Stochastic Differential Equations
Every trajectory in the previous sections was fixed by its start, and a flow never forgets where it came from: two starts always reach two different ends. The diffusion models of Chapter 17 are built on a process that does forget. Their forward process mixes new noise into its state, a little at a time, until nothing of the start remains, and generation, which runs it backward, has a known place to begin. Such a process solves a differential equation too, but not one that ordinary calculus can handle.
Let us begin with a case small enough to follow by hand. Take one number, . At each step keep of it and add an independent Gaussian draw of standard deviation :
After steps the mean is , and the variance is close to , where the that a step removes balances the that it adds. Any other start ends in the same place, a draw from nearly . One feature of the recurrence looks odd. If it describes a process in continuous time with time step , then the decay changes by an amount of order , but the noise has size , not . This choice is forced. Noise of size would vanish as , while noise of size survives, and its square is of order , the same order as the drift. Ordinary calculus discards squares of small changes, so this one fact requires a new calculus.
The limit of such noise is Brownian motion, named after the botanist Robert Brown, who in 1827 watched particles from pollen grains jitter in water. Norbert Wiener made it a mathematical object in 1923, and Kiyoshi Itô built its calculus in the 1940s (Itô, 1944) on one rule: the squares of short Brownian increments add up to the elapsed time, so the chain rule gains a second-derivative term.
We build Brownian motion from coin flips and the calculus from that rule. Then we solve the process behind the recurrence, the forward process of Section 17.2. Given the start, its distribution at every time is a Gaussian, so a diffusion model can noise its data to any level in one draw. Simulation, and the measurement of its error, can wait for a second reading. Only the rule for squares is hard to believe, and its proof takes six lines.
26.4.1 Brownian Motion#
26.4.1.1 Noise as a Forward Process#
Before building any machinery, let us check what a forward process must do. Starting from data distributed as , it must end at one known distribution, whatever the data looked like,
so that generation always knows where to start. No fixed flow does this for two datasets at once. A flow is an invertible map (Section 26.1), so if it carried two distributions and to the same one, applying would show .
Let us try three processes on two "datasets" that are as simple as datasets can be: point masses at and at .
- Drift alone, . The solution puts the two starts at at . They approach the point , which is not a Gaussian, and at every finite time they are still two distinct points.
- Noise alone, , which means for a noise whose variance grows linearly in time (the next subsection constructs it). The distribution of , its law, is : each cloud keeps its center at while its standard deviation grows without bound ( at ). The start is forgotten only relative to this growing width, and there is no limiting law.
- Both together, . From either start the law at is , as Section 26.4.3 proves. The two laws are nearly indistinguishable from each other and from .
One failure, one usable process and the one we use, from the two starts . Drift alone sends every start to the point . Noise alone keeps each start as the center of a cloud whose two-standard-deviation envelope (dashed) grows without bound. Both together carry every start into the same limiting law , drawn sideways at the right. Green lines are the means.
Figure 26.4.1 draws the three. Only the first fails outright. The second is usable, and is in use. Once its variance is far larger than that of the data, the start hardly matters. Processes of this kind are called variance-exploding, because without a limiting law they must make their final variance huge. The third is the running example of this section, and the recurrence of the opening simulates it. Its drift pulls each start toward zero while the noise refills the variance that the drift removes, and the two balance at variance .
In general, a forward process of this kind is a deterministic vector field plus a noise term. For data in we write
which reads: over a short time , the state moves by the velocity times and receives a random kick whose size is set by the noise amplitude . The drift steers the mean, and the diffusion injects variance. So far the kick is only a symbol. We give it a meaning in one coordinate, and return to only at the end of the Itô calculus.
26.4.1.2 From Random Walks to the Wiener Process#
We put an object behind the symbol by taking the limit of the simplest random process there is, a walk driven by coin flips. The limit explains the square root in our recurrence.
Fix a step duration and let a walker take independent steps of size , each sign chosen by a fair coin. After steps, at time , the position is a sum of independent mean-zero steps of variance apiece. Variances of independent terms add (Section 24.2.2.1), so
whatever the step size. With , for instance, steps of give variance at time . Steps of on the same clock would give variance , and steps of would give . In general, steps of size give variance at time , which tends to for and to for . Only the square root leaves a finite nonzero variance in the limit, which is why it returns in the noise term of every numerical scheme below.
As the number of steps before time grows without bound, and the central limit theorem (Section 24.3.2.3) makes the position Gaussian: a sum of many independent mean-zero terms with total variance is approximately .
The limit process is called Brownian motion or the Wiener process (Wiener, 1923). It is defined by four properties:
- ;
- independent increments: for , the increment is independent of the entire path up to time ;
- Gaussian increments: ;
- continuous sample paths.
That a process with these properties exists is Wiener's theorem, and that the rescaled walks converge to it is Donsker's theorem; we take both as given. The process spreads with standard deviation forever (Figure 26.4.2), and its increments have the form
a standard normal draw scaled by .
One coin-flip walk of steps , viewed on meshes , and (faint gray: the full path). Each view is itself a random walk with step variance ; refining the mesh fills in detail without changing the large-scale path. At each fixed time the spread follows the and envelopes.
Independent increments also fix how the values of at two times are related. For write . The increment is independent of and has mean zero, so : the walk carries its position at time forward and adds noise that is uncorrelated with it. The formula is worth more than its one-line proof suggests. Jointly Gaussian values are determined by their means and covariances, so a process with jointly Gaussian values at any finite set of times, mean zero, covariance and continuous paths is a Brownian motion.
The same increments make the path rough. Brownian paths are continuous but nowhere differentiable, a theorem of Paley, Wiener, and Zygmund (Paley et al., 1933). The increment scaling (26.4.2) gives the heuristic reason:
so a difference quotient grows without bound as the step shrinks. This is not a proof (it rules out a derivative at each fixed time, while "nowhere" concerns all times at once), but it shows the obstruction.
Rescaling time by a factor and space by returns a Brownian motion (Exercise 2), so zooming in on a path shows the same roughness at every scale, where a differentiable curve would flatten into its tangent. Hence does not exist, and has to be given a meaning inside integrals. The Itô calculus supplies that meaning.
26.4.1.3 Simulation of Brownian Paths#
The increment form (26.4.2) is also a simulation recipe: take cumulative sums of steps. We generate paths on in steps and put a question to them. At any one time , so of the paths lie inside , the outer envelope of Figure 26.4.2. What fraction stays inside the envelope at all times? It is worth a guess before running the cell.
rng = np.random.default_rng()
T_bm, n_bm, n_paths = 1.0, 500, 20000
dt_bm = T_bm / n_bm
dW_bm = np.sqrt(dt_bm) * rng.standard_normal((n_paths, n_bm))
W_bm = np.cumsum(dW_bm, axis=1) # W at t = dt, 2 dt, ..., 1
band = 2 * np.sqrt(dt_bm * np.arange(1, n_bm + 1)) # 2 sqrt(t) on the grid
inside = np.abs(W_bm) < band
print(f'inside +-2 sqrt(t) at t = 1: {inside[:, -1].mean():.3f}'
' (Gaussian: 0.954)')
for stride in (10, 1): # same paths, coarse then fine grid
print(f'inside at all {n_bm // stride} grid times: '
f'{inside[:, stride - 1::stride].all(axis=1).mean():.3f}')inside +-2 sqrt(t) at t = 1: 0.954 (Gaussian: 0.954)
inside at all 50 grid times: 0.697
inside at all 500 grid times: 0.535
At the single time the fraction is about , as it must be. But only about seven paths in ten are inside at each of equally spaced times, and only a little over half at all . A band that holds at each time does not hold for a path: every look is another chance to find the path outside. Watched at every instant, no path stays inside, since near a Brownian path crosses again and again (the law of the iterated logarithm, which we do not prove). A statement about the law at one time is much weaker than a statement about whole paths, and the two return as the weak and the strong error of a simulation (Section 26.4.4.2).
26.4.2 Itô Calculus#
26.4.2.1 Quadratic Variation#
Ordinary calculus stops its Taylor expansions at first order because the square of a small change is negligible. For Brownian motion this fails, and the result of this subsection says by how much. It is the one on which the rest of the section rests.
Take a partition with increments and mesh , and add up the squared increments of a path along it. For a differentiable path with , the mean value theorem gives , so
as the mesh shrinks: a smooth increment squared is of order . A Brownian increment squared is of order , since , and these add up to however fine the mesh (Figure 26.4.3). The sum is random, but its fluctuations vanish in the limit.
Proposition (quadratic variation of Brownian motion). As the mesh ,
Proof. Each increment is , so and for every partition. For the spread, a Gaussian has fourth moment , so ; the increments are independent, so their variances add:
and mean-square convergence follows.
The statement deserves a second look: every increment is random, and in the limit the sum of their squares is not. On a uniform grid with intervals of the proof gives the sum a standard deviation of , which is for and for .
Running sums of squared increments along one Brownian path for meshes of , , and intervals (darker shades are finer meshes). The sums approach , whereas the sums for the smooth path (gray) shrink like .
The proposition is usually written as the Itô multiplication table, the working rules for products of differentials:
The first rule is (26.4.3) in shorthand, and it is a statement about sums. A single squared increment is , which is rarely close to : about one time in four it is below a tenth of , and about one time in six it is above twice . Only the sum over many steps settles, as the proof showed. (For the coin-flip walk every squared step equals , and nothing needs to settle.) The other two rules record that , of size , and vanish faster than and contribute nothing in the limit.
At fine meshes the fluctuations are so small that a single path shows the limit. We sample a path on intervals of , view it on coarser subgrids, and print its sum of squares next to the predicted standard deviation. For comparison we print the same sum for the smooth path next to , the mesh times .
n_fine = 2**18
dW_qv = np.sqrt(1.0 / n_fine) * rng.standard_normal(n_fine)
W_qv = np.concatenate([[0.0], np.cumsum(dW_qv)])
print(f'{"n":>7} {"QV of W":>8} {"sqrt(2/n)":>10} {"QV of sin":>10}'
f' {"2 pi^2/n":>9}')
for k in range(4, 19, 2):
n = 2**k
W_n = W_qv[::n_fine // n] # the same path on a coarser grid
s_n = np.sin(2 * np.pi * np.linspace(0, 1, n + 1))
print(f'{n:7d} {np.sum(np.diff(W_n)**2):8.4f} {np.sqrt(2 / n):10.4f} '
f'{np.sum(np.diff(s_n)**2):10.6f} {2 * np.pi**2 / n:9.6f}') n QV of W sqrt(2/n) QV of sin 2 pi^2/n
16 1.1551 0.3536 1.217927 1.233701
64 0.9103 0.1768 0.308177 0.308425
256 0.8957 0.0884 0.077102 0.077106
1024 0.9560 0.0442 0.019277 0.019277
4096 1.0044 0.0221 0.004819 0.004819
16384 0.9893 0.0110 0.001205 0.001205
65536 1.0007 0.0055 0.000301 0.000301
262144 1.0017 0.0028 0.000075 0.000075
The Brownian column scatters around with the standard deviation that the proof predicts. On intervals it typically lands between about and , and at it is within about of . The smooth column is still at , but it shrinks like and agrees with that prediction to three digits from on.
26.4.2.2 The Itô Integral#
The rough path forces us to define integrals against directly. We start with the simplest one, , and find that the usual Riemann-sum definition does not single out an answer.
For a smooth integrator, Riemann sums with the integrand evaluated at the left endpoint, the right endpoint, or the midpoint of each interval all converge to the same limit. Here they do not. With itself as the integrand, the right-endpoint sum exceeds the left-endpoint sum by
by the proposition just proved. The two discretizations of "the same" integral disagree by a finite, deterministic amount. Let us look at one path with steps.
n_lr = 1000
dt_lr = 1.0 / n_lr
t_lr = np.linspace(0, 1, n_lr + 1)
dW_lr = np.sqrt(dt_lr) * rng.standard_normal(n_lr)
W_lr = np.concatenate([[0.0], np.cumsum(dW_lr)])
left = np.sum(W_lr[:-1] * dW_lr) # integrand at the left endpoint
right = np.sum(W_lr[1:] * dW_lr) # integrand at the right endpoint
print(f'left sum {left:.4f} right sum {right:.4f}')
print(f'right - left {right - left:.4f} sum of (dW)^2 {np.sum(dW_lr**2):.4f}')left sum -0.3614 right sum 0.6124
right - left 0.9738 sum of (dW)^2 0.9738
The left sum is a random number that changes from run to run. The right sum exceeds it by the sum of squared increments in every printed digit, as the identity above says it must. What the run adds is the size of the gap. It usually lies within about of (its standard deviation is ), and a finer mesh would not close it.
Both sums have limits, and we can find them with what we have. Their total telescopes, because adds up to on every partition, and their difference tends to . Hence the left sum tends to and the right sum to , in mean square. Ordinary calculus would answer , which is neither limit but their average. We must choose an evaluation point, and the choice changes the answer. Which of the two sums should be the integral?
Itô's choice is the left endpoint, so that the integrand never sees the coming increment. A fair game explains why. Think of as the outcome of the -th fair bet and of as the stake placed on it. A gambler must choose the stake from what is known at time , before the bet is settled, and the total winnings are . Because the increment is independent of everything known at , including , each bet has expected winnings , so no betting strategy has positive expected winnings. A stake that could peek at the outcome would make money on average. The right-endpoint sum places such a stake, and its mean is indeed , not zero.
The definition writes this rule down. An integrand is predictable if its value on each interval is decided before the increment over that interval is drawn. A simple predictable process is constant on each interval, for , where is determined by the path up to time and . Its Itô integral is the sum of the winnings,
The fair-game argument shows that it has mean zero, . Its variance is computable as well.
Proposition (Itô isometry). For a simple predictable ,
Proof. Expand the square of the sum in (26.4.5). The step that needs care is the cross terms. A cross term with contains the factor , which is independent of everything known at time , including the product . So the expectation factorizes: . A diagonal term factorizes the same way into . Summing the diagonal gives .
The isometry also carries the definition beyond step processes, to integrands such as itself. It says that preserves the norm . So if simple predictable processes converge to in this norm, their integrals converge in mean square, and the limit is taken as the definition of . The zero mean and the isometry survive the limit and hold for every predictable of finite norm, and the left-endpoint sums of a continuous integrand of this kind converge to its integral. We do not prove these statements; see Øksendal (2003), chapter 3.
The integral we started from now has a value, the limit of its left-endpoint sums:
This is the answer of ordinary calculus minus . The gives it the mean zero that a fair game must have, since . The isometry can be checked on it too. It turns the variance of a noise integral into an ordinary integral of a second moment, here at , and the closed form agrees: is a squared standard normal, with variance , so .
The other evaluation points define other integrals. The midpoint choice, or the average of the left and right sums, defines the Stratonovich integral (Stratonovich, 1966). It obeys the ordinary chain rule, as the average above suggests, but gives up the zero mean, because its integrand sees half of the coming increment. This book uses Itô's convention, for two reasons: the zero mean makes expectations easy, and the simplest simulation step, which evaluates the coefficients at the start of the step, is an Itô sum (Exercise 6).
26.4.2.3 Drift, Diffusion, and Solutions#
With the integral in hand, the forward-process template (26.4.1) acquires a meaning. A stochastic differential equation is written
and the differential form is shorthand for the integral equation
an ordinary integral plus an Itô integral. Over a short step, with the coefficients frozen at its start, and . So the drift is the conditional mean velocity, and the diffusion coefficient sets the rate at which variance is pumped in. With the equation is the ODE of Section 26.1, and with and a constant it is the noise-only process of Figure 26.4.1.
What is a solution? For an ODE it is one curve. Here it is one curve for each Brownian path. If and are Lipschitz in and grow at most linearly, , and is independent of with , then the start and the Brownian path determine the solution path uniquely (Øksendal (2003), Theorem 5.2.1). The proof is a stochastic version of the Picard iteration of Section 26.1.1.3, with the isometry in place of the integral bound. All the randomness therefore sits in . Running the equation many times from the same start with fresh noise gives a cloud of paths like those of Figure 26.4.1, and what a generative model cares about is the law of the cloud at each time.
One distinction will matter when we simulate. Noise is additive if its amplitude depends on time only, , as in the template (26.4.1) and in every diffusion-model SDE of this chapter, the running example among them. It is multiplicative if the amplitude depends on the state, , as for a stock price whose fluctuations are proportional to its level. The difference looks cosmetic, but it decides how accurately a simulated path follows the true one (Section 26.4.4.2).
26.4.2.4 Itô's Lemma#
To compute with an SDE we need the chain rule: if solves an SDE, what equation does a function solve? The ordinary chain rule would give , and we know that this is wrong, since by (26.4.7). Something is missing.
One step of a walk shows where the missing term comes from, and what it is for other functions. Take and one step from , each sign with probability . The average of after the step is
since . The rise comes from the square of the step, which for a coin flip is every time, and which the ordinary chain rule throws away.
With and the step lands at or , where is or . The average lies above by (Figure 26.4.4). A convex function gains from symmetric noise, and because a squared Brownian increment is of order , the gain per unit time, , does not vanish in the limit.
The Itô correction as Jensen's gap. One step of from moves a convex to an average that lies above by ; here , , , and the gap is .
The general formula comes from the same computation. Let solve and let be smooth. A small change of , expanded to second order because first order is no longer enough, is
Substitute and multiply out with the table (26.4.4):
The drift and cross terms vanish, and the noise term survives at first order. Collecting terms gives the chain rule of stochastic calculus. What we have given is a heuristic derivation, so we state the result as a theorem without proof.
Theorem (Itô's lemma). Let solve under the conditions of the previous subsection, and let , once continuously differentiable in time and twice in the state. Then satisfies
This is the working formula of the subject: the ordinary chain rule, plus half the second derivative times the rate at which variance arrives. The new term is called the Itô correction. The proof has to control the remainder terms of the Taylor expansion in mean square (Øksendal (2003), chapter 4), and it needs both derivatives in the state: the lemma does not apply as stated to a function with a kink, such as .
Example 1: . Take (so , ) and . The lemma gives , with the that the ordinary chain rule dropped. In integrated form this is , which is (26.4.7) again. One line of the lemma has replaced the telescoping sums.
The correction can be watched as it accumulates. On any grid the gap between and the left-endpoint sum for telescopes, , so it is the running quadratic variation and should follow the line . We reuse the path of the left and right sums.
ito = np.concatenate([[0.0], np.cumsum(2 * W_lr[:-1] * dW_lr)]) # int 2W dW
gap = W_lr**2 - ito
print(f'final gap W_1^2 - int 2W dW = {gap[-1]:.4f} (Ito correction: t = 1)')
print(f'max |gap_t - t| along the path = {np.abs(gap - t_lr).max():.4f}')
d2l.plot(t_lr, [W_lr**2, ito, ito + t_lr], 't', 'value',
legend=['$W_t^2$', 'naive $\\int_0^t 2W\\,dW$',
'$\\int_0^t 2W\\,dW + t$'], figsize=(5, 3))final gap W_1^2 - int 2W dW = 0.9738 (Ito correction: t = 1)
max |gap_t - t| along the path = 0.0364
The curve labeled naive is the Itô integral , which the ordinary chain rule would take for . It sags below , and adding puts it back on top. Along the whole path the gap usually stays within about of , since by the proof of (26.4.3) its standard deviation at time is on this grid. At the gap is the sum of squared increments that the earlier cell printed.
Example 2: geometric Brownian motion. The SDE with models a quantity that grows at mean rate with noise proportional to its size. It is Samuelson's model of a stock price (Samuelson, 1965), on which the option-pricing formula of Black and Scholes rests (Black and Scholes, 1973). Its noise is multiplicative. Apply the lemma to , with , , and . The logarithm is smooth only for , so assume for the moment that stays positive:
The formula we obtain is positive, and the lemma applied to it as a function of and confirms that it solves the equation, which removes the assumption. The is the correction with : a concave function loses from symmetric noise. Noise therefore lowers the typical growth rate below the mean growth rate , and Exercise 3 shows how far the mean and the median of drift apart. We will measure simulation errors against this exact solution.
In several dimensions the pattern is the same, and we take the result as given (Øksendal, 2003). For with , a matrix , and a Brownian motion whose coordinates are independent scalar Brownian motions, the multiplication table reads , and a twice continuously differentiable satisfies
The correction weights each second derivative by the covariance rate of the noise. The diffusion-model SDEs of this chapter treat every coordinate alike, , and for them it reduces to , a multiple of the Laplacian of . The next section needs the lemma in this form.
26.4.3 The Ornstein--Uhlenbeck Process#
The running example now gets its name and its solution. The Ornstein--Uhlenbeck (OU) process (Uhlenbeck and Ornstein, 1930) is
the decay ODE of Section 26.1.2 with noise of constant amplitude added. Its authors wrote it for the velocity of a particle that is kicked by molecules and slowed by friction. The drift pulls excursions back toward zero at rate , and the noise keeps producing new ones (Figure 26.4.5). The recurrence of the opening is this process with and , advanced on a grid with step by freezing the drift over each step: one step multiplies by and adds noise of standard deviation .
Mean reversion. The drift (arrows) pulls every path toward at rate while noise of amplitude keeps it moving; paths from three starts forget them within a few multiples of and then fluctuate inside the band of two standard deviations of the limiting law, (labeled stationary). Right: its density.
26.4.3.1 The Transition Kernel#
The OU process is one of the few SDEs whose law is known in closed form at every time, and this is why diffusion models are built on it. The law of given the start , read as a function of the start, is called the transition kernel (no relation to the kernels of a convolution). For the OU process it is Gaussian. Of all the results of this section, this is the one the rest of the book uses most.
Proposition (OU transition kernel). For the OU process (26.4.12),
Proof. The integrating factor solved the decay equation with an input in Section 26.1.2.3 (by the variation of constants formula), and it works when the input is noise. Apply Itô's lemma (26.4.9) to , for which , , and , so there is no correction:
The drift cancels, and integrating from to and multiplying by gives
The remaining integral has a deterministic integrand, so it is a limit of weighted sums of independent Gaussian increments and is Gaussian with mean zero (we grant that mean-square limits of Gaussians are Gaussian). The Itô isometry (26.4.6) gives its variance:
The solution (26.4.14) reads as a fading memory. The start decays at rate , and a noise kick from time survives with weight : recent noise counts, old noise is forgotten. In the recurrence a kick from steps ago survives with weight . Every later section, and Section 17.2 in the main text, writes the kernel with two coefficients, the mean factor and the standard deviation,
The data enter only through the mean , and the noise only through the variance . For the running example (, , ) started at , the kernel is at , at , and at . Because the kernel is Gaussian at every time and for every start, everything about the noised state given its start is known in closed form, including the gradient of its log-density, . Generation will turn out to depend on this gradient.
The recurrence is only a discretization of the process, so its cloud should follow the kernel closely but need not follow it exactly. We run it as a plain loop on copies of , save the cloud at five times, and print its mean and standard deviation next to and , together with the fraction of the cloud inside .
theta_ou, g_ou, h_ou = 1.0, np.sqrt(2.0), 0.01
X_ou = np.full(10000, 2.0) # 10,000 copies of x_0 = 2
snap_steps = {round(t / h_ou): t for t in (0.5, 1.0, 1.5, 2.0, 4.0)}
X_ou_snap = {}
for k in range(1, 401):
xi = rng.standard_normal(X_ou.size)
X_ou = (1 - theta_ou * h_ou) * X_ou + g_ou * np.sqrt(h_ou) * xi
if k in snap_steps:
X_ou_snap[snap_steps[k]] = X_ou.copy()
print(f'{"t":>4} {"mean":>6} {"2alpha_t":>8} {"std":>6} {"sigma_t":>7}'
f' {"inside":>7}')
for t, X in X_ou_snap.items():
alpha_t = np.exp(-theta_ou * t)
sigma_t = np.sqrt(g_ou**2 / (2 * theta_ou) * (1 - alpha_t**2))
inside = np.mean(np.abs(X - 2 * alpha_t) < 2 * sigma_t)
print(f'{t:4.1f} {X.mean():6.3f} {2 * alpha_t:8.3f} {X.std():6.3f} '
f'{sigma_t:7.3f} {inside:7.3f}') t mean 2alpha_t std sigma_t inside
0.5 1.209 1.213 0.803 0.795 0.951
1.0 0.733 0.736 0.943 0.930 0.955
1.5 0.433 0.446 0.968 0.975 0.957
2.0 0.259 0.271 0.992 0.991 0.953
4.0 0.042 0.037 1.012 1.000 0.952
Means and standard deviations agree with the kernel within two or three standard errors (about for a mean and for a standard deviation from samples). About of the cloud lies inside the band at every time, as for any Gaussian. The cloud that began as the single point widens quickly and then stops widening. At this sample size the discretization cannot be seen.
26.4.3.2 The Stationary Distribution#
A forward process must forget its start, and the kernel (26.4.13) shows that the OU process does. As the mean decays to zero and the variance approaches , so
This is the endpoint, the same for all data, that Section 26.4.1.1 asked for. The limit is more than an endpoint. A process started in it stays in it, and a law with this property is called stationary. To see it, let be independent of . By (26.4.14), is then the sum of and an independent Gaussian of variance , hence Gaussian with mean zero and variance
The decay of the start removes as much variance as the noise adds. How long does the forgetting take? Its time scale is , the relaxation time, and after a few multiples of it is negligible. For the running example and , so the stationary law is , and by the mean had fallen from to .
The recurrence has a stationary law of its own, and it is slightly different. One step maps a variance to . From a step of the running example gives , slightly more than , and the fixed point of the map is
The recurrence therefore settles half a percent above the exact variance . No cloud of points can show half a percent, but the pencil can. This is the first sign of a discretization error, and Section 26.4.4.2 shows that it shrinks in proportion to .
26.4.3.3 The Variance-Preserving Normalization#
The stationary variance is a free parameter, and diffusion models fix it to by choosing
The running example makes this choice. With it , so one coefficient describes the kernel.
So far the start was a single number . Let it now be a draw from the data. In distribution, the solution (26.4.14) then reads with a standard Gaussian independent of . The law of this , which is the kernel averaged over the data, is called the marginal at time . Most papers write it with another letter. They follow the denoising diffusion probabilistic model (DDPM) of Ho et al. (2020), the discrete-time diffusion model of Section 17.2, which writes for our . The main text does the same, and so do we:
The marginal is a weighted mix of data and fresh noise, with weights whose squares add to one. Suppose the data have zero mean and unit variance. Taking variances of the two independent terms gives
This is what variance-preserving (VP) means. For unit-variance data the marginal variance equals at every time, not only in the limit. The process moves variance from the data to the noise, a fraction still carried by the data and already replaced by noise, without changing the total. The name is accurate for unit-variance data only. For data of variance the marginal variance drifts from to (Exercise 5), so the scale of the data matters. Images scaled to , as in Section 17.1, have variance below one, while latent diffusion models rescale their latents to about unit variance (Rombach et al., 2022).
The variance is preserved; the shape of the distribution is not. Take data that are with probability each, the outcome of a coin flip. Their fourth moment is , against for a standard Gaussian, and along the process it climbs as , which is at and at for the running example (same exercise). The coin turns into a bell curve, and its variance never moves.
Diffusion models usually let the rate vary with time. The VP-SDE of score-based diffusion (Song et al., 2021),
is an OU process with time-dependent rate and noise amplitude ; the running example is the constant schedule . It keeps at every instant, so the variance stays at along the whole schedule, and its marginal is (26.4.16) with (Exercise 7 proves that its transitions are exact Gaussians). This is the variance-preserving path of Section 17.2, the forward process that a diffusion model learns to reverse.
26.4.4 Simulation#
26.4.4.1 The Euler--Maruyama Scheme#
Most SDEs have no closed-form solution, so we need to simulate them. Our recurrence already shows how. To simulate (26.4.8) on a grid we freeze the coefficients over each step, as forward Euler does for ODEs (Section 26.2), and add a Gaussian kick whose size the increment form (26.4.2) dictates. The Euler--Maruyama update (Maruyama, 1955) is
where approximates and . The kick scales as , since any other exponent makes the noise vanish or explode in the limit (Section 26.4.1.2), and with the scheme is forward Euler.
For the OU process the step reads
where the second form is the running example at , the recurrence we have been running all along.
For this process we could have done better. With the kernel (26.4.13) over one interval is , and sampling from it is the forward step of DDPM (Section 17.2), with . DDPM's step is therefore exact at every step size, and Euler--Maruyama is its first-order approximation. At and the exact step multiplies by and adds noise of variance , against and . The two betas should not be confused. The of the step is the fraction of the variance that one step replaces by noise. It is about for the rate of (26.4.17), here against . Exact steps need a linear equation (Exercise 7). A general drift has no transition law in closed form, and the approximate scheme is all we have.
The helper below implements (26.4.18) for a whole batch of paths. It takes the increments as an argument, so that two simulations can be driven by the same noise. We need that at once: with the noise switched on, "error" itself needs a definition, and there are two.
def euler_maruyama(f, g, x0, t, dW):
"""Simulate dX = f dt + g dW on the grid t for a batch of paths."""
X = np.empty((len(x0), len(t)))
X[:, 0] = x0
for k in range(len(t) - 1):
h = t[k + 1] - t[k]
X[:, k + 1] = (X[:, k] + f(X[:, k], t[k]) * h
+ g(X[:, k], t[k]) * dW[:, k])
return X
26.4.4.2 Strong and Weak Convergence#
A simulated path is random, and so is the true one. The two definitions of error differ in what they compare: paths or laws, the two kinds of statement that the band experiment told apart.
Let be the number of steps, so that approximates . Drive the scheme and the exact solution with the same Brownian increments. The strong error measures pathwise tracking: does the simulated trajectory follow the true trajectory driven by that noise? The weak error , for smooth test functions , measures only whether the law at time comes out right. A generative model needs weak accuracy, since it only uses the samples at the final time. Strong accuracy matters when paths are coupled across resolutions, as in multilevel Monte Carlo, which makes most of its estimate on cheap coarse paths and corrects it with a few expensive fine ones (Exercise 8). Figure 26.4.6 shows the two notions side by side.
Strong versus weak convergence of Euler--Maruyama on the running example from on . Left: one coarse path ( steps, orange) against a fine reference ( steps, blue) driven by the same Brownian increments; the strip below magnifies their gap at the coarse grid times, which is what the strong error measures. Right: the terminal histograms of paths at the two step sizes nearly match each other and the exact law (black), although at steps the variance is about too large.
A scheme has strong order if its strong error is at most , and weak order likewise. The orders of Euler--Maruyama are classical.
Theorem (orders of Euler--Maruyama; stated without proof). Let , , and be smooth, with the growth conditions and the moments of that Kloeden and Platen (1992) make precise.
- Euler--Maruyama has strong order : .
- If the noise is additive, , the strong order is : .
- The weak order is , for additive and multiplicative noise alike: .
A count of single-step errors explains the exponents. It is not a proof: it adds the errors of the steps as if each stayed where it was made, and the proofs must also control how the later dynamics carry an early error forward.
Euler--Maruyama freezes over the step, but moves with the path. At a time inside the step the path has moved by about , so the noise coefficient there is about . The largest term that the scheme leaves out is the integral of the second part against , which is (26.4.7) for the Brownian motion that starts afresh at :
Milstein's scheme puts this term back (Milstein, 1975). Its random factor is the rule for squares seen a step at a time: is true in sums, and off by something of mean zero and size in every step. The steps contribute uncorrelated terms of this kind, which add like a random walk to . That is order .
For additive noise removes this term. The next omitted stochastic terms have size per step and add to , as do the deterministic remainders, , and the order is . For the weak error only means matter. Every omitted stochastic term has mean zero, the bias of one step is of order , and steps give , whatever the noise.
We measure both strong orders on the same noise. Geometric Brownian motion (, ) is compared with its exact solution (26.4.10), and the running example from with a reference on a -step grid, since the noise integral in its exact solution (26.4.14) could itself be evaluated only on a grid. Coarse increments are sums of consecutive fine ones, so every resolution sees the same Brownian path.
T, n_ref, n_em = 1.0, 2**12, 2000
mu_g, nu_g = 1.0, 1.0 # GBM: multiplicative noise
ou_f, ou_g = lambda x, s: -theta_ou * x, lambda x, s: g_ou
gbm_f, gbm_g = lambda x, s: mu_g * x, lambda x, s: nu_g * x
x0_ou, x0_gbm = np.full(n_em, 2.0), np.full(n_em, 1.5)
dW_f = np.sqrt(T / n_ref) * rng.standard_normal((n_em, n_ref))
t_f = np.linspace(0, T, n_ref + 1)
ou_ref = euler_maruyama(ou_f, ou_g, x0_ou, t_f, dW_f)[:, -1]
gbm_exact = 1.5 * np.exp((mu_g - nu_g**2 / 2) * T + nu_g * dW_f.sum(axis=1))
dts, errs_ou, errs_gbm = [], [], []
for n in [2**k for k in range(3, 9)]: # 8 to 256 steps
dW = dW_f.reshape(n_em, n, n_ref // n).sum(axis=2)
t = np.linspace(0, T, n + 1)
ou = euler_maruyama(ou_f, ou_g, x0_ou, t, dW)[:, -1]
gbm = euler_maruyama(gbm_f, gbm_g, x0_gbm, t, dW)[:, -1]
dts.append(T / n)
errs_ou.append(np.abs(ou - ou_ref).mean())
errs_gbm.append(np.abs(gbm - gbm_exact).mean())
print('strong-order slopes: OU (additive) '
f'{np.polyfit(np.log(dts), np.log(errs_ou), 1)[0]:.2f},'
' GBM (multiplicative) '
f'{np.polyfit(np.log(dts), np.log(errs_gbm), 1)[0]:.2f}')
d2l.plot(dts, [errs_ou, errs_gbm, np.array(dts), 0.5 * np.sqrt(dts)],
'step size', 'strong error', xscale='log', yscale='log',
legend=['OU (additive)', 'GBM (multiplicative)',
'slope 1', 'slope 1/2'], figsize=(5, 3))strong-order slopes: OU (additive) 1.03, GBM (multiplicative) 0.48
The measured slopes are close to for the additive-noise OU process and close to for the multiplicative-noise geometric Brownian motion, the two strong orders of the theorem. The two curves have different heights because the processes have different scales. What can be compared is how they fall: each halving of the step halves the OU error and divides the error of geometric Brownian motion by about .
For the weak order no sampling is needed. Euler--Maruyama applied to the OU process is a linear Gaussian recursion: if is Gaussian, so is . So the simulated marginal is Gaussian at every step, with mean and variance
The mean is multiplied by per step where the exact solution multiplies by ( against at ). The variance recursion sums a geometric series, with and , whose limit is the fixed point found earlier. Evaluating these closed forms at from for six step counts gives the errors of the simulated law with no sampling error to blur their slopes.
mean_T, var_T = 2 * np.exp(-1), 1 - np.exp(-2) # exact OU kernel at T = 1
print(f'{"n":>4} {"EM mean":>8} {"EM var":>7}'
f' exact {mean_T:.4f}, {var_T:.4f}')
dts, errs = [], []
for n in [10, 20, 40, 80, 160, 320]:
h = 1 / n
a_h = 1 - theta_ou * h # one-step mean multiplier
m = 2 * a_h**n # EM mean after n steps
v = g_ou**2 * h * (1 - a_h**(2 * n)) / (1 - a_h**2) # geometric series
print(f'{n:4d} {m:8.4f} {v:7.4f}')
dts.append(h)
errs.append([abs(m - mean_T), abs(v - var_T)])
s_m, s_v = np.polyfit(np.log(dts), np.log(np.array(errs)), 1)[0]
print(f'weak-order slopes: mean {s_m:.2f}, variance {s_v:.2f}')
n EM mean EM var exact 0.7358, 0.8647
10 0.6974 0.9247
20 0.7170 0.8938
40 0.7265 0.8791
80 0.7311 0.8718
160 0.7335 0.8682
320 0.7346 0.8664
weak-order slopes: mean 1.01, variance 1.01
At steps the simulated law has mean and variance , against the exact and (the kernel from before), and at steps it has and . Both fitted slopes are : halving the step halves the error of the simulated law, which is weak order .
The same computation for geometric Brownian motion also gives weak order , so multiplicative noise costs half an order in the paths and nothing in the law. A scheme that looks more accurate can even converge to the wrong equation. Heun's method, which averages the noise coefficient over the step, converges to the Stratonovich solution instead of the Itô one (Exercise 6).
Simulation produces samples of the forward process, and the kernel gives its law from a single start. Generation asks for more. Data are not a single point: the marginal of the noised data is the kernel averaged over all starts, and for real data, which we know only through samples, it has no closed form. Yet running the process backward will require the gradient of , the quantity that we could write down for one start, and so far we do not even have an equation that obeys.
26.4.5 Summary#
A forward process must forget its start, which no deterministic flow can do, so it is driven by noise. Noise that survives the limit of small steps has size , and the squares of its increments add up to the elapsed time, . An integral against therefore depends on where its integrand is evaluated, and Itô's left endpoint gives it mean zero and the isometry . For the same reason the chain rule gains the correction . With these tools the Ornstein--Uhlenbeck process is solved: given its start it is Gaussian at every time, with mean and variance , and with it is the variance-preserving forward process of diffusion models. Equations without a closed form are simulated by Euler--Maruyama, Euler's step plus a kick, which follows paths at order for additive noise and for multiplicative noise and reproduces laws at order for both.
26.4.6 Exercises#
-
Infinite total variation. The total variation of a path along a partition is . Pathwise integrals , defined as limits of sums with arbitrary evaluation points , exist for every continuous when stays bounded as the mesh shrinks.
- Let and use the uniform partition with . Compute and , using for , and conclude that in probability as .
- Let be continuous with for every partition. Show that as the mesh shrinks, and deduce : such a path has quadratic variation zero. Why does (26.4.3) then give a second proof that Brownian paths have unbounded total variation?
- Let be continuous with bounded total variation. Show that the left-endpoint sums and the right-endpoint sums both converge to . Compare with the two limits for in Section 26.4.2.2. Which step of your argument fails for a Brownian path?
-
[code] Brownian scaling and exit times.
- For let . Check properties 1–4 of Section 26.4.1.2 and conclude that is a Brownian motion. Which property of the walk does this make exact?
- Let be the first time reaches a level . Use (a) to show that has the same distribution as , so that .
- Granting (it follows from , a consequence of (26.4.7) and the zero mean of the Itô integral up to a stopping time), simulate walks with Gaussian steps of variance and estimate for , with Monte Carlo standard errors. The estimates tend to run slightly above , most clearly for small . Explain the sign of the bias from the way a discrete walk crosses a level, and say how it scales with and .
- In the experiment of the text a little over half of the paths stay inside at all grid times. Use (a) to show that this fraction depends only on the number of grid times and not on the length of the interval. Measure it for , , and . By what factor does it fall each time grows tenfold, and what does that say about the limit ?
-
Geometric Brownian motion and the correction. Consider with and its solution, given by (26.4.10).
- Using for , show that and . Find the median of .
- Take and . What happens to the mean, to the median, and to a typical path as ? How can these statements hold at the same time?
- For which , at a fixed , does the median stop growing?
Check the condition for the parameters of (b) on paths
simulated with
euler_maruyamato at : what fraction of the paths ends below , and what fraction does the exact solution (26.4.10) predict?
Adapted from Simo Särkkä and Arno Solin, Applied Stochastic Differential Equations, Exercise 4.3.
-
[code] Strong order and Milstein's correction. As Section 26.4.4.2 explains, Euler--Maruyama omits the Milstein term , and its strong order is unless that term vanishes.
- By (26.4.10), satisfies an SDE with
additive noise. Apply
euler_maruyamato that SDE with the incrementsdW_fand the step sizes of the strong-order experiment, exponentiate the endpoints, and measure the strong error againstgbm_exact. Explain the result. - Use Itô's lemma to show that for with , the variable with has unit additive noise, and find its drift.
- Milstein's scheme (Milstein, 1975) adds that term to the Euler--Maruyama step,
- By (26.4.10), satisfies an SDE with
additive noise. Apply
with , , and evaluated at . Implement it for the geometric Brownian motion of the strong-order experiment, and measure its strong-order slope on the same increments and step sizes. By what factor does it reduce the strong error at ?
-
Variance preservation, exactly. Let follow (26.4.16) with zero-mean data .
- Assume unit-variance data and show that . Specialize to Rademacher data to obtain the prediction of the text.
- The excess kurtosis is zero for every Gaussian. At what rate in does it decay for ? Compare this rate with the rate at which the conditional mean forgets the data.
- Suppose instead that the data have variance . Find . For and , how long must the process run before is within of the variance of the reference ?
-
[code] Itô versus Stratonovich. ● The left- and right-endpoint sums for add up to on every partition (Section 26.4.2.2), so their average equals . Sums of this kind define the Stratonovich integral (Stratonovich, 1966), which obeys the ordinary chain rule.
- Heun's method of Section 26.2 carries over to SDEs if the noise term is treated like a second slope. The predictor is the Euler--Maruyama step , and the corrector averages both coefficients:
Implement it for the geometric Brownian motion of the strong-order
experiment, on its increments dW_f and step sizes. Compare its endpoints with the exact Itô solution
(26.4.10) and with . To which
of the two does the scheme converge?
- Expand the corrector's noise term to first order in , and use to show that the scheme behaves like Euler--Maruyama for an Itô SDE with a modified drift. Find that drift and check that it explains the limit in (a).
- Why do the two conventions give the same solution for every SDE of the form (26.4.1)?
-
Exact transitions of linear SDEs. ● Consider the linear SDE with continuous and , and let .
- Apply Itô's lemma to and show that, given , the state at a later time is Gaussian with mean and variance .
- Specialize (a) to the VP-SDE (26.4.17) and show that a transition of any length maps a unit-variance state to a unit-variance state. Conversely, assume for the linear SDE of (a) that for every whenever , and show that at every .
- Consider the semilinear SDE with constants and a smooth function . The exponential Euler--Maruyama step holds at the value over a step of length and solves the remaining linear SDE exactly, by the method of (a). Write the step. Show that it agrees with the Euler--Maruyama step (26.4.18) to first order in and that it is exact when is constant. For , Euler--Maruyama damps the mean only for (Section 26.2.3). What limits the step size of the exponential step?
- Exact steps have zero weak error at every step size. Which property of the drift and the diffusion of the VP-SDE makes them available? The generative sampler of a diffusion model simulates, backward in time, an SDE whose drift is : the VP drift plus a multiple of , the score of the forward marginal, which is a nonlinear function of for non-Gaussian data. Why can its steps not be made exact? Exponential integrators for diffusion samplers (Zhang and Chen, 2023) apply the idea of (c) to the deterministic counterpart of this sampler, an ODE whose drift has the same two parts with half the score term (Section 26.5). Which part of such a drift does the step treat exactly, and which part does it approximate?
-
[extended] Multilevel Monte Carlo. ●● Estimating by averaging over Euler--Maruyama paths has two sources of error, the weak bias of the scheme and the sampling noise. Multilevel Monte Carlo (Giles, 2008) reduces the cost by coupling paths across step sizes, which is one of the uses of strong accuracy named in Section 26.4.4.2. Throughout, the mean-square strong error has the same orders as the strong error of that section.
- Plain Monte Carlo averages over independent paths at a cost of steps. Assume a weak bias and a variance of . Show that a mean squared error below costs order steps at the best choice of and .
- Let be of the Euler--Maruyama endpoint with step
, and write
.
Each term is estimated from independent pairs in which the coarse
path uses the sums of consecutive pairs of fine increments, as in
the strong-order experiment. For Lipschitz , bound
by the mean-square strong
error. Take , and predict how scales with
for the OU process and the geometric Brownian motion of that
experiment, with its parameters. Measure
for with
euler_maruyama, and fit the slopes on the finer levels. - Minimize the total cost subject to with a Lagrange multiplier. Choose the finest level so that the bias stays below . Assuming , show that the cost is of order for and of order for .
- Implement both estimators for of the
geometric Brownian motion of the strong-order experiment, with from
(c) and your measured . For
, record the total number of
steps each estimator uses and check its error over a few repetitions.
Plot times the cost against . Repeat with
the Milstein scheme of Exercise 4c
in place of Euler--Maruyama.
euler_maruyamastores every path in full, so simulate large in batches. - Repeat the measurement of (b) for the discontinuous . Why does decay more slowly, and what does the slower decay do to the cost?