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 is ideal flow and its approximation on the finest grid, Monte Carlo with independent samples satisfies
This bias, variance and cost tradeoff requires refining to reduce the first and increasing to reduce the second. If bias is , cost per sample is and variance of the fine functional remains bounded, MC costs for mean-square error of order . For Euler with this gives .
A telescoping sum
Multilevel Monte Carlo writes and for . By linearity,
Each level uses samples independent of the others; randomness is shared within each pair. With total variance is . For fixed , the estimator is unbiased for , not necessarily for .
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 . Without positive covariance, the correction usually remains noisy.
Allocating work
Minimize subject to . Using a multiplier, and
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 , variance and cost , with and . Then, for mean-square error at most proportional to , cost is bounded by:
The proof uses the allocation above: the sum of is a decreasing, constant or increasing geometric series depending on . Choosing controls bias; the condition on controls the cost of at least one sample on fine levels. These are asymptotic bounds under assumptions, not guaranteed timings for every run.
Milstein can increase 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 , , , , 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 on with , and ; are independent normals and . 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 using a heuristic bias extrapolation with two standard errors, and determines . 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 . Cost counts state steps or nodes processed, including the pilot; it does not measure time or include all execution overhead.
"""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')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.
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 and work per sample as : the theorem predicts 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 and are high- and low-fidelity payoffs and the mean of is estimated on an independent sample, use
Conditioned on obtained from an independent pilot, the expectation is . Its variance is ; 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.
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
Step 1 of 3. Which Lagrangian applies?
import numpy as np
def mlmc_level(l,N,rng):
pass