Algorithm Search⌘K

Algorithmresearch

Multifidelity Monte Carlo

Combines a high fidelity model with cheaper surrogates as control variates, choosing sample sizes to minimize the variance at a fixed cost.

Time
O(p + k N) worst
Space
O(N) extra
Where
N = the number of draws of the random input (the count of the cheapest model); k = the number of models; p = the budget in units of model cost
Properties
randomizednot exactnot iterativerandomized
Origin
Benjamin Peherstorfer, Karen Willcox, Max Gunzburger, 2016

Multifidelity Monte Carlo (MFMC) estimates the mean of the output of an expensive high fidelity model, with the help of cheaper models of the same output, such as a coarse mesh, a reduced model or a data fit. The cheap models are control variates: their sample means over many inputs correct the noisy sample mean of the expensive model over a few of the same inputs. The estimate stays unbiased for the mean of the expensive model, whatever the cheap models are. Their quality changes only the variance, and the method picks the number of runs of each model and the weights of the corrections to make the variance as small as possible for a fixed total cost. Unlike multilevel Monte Carlo, it needs no hierarchy of levels and no rates, only the correlation of each cheap model with the expensive one and its cost.

In plain words

You have one slow, trusted model and some fast models that are only roughly right. You want the average output of the slow model over random inputs.

Run the slow model a few times and average. That average is noisy. Now run a fast model on the same inputs and also on many more inputs. If the fast model goes up when the slow one goes up, the gap between its average on the few inputs and on the many inputs tells you how lucky or unlucky the few inputs were. Use that gap to correct the slow average. A good fast model removes most of the noise, and a bad one removes little, but the correction never shifts the answer on average. The method works out how many runs to give each model for the money you have.

The problem

The input is a high fidelity model f1f_1 and cheaper models f2,…,fkf_2, \ldots, f_k, all functions of the same random input zz, the costs w1,…,wkw_1, \ldots, w_k of one run of each, and a budget pp. The output is an estimate s^\widehat{s} of E[f1(z)]\mathbb{E}[f_1(z)] with cost ∑iwimi=p\sum_i w_i m_i = p and the smallest variance. Here mim_i is the number of runs of model ii. Let σi2=Var(fi(z))\sigma_i^2 = \mathrm{Var}(f_i(z)) and ρi=Corr(f1(z),fi(z))\rho_i = \mathrm{Corr}(f_1(z), f_i(z)), with ρ1=1\rho_1 = 1 and ρk+1=0\rho_{k+1} = 0.

The estimator uses nested draws z1,…,zmkz_1, \ldots, z_{m_k} with m1≤m2≤⋯≤mkm_1 \le m_2 \le \cdots \le m_k, and fˉi(m)\bar{f}_i^{(m)} is the mean of fif_i over the first mm draws:

s^=fˉ1(m1)+∑i=2kαi(fˉi(mi)−fˉi(mi−1)).\widehat{s} = \bar{f}_1^{(m_1)} + \sum_{i=2}^{k} \alpha_i \big(\bar{f}_i^{(m_i)} - \bar{f}_i^{(m_{i-1})}\big).

The optimal counts and weights exist under two conditions on the models: ∣ρ1∣>∣ρ2∣>⋯>∣ρk∣|\rho_1| > |\rho_2| > \cdots > |\rho_k|, and each model is cheap enough for its correlation,

wi−1wi>ρi−12−ρi2ρi2−ρi+12,i=2,…,k.\frac{w_{i-1}}{w_i} > \frac{\rho_{i-1}^2 - \rho_i^2}{\rho_i^2 - \rho_{i+1}^2}, \qquad i = 2, \ldots, k.

The algorithm

  1. MFMC(f_1..f_k, w_1..w_k, p, DRAW, n)
  2. 1σ_i, ρ_i ← sample standard deviations and correlations with f_1, from n pilot draws
  3. 2if |ρ_i| does not decrease, or w_(i-1)/w_i ≤ (ρ_(i-1)^2 - ρ_i^2)/(ρ_i^2 - ρ_(i+1)^2) for some i, then stop
  4. 3r_i ← sqrt(w_1 (ρ_i^2 - ρ_(i+1)^2) / (w_i (1 - ρ_2^2))) for i = 1..k ▷ r_1 = 1, ρ_(k+1) = 0
  5. 4m_1 ← p / (w_1 r_1 + ... + w_k r_k); m_i ← m_1 r_i, rounded down and kept in order
  6. 5α_i ← ρ_i σ_1 / σ_i for i = 2..k
  7. 6draw z_1, ..., z_(m_k) by DRAW
  8. 7s ← mean of f_1(z_1), ..., f_1(z_(m_1))
  9. 8for i = 2..k: s ← s + α_i (mean of f_i over z_1..z_(m_i) - mean of f_i over z_1..z_(m_(i-1)))
  10. 9return s

Line L1 is the only step that needs runs of all models on the same inputs; the pilot draws are separate from the draws of line L6. Line L2 tests the two conditions; if they fail, drop or reorder a model and start again. Lines L3 and L4 give the counts: model ii gets rir_i times as many runs as model 1, and the budget fixes m1m_1. Line L5 is the best weight of a control variate. In lines L7 and L8, the second mean of a correction is over the first mi−1m_{i-1} draws of the same list, so the two means of a correction are strongly correlated and their difference is small.

Example

Let zz be uniform on [0,1][0, 1], f1(z)=ezf_1(z) = e^z, f2(z)=1+z+z2/2f_2(z) = 1 + z + z^2/2 and f3(z)=1+zf_3(z) = 1 + z, the exponential and two of its Taylor polynomials. The costs are w=(1,0.01,0.001)w = (1, 0.01, 0.001) and the budget is p=100p = 100. The exact statistics, from E[f1]=e−1\mathbb{E}[f_1] = e - 1, Cov(f1,f2)=(2−e/2)/3\mathrm{Cov}(f_1, f_2) = (2 - e/2)/3 and Cov(f1,f3)=(3−e)/2\mathrm{Cov}(f_1, f_3) = (3 - e)/2, are:

model ii mean σi\sigma_i ρi\rho_i wiw_i
1 1.71828 0.4919711 1 1
2 5/3 0.4346135 0.9990758 0.01
3 1.5 0.2886751 0.9918268 0.001

Line L2: the cost ratios are 100>0.128100 > 0.128 and 10>0.0146710 > 0.01467, so the conditions hold. Lines L3 to L5 then give:

model ii rir_i mim_i αi\alpha_i cost wimiw_i m_i
1 1 49.771 1 49.77
2 27.9495 1391.08 1.130928 13.91
3 729.703 36318.1 1.690309 36.32

The variance of s^\widehat{s} is 1.805×10−51.805 \times 10^{-5}. Plain Monte Carlo with the same budget runs f1f_1 100 times and has the variance σ12/100=0.00242\sigma_1^2/100 = 0.00242, 134 times as large. More than a third of the budget goes to the cheapest model, because it is very cheap and still has ρ32=0.984\rho_3^2 = 0.984.

Correctness

The claim has two parts. First, s^\widehat{s} is unbiased for E[f1]\mathbb{E}[f_1] for every choice of counts and weights, because each correction is a difference of two sample means of the same model. Second, with the true σi\sigma_i and ρi\rho_i and under the conditions of line L2, the counts and weights of lines L3 to L5 minimize the variance among all choices with cost pp. The key step is the variance formula

Var(s^)=σ12∑i=1kρi2−ρi+12mi\mathrm{Var}(\widehat{s}) = \sigma_1^2 \sum_{i=1}^{k} \frac{\rho_i^2 - \rho_{i+1}^2}{m_i}

at the best weights, which uses that the covariance of two nested means is the covariance of one draw over the larger count. The Cauchy-Schwarz inequality with the cost constraint then gives mi∝(ρi2−ρi+12)/wim_i \propto \sqrt{(\rho_i^2 - \rho_{i+1}^2)/w_i}, and the second condition is exactly what makes these counts increase with ii, as nesting requires. The full proof is in the proof file. It does not cover the pilot: with estimated statistics the allocation is close to the optimum, not at it.

Proof: The multifidelity estimator is unbiased and its allocation minimizes the variance at a fixed costfull

We assume exact arithmetic and exact random numbers. The models f1,…,fkf_1, \ldots, f_k are square integrable functions of one random input zz. Let σi2=Var(fi(z))\sigma_i^2 = \mathrm{Var}(f_i(z)), ρi=Corr(f1(z),fi(z))\rho_i = \mathrm{Corr}(f_1(z), f_i(z)) with ρ1=1\rho_1 = 1 and ρk+1=0\rho_{k+1} = 0, and let wi>0w_i > 0 be the cost of one run of model ii. The sample counts are integers or reals with 1≤m1≤m2≤⋯≤mk1 \le m_1 \le m_2 \le \cdots \le m_k. For independent draws z1,…,zmkz_1, \ldots, z_{m_k} and m≤mkm \le m_k write fˉi(m)=1m∑j=1mfi(zj)\bar{f}_i^{(m)} = \frac{1}{m} \sum_{j=1}^{m} f_i(z_j), the mean over the first mm draws. The estimator is

s^=fˉ1(m1)+∑i=2kαi(fˉi(mi)−fˉi(mi−1)).\widehat{s} = \bar{f}_1^{(m_1)} + \sum_{i=2}^{k} \alpha_i \big(\bar{f}_i^{(m_i)} - \bar{f}_i^{(m_{i-1})}\big).

The weights αi\alpha_i and the counts mim_i are fixed before the draws. In the algorithm they come from a pilot run with its own draws, so they are independent of z1,…,zmkz_1, \ldots, z_{m_k}, and the statements below hold conditionally on the pilot.

Lemma 1 (unbiased). E[s^]=E[f1(z)]\mathbb{E}[\widehat{s}] = \mathbb{E}[f_1(z)] for all weights and counts.

Proof. Both means of fif_i in a correction have the mean E[fi(z)]\mathbb{E}[f_i(z)], so each correction has mean zero. □\square

Lemma 2 (covariance of nested means). Cov(fˉi(m),fˉj(n))=Cov(fi,fj)/max⁡(m,n)\mathrm{Cov}(\bar{f}_i^{(m)}, \bar{f}_j^{(n)}) = \mathrm{Cov}(f_i, f_j) / \max(m, n).

Proof. Only the pairs with the same draw are correlated, and there are min⁡(m,n)\min(m, n) of them. So the covariance is min⁡(m,n) Cov(fi,fj)/(mn)=Cov(fi,fj)/max⁡(m,n)\min(m, n)\, \mathrm{Cov}(f_i, f_j) / (m n) = \mathrm{Cov}(f_i, f_j) / \max(m, n). □\square

Lemma 3 (the variance). With Δi=1/mi−1−1/mi≥0\Delta_i = 1/m_{i-1} - 1/m_i \ge 0,

Var(s^)=σ12m1+∑i=2kΔi(αi2σi2−2αiρiσ1σi).\mathrm{Var}(\widehat{s}) = \frac{\sigma_1^2}{m_1} + \sum_{i=2}^{k} \Delta_i \big(\alpha_i^2 \sigma_i^2 - 2 \alpha_i \rho_i \sigma_1 \sigma_i\big).

Proof. Let Di=fˉi(mi)−fˉi(mi−1)D_i = \bar{f}_i^{(m_i)} - \bar{f}_i^{(m_{i-1})}. By Lemma 2, Var(Di)=σi2(1/mi+1/mi−1−2/mi)=σi2Δi\mathrm{Var}(D_i) = \sigma_i^2 (1/m_i + 1/m_{i-1} - 2/m_i) = \sigma_i^2 \Delta_i. The covariance of fˉ1(m1)\bar{f}_1^{(m_1)} with DiD_i is ρiσ1σi(1/mi−1/mi−1)=−ρiσ1σiΔi\rho_i \sigma_1 \sigma_i (1/m_i - 1/m_{i-1}) = -\rho_i \sigma_1 \sigma_i \Delta_i, because m1≤mi−1≤mim_1 \le m_{i-1} \le m_i. For 2≤i<j2 \le i < j, the four terms of Cov(Di,Dj)\mathrm{Cov}(D_i, D_j) have the maxima mj,mj−1,mj,mj−1m_j, m_{j-1}, m_j, m_{j-1} with signs +,−,−,++, -, -, +, because mi−1≤mi≤mj−1≤mjm_{i-1} \le m_i \le m_{j-1} \le m_j, so Cov(Di,Dj)=0\mathrm{Cov}(D_i, D_j) = 0. Adding the variances and twice the covariances gives the formula. □\square

Lemma 4 (the best weights). For fixed counts with Δi>0\Delta_i > 0, the variance is smallest at αi=ρiσ1/σi\alpha_i = \rho_i \sigma_1 / \sigma_i, and then

Var(s^)=σ12∑i=1kρi2−ρi+12mi.\mathrm{Var}(\widehat{s}) = \sigma_1^2 \sum_{i=1}^{k} \frac{\rho_i^2 - \rho_{i+1}^2}{m_i}.

Proof. The term of αi\alpha_i is the quadratic Δi(αi2σi2−2αiρiσ1σi)\Delta_i (\alpha_i^2 \sigma_i^2 - 2 \alpha_i \rho_i \sigma_1 \sigma_i), with its minimum −Δiρi2σ12-\Delta_i \rho_i^2 \sigma_1^2 at αi=ρiσ1/σi\alpha_i = \rho_i \sigma_1 / \sigma_i. So the variance is σ12(1/m1−∑i≥2ρi2(1/mi−1−1/mi))\sigma_1^2 \big(1/m_1 - \sum_{i \ge 2} \rho_i^2 (1/m_{i-1} - 1/m_i)\big). Collect the factor of each 1/mi1/m_i: it is 1−ρ221 - \rho_2^2 for i=1i = 1, ρi2−ρi+12\rho_i^2 - \rho_{i+1}^2 for 2≤i<k2 \le i < k, and ρk2\rho_k^2 for i=ki = k. With ρ1=1\rho_1 = 1 and ρk+1=0\rho_{k+1} = 0 this is the formula. □\square

Theorem (optimal allocation). Assume ∣ρ1∣>∣ρ2∣>⋯>∣ρk∣|\rho_1| > |\rho_2| > \cdots > |\rho_k| and

wi−1wi>ρi−12−ρi2ρi2−ρi+12,i=2,…,k.\frac{w_{i-1}}{w_i} > \frac{\rho_{i-1}^2 - \rho_i^2}{\rho_i^2 - \rho_{i+1}^2}, \qquad i = 2, \ldots, k.

Among all real counts with m1≤⋯≤mkm_1 \le \cdots \le m_k and cost ∑iwimi=p\sum_i w_i m_i = p, and all weights, the smallest variance is σ12p(∑i=1kwi(ρi2−ρi+12))2\frac{\sigma_1^2}{p} \big(\sum_{i=1}^{k} \sqrt{w_i (\rho_i^2 - \rho_{i+1}^2)}\big)^2. It is reached by αi=ρiσ1/σi\alpha_i = \rho_i \sigma_1 / \sigma_i and mi=m1rim_i = m_1 r_i with

ri=w1(ρi2−ρi+12)wi(1−ρ22),m1=p∑iwiri.r_i = \sqrt{\frac{w_1 (\rho_i^2 - \rho_{i+1}^2)}{w_i (1 - \rho_2^2)}}, \qquad m_1 = \frac{p}{\sum_i w_i r_i}.

Proof. Let ai=ρi2−ρi+12a_i = \rho_i^2 - \rho_{i+1}^2, which is positive by the first assumption. For every admissible choice of counts, Lemma 3 and Lemma 4 give Var(s^)≥σ12∑iai/mi\mathrm{Var}(\widehat{s}) \ge \sigma_1^2 \sum_i a_i / m_i: if Δi>0\Delta_i > 0 this is Lemma 4, and if Δi=0\Delta_i = 0 the term of αi\alpha_i is zero, which is also the value of the minimum in Lemma 4. By the Cauchy-Schwarz inequality,

(∑iaiwi)2=(∑iai/mi wimi)2≤(∑iaimi)(∑iwimi)=p∑iaimi,\Big(\sum_i \sqrt{a_i w_i}\Big)^2 = \Big(\sum_i \sqrt{a_i / m_i}\, \sqrt{w_i m_i}\Big)^2 \le \Big(\sum_i \frac{a_i}{m_i}\Big) \Big(\sum_i w_i m_i\Big) = p \sum_i \frac{a_i}{m_i},

so every admissible choice has variance at least the stated value. Equality holds when wimiw_i m_i is a fixed multiple of ai/mia_i / m_i, that is mi∝ai/wim_i \propto \sqrt{a_i / w_i}, which is mi=m1rim_i = m_1 r_i, and the cost constraint fixes m1m_1. It remains to show that these counts are admissible: mi−1<mim_{i-1} < m_i holds if and only if ai−1/wi−1<ai/wia_{i-1} / w_{i-1} < a_i / w_i, which is the second assumption. Then Δi>0\Delta_i > 0 and Lemma 4 gives the weights. ■\blacksquare

Corollary (the gain over plain Monte Carlo). Plain Monte Carlo with the budget pp uses p/w1p / w_1 runs of f1f_1 and has the variance σ12w1/p\sigma_1^2 w_1 / p. The ratio of the optimal multifidelity variance to it is

(∑i=1kwiw1(ρi2−ρi+12))2.\Big(\sum_{i=1}^{k} \sqrt{\frac{w_i}{w_1} (\rho_i^2 - \rho_{i+1}^2)}\Big)^2.

The assumptions of the theorem do not make this ratio smaller than 1. For k=2k = 2, ρ22=0.01\rho_2^2 = 0.01 and w2=w1/100w_2 = w_1 / 100, the cost condition holds (100>99100 > 99), but the ratio is (0.99+0.0001)2=1.0100(\sqrt{0.99} + \sqrt{0.0001})^2 = 1.0100. So the ratio is a separate test: use the cheap model only when the ratio is below 1.

The algorithm. Line L1 estimates σi\sigma_i and ρi\rho_i from pilot runs. Line L2 tests the two assumptions and stops if they fail; then a model must be removed or reordered. Lines L3 to L5 compute rir_i, m1m_1 and αi\alpha_i by the theorem. The code rounds the counts down, keeps them in order and keeps m1≥2m_1 \ge 2. Lines L6 to L9 compute s^\widehat{s} with nested draws. By Lemma 1 the result is unbiased for any counts and weights, and Lemma 3 gives its variance for the rounded counts.

What is not proved. With estimated σi\sigma_i and ρi\rho_i, the counts and weights are near the optimum, not at it. The variance formula of the theorem then holds with the true statistics in Lemma 3 and the used weights, and it can be larger than the stated minimum. If the pilot runs are also used in the estimate, the weights depend on the samples and Lemma 1 holds only approximately. The estimator gives the mean of f1f_1; the error of f1f_1 against the real system is a modeling error outside the method.

Complexity

In the real RAM model with a model run of cost wiw_i, lines L6 to L8 cost ∑iwimi=p\sum_i w_i m_i = p in model work, plus O(mi)O(m_i) additions for each model, which is O(kN)O(k N) with N=mkN = m_k. The pilot of line L1 costs n∑iwin \sum_i w_i, outside the budget. Lines L2 to L5 cost O(k)O(k). The list of draws takes O(N)O(N) space; a version that draws each input once and adds it to all running sums needs O(k)O(k).

The variance at the optimum is σ12p(∑iwi(ρi2−ρi+12))2\frac{\sigma_1^2}{p} \big(\sum_i \sqrt{w_i (\rho_i^2 - \rho_{i+1}^2)}\big)^2, so the error falls like p−1/2p^{-1/2}, as for plain Monte Carlo, with a smaller constant. The ratio of the two variances is (∑i(wi/w1)(ρi2−ρi+12))2\big(\sum_i \sqrt{(w_i/w_1)(\rho_i^2 - \rho_{i+1}^2)}\big)^2, which is 0.00746 in the example.

Properties

  • Unbiased. The mean of the estimate is the mean of the high fidelity model, for any cheap models. A bad cheap model costs efficiency, not accuracy.
  • Non-intrusive. All models are black boxes on the same input. There is no need for levels, meshes or rates.
  • Optimal for its class. Among estimators of this nested form with a fixed cost, the allocation is the best, given the true statistics.
  • Not always better than plain Monte Carlo. The conditions of line L2 do not ensure a gain; the variance ratio must also be below 1.

Variants and improvements

  • Multilevel Monte Carlo as a special case. With levels of one discretization as the models and all weights αi=1\alpha_i = 1, the estimator is close to multilevel Monte Carlo, which uses independent draws on each level instead of nested ones.
  • Approximate control variates. Later work generalizes the sharing of draws between the models (for example, each cheap model compared with model 1 directly) and optimizes over these sample structures.
  • Model selection. Run the allocation for every ordered subset of the cheap models and keep the subset with the smallest variance. With a few models this is cheap, because it uses only the pilot statistics.
  • Multifidelity for other statistics. The same idea applies to variances, quantiles or Sobol indices, with the estimator of that statistic in place of the mean.

When to use it

Use MFMC when one model is expensive and you have cheap models whose outputs are strongly correlated with it, but that do not form a sequence of levels with known rates: reduced models such as the reduced basis method or a POD-Galerkin reduced model, a Gaussian process fit, or a simpler physics model. Use multilevel Monte Carlo when the models are discretization levels and the bias of the finest level must also go to zero. Use the cheap model alone only when its error against the expensive one is known to be small; MFMC does not need this, because the expensive model removes the bias. Use plain Monte Carlo integration when no cheap model has a correlation close to 1.

Pitfalls

  • Independent draws in a correction. If line L8 takes the second mean over new draws instead of the first mi−1m_{i-1} of the same list, the two means are independent, the correction adds variance instead of removing it, and the estimate is worse than plain Monte Carlo. Nest the draws as in line L6.
  • Using the pilot runs in the estimate. If the draws of line L1 are reused in lines L7 and L8, the weights depend on the samples and the estimate is slightly biased. Keep the pilot separate, or accept the bias knowingly.
  • Ordering by cost instead of correlation. Line L2 needs the models in order of decreasing ∣ρi∣|\rho_i|. A cheap model with a higher correlation than a more expensive one must come first, or the counts of line L4 are not in order.
  • A weak cheap model. With ρ22=0.01\rho_2^2 = 0.01 and w2=w1/100w_2 = w_1/100, the conditions hold, but the variance ratio is 1.01, so the method loses to plain Monte Carlo. Check the ratio after line L4 and drop such a model.
  • Few pilot runs. Line L1 with a few runs gives noisy correlations near 1, where the counts of line L3 are very sensitive to ρi2−ρi+12\rho_i^2 - \rho_{i+1}^2. Use enough pilot runs that these differences are clearly resolved.

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.

multifidelity_monte_carlo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multifidelity-monte-carlo/. The authors are listed in prov/SQG1XP.jsonl.
"""Multifidelity Monte Carlo (Peherstorfer, Willcox and Gunzburger 2016).

Model 1 is the high fidelity model, and models 2, ..., k are cheaper models of
the same output. Each model is a function of the same random input z. The
estimator is

    s = mean of f_1 over z_1..z_{m_1}
        + sum over i >= 2 of alpha_i (mean of f_i over z_1..z_{m_i}
                                      - mean of f_i over z_1..z_{m_(i-1)}),

with m_1 <= m_2 <= ... <= m_k and nested samples. It is unbiased for
E[f_1]. The sample counts and the weights minimize the variance at a fixed
cost p = sum w_i m_i, where w_i is the cost of one run of model i.

Lists are 0-based in the code: index 0 is model 1 of the text.
"""

import math
import random
from typing import Callable, Sequence

Model = Callable[[object], float]
Draw = Callable[[random.Random], object]


def pilot_statistics(models: Sequence[Model], draw: Draw, n: int, rng: random.Random):
    """Sample standard deviations sigma_i and correlations rho_i = corr(f_1, f_i) from n pilot inputs."""
    zs = [draw(rng) for _ in range(n)]
    ys = [[f(z) for z in zs] for f in models]
    means = [sum(y) / n for y in ys]
    sig = [math.sqrt(sum((v - mu) ** 2 for v in y) / (n - 1)) for y, mu in zip(ys, means)]
    rho = []
    for i, y in enumerate(ys):
        c = sum((a - means[0]) * (b - means[i]) for a, b in zip(ys[0], y)) / (n - 1)
        rho.append(c / (sig[0] * sig[i]))
    return sig, rho


def check_conditions(rho: Sequence[float], w: Sequence[float]) -> None:
    """The conditions of the optimal allocation: |rho_1| > ... > |rho_k| and the cost ratio test."""
    k = len(rho)
    r2 = [x * x for x in rho] + [0.0]
    for i in range(1, k):
        if not r2[i - 1] > r2[i]:
            raise ValueError("the models must be ordered by decreasing |rho|")
        if not w[i - 1] / w[i] > (r2[i - 1] - r2[i]) / (r2[i] - r2[i + 1]):
            raise ValueError(f"model {i + 1} is not cheap enough for its correlation")


def mfmc_allocation(sig: Sequence[float], rho: Sequence[float], w: Sequence[float], budget: float):
    """The optimal real sample counts m_i and weights alpha_i for the budget p."""
    k = len(rho)
    check_conditions(rho, w)  # @line L2
    r2 = [x * x for x in rho] + [0.0]
    ratio = [math.sqrt(w[0] * (r2[i] - r2[i + 1]) / (w[i] * (1.0 - r2[1]))) for i in range(k)]  # @line L3
    m1 = budget / sum(wi * ri for wi, ri in zip(w, ratio))  # @line L4
    m = [m1 * ri for ri in ratio]
    alpha = [rho[i] * sig[0] / sig[i] for i in range(k)]  # @line L5
    return m, alpha


def mfmc_variance(sig: Sequence[float], rho: Sequence[float], m: Sequence[float], alpha: Sequence[float]) -> float:
    """Var(s) = sigma_1^2 / m_1 + sum_{i>=2} (1/m_(i-1) - 1/m_i)(alpha_i^2 sigma_i^2 - 2 alpha_i rho_i sigma_1 sigma_i)."""
    v = sig[0] ** 2 / m[0]
    for i in range(1, len(m)):
        v += (1.0 / m[i - 1] - 1.0 / m[i]) * (alpha[i] ** 2 * sig[i] ** 2 - 2 * alpha[i] * rho[i] * sig[0] * sig[i])
    return v


def optimal_variance(sig: Sequence[float], rho: Sequence[float], w: Sequence[float], budget: float) -> float:
    """The minimum variance sigma_1^2 / p (sum_i sqrt(w_i (rho_i^2 - rho_(i+1)^2)))^2."""
    r2 = [x * x for x in rho] + [0.0]
    return sig[0] ** 2 / budget * sum(math.sqrt(w[i] * (r2[i] - r2[i + 1])) for i in range(len(rho))) ** 2


def integer_counts(m: Sequence[float]) -> list[int]:
    """Round down, keep at least 2 samples of model 1 and keep the counts non-decreasing."""
    out = []
    for x in m:
        c = max(2, int(math.floor(x)))
        if out and c < out[-1]:
            c = out[-1]
        out.append(c)
    return out


def mfmc_estimate(models: Sequence[Model], draw: Draw, m: Sequence[int], alpha: Sequence[float], rng: random.Random) -> float:
    """The multifidelity estimate with nested samples: z_1..z_(m_(i-1)) are the first m_(i-1) of z_1..z_(m_i)."""
    zs = [draw(rng) for _ in range(m[-1])]  # @line L6
    s = sum(models[0](z) for z in zs[: m[0]]) / m[0]  # @line L7
    for i in range(1, len(models)):  # @line L8
        y = [models[i](z) for z in zs[: m[i]]]
        s += alpha[i] * (sum(y) / m[i] - sum(y[: m[i - 1]]) / m[i - 1])
    return s  # @line L9


def mfmc(models: Sequence[Model], w: Sequence[float], budget: float, draw: Draw, rng: random.Random, n_pilot: int = 200) -> dict:
    """The full method: pilot statistics, optimal allocation, then one estimate."""
    sig, rho = pilot_statistics(models, draw, n_pilot, rng)  # @line L1
    m, alpha = mfmc_allocation(sig, rho, w, budget)
    mi = integer_counts(m)
    est = mfmc_estimate(models, draw, mi, alpha, rng)
    return {"estimate": est, "m": mi, "alpha": alpha, "sigma": sig, "rho": rho, "variance": mfmc_variance(sig, rho, mi, alpha)}
test_multifidelity_monte_carlo.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multifidelity-monte-carlo/. The authors are listed in prov/SQG1XP.jsonl.
import math
import random

import pytest

from multifidelity_monte_carlo import (
    check_conditions,
    integer_counts,
    mfmc,
    mfmc_allocation,
    mfmc_estimate,
    mfmc_variance,
    optimal_variance,
    pilot_statistics,
)

E = math.e
# f_1 = exp(z), f_2 = 1 + z + z^2 / 2, f_3 = 1 + z with z uniform on [0, 1]
MODELS = [math.exp, lambda z: 1.0 + z + z * z / 2.0, lambda z: 1.0 + z]
W = [1.0, 0.01, 0.001]
MEAN = E - 1.0
SIG = [math.sqrt((E * E - 1) / 2 - (E - 1) ** 2), math.sqrt(17.0 / 90.0), math.sqrt(1.0 / 12.0)]
RHO = [1.0, ((2 - E / 2) / 3) / (SIG[0] * SIG[1]), ((3 - E) / 2) / (SIG[0] * SIG[2])]


def draw(rng):
    return rng.random()


def test_exact_statistics_of_the_example():
    assert abs(SIG[0] - 0.4919711) < 1e-7
    assert abs(RHO[1] - 0.9990758) < 1e-7
    assert abs(RHO[2] - 0.9918268) < 1e-7


def test_allocation_of_the_example():
    m, alpha = mfmc_allocation(SIG, RHO, W, 100.0)
    assert abs(m[0] - 49.7711) < 1e-3
    assert abs(m[1] - 1391.077) < 1e-2
    assert abs(m[2] - 36318.12) < 1e-1
    assert abs(sum(wi * mi for wi, mi in zip(W, m)) - 100.0) < 1e-9
    assert abs(alpha[1] - 1.130928) < 1e-6 and abs(alpha[2] - 1.690309) < 1e-6
    assert abs(mfmc_variance(SIG, RHO, m, alpha) - optimal_variance(SIG, RHO, W, 100.0)) < 1e-15
    assert abs(optimal_variance(SIG, RHO, W, 100.0) - 1.805113e-5) < 1e-10


def test_allocation_beats_a_brute_force_grid_with_two_models():
    sig, rho, w, p = SIG[:2], RHO[:2], [1.0, 0.05], 10.0
    m, alpha = mfmc_allocation(sig, rho, w, p)
    best = mfmc_variance(sig, rho, m, alpha)
    for k in range(1, 200):
        m1 = k * p / (200 * w[0])
        m2 = (p - w[0] * m1) / w[1]
        if m2 < m1:
            continue
        for a in (alpha[1] * 0.9, alpha[1], alpha[1] * 1.1):
            assert mfmc_variance(sig, rho, [m1, m2], [1.0, a]) >= best - 1e-15


def test_estimator_is_unbiased_with_the_stated_variance():
    m, alpha = mfmc_allocation(SIG, RHO, W, 5.0)
    mi = integer_counts(m)
    assert mi[0] >= 2 and mi[0] <= mi[1] <= mi[2]
    rng = random.Random(42)
    reps = 300
    vals = [mfmc_estimate(MODELS, draw, mi, alpha, rng) for _ in range(reps)]
    mean = sum(vals) / reps
    var = sum((v - mean) ** 2 for v in vals) / (reps - 1)
    v_theory = mfmc_variance(SIG, RHO, mi, alpha)
    assert abs(mean - MEAN) < 4 * math.sqrt(v_theory / reps)
    assert abs(var / v_theory - 1.0) < 4 * math.sqrt(2.0 / (reps - 1))


def test_full_method_with_pilot_beats_plain_monte_carlo():
    rng = random.Random(9)
    res = mfmc(MODELS, W, 20.0, draw, rng, n_pilot=200)
    assert abs(res["estimate"] - MEAN) < 4 * math.sqrt(res["variance"])
    plain_variance = SIG[0] ** 2 / 20.0  # 20 runs of f_1 cost the same budget
    assert res["variance"] < plain_variance / 10


def test_pilot_statistics_are_close_to_the_exact_ones():
    sig, rho = pilot_statistics(MODELS, draw, 2000, random.Random(1))
    assert abs(sig[0] - SIG[0]) < 0.03
    assert abs(rho[2] - RHO[2]) < 0.002


def test_conditions_reject_a_model_that_is_too_expensive():
    with pytest.raises(ValueError):
        # w_2 / w_3 = 0.01 is below (rho_2^2 - rho_3^2) / rho_3^2 = 0.01467
        check_conditions(RHO, [1.0, 0.01, 1.0])
    with pytest.raises(ValueError):
        check_conditions([1.0, 0.5, 0.9], W)

History

Control variates are an old variance reduction method of Monte Carlo simulation, in which a correlated variable with a known mean corrects a sample mean. Multifidelity methods replace the known mean by a cheap estimate from many runs of a cheap model. Peherstorfer, Willcox and Gunzburger gave the estimator with nested draws, the optimal counts and weights for any number of models, and the two conditions on correlations and costs in 2016, and surveyed multifidelity methods for uncertainty propagation, inference and optimization in 2018.

References

  1. Benjamin Peherstorfer, Karen Willcox and Max Gunzburger, Optimal model management for multifidelity Monte Carlo estimation, SIAM Journal on Scientific Computing 38(5), 2016, A3163-A3194, Section 3 (the estimator, its variance, the optimal sample counts and weights, and the conditions on correlations and costs)
  2. Benjamin Peherstorfer, Karen Willcox and Max Gunzburger, Survey of multifidelity methods in uncertainty propagation, inference, and optimization, SIAM Review 60(3), 2018, 550-591, the section on multifidelity uncertainty propagation by control variates

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.worst
  • 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
  • at least three sources
  • a scene preset for the example