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
- Model
- Real RAM
- Properties
- randomizednot exactnot iterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- 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 and cheaper models , all functions of the same random input , the costs of one run of each, and a budget . The output is an estimate of with cost and the smallest variance. Here is the number of runs of model . Let and , with and .
The estimator uses nested draws with , and is the mean of over the first draws:
The optimal counts and weights exist under two conditions on the models: , and each model is cheap enough for its correlation,
The algorithm
MFMC(f_1..f_k, w_1..w_k, p, DRAW, n)- 1
σ_i, ρ_i ← sample standard deviations and correlations with f_1, from n pilot draws - 2
if |ρ_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 - 3
r_i ← sqrt(w_1 (ρ_i^2 - ρ_(i+1)^2) / (w_i (1 - ρ_2^2))) for i = 1..k ▷ r_1 = 1, ρ_(k+1) = 0 - 4
m_1 ← p / (w_1 r_1 + ... + w_k r_k); m_i ← m_1 r_i, rounded down and kept in order - 5
α_i ← ρ_i σ_1 / σ_i for i = 2..k - 6
draw z_1, ..., z_(m_k) by DRAW - 7
s ← mean of f_1(z_1), ..., f_1(z_(m_1)) - 8
for 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))) - 9
return 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 gets times as many runs as model 1, and the budget fixes . 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 draws of the same list, so the two means of a correction are strongly correlated and their difference is small.
Example
Let be uniform on , , and , the exponential and two of its Taylor polynomials. The costs are and the budget is . The exact statistics, from , and , are:
| model | mean | |||
|---|---|---|---|---|
| 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 and , so the conditions hold. Lines L3 to L5 then give:
| model | cost | |||
|---|---|---|---|---|
| 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 is . Plain Monte Carlo with the same budget runs 100 times and has the variance , 134 times as large. More than a third of the budget goes to the cheapest model, because it is very cheap and still has .
Correctness
The claim has two parts. First, is unbiased for 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 and and under the conditions of line L2, the counts and weights of lines L3 to L5 minimize the variance among all choices with cost . The key step is the variance formula
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 , and the second condition is exactly what makes these counts increase with , 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 are square integrable functions of one random input . Let , with and , and let be the cost of one run of model . The sample counts are integers or reals with . For independent draws and write , the mean over the first draws. The estimator is
The weights and the counts are fixed before the draws. In the algorithm they come from a pilot run with its own draws, so they are independent of , and the statements below hold conditionally on the pilot.
Lemma 1 (unbiased). for all weights and counts.
Proof. Both means of in a correction have the mean , so each correction has mean zero.
Lemma 2 (covariance of nested means). .
Proof. Only the pairs with the same draw are correlated, and there are of them. So the covariance is .
Lemma 3 (the variance). With ,
Proof. Let . By Lemma 2, . The covariance of with is , because . For , the four terms of have the maxima with signs , because , so . Adding the variances and twice the covariances gives the formula.
Lemma 4 (the best weights). For fixed counts with , the variance is smallest at , and then
Proof. The term of is the quadratic , with its minimum at . So the variance is . Collect the factor of each : it is for , for , and for . With and this is the formula.
Theorem (optimal allocation). Assume and
Among all real counts with and cost , and all weights, the smallest variance is . It is reached by and with
Proof. Let , which is positive by the first assumption. For every admissible choice of counts, Lemma 3 and Lemma 4 give : if this is Lemma 4, and if the term of is zero, which is also the value of the minimum in Lemma 4. By the Cauchy-Schwarz inequality,
so every admissible choice has variance at least the stated value. Equality holds when is a fixed multiple of , that is , which is , and the cost constraint fixes . It remains to show that these counts are admissible: holds if and only if , which is the second assumption. Then and Lemma 4 gives the weights.
Corollary (the gain over plain Monte Carlo). Plain Monte Carlo with the budget uses runs of and has the variance . The ratio of the optimal multifidelity variance to it is
The assumptions of the theorem do not make this ratio smaller than 1. For , and , the cost condition holds (), but the ratio is . So the ratio is a separate test: use the cheap model only when the ratio is below 1.
The algorithm. Line L1 estimates and 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 , and by the theorem. The code rounds the counts down, keeps them in order and keeps . Lines L6 to L9 compute 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 and , 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 ; the error of against the real system is a modeling error outside the method.
Complexity
In the real RAM model with a model run of cost , lines L6 to L8 cost in model work, plus additions for each model, which is with . The pilot of line L1 costs , outside the budget. Lines L2 to L5 cost . The list of draws takes space; a version that draws each input once and adds it to all running sums needs .
The variance at the optimum is , so the error falls like , as for plain Monte Carlo, with a smaller constant. The ratio of the two variances is , 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 , 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 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 . 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 and , 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 . 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.
# 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
- 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)
- 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.
| 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 SQG1XP Edit this page History Report an error Markdown