Module contents
Lesson 15 of 27Advanced 100 min

Advanced Monte Carlo III: multilevel and multifidelity Monte Carlo

Reduce simulation cost by combining coupled grid-level corrections in multilevel Monte Carlo, then extend the idea to control variates of different fidelity.

After this lesson you can

  • Decompose discretized estimator mean-square error into squared bias and variance and optimize the standard Monte Carlo tradeoff.
  • Construct a coupled telescoping MLMC estimator and explain why coupling matters.
  • Prove the MLMC complexity theorem and calculate optimal samples per level.
  • Implement adaptive MLMC for an SDE with Euler-Maruyama and an elliptic PDE with random coefficients.
  • Combine different-fidelity models through multifidelity Monte Carlo control variates.

Before you start

Two sources of error

To estimate mean flow in an uncertain aquifer, each permeability realization may require a PDE solve. If PP is ideal flow and PLP_L its approximation on the finest grid, Monte Carlo with NN independent samples satisfies

E[(P^L,N−EP)2]=(EPL−EP)2+Var⁡(PL)N.\mathbb E[(\widehat P_{L,N}-\mathbb EP)^2] =(\mathbb EP_L-\mathbb EP)^2+\frac{\operatorname{Var}(P_L)}N.

This bias, variance and cost tradeoff requires refining to reduce the first and increasing NN to reduce the second. If bias is O(2−αL)O(2^{-\alpha L}), cost per sample is O(2γL)O(2^{\gamma L}) and variance of the fine functional remains bounded, MC costs O(ε−2−γ/α)O(\varepsilon^{-2-\gamma/\alpha}) for mean-square error of order ε2\varepsilon^2. For Euler with α=γ=1\alpha=\gamma=1 this gives O(ε−3)O(\varepsilon^{-3}).

A telescoping sum

Multilevel Monte Carlo writes Y0=P0Y_0=P_0 and Yℓ=Pℓ−Pℓ−1Y_\ell=P_\ell-P_{\ell-1} for ℓ≥1\ell\ge1. By linearity,

EPL=∑ℓ=0LEYℓ,P^ML=∑ℓ=0L1Nℓ∑i=1NℓYℓ(i).\mathbb EP_L=\sum_{\ell=0}^{L}\mathbb EY_\ell,\qquad \widehat P_{\rm ML}=\sum_{\ell=0}^{L}\frac1{N_\ell}\sum_{i=1}^{N_\ell}Y_\ell^{(i)}.

Each level uses samples independent of the others; randomness is shared within each pair. With Vℓ=Var⁡(Yℓ)V_\ell=\operatorname{Var}(Y_\ell) total variance is ∑ℓVℓ/Nℓ\sum_\ell V_\ell/N_\ell. For fixed LL, the estimator is unbiased for EPL\mathbb EP_L, not necessarily for EP\mathbb EP.

InteractiveThe telescoping ladder
  • Selected level
  • Coupled level 4
L0: 2071
L1: 162
L2: 86
L3: 41

The allocation comes from an independent pilot for ε=0.5, Euler European option and levels 0 to 3; numbers are final samples, excluding the 1000 pilot samples per level. Coarse-level noise is the sum of fine increments.

2
Level steps4
Final value78.0662
State difference from previous level0.0285
A trajectory and an actual allocation with an independent pilot.

Coupling between levels determines efficiency. Two fine Brownian increments are added to obtain the coarse increment; for a PDE the same random field is evaluated on both grids. The pair retains its marginal distributions and tends to become closer under refinement. Its variance is Var⁡(Pℓ)+Var⁡(Pℓ−1)−2Cov⁡(Pℓ,Pℓ−1)\operatorname{Var}(P_\ell)+\operatorname{Var}(P_{\ell-1})-2\operatorname{Cov}(P_\ell,P_{\ell-1}). Without positive covariance, the correction usually remains noisy.

InteractiveCouple or decouple
  • Coupled
  • Independent

Vertical axis: log₁₀ Var(Pℓ−Pℓ₋₁). Independent differences preserve the identity of expectations, but do not exploit correlation between grids. Observed slopes depend on scheme and payoff.

Scheme
Payoff
Variance ratio at level 64675.7
Empirical variances of 20,000 pairs per level, with a fixed seed.

Allocating work

Minimize ∑ℓNℓCℓ\sum_\ell N_\ell C_\ell subject to ∑ℓVℓ/Nℓ≤ε2/2\sum_\ell V_\ell/N_\ell\le \varepsilon^2/2. Using a multiplier, Cℓ−λVℓ/Nℓ2=0C_\ell-\lambda V_\ell/N_\ell^2=0 and

Nℓ=2ε2VℓCℓ∑j=0LVjCj,WML≈2ε2(∑ℓ=0LVℓCℓ)2.N_\ell=\frac{2}{\varepsilon^2} \sqrt{\frac{V_\ell}{C_\ell}} \sum_{j=0}^{L}\sqrt{V_jC_j},\qquad W_{\rm ML}\approx\frac{2}{\varepsilon^2} \left(\sum_{\ell=0}^{L}\sqrt{V_\ell C_\ell}\right)^2.

Round upward and impose a minimum number of samples. These formulas use known variances and costs; in practice a pilot estimates them, making the resulting allocation approximate.

The Giles MLMC complexity theorem assumes uniform bounds on bias O(2−αL)O(2^{-\alpha L}), variance Vℓ=O(2−βℓ)V_\ell=O(2^{-\beta\ell}) and cost Cℓ=O(2γℓ)C_\ell=O(2^{\gamma\ell}), with α,β,γ>0\alpha,\beta,\gamma>0 and α≥min⁡(β,γ)/2\alpha\ge\min(\beta,\gamma)/2. Then, for mean-square error at most proportional to ε2\varepsilon^2, cost is bounded by:

β>γO(ε−2)β=γO(ε−2(log⁡ε)2)β<γO(ε−2−(γ−β)/α)\begin{array}{c|c} \beta>\gamma & O(\varepsilon^{-2})\\ \beta=\gamma & O(\varepsilon^{-2}(\log\varepsilon)^2)\\ \beta<\gamma & O(\varepsilon^{-2-(\gamma-\beta)/\alpha}) \end{array}

The proof uses the allocation above: the sum of VℓCℓ\sqrt{V_\ell C_\ell} is a decreasing, constant or increasing geometric series depending on β−γ\beta-\gamma. Choosing L=O(log⁡ε−1/α)L=O(\log\varepsilon^{-1}/\alpha) controls bias; the condition on α\alpha controls the cost of at least one sample on fine levels. These are asymptotic bounds under assumptions, not guaranteed timings for every run.

InteractiveComplexity regimes
  • Fine MC
  • MLMC

The horizontal axis is −log₁₀ ε and the vertical axis is log₁₀ cost. We reserve ε²/2 for squared bias and ε²/2 for variance, and round sample sizes upward. These are idealized bounds with unit constants, not a runtime prediction.

1.0
1.0
1.0
Regimeβ = γ
Assumption α≥min(β,γ)/2satisfied in this model
MLMC cost at ε=10⁻³2.88e+8
Idealized model with unit constants and integer rounding; it does not measure time.

Milstein can increase β\beta when regularity and the functional allow; discontinuous payoffs or barriers can reduce it. Antithetic and multilevel QMC are other variants requiring analysis of coupling and their own uncertainty estimate. Strong convergence helps control differences, but does not by itself determine the rate of every functional.

Lab: SDE, PDE and fidelity

Run this cell first and the following cells in the same session. For GBM use S0=K=100S_0=K=100, r=0.05r=0.05, σ=0.2\sigma=0.2, T=1T=1, discounted European and discrete Asian payoffs, and Euler or Milstein. At each Asian level we average values on that level’s own grid. For the PDE solve −(ku′)′=1-(ku')'=1 on [0,1][0,1] with u(0)=u(1)=0u(0)=u(1)=0, and k(x)=exp⁡{12(Z0cos⁡πx+Z1sin⁡2πx)}k(x)=\exp\{\tfrac12(Z_0\cos\pi x+Z_1\sin2\pi x)\}; Z0,Z1Z_0,Z_1 are independent normals and P=u(1/2)P=u(1/2). This is a custom conservative finite-difference extension to variable coefficients; it does not claim to be the constant-coefficient solver from lesson 7. The observation is the center value, not the motivating example’s flow.

The pilot is independent of the final sample: it estimates rates and variances, selects LL using a heuristic bias extrapolation with two standard errors, and determines NℓN_\ell. Whether that criterion is met is reported; it does not certify actual bias or mean-square error. Mean rates can be very noisy; the extrapolation rate is limited to [0.5,2][0.5,2]. Cost counts state steps or nodes processed, including the pilot; it does not measure time or include all execution overhead.

[ ]MLMC and models from scratchBrowser
"""MLMC con piloto independiente para GBM y difusión 1D lognormal."""
import numpy as np

def gbm_level(level,N,rng,scheme='euler',payoff='european',coupled=True):
    """Devuelve contribuciones por trayectoria; coste medido en pasos de estado."""
    if level<0 or N<1 or scheme not in ('euler','milstein') or payoff not in ('european','asian'):raise ValueError('parámetros inválidos')
    fine=2**level;h=1/fine;r=.05;sigma=.2;S0=100.;strike=100.
    Sf=np.full(N,S0);Sc=np.full(N,S0);sumf=np.zeros(N);sumc=np.zeros(N)
    def step(s,dw,dt):
        result=s*(1+r*dt+sigma*dw)
        if scheme=='milstein':result+=.5*s*sigma**2*(dw*dw-dt)
        return result
    if level==0:
        dw=rng.normal(0,np.sqrt(h),N);Sf=step(Sf,dw,h);sumf=Sf.copy()
    else:
        for _ in range(fine//2):
            dw1=rng.normal(0,np.sqrt(h),N);dw2=rng.normal(0,np.sqrt(h),N)
            Sf=step(Sf,dw1,h);sumf+=Sf
            Sf=step(Sf,dw2,h);sumf+=Sf
            coarse_dw=dw1+dw2 if coupled else rng.normal(0,np.sqrt(2*h),N)
            Sc=step(Sc,coarse_dw,2*h);sumc+=Sc
    Pf=np.exp(-r)*np.maximum((Sf if payoff=='european' else sumf/fine)-strike,0)
    if level==0:return Pf
    Pc=np.exp(-r)*np.maximum((Sc if payoff=='european' else sumc/(fine//2))-strike,0)
    return Pf-Pc

def elliptic_value(z,level):
    """-∂x(k∂xu)=1, Dirichlet 0; campo compartido exp(.5(z0 cos πx+z1 sin 2πx))."""
    z=np.asarray(z,dtype=float);n=2**(level+2);h=1/n
    x=(np.arange(n)+.5)*h
    k=np.exp(.5*(z[:,0,None]*np.cos(np.pi*x)+z[:,1,None]*np.sin(2*np.pi*x)))
    diagonal=(k[:,:-1]+k[:,1:])/h**2;off=-k[:,1:-1]/h**2
    rhs=np.ones_like(diagonal);diag=diagonal.copy()
    for j in range(1,n-1):
        factor=off[:,j-1]/diag[:,j-1];diag[:,j]-=factor*off[:,j-1];rhs[:,j]-=factor*rhs[:,j-1]
    u=np.zeros_like(rhs);u[:,-1]=rhs[:,-1]/diag[:,-1]
    for j in range(n-3,-1,-1):u[:,j]=(rhs[:,j]-off[:,j]*u[:,j+1])/diag[:,j]
    return u[:,n//2-1]

def elliptic_level(level,N,rng,coupled=True):
    z=rng.normal(size=(N,2));fine=elliptic_value(z,level)
    if level==0:return fine
    coarse=elliptic_value(z if coupled else rng.normal(size=(N,2)),level-1)
    return fine-coarse

def estimate_rates(means,variances,costs):
    """Pendientes estimadas por regresión en niveles positivos; sesgo ruidoso."""
    ell=np.arange(1,len(means));mask=(np.abs(np.asarray(means)[1:])>1e-15)&(np.asarray(variances)[1:]>1e-15)
    if mask.sum()<2:return np.nan,np.nan,np.nan
    a=-np.polyfit(ell[mask],np.log2(np.abs(np.asarray(means)[1:][mask])),1)[0]
    b=-np.polyfit(ell[mask],np.log2(np.asarray(variances)[1:][mask]),1)[0]
    g=np.polyfit(ell[mask],np.log2(np.asarray(costs)[1:][mask]),1)[0]
    return float(a),float(b),float(g)

def adaptive_mlmc(level_sampler,cost_fn,eps,seed=42,pilot=1000,min_level=3,max_level=7):
    """Piloto por nivel, selección heurística de L y muestra final independiente."""
    if eps<=0 or pilot<30 or min_level<1 or max_level<min_level:raise ValueError('parámetros inválidos')
    rng=np.random.default_rng(seed);means=[];variances=[];costs=[]
    selected=max_level;bias_est=np.inf;rates=(np.nan,np.nan,np.nan)
    for level in range(max_level+1):
        y=level_sampler(level,pilot,rng);means.append(float(y.mean()));variances.append(float(y.var(ddof=1)));costs.append(float(cost_fn(level)))
        if level>=min_level:
            rates=estimate_rates(means,variances,costs)
            alpha=np.clip(rates[0] if np.isfinite(rates[0]) else 1.,.5,2.)
            # Añadimos dos errores estándar para no tratar una media ruidosa como cero.
            bias_est=(abs(means[-1])+2*np.sqrt(variances[-1]/pilot))/(2**alpha-1)
            if bias_est<eps/np.sqrt(2):selected=level;break
    V=np.maximum(variances,1e-30);C=np.asarray(costs)
    counts=np.maximum(2,np.ceil(2*eps**-2*np.sqrt(V/C)*np.sum(np.sqrt(V*C))).astype(int))
    # La estimación final es independiente del piloto que seleccionó tamaños y L.
    final_rng=np.random.default_rng(seed+100000);values=[];estimated_var=0.
    for l,n in enumerate(counts):
        y=level_sampler(l,int(n),final_rng);values.append(float(y.mean()));estimated_var+=float(y.var(ddof=1)/n)
    final_work=int(np.dot(counts,C));pilot_work=int(pilot*np.sum(C))
    return {'estimate':sum(values),'se':np.sqrt(estimated_var),'counts':counts,'means':means,'variances':variances,'costs':costs,'rates':rates,'bias_proxy':bias_est,'level':selected,'budget_met':bias_est<eps/np.sqrt(2),'final_work':final_work,'pilot_work':pilot_work,'total_work':final_work+pilot_work}

def fidelity_pair(N,rng,fine=64,coarse=4):
    """Pago europeo: Milstein fino y Euler grueso con los mismos incrementos."""
    if fine%coarse or fine<coarse or N<1:raise ValueError('mallas incompatibles')
    h=1/fine;r=.05;sigma=.2;Sf=np.full(N,100.);Sc=np.full(N,100.)
    for _ in range(coarse):
        total=np.zeros(N)
        for _ in range(fine//coarse):
            dw=rng.normal(0,np.sqrt(h),N);total+=dw
            Sf=Sf*(1+r*h+sigma*dw+.5*sigma**2*(dw*dw-h))
        Sc=Sc*(1+r/coarse+sigma*total)
    return np.exp(-r)*np.maximum(Sf-100,0),np.exp(-r)*np.maximum(Sc-100,0)

def multifidelity(Nhigh=10000,Nlow=50000,pilot=2000,seed=123):
    """Control con esperanza barata estimada en una muestra independiente."""
    rng=np.random.default_rng(seed);yh,yl=fidelity_pair(pilot,rng)
    beta=np.cov(yh,yl,ddof=1)[0,1]/np.var(yl,ddof=1)
    yh,yl=fidelity_pair(Nhigh,rng)
    # El valor grueso se simula por separado, sin generar malla fina.
    h=.25;S=np.full(Nlow,100.)
    for _ in range(4):S*=1+.05*h+.2*rng.normal(0,np.sqrt(h),Nlow)
    low=np.exp(-.05)*np.maximum(S-100,0)
    z=yh-beta*yl;estimate=z.mean()+beta*low.mean()
    variance=z.var(ddof=1)/Nhigh+beta**2*low.var(ddof=1)/Nlow
    return {'estimate':float(estimate),'se':float(np.sqrt(variance)),'beta':float(beta),
            'pilot_work':pilot*(64+4),'final_work':Nhigh*(64+4)+Nlow*4}
print('MLMC listo')
[ ]SDE: variances and allocationBrowser
cost=lambda l:2**l+(2**(l-1) if l else 0)
for scheme in ('euler','milstein'):
    for payoff in ('european','asian'):
        r=adaptive_mlmc(lambda l,n,g:gbm_level(l,n,g,scheme,payoff),
                        cost,.5,pilot=1000)
        print(scheme,payoff,'estimación',round(r['estimate'],4),
              'SE',round(r['se'],4),'L',r['level'],
              'N',r['counts'],'tasas',np.round(r['rates'],3),
              'sesgo heurístico aceptado',r['budget_met'],
              'trabajo final/piloto/total',
              r['final_work'],r['pilot_work'],r['total_work'])

In the local run with these seeds, the Euler European call gives 10.429 with SE 0.330; Black-Scholes for the continuous model gives approximately 10.451. The SE measures variability of the final sum and excludes bias. For the Asian option the discrete definition also changes with level.

[ ]PDE: cost and couplingBrowser
cost_pde=lambda l:2**(l+2)+(2**(l+1) if l else 0)
rng=np.random.default_rng(7)
for l in range(1,6):
    a=elliptic_level(l,5000,rng,True)
    b=elliptic_level(l,5000,rng,False)
    print('nivel',l,'var acoplada',a.var(ddof=1),'independiente',b.var(ddof=1))
for eps in (.002,.001,.0005,.00025,.000125):
    r=adaptive_mlmc(elliptic_level,cost_pde,eps,pilot=200)
    print('eps',eps,'L',r['level'],'N',r['counts'],
          'SE',r['se'],'trabajo final',r['final_work'],
          'piloto',r['pilot_work'],'total',r['total_work'],
          'criterio heurístico',r['budget_met'])

For this smooth field, observed correction variance decays approximately as 2−4ℓ2^{-4\ell} and work per sample as 2ℓ2^\ell: the theorem predicts O(ε−2)O(\varepsilon^{-2}) if those rates and the other assumptions hold. The table shows how final work scales; the pilot and minimum sample counts dominate at large tolerances. A handful of tolerances proves neither an asymptotic law nor the extrapolated bias. Cliffe and colleagues develop MLMC for random elliptic PDEs under precise assumptions.

Models of different fidelity

In multifidelity Monte Carlo, a cheap correlated approximation can act as a control. If HH and LL are high- and low-fidelity payoffs and the mean of LL is estimated on an independent sample, use

μ^H=H−θL‾ n+θ L‾ mindependiente.\widehat\mu_H=\overline{H-\theta L}_{\,n} +\theta\,\overline L_{\,m}^{\rm independiente}.

Conditioned on θ\theta obtained from an independent pilot, the expectation is EH\mathbb EH. Its variance is Var⁡(H−θL)/n+θ2Var⁡(L)/m\operatorname{Var}(H-\theta L)/n+\theta^2\operatorname{Var}(L)/m; ignoring the second term would misstate uncertainty. In the example high fidelity is Milstein with 64 steps and low fidelity is Euler with 4, sharing increments in each pair. The target is the expectation of the 64-step model, not exactly the continuous solution.

[ ]Multifidelity controlBrowser
r=multifidelity()
print('estimación',r['estimate'],'SE',r['se'],'coeficiente piloto',r['beta'])
print('pasos piloto',r['pilot_work'],'final',r['final_work'],
      'total',r['pilot_work']+r['final_work'])
# Comparación con alta fidelidad sola y el mismo presupuesto de pasos.
budget=r['pilot_work']+r['final_work'];n=budget//64
g=np.random.default_rng(456);s=np.full(n,100.);h=1/64
for _ in range(64):
    dw=g.normal(0,np.sqrt(h),n)
    s*=1+.05*h+.2*dw+.5*.2**2*(dw*dw-h)
y=np.exp(-.05)*np.maximum(s-100,0)
print('alta sola N',n,'media',y.mean(),'SE',y.std(ddof=1)/np.sqrt(n),
      'pasos',64*n)

Correlation, cost and allocation determine the gain. A cheap, poorly correlated surrogate may not pay off; if it is learned from data dependent on the final evaluation, the unbiasedness formula needs further justification. General allocation and hierarchy strategies are studied by Peherstorfer, Willcox and Gunzburger.

Exercises

ProofOptimal allocation
Prove: Minimize total cost at target variance v, assuming positive Vℓ,Cℓ and real Nℓ.
0
Levels are independent and variance is ΣVℓ/Nℓ.

Step 1 of 3. Which Lagrangian applies?

NumericMC cost
For α=β=γ=1, what exponent p appears in standard MC cost ε^(-p)?
NumericMultilevel cost
With α=β=γ=1 and ε=10^-3, what exponent p appears in ε^(-p) for MLMC, apart from the logarithmic factor?
QuizIndependent noise
What happens when generating the fine and coarse grid independently for each correction?
CodeA coupled correction
Implement mlmc_level(l,N,rng): return the sum and sum of squares of N discounted payoffs Yℓ. Use GBM with S₀=K=100, r=0.05, σ=0.2, T=1 and Euler-Maruyama in 2^ℓ steps; for ℓ>0 sum the two fine increments in each coarse step. At ℓ=0 return the payoff itself.
import numpy as np
def mlmc_level(l,N,rng):
  pass
Shift+Enter to run
Key idea
Telescoping preserves the expectation of the fine approximation; coupling and allocation by variance and cost can reduce work.