Algorithmcore
Multilevel Monte Carlo
Also called MLMC.
Writes a fine-level expectation as a coarse one plus telescoping corrections, each estimated with fewer samples as the level grows.
- Time
- O(e^-2 (log e)^2) expected
- Space
- O(L) extra
- Where
- L = the finest level; N = the total number of samples over all levels; e = the target root mean square error, in the case beta = gamma of the Euler example
- Model
- Real RAM
- Properties
- randomizednot exactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michael B. Giles, Stefan Heinrich, 2008
Multilevel Monte Carlo (MLMC) estimates an expected value, such as the mean output of a simulation or an integral that a renderer computes by random sampling, when each sample comes from an approximation that gets more accurate and more expensive on finer levels. Plain Monte Carlo integration takes all samples on the finest level. MLMC writes the fine-level mean as the mean on a coarse level plus a sum of corrections between neighbor levels, and estimates each term with its own samples. A correction is the difference of two close approximations that use the same random input, so it has a small variance and needs few samples, and the many samples go to the cheap coarse level. For an output of a stochastic differential equation solved by the Euler-Maruyama method, this reduces the cost for a root mean square error from to .
In plain words
Say you want the average result of a simulation with random inputs. A fine simulation is accurate but slow, and a coarse one is fast but a little wrong. Plain Monte Carlo runs the fine simulation many times.
The multilevel idea is to ask the cheap question many times and the expensive question only a few times. First, average many coarse runs. Then fix the error of the coarse runs: run a fine and a coarse simulation on the same random input, and average the difference. The two runs see the same random input, so their difference is small and changes little from one input to the next. A small number of such pairs gives a good average of the difference. Do this again for each finer level. The sum of all the averages is as accurate as the finest level, at a fraction of the cost.
The problem
The input is a random output of a model, for example for a random input on a probability space , and approximations on levels , which get more accurate and more expensive as grows. The output is an estimate of with mean squared error . This is the moment form of forward uncertainty propagation.
With and , the means telescope:
The estimator takes independent samples of on each level: . In one sample of , the fine value and the coarse value use the same random input ; samples on different levels are independent. With and the cost of one sample of , the mean squared error is
a variance plus a squared bias. The method keeps each part below . The rates , , of the area notation describe the levels: , and .
The algorithm
MLMC(SAMPLE, ε, α, β, γ, L_0, N_0)- 1
L ← L_0; N_l ← 0 and dN_l ← N_0 for l = 0..L - 2
while dN_l > 0 for some l do - 3
for each l with dN_l > 0: draw dN_l coupled samples of Y_l = P_l - P_(l-1) by SAMPLE, add their sum, sum of squares and cost, and set N_l ← N_l + dN_l- 4
V_l ← sample variance of Y_l, C_l ← mean cost of one sample of Y_l, for l = 0..L - 5
dN_l ← max(0, ⌈2 ε^(-2) sqrt(V_l / C_l) Σ_k sqrt(V_k C_k)⌉ - N_l) for l = 0..L - 6
if dN_l = 0 for all l then - 7
bias ← max(|Ŷ_L|, |Ŷ_(L-1)| / 2^α) / (2^α - 1) ▷ Ŷ_l is the sample mean of Y_l - 8
if bias > ε / sqrt(2) then L ← L + 1, set V_L ← V_(L-1) / 2^β and C_L ← C_(L-1) 2^γ, redo L5 - 9
return Ŷ = Ŷ_0 + Ŷ_1 + ... + Ŷ_L
Line L3 is the only place where the model runs. SAMPLE must return, for one random input, both and ; for Euler paths the coarse path adds pairs of the fine Brownian increments. Line L5 is the optimal sample count of Giles: it minimizes the cost under the variance target , and it is derived in the proof. Line L7 estimates the bias as the tail of a geometric series with ratio , from the last correction and, as a guard, from the one before it. Line L8 adds a level when the bias is too large; the new level has no samples yet, so its and come from the rates and until line L3 samples it.
Example
The output is for the geometric Brownian motion with , , and . The exact mean is . Level is the Euler-Maruyama value with steps; its mean is exactly , so the bias on level is known. The cost of a sample is its number of time steps, fine plus coarse. The run uses , , , and random.Random(2024) (a measurement):
| level | exact | ||||
|---|---|---|---|---|---|
| 0 | 495412 | 1.050 | 1.05 | 495412 | |
| 1 | 29469 | 88407 | |||
| 2 | 15186 | 91116 | |||
| 3 | 7672 | 92064 |
The variance drops by a factor of about 100 from level 0 to level 1, because a correction is the difference of two close paths, and then halves with each level, as says. The counts follow line L5: is proportional to . The loop stopped at , where line L7 gave , below . The true bias at is .
The estimate is , with error , at a total cost of 766999 time steps. Plain Monte Carlo on level 3 needs samples of 8 steps each for the same variance, that is 2561384 steps, 3.3 times as many. The gap grows as falls, as the complexity section shows. Over 30 seeds at , the root mean square error was 0.00119, below the target.
Correctness
The claim is that the estimate of line L9 has mean , and that its mean squared error is at most when the estimated variances and the bias test are right. The mean follows from the telescoping sum and linearity of expectation. The variance is because the samples are independent, and the counts of line L5 make it at most ; by the Cauchy-Schwarz inequality no other counts reach this target at a lower cost. If follows the rate beyond level , the remaining bias is the geometric tail of line L7, which line L8 keeps at most . The full proof, with termination, is in the proof file. It does not cover the error of the estimated and : with too few samples, or a correction that does not yet follow its rate, the bias test can pass too early.
Proof: The multilevel estimator is unbiased for the finest level and meets its variance target at the least costfull
We assume exact arithmetic and exact random numbers. The approximations of the output are square integrable random variables on one probability space . For let with , and the mean cost of one sample of . The estimator with finest level and sample counts is
where the samples are independent for all and , and each has the law of . Inside one sample, and use the same random input; this changes but none of the statements below.
Lemma 1 (the telescoping sum). .
Proof. By linearity of expectation, . The sum over telescopes to .
Lemma 2 (the variance). .
Proof. The samples are independent, so the variance of the sum is the sum of the variances: .
Lemma 3 (the error split). .
Proof. Write . The first term has mean zero by Lemma 1 and the second is a constant, so the cross term has mean zero. The mean square of the first term is the variance of Lemma 2.
So the mean squared error is at most if the variance is at most and the bias is at most . The algorithm aims at these two targets separately.
Lemma 4 (the least cost for the variance target). For fixed and real , every choice with has cost . Equality holds for
Proof. By the Cauchy-Schwarz inequality for the vectors with entries and ,
Equality in the first step holds if and only if is a fixed multiple of , that is . Equality in the second step needs , which gives . The same counts come from a Lagrange multiplier for the cost with the variance constraint.
Line L5 rounds these counts up. The variance target still holds: with and ,
The rounding adds at most one sample on each level, so at most to the cost.
Lemma 5 (the bias test). Assume that for all , with and a constant . Then .
Proof. If , then , a geometric series.
Line L7 puts the sample means and into this formula and takes the larger value. Under the assumption of Lemma 5 from level on, both are estimates of ; the second one guards against a sample mean that is small by chance. Line L8 adds a level while the estimate is above .
Theorem (correctness). When the loop ends, the estimate of line L9 has mean . If the sample variances and means of lines L4 and L7 are equal to the true and , and for , then its mean squared error is at most , and no choice of real sample counts for this reaches the variance target at a lower cost.
Proof. The first claim is Lemma 1. The loop ends only when all , so the counts are at least those of Lemma 4 and the variance is at most ; the bias test passed, so by Lemma 5 the bias is at most . Lemma 3 adds the two parts. The cost claim is Lemma 4.
Termination. Each pass of lines L2 to L8 with some adds at least one sample, and the counts never go down. On a fixed level set, the sample variances converge almost surely as the counts grow (the law of large numbers), so the optimal counts of line L5 stay bounded and the counts pass them after finitely many passes. The number of levels is at most max_level, after which the code stops with an error. So the loop ends with probability 1.
The geometric Brownian motion example. The Euler-Maruyama step for is . The factors are independent with mean , so after steps of size , . This is the exact level mean that the tests compare with. Since , , so the weak rate is . The coarse path of a sample sums pairs of the fine increments, so it has the law of a coarse Euler path, and is the difference of two consecutive level means, as Lemma 1 needs.
What is not proved. The theorem is conditional on exact moments. In a real run, and are estimated from the same samples, the rate is an assumption, and the bias test can pass too early when does not yet follow its rate. Then the mean squared error can be larger than . The cost bound as a function of is the MLMC complexity theorem, and it needs the rate hypotheses of that theorem.
Complexity
The cost is model work, plus arithmetic per sample and per pass of the loop in the real RAM model. With the counts of line L5,
The bias test stops at . If , the sum is a convergent geometric series and the cost is , the cost of plain Monte Carlo with exact samples of unit cost. If , every term is , the sum is and the cost is . If , the last term dominates and the cost is . These three cases are the MLMC complexity theorem; its proof needs and adds the rounding cost.
For the Euler example, , so MLMC costs . Plain Monte Carlo needs samples on a level with steps, which is . The extra space is for the sums of each level; the samples themselves are not stored.
Properties
- Unbiased for the finest level. The estimate has mean for any counts. All the bias is the bias of level .
- Randomized. The estimate is random and its error is statistical. The error bound holds in mean square, not for every run.
- Non-intrusive. The model is a black box that returns a fine and a coarse value for one random input. The only demand on it is the coupling.
- Adaptive. The number of levels and the counts come from the run, with three rate parameters from the user.
- Parallel. The samples of a level are independent and can run in parallel; only the sums are shared.
Variants and improvements
- Coarsening factor 4. Giles 2008 uses step sizes . Then the rates are in powers of 2, with the same order of cost.
- Antithetic and Milstein corrections. A better coupling raises . With the Milstein method in one dimension, , and the cost is .
- Multilevel quasi-Monte Carlo. Each level uses randomized quasi-Monte Carlo integration instead of independent samples, which can lower the cost further when the corrections are smooth in the random input.
- Multi-index Monte Carlo. The levels have several indices, for example the time step and the space mesh, and the corrections are mixed differences.
- Randomized unbiased estimators. A random level with known probabilities gives an estimator that is unbiased for itself, if .
- Elliptic PDEs with random coefficients. The levels are meshes of a finite element method, and the input is a random field. Cliffe, Giles, Scheichl and Teckentrup showed the method for this case in 2011.
When to use it
Use MLMC when the output is a mean, the model has a hierarchy of discretizations, and you can couple two neighbor levels so that decays: SDE paths in finance, PDEs with random fields, particle systems. Use plain Monte Carlo integration when there is no useful hierarchy, or when the finest level is cheap. Use multifidelity Monte Carlo when the cheap models are not levels of one discretization, for example a reduced model and a data fit, and their correlation with the fine model is known. Use polynomial chaos expansion or stochastic collocation when the input has few dimensions and the output is smooth in it. MLMC is unlike Richardson extrapolation: it does not cancel the bias by a known error expansion, it estimates each correction by sampling.
Pitfalls
- Independent coarse samples. If line L3 draws the coarse value with its own random input, and does not decay; the method is then slower than plain Monte Carlo. The fine and the coarse value of one sample must use the same input.
- Level 0 as a difference. is itself (). Starting the sum at a correction drops the main term.
- Too few initial samples. Line L4 estimates from samples. With heavy-tailed corrections, a small underestimates , and line L5 then takes too few samples. Use of a few hundred, and check the rates against the level variances.
- A bias test on one noisy mean. If line L7 used only , a correction that is small by chance stops the loop early. The maximum with guards against this, but cannot help if the true corrections have not reached their asymptotic rate.
- A wrong rate. A non-smooth output, such as an indicator of an event, has with Euler paths, not 1. With in line L8, the new levels get too few samples until they are sampled.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multilevel-monte-carlo/. The authors are listed in prov/SAT4ZW.jsonl.
"""Multilevel Monte Carlo with the adaptive level and sample choice of Giles (2008, 2015).
The caller gives a function sample(l, n, rng) that draws n independent samples
of the correction Y_l = P_l - P_(l-1) (with P_(-1) = 0). The fine and the coarse
value in one sample must use the same random input, or the variance of Y_l does
not decay. The function returns the sum of the samples, the sum of their
squares and the total cost of the n samples.
The rates alpha (weak error), beta (variance of Y_l) and gamma (cost of Y_l)
are given by the caller, as in Giles 2008. The estimator stops when the
estimated variance is at most eps^2 / 2 and the estimated bias is at most
eps / sqrt(2), so that the mean squared error is at most eps^2 if the
estimates are right.
"""
import math
import random
from typing import Callable
Sampler = Callable[[int, int, random.Random], tuple[float, float, float]]
def optimal_counts(v: list[float], c: list[float], eps: float) -> list[int]:
"""N_l = ceil(2 eps^-2 sqrt(V_l / C_l) sum_k sqrt(V_k C_k)), so that sum V_l / N_l <= eps^2 / 2."""
total = sum(math.sqrt(vk * ck) for vk, ck in zip(v, c))
return [math.ceil(2.0 / eps**2 * math.sqrt(vl / cl) * total) for vl, cl in zip(v, c)]
def mlmc(
sample: Sampler,
eps: float,
alpha: float,
beta: float,
gamma: float,
rng: random.Random,
l0: int = 2,
n0: int = 200,
max_level: int = 20,
) -> dict:
"""Estimate E[P] to a root mean square error of about eps.
Returns a dict with the estimate, the finest level L, the sample counts,
the mean and variance of each correction, and the total cost.
"""
big_l = l0 # @line L1
n = [0] * (big_l + 1)
dn = [n0] * (big_l + 1)
s1 = [0.0] * (big_l + 1)
s2 = [0.0] * (big_l + 1)
cost = [0.0] * (big_l + 1)
while any(x > 0 for x in dn): # @line L2
for l in range(big_l + 1): # @line L3
if dn[l] > 0:
a, b, w = sample(l, dn[l], rng)
s1[l] += a
s2[l] += b
cost[l] += w
n[l] += dn[l]
v, c = _moments(n, s1, s2, cost, beta, gamma) # @line L4
dn = [max(0, nl - ml) for nl, ml in zip(optimal_counts(v, c, eps), n)] # @line L5
if all(x == 0 for x in dn): # @line L6
m = [s1[l] / n[l] for l in range(big_l + 1)]
bias = max(abs(m[big_l]), abs(m[big_l - 1]) / 2**alpha) / (2**alpha - 1) # @line L7
if bias > eps / math.sqrt(2.0): # @line L8
if big_l == max_level:
raise RuntimeError("the bias test failed at the largest level")
big_l += 1
n.append(0)
s1.append(0.0)
s2.append(0.0)
cost.append(0.0)
v, c = _moments(n, s1, s2, cost, beta, gamma)
dn = [max(0, nl - ml) for nl, ml in zip(optimal_counts(v, c, eps), n)]
means = [s1[l] / n[l] for l in range(big_l + 1)]
v, _ = _moments(n, s1, s2, cost, beta, gamma)
return {
"estimate": sum(means), # @line L9
"L": big_l,
"N": n,
"means": means,
"variances": v,
"cost": sum(cost),
}
def _moments(n, s1, s2, cost, beta, gamma):
"""Sample variance and mean cost per level. A new level with no samples gets V and C from the rates."""
v, c = [], []
for l in range(len(n)):
if n[l] > 0:
mean = s1[l] / n[l]
v.append(max(s2[l] / n[l] - mean * mean, 1e-300))
c.append(cost[l] / n[l])
else:
v.append(v[l - 1] / 2**beta)
c.append(c[l - 1] * 2**gamma)
return v, c
def gbm_euler_sampler(s0: float, r: float, sigma: float, t: float) -> Sampler:
"""Coupled Euler-Maruyama samples of P_l - P_(l-1) for P = S_T of geometric Brownian motion.
Level l uses 2^l steps of size h_l = T / 2^l. The coarse path of a sample sums
pairs of the fine Brownian increments, so both paths see the same noise.
The cost of one sample is the number of fine plus coarse steps.
"""
def sample(l: int, nsamp: int, rng: random.Random) -> tuple[float, float, float]:
nf = 2**l
hf = t / nf
sq = math.sqrt(hf)
sum1 = sum2 = 0.0
for _ in range(nsamp):
xf = s0
xc = s0
dwc = 0.0
for k in range(nf):
dw = sq * rng.gauss(0.0, 1.0)
xf += r * xf * hf + sigma * xf * dw
dwc += dw
if l > 0 and k % 2 == 1:
xc += r * xc * (2 * hf) + sigma * xc * dwc
dwc = 0.0
y = xf - xc if l > 0 else xf
sum1 += y
sum2 += y * y
steps = nf + (nf // 2 if l > 0 else 0)
return sum1, sum2, float(steps * nsamp)
return sample
def euler_gbm_mean(s0: float, r: float, t: float, l: int) -> float:
"""The exact mean E[P_l] = S_0 (1 + r h_l)^(2^l) of the Euler value of S_T, with h_l = T / 2^l."""
return s0 * (1.0 + r * t / 2**l) ** (2**l)
test_multilevel_monte_carlo.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multilevel-monte-carlo/. The authors are listed in prov/SAT4ZW.jsonl.
import math
import random
from multilevel_monte_carlo import euler_gbm_mean, gbm_euler_sampler, mlmc, optimal_counts
S0, R, SIGMA, T = 1.0, 0.05, 0.2, 1.0
EXACT = S0 * math.exp(R * T) # E[S_T] for geometric Brownian motion
def deterministic_sampler(l, n, rng):
"""P_l = 1 - 2^-(l+1) with no noise: Y_0 = 1/2 and Y_l = 2^-(l+1) for l >= 1."""
y = 0.5 if l == 0 else 2.0 ** -(l + 1)
return n * y, n * y * y, float(n * 2**l)
def test_telescoping_sum_is_exact_without_noise():
res = mlmc(deterministic_sampler, 1e-3, 1.0, 1.0, 1.0, random.Random(0), l0=2, n0=4)
big_l = res["L"]
assert abs(res["estimate"] - (1.0 - 2.0 ** -(big_l + 1))) < 1e-15
# the bias estimate of level L is 2^-(L+1); L is the first level where it is at most eps / sqrt(2)
assert big_l == 10
assert 2.0 ** -(big_l + 1) <= 1e-3 / math.sqrt(2) < 2.0**-big_l
def test_optimal_counts_reach_half_eps_squared():
v = [0.04, 4e-4, 2e-4, 1e-4]
c = [1.0, 3.0, 6.0, 12.0]
eps = 0.001
n = optimal_counts(v, c, eps)
assert sum(vl / nl for vl, nl in zip(v, n)) <= eps**2 / 2
# the counts follow sqrt(V_l / C_l), up to the rounding up
for l in range(1, 4):
ratio = n[l] / n[0]
assert abs(ratio - math.sqrt(v[l] / c[l]) / math.sqrt(v[0] / c[0])) < 2e-3
def test_level_means_match_the_exact_euler_bias():
sample = gbm_euler_sampler(S0, R, SIGMA, T)
rng = random.Random(7)
n = 4000
for l in range(4):
a, b, _ = sample(l, n, rng)
mean = a / n
se = math.sqrt((b / n - mean * mean) / n)
exact = euler_gbm_mean(S0, R, T, l) - (euler_gbm_mean(S0, R, T, l - 1) if l > 0 else 0.0)
assert abs(mean - exact) < 4 * se
def test_correction_variance_halves_per_level():
sample = gbm_euler_sampler(S0, R, SIGMA, T)
rng = random.Random(11)
n = 3000
v = []
for l in range(1, 6):
a, b, _ = sample(l, n, rng)
v.append(b / n - (a / n) ** 2)
for l in range(1, len(v)):
assert 0.35 < v[l] / v[l - 1] < 0.65 # beta = 1 for Euler-Maruyama on GBM
def test_mlmc_rmse_on_gbm_is_below_eps():
sample = gbm_euler_sampler(S0, R, SIGMA, T)
eps = 0.002
errors = []
for seed in range(20):
res = mlmc(sample, eps, 1.0, 1.0, 1.0, random.Random(seed))
errors.append(res["estimate"] - EXACT)
assert sum(vl / nl for vl, nl in zip(res["variances"], res["N"])) <= eps**2 / 2 * 1.0001
rmse = math.sqrt(sum(e * e for e in errors) / len(errors))
assert rmse < 1.3 * eps
def test_mlmc_is_cheaper_than_plain_monte_carlo():
sample = gbm_euler_sampler(S0, R, SIGMA, T)
eps = 0.001
res = mlmc(sample, eps, 1.0, 1.0, 1.0, random.Random(3))
v0 = res["variances"][0]
plain_cost = 2 * v0 / eps**2 * 2 ** res["L"]
assert res["cost"] < plain_cost
History
Heinrich used a multilevel splitting of the expectation for parametric integration in 1998, and published it as multilevel Monte Carlo in 2001. Kebaier used two levels of time steps, a statistical form of Romberg extrapolation, for SDE simulation in 2005. Giles gave the general method with any number of levels, the optimal sample counts and the complexity theorem for SDE paths in 2008. The idea is close to the multigrid method, which also does most of its work on coarse grids and only a little on the fine one. Cliffe, Giles, Scheichl and Teckentrup extended it to elliptic PDEs with random coefficients in 2011, and Giles wrote a review of the field in Acta Numerica in 2015.
References
- Michael B. Giles, Multilevel Monte Carlo path simulation, Operations Research 56(3), 2008, 607-617, Theorem 3.1 (the complexity theorem) and the numerical algorithm with its bias test, for Euler paths with step sizes in ratio 4
- Michael B. Giles, Multilevel Monte Carlo methods, Acta Numerica 24, 2015, 259-328, Section 1.3 (the optimal number of samples on each level), Section 2.1, Theorem 1 (the complexity theorem), Section 5.1 (Euler-Maruyama paths and their coupling)
- Stefan Heinrich, Multilevel Monte Carlo methods, in Large-Scale Scientific Computing (LSSC 2001), Lecture Notes in Computer Science 2179, Springer, 2001, 58-67, the multilevel splitting for parametric integration
- K. Andrew Cliffe, Michael B. Giles, Robert Scheichl and Aretha L. Teckentrup, Multilevel Monte Carlo methods and applications to elliptic PDEs with random coefficients, Computing and Visualization in Science 14, 2011, 3-15, the complexity theorem in the form with alpha, beta and gamma, and the application to elliptic PDEs with random fields
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SAT4ZW Edit this page History Report an error Markdown