Algorithm Search⌘K

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
Properties
randomizednot exactiterativerandomized
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 ε\varepsilon from O(ε−3)O(\varepsilon^{-3}) to O(ε−2(log⁡ε)2)O(\varepsilon^{-2} (\log \varepsilon)^2).

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 PP of a model, for example P=q(u(ξ))P = q(u(\xi)) for a random input ξ\xi on a probability space (Ω,F,P)(\Omega, \mathcal{F}, \mathbb{P}), and approximations P0,P1,P2,…P_0, P_1, P_2, \ldots on levels l=0,1,2,…l = 0, 1, 2, \ldots, which get more accurate and more expensive as ll grows. The output is an estimate Y^\widehat{Y} of E[P]\mathbb{E}[P] with mean squared error E[(Y^−E[P])2]≤ε2\mathbb{E}[(\widehat{Y} - \mathbb{E}[P])^2] \le \varepsilon^2. This is the moment form of forward uncertainty propagation.

With Yl=Pl−Pl−1Y_l = P_l - P_{l-1} and P−1=0P_{-1} = 0, the means telescope:

E[PL]=∑l=0LE[Yl]=E[P0]+∑l=1LE[Pl−Pl−1].\mathbb{E}[P_L] = \sum_{l=0}^{L} \mathbb{E}[Y_l] = \mathbb{E}[P_0] + \sum_{l=1}^{L} \mathbb{E}[P_l - P_{l-1}].

The estimator takes NlN_l independent samples of YlY_l on each level: Y^=∑l=0LNl−1∑n=1NlYl(n,l)\widehat{Y} = \sum_{l=0}^{L} N_l^{-1} \sum_{n=1}^{N_l} Y_l^{(n, l)}. In one sample of YlY_l, the fine value PlP_l and the coarse value Pl−1P_{l-1} use the same random input ω\omega; samples on different levels are independent. With Vl=Var(Yl)V_l = \mathrm{Var}(Y_l) and ClC_l the cost of one sample of YlY_l, the mean squared error is

MSE=∑l=0LVlNl+(E[PL]−E[P])2,\mathrm{MSE} = \sum_{l=0}^{L} \frac{V_l}{N_l} + \big(\mathbb{E}[P_L] - \mathbb{E}[P]\big)^2,

a variance plus a squared bias. The method keeps each part below ε2/2\varepsilon^2/2. The rates α\alpha, β\beta, γ\gamma of the area notation describe the levels: ∣E[Pl−P]∣≤c 2−αl|\mathbb{E}[P_l - P]| \le c\, 2^{-\alpha l}, Vl≤c 2−βlV_l \le c\, 2^{-\beta l} and Cl≤c 2γlC_l \le c\, 2^{\gamma l}.

The algorithm

  1. MLMC(SAMPLE, ε, α, β, γ, L_0, N_0)
  2. 1L ← L_0; N_l ← 0 and dN_l ← N_0 for l = 0..L
  3. 2while dN_l > 0 for some l do
  4. 3for each l with dN_l > 0: draw dN_l coupled samples of Y_l = P_l - P_(l-1) by SAMPLE,
  5. add their sum, sum of squares and cost, and set N_l ← N_l + dN_l
  6. 4V_l ← sample variance of Y_l, C_l ← mean cost of one sample of Y_l, for l = 0..L
  7. 5dN_l ← max(0, ⌈2 ε^(-2) sqrt(V_l / C_l) Σ_k sqrt(V_k C_k)⌉ - N_l) for l = 0..L
  8. 6if dN_l = 0 for all l then
  9. 7bias ← max(|Ŷ_L|, |Ŷ_(L-1)| / 2^α) / (2^α - 1) ▷ Ŷ_l is the sample mean of Y_l
  10. 8if bias > ε / sqrt(2) then L ← L + 1, set V_L ← V_(L-1) / 2^β and C_L ← C_(L-1) 2^γ, redo L5
  11. 9return Ŷ = Ŷ_0 + Ŷ_1 + ... + Ŷ_L

Line L3 is the only place where the model runs. SAMPLE must return, for one random input, both PlP_l and Pl−1P_{l-1}; 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 ∑lNlCl\sum_l N_l C_l under the variance target ∑lVl/Nl≤ε2/2\sum_l V_l / N_l \le \varepsilon^2/2, and it is derived in the proof. Line L7 estimates the bias E[P]−E[PL]\mathbb{E}[P] - \mathbb{E}[P_L] as the tail of a geometric series with ratio 2−α2^{-\alpha}, 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 VLV_L and CLC_L come from the rates β\beta and γ\gamma until line L3 samples it.

Example

The output is P=STP = S_T for the geometric Brownian motion dS=rS dt+σS dWdS = r S\, dt + \sigma S\, dW with S0=1S_0 = 1, r=0.05r = 0.05, σ=0.2\sigma = 0.2 and T=1T = 1. The exact mean is E[ST]=erT=1.0512711\mathbb{E}[S_T] = e^{rT} = 1.0512711. Level ll is the Euler-Maruyama value with 2l2^l steps; its mean is exactly E[Pl]=(1+rT/2l)2l\mathbb{E}[P_l] = (1 + r T/2^l)^{2^l}, so the bias on level ll is known. The cost of a sample is its number of time steps, fine plus coarse. The run uses ε=0.0005\varepsilon = 0.0005, α=β=γ=1\alpha = \beta = \gamma = 1, L0=2L_0 = 2, N0=200N_0 = 200 and random.Random(2024) (a measurement):

level ll NlN_l VlV_l Y^l\widehat{Y}_l exact E[Yl]\mathbb{E}[Y_l] NlClN_l C_l
0 495412 4.002×10−24.002 \times 10^{-2} 1.050 1.05 495412
1 29469 4.247×10−44.247 \times 10^{-4} 5.54×10−45.54 \times 10^{-4} 6.25×10−46.25 \times 10^{-4} 88407
2 15186 2.236×10−42.236 \times 10^{-4} 4.23×10−44.23 \times 10^{-4} 3.20×10−43.20 \times 10^{-4} 91116
3 7672 1.152×10−41.152 \times 10^{-4} 1.10×10−41.10 \times 10^{-4} 1.62×10−41.62 \times 10^{-4} 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 β=1\beta = 1 says. The counts follow line L5: NlN_l is proportional to Vl/Cl\sqrt{V_l / C_l}. The loop stopped at L=3L = 3, where line L7 gave max⁡(1.10×10−4,4.23×10−4/2)/1=2.11×10−4\max(1.10 \times 10^{-4}, 4.23 \times 10^{-4}/2) / 1 = 2.11 \times 10^{-4}, below ε/2=3.54×10−4\varepsilon/\sqrt{2} = 3.54 \times 10^{-4}. The true bias at L=3L = 3 is 1.0512711−1.0511075=1.64×10−41.0512711 - 1.0511075 = 1.64 \times 10^{-4}.

The estimate is 1.05127841.0512784, with error 7.3×10−67.3 \times 10^{-6}, at a total cost of 766999 time steps. Plain Monte Carlo on level 3 needs 2ε−2V(P3)=3201732 \varepsilon^{-2} V(P_3) = 320173 samples of 8 steps each for the same variance, that is 2561384 steps, 3.3 times as many. The gap grows as ε\varepsilon falls, as the complexity section shows. Over 30 seeds at ε=0.002\varepsilon = 0.002, the root mean square error was 0.00119, below the target.

Correctness

The claim is that the estimate of line L9 has mean E[PL]\mathbb{E}[P_L], and that its mean squared error is at most ε2\varepsilon^2 when the estimated variances and the bias test are right. The mean follows from the telescoping sum and linearity of expectation. The variance is ∑lVl/Nl\sum_l V_l / N_l because the samples are independent, and the counts of line L5 make it at most ε2/2\varepsilon^2/2; by the Cauchy-Schwarz inequality no other counts reach this target at a lower cost. If E[Yl]\mathbb{E}[Y_l] follows the rate 2−αl2^{-\alpha l} beyond level L−1L - 1, the remaining bias is the geometric tail of line L7, which line L8 keeps at most ε/2\varepsilon/\sqrt{2}. The full proof, with termination, is in the proof file. It does not cover the error of the estimated VlV_l and E[Yl]\mathbb{E}[Y_l]: 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 P0,P1,…P_0, P_1, \ldots of the output PP are square integrable random variables on one probability space (Ω,F,P)(\Omega, \mathcal{F}, \mathbb{P}). For l≥0l \ge 0 let Yl=Pl−Pl−1Y_l = P_l - P_{l-1} with P−1=0P_{-1} = 0, Vl=Var(Yl)V_l = \mathrm{Var}(Y_l) and ClC_l the mean cost of one sample of YlY_l. The estimator with finest level LL and sample counts N0,…,NLN_0, \ldots, N_L is

Y^=∑l=0LY^l,Y^l=1Nl∑n=1NlYl(n,l),\widehat{Y} = \sum_{l=0}^{L} \widehat{Y}_l, \qquad \widehat{Y}_l = \frac{1}{N_l} \sum_{n=1}^{N_l} Y_l^{(n, l)},

where the samples Yl(n,l)Y_l^{(n, l)} are independent for all nn and ll, and each has the law of YlY_l. Inside one sample, PlP_l and Pl−1P_{l-1} use the same random input; this changes VlV_l but none of the statements below.

Lemma 1 (the telescoping sum). E[Y^]=E[PL]\mathbb{E}[\widehat{Y}] = \mathbb{E}[P_L].

Proof. By linearity of expectation, E[Y^l]=E[Yl]=E[Pl]−E[Pl−1]\mathbb{E}[\widehat{Y}_l] = \mathbb{E}[Y_l] = \mathbb{E}[P_l] - \mathbb{E}[P_{l-1}]. The sum over l=0,…,Ll = 0, \ldots, L telescopes to E[PL]−E[P−1]=E[PL]\mathbb{E}[P_L] - \mathbb{E}[P_{-1}] = \mathbb{E}[P_L]. □\square

Lemma 2 (the variance). Var(Y^)=∑l=0LVl/Nl\mathrm{Var}(\widehat{Y}) = \sum_{l=0}^{L} V_l / N_l.

Proof. The N0+⋯+NLN_0 + \cdots + N_L samples are independent, so the variance of the sum is the sum of the variances: Var(Y^)=∑lNl−2∑nVar(Yl(n,l))=∑lVl/Nl\mathrm{Var}(\widehat{Y}) = \sum_l N_l^{-2} \sum_n \mathrm{Var}(Y_l^{(n, l)}) = \sum_l V_l / N_l. □\square

Lemma 3 (the error split). E[(Y^−E[P])2]=∑lVl/Nl+(E[PL]−E[P])2\mathbb{E}[(\widehat{Y} - \mathbb{E}[P])^2] = \sum_l V_l / N_l + (\mathbb{E}[P_L] - \mathbb{E}[P])^2.

Proof. Write Y^−E[P]=(Y^−E[PL])+(E[PL]−E[P])\widehat{Y} - \mathbb{E}[P] = (\widehat{Y} - \mathbb{E}[P_L]) + (\mathbb{E}[P_L] - \mathbb{E}[P]). 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. □\square

So the mean squared error is at most ε2\varepsilon^2 if the variance is at most ε2/2\varepsilon^2/2 and the bias ∣E[PL]−E[P]∣|\mathbb{E}[P_L] - \mathbb{E}[P]| is at most ε/2\varepsilon/\sqrt{2}. The algorithm aims at these two targets separately.

Lemma 4 (the least cost for the variance target). For fixed LL and real Nl>0N_l > 0, every choice with ∑lVl/Nl≤ε2/2\sum_l V_l / N_l \le \varepsilon^2/2 has cost ∑lNlCl≥2ε−2(∑lVlCl)2\sum_l N_l C_l \ge 2 \varepsilon^{-2} \big(\sum_l \sqrt{V_l C_l}\big)^2. Equality holds for

Nl=2ε−2Vl/Cl ∑k=0LVkCk.N_l = 2 \varepsilon^{-2} \sqrt{V_l / C_l}\, \sum_{k=0}^{L} \sqrt{V_k C_k}.

Proof. By the Cauchy-Schwarz inequality for the vectors with entries Vl/Nl\sqrt{V_l / N_l} and NlCl\sqrt{N_l C_l},

(∑lVlCl)2=(∑lVl/Nl NlCl)2≤(∑lVlNl)(∑lNlCl)≤ε22∑lNlCl.\Big(\sum_l \sqrt{V_l C_l}\Big)^2 = \Big(\sum_l \sqrt{V_l / N_l}\, \sqrt{N_l C_l}\Big)^2 \le \Big(\sum_l \frac{V_l}{N_l}\Big) \Big(\sum_l N_l C_l\Big) \le \frac{\varepsilon^2}{2} \sum_l N_l C_l.

Equality in the first step holds if and only if NlClN_l C_l is a fixed multiple of Vl/NlV_l / N_l, that is Nl=μVl/ClN_l = \mu \sqrt{V_l / C_l}. Equality in the second step needs ∑lVl/Nl=ε2/2\sum_l V_l / N_l = \varepsilon^2/2, which gives μ=2ε−2∑kVkCk\mu = 2 \varepsilon^{-2} \sum_k \sqrt{V_k C_k}. The same counts come from a Lagrange multiplier for the cost with the variance constraint. □\square

Line L5 rounds these counts up. The variance target still holds: with S=∑kVkCkS = \sum_k \sqrt{V_k C_k} and Nl≥2ε−2Vl/Cl SN_l \ge 2 \varepsilon^{-2} \sqrt{V_l / C_l}\, S,

∑lVlNl≤∑lε2Vl2SVl/Cl=ε22S∑lVlCl=ε22.\sum_l \frac{V_l}{N_l} \le \sum_l \frac{\varepsilon^2 V_l}{2 S \sqrt{V_l / C_l}} = \frac{\varepsilon^2}{2 S} \sum_l \sqrt{V_l C_l} = \frac{\varepsilon^2}{2}.

The rounding adds at most one sample on each level, so at most ∑lCl\sum_l C_l to the cost.

Lemma 5 (the bias test). Assume that E[Yl]=c 2−αl\mathbb{E}[Y_l] = c\, 2^{-\alpha l} for all l≥Ll \ge L, with α>0\alpha > 0 and a constant cc. Then ∣E[P]−E[PL]∣=∣E[YL]∣/(2α−1)|\mathbb{E}[P] - \mathbb{E}[P_L]| = |\mathbb{E}[Y_L]| / (2^\alpha - 1).

Proof. If E[Pl]→E[P]\mathbb{E}[P_l] \to \mathbb{E}[P], then E[P]−E[PL]=∑l>LE[Yl]=E[YL]∑k≥12−αk=E[YL]/(2α−1)\mathbb{E}[P] - \mathbb{E}[P_L] = \sum_{l > L} \mathbb{E}[Y_l] = \mathbb{E}[Y_L] \sum_{k \ge 1} 2^{-\alpha k} = \mathbb{E}[Y_L] / (2^\alpha - 1), a geometric series. □\square

Line L7 puts the sample means Y^L\widehat{Y}_L and Y^L−1/2α\widehat{Y}_{L-1} / 2^\alpha into this formula and takes the larger value. Under the assumption of Lemma 5 from level L−1L - 1 on, both are estimates of ∣E[YL]∣|\mathbb{E}[Y_L]|; the second one guards against a sample mean Y^L\widehat{Y}_L that is small by chance. Line L8 adds a level while the estimate is above ε/2\varepsilon/\sqrt{2}.

Theorem (correctness). When the loop ends, the estimate of line L9 has mean E[PL]\mathbb{E}[P_L]. If the sample variances and means of lines L4 and L7 are equal to the true VlV_l and E[Yl]\mathbb{E}[Y_l], and E[Yl]=c 2−αl\mathbb{E}[Y_l] = c\, 2^{-\alpha l} for l≥L−1l \ge L - 1, then its mean squared error is at most ε2\varepsilon^2, and no choice of real sample counts for this LL reaches the variance target at a lower cost.

Proof. The first claim is Lemma 1. The loop ends only when all dNl=0dN_l = 0, so the counts are at least those of Lemma 4 and the variance is at most ε2/2\varepsilon^2/2; the bias test passed, so by Lemma 5 the bias is at most ε/2\varepsilon/\sqrt{2}. Lemma 3 adds the two parts. The cost claim is Lemma 4. ■\blacksquare

Termination. Each pass of lines L2 to L8 with some dNl>0dN_l > 0 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 dS=rS dt+σS dWdS = rS\, dt + \sigma S\, dW is Sk+1=Sk(1+rh+σΔWk)S_{k+1} = S_k (1 + r h + \sigma \Delta W_k). The factors are independent with mean 1+rh1 + r h, so after 2l2^l steps of size hl=T/2lh_l = T/2^l, E[Pl]=S0(1+rT/2l)2l\mathbb{E}[P_l] = S_0 (1 + r T/2^l)^{2^l}. This is the exact level mean that the tests compare with. Since ln⁡(1+x)=x−x2/2+O(x3)\ln(1 + x) = x - x^2/2 + O(x^3), E[Pl]=S0erT(1−r2Thl/2+O(hl2))\mathbb{E}[P_l] = S_0 e^{rT} (1 - r^2 T h_l / 2 + O(h_l^2)), so the weak rate is α=1\alpha = 1. The coarse path of a sample sums pairs of the fine increments, so it has the law of a coarse Euler path, and E[Yl]\mathbb{E}[Y_l] 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, VlV_l and E[Yl]\mathbb{E}[Y_l] are estimated from the same samples, the rate α\alpha is an assumption, and the bias test can pass too early when E[Yl]\mathbb{E}[Y_l] does not yet follow its rate. Then the mean squared error can be larger than ε2\varepsilon^2. The cost bound as a function of ε\varepsilon is the MLMC complexity theorem, and it needs the rate hypotheses of that theorem.

Complexity

The cost is ∑lNlCl\sum_l N_l C_l model work, plus O(1)O(1) arithmetic per sample and O(L)O(L) per pass of the loop in the real RAM model. With the counts of line L5,

∑lNlCl≈2ε−2(∑l=0LVlCl)2,VlCl≤c 2(γ−β)l/2.\sum_l N_l C_l \approx 2 \varepsilon^{-2} \Big(\sum_{l=0}^{L} \sqrt{V_l C_l}\Big)^2, \qquad \sqrt{V_l C_l} \le c\, 2^{(\gamma - \beta) l / 2}.

The bias test stops at L≈log⁡2(ε−1)/αL \approx \log_2(\varepsilon^{-1}) / \alpha. If β>γ\beta > \gamma, the sum is a convergent geometric series and the cost is O(ε−2)O(\varepsilon^{-2}), the cost of plain Monte Carlo with exact samples of unit cost. If β=γ\beta = \gamma, every term is O(1)O(1), the sum is O(L)O(L) and the cost is O(ε−2L2)=O(ε−2(log⁡ε)2)O(\varepsilon^{-2} L^2) = O(\varepsilon^{-2} (\log \varepsilon)^2). If β<γ\beta < \gamma, the last term dominates and the cost is O(ε−2−(γ−β)/α)O(\varepsilon^{-2 - (\gamma - \beta)/\alpha}). These three cases are the MLMC complexity theorem; its proof needs α≥min⁡(β,γ)/2\alpha \ge \min(\beta, \gamma)/2 and adds the rounding cost.

For the Euler example, α=β=γ=1\alpha = \beta = \gamma = 1, so MLMC costs O(ε−2(log⁡ε)2)O(\varepsilon^{-2} (\log \varepsilon)^2). Plain Monte Carlo needs O(ε−2)O(\varepsilon^{-2}) samples on a level with O(ε−1)O(\varepsilon^{-1}) steps, which is O(ε−3)O(\varepsilon^{-3}). The extra space is O(L)O(L) for the sums of each level; the samples themselves are not stored.

Properties

  • Unbiased for the finest level. The estimate has mean E[PL]\mathbb{E}[P_L] for any counts. All the bias is the bias of level LL.
  • 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 hl=4−lh0h_l = 4^{-l} h_0. Then the rates are α=β=γ=2\alpha = \beta = \gamma = 2 in powers of 2, with the same order of cost.
  • Antithetic and Milstein corrections. A better coupling raises β\beta. With the Milstein method in one dimension, β=2>γ=1\beta = 2 > \gamma = 1, and the cost is O(ε−2)O(\varepsilon^{-2}).
  • 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 E[P]\mathbb{E}[P] itself, if β>γ\beta > \gamma.
  • 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 VlV_l 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 Pl−1P_{l-1} with its own random input, Vl=Var(Pl)+Var(Pl−1)V_l = \mathrm{Var}(P_l) + \mathrm{Var}(P_{l-1}) 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. Y0Y_0 is P0P_0 itself (P−1=0P_{-1} = 0). Starting the sum at a correction drops the main term.
  • Too few initial samples. Line L4 estimates VlV_l from N0N_0 samples. With heavy-tailed corrections, a small N0N_0 underestimates VlV_l, and line L5 then takes too few samples. Use N0N_0 of a few hundred, and check the rates against the level variances.
  • A bias test on one noisy mean. If line L7 used only ∣Y^L∣|\widehat{Y}_L|, a correction that is small by chance stops the loop early. The maximum with ∣Y^L−1∣/2α|\widehat{Y}_{L-1}|/2^\alpha 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 β=1/2\beta = 1/2 with Euler paths, not 1. With β=1\beta = 1 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.

multilevel_monte_carlo.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example