Frontier: simulation-based inference, amortized inference and neural samplers
When a simulator supplies samples but no tractable likelihood, or inference must be repeated thousands of times, a network can learn to do the inference. This lesson goes from ABC to neural posterior, likelihood, and ratio estimation (NPE, NLE, NRE), checks calibration with expected coverage, trains a prior-data fitted network to approximate the Bayesian predictive distribution, and introduces neural samplers for unnormalized densities.
After this lesson you can
- Implement rejection ABC and ABC-SMC and analyze the effects of tolerance and summary statistics.
- Explain NPE, NLE, and NRE and choose among them based on the simulation budget and downstream use.
- Train a neural posterior estimator with sbi and assess its expected coverage and simulation-based calibration.
- Train a small PFN on a Gaussian-process prior and compare it with the exact posterior.
- Compare neural samplers, including Boltzmann generators and diffusion samplers, with MCMC.
Before you start
- 14Amortized inferenceExpressive variational familiesSimulation-based calibrationImportance-sampling effective sample sizeSequential importance samplingMarkov chain Monte CarloGaussian process regression
- 11Prior-fitted networks and tabular foundation modelsLogistic loss as Bernoulli likelihood
- 19Normalizing flow
- 18Transformer block
- 00Canonical training and evaluation loopnn.Module
- 07Cross-entropy minimization as maximum likelihood
When you can simulate but cannot evaluate
An epidemic or population dynamics simulator can generate observations at a parameter value even when evaluating its likelihood is impractical. Approximate Bayesian computation (ABC) draws from the prior, simulates , and accepts if the distance between summaries and is at most . The result approximates by comparing summary statistics within a tolerance.
Reducing usually reduces tolerance bias and lowers the acceptance rate. If the summary discards information, even cannot recover it. ABC-SMC reuses populations. Select a previously accepted particle by weight, perturb it, and accept if the distance is within the new threshold. For a kernel the importance correction is
Normalize the weights and count rejected simulations in the cost. When a kernel proposes points outside the prior support, handle those proposals consistently with the proposal density. The review by Cranmer and colleagues places ABC within simulation-based inference.
Amortizing the cost
Neural simulation-based inference generates pairs and learns a reusable approximation. NPE directly estimates . NLE estimates and then requires inference for each observation. NRE trains a classifier to estimate the ratio between the joint distribution and the product of its marginals. A correctly estimated ratio can be combined with a different prior whose support is covered. Training coverage still limits where that ratio can be used.
Training costs are paid before querying the network. Sequential approaches concentrate simulations near an observation and correct for the change in proposal. That concentration limits amortization across other observations. Accuracy depends on the prior, simulator, estimator capacity, and simulation budget. A misspecified simulator remains a source of error after training.
Checking calibration
Expected coverage measures the fraction of true parameter values that fall inside a nominal credible region over pairs simulated from the prior. The diagonal is a marginal target under the data generator. Coverage for a particular observation can differ. Simulation-based calibration (SBC) compares the rank of each simulated parameter with posterior draws. Correlated draws and few replications affect this diagnostic. Hermans and colleagues show that SBI approximations can be overconfident.
A curve near the diagonal satisfies this check for the chosen family of regions. Good marginal coverage can still coexist with local errors or a misspecified simulator. Also check simulated predictions, observations outside the support, and sensitivity to the prior.
A transformer fitted to the prior
A prior-data fitted network (PFN) sees many datasets simulated from the prior and learns to predict a held-out label from its context. The expected log loss is the KL divergence from the true predictive distribution to the learned one plus a constant. If the model can represent any distribution, the population optimum is the Bayesian predictive. Finite capacity, optimization, and the training distribution affect the approximation. Müller and colleagues develop PFNs using transformers.
The transformer predicts a Gaussian mean and scale and trains with continuous log loss. Across 512 new tasks from the same prior, the RMSE of the means against the exact GP was 0.160. The atypical sample illustrates one specific distribution shift. Robustness across other shifts requires separate evaluation.
Sampling from an energy function
Neural samplers learn to propose samples from a density known up to its normalizing constant. Boltzmann generators use invertible transformations and can be corrected with importance weights where the densities and support allow it. Diffusion samplers approximate reverse dynamics. For an unnormalized energy, the score at intermediate times has to be estimated or otherwise derived. Training and sampling can be expensive, and missing modes can make the weights degenerate. MCMC has different costs and needs its own diagnostics. See Noé and colleagues and Vargas and colleagues.
Labs
Rejection and SMC from scratch
The Lotka–Volterra simulator uses an Euler step of 0.05 and six observations with Gaussian noise of standard deviation 2. In the normal control case, and with give the posterior . Choose tolerances from quantiles of the previous population’s distances. They vary between models and can yield different errors.
"""ABC rechazo y ABC-SMC para Lotka-Volterra y un control conjugado."""
import numpy as np
from scipy.special import logsumexp
def lotka(theta):
"""Euler explícito; observaciones deterministas en t=1,2,3."""
theta=np.atleast_2d(theta);x=np.full(len(theta),30.);y=np.full(len(theta),4.);out=[]
for t in range(60):
dx=theta[:,0]*x-.02*x*y;dy=.01*x*y-theta[:,1]*y
x=np.maximum(x+.05*dx,0);y=np.maximum(y+.05*dy,0)
if (t+1)%20==0:out.extend([x.copy(),y.copy()])
return np.stack(out,axis=1)
def prior(rng,n,model):
return rng.uniform([.4,.3],[1.6,1.3],size=(n,2)) if model=='lv' else rng.normal(size=(n,1))
def logprior(theta,model):
if model=='lv':
inside=np.all((theta>=[.4,.3])&(theta<=[1.6,1.3]),axis=-1)
return np.where(inside,-np.log(1.2),-np.inf)
return -.5*theta[...,0]**2-.5*np.log(2*np.pi)
def simulate(theta,rng,model):
return lotka(theta)+rng.normal(0,2,(len(theta),6)) if model=='lv' else theta+rng.normal(size=(len(theta),1))
def distance(x,obs,model):
return np.sqrt(np.mean(((x-obs)/2)**2,axis=1)) if model=='lv' else abs(x[:,0]-obs)
def smc(obs,model,seed=27,n=120):
rng=np.random.default_rng(seed);theta=prior(rng,4000,model);x=simulate(theta,rng,model);dist=distance(x,obs,model)
keep=np.argsort(dist)[:n];theta=theta[keep];dist=dist[keep];weights=np.ones(n)/n;calls=4000
history=[(float(dist.max()),calls,float(1/(weights@weights)))]
for _ in range(2):
eps=float(np.quantile(dist,.6));cov=np.atleast_2d(np.cov(theta.T,aweights=weights))*2+np.eye(theta.shape[1])*1e-5
L=np.linalg.cholesky(cov);inv=np.linalg.inv(cov);logdet=np.linalg.slogdet(cov)[1];accepted=[];ad=[]
for batch in range(500):
parent=rng.choice(n,size=400,p=weights);proposal=theta[parent]+rng.normal(size=(400,theta.shape[1]))@L.T
valid=np.isfinite(logprior(proposal,model));candidates=proposal[valid];calls+=len(candidates)
if not len(candidates):continue
dd=distance(simulate(candidates,rng,model),obs,model);mask=dd<=eps
if mask.any():accepted.extend(candidates[mask]);ad.extend(dd[mask])
if len(accepted)>=n:break
if len(accepted)<n:raise RuntimeError('presupuesto de simulación insuficiente')
new=np.array(accepted[:n]);dist=np.array(ad[:n]);diff=new[:,None,:]-theta[None,:,:]
logkernel=-.5*np.einsum('nki,ij,nkj->nk',diff,inv,diff)-.5*(theta.shape[1]*np.log(2*np.pi)+logdet)
logw=logprior(new,model)-logsumexp(np.log(weights)[None,:]+logkernel,axis=1)
weights=np.exp(logw-logsumexp(logw));theta=new
history.append((eps,calls,float(1/(weights@weights))))
return theta,weights,history"""Rechazo ABC usando las funciones de abc_smc.py ya definidas."""
rng=np.random.default_rng(71)
for model,obs in [('normal',1.),('lv',simulate(np.array([[1.,.7]]),np.random.default_rng(33),'lv')[0])]:
theta=prior(rng,20000,model);dist=distance(simulate(theta,rng,model),obs,model)
for eps in ([.1,.5,1.] if model=='normal' else [2.,5.,10.]):
accepted=theta[dist<=eps]
print(model,'epsilon',eps,'aceptadas',len(accepted),'simulaciones',len(theta),'media',accepted.mean(0) if len(accepted) else 'sin aceptadas')obs=simulate(np.array([[1.,.7]]),np.random.default_rng(33),'lv')[0]
particles,weights,history=smc(obs,'lv');print('Lotka observación',obs,'ABC-SMC',history,'media',weights@particles)particles,weights,history=smc(1.,'normal');mean=float(weights@particles[:,0]);var=float(weights@((particles[:,0]-mean)**2))
print('Normal conjugada ABC-SMC',history,'media',mean,'varianza',var,'exacta',.5,.5)NPE with sbi and SIR
Run the code locally or download sbi_lab.py. It requires sbi 0.27.0, PyTorch, NumPy, and SciPy. Training uses CUDA when available. The synthetic SIR simulator uses Euler integration, two uniform parameters, and five noisy observations. ABC-SMC uses the same simulator and counts calls. NPE amortizes fitting over 6000 simulations, while ABC must rerun for the given observation. The lab computes SBC ranks and 90 % marginal coverage for 80 new pairs, using 200 samples per posterior. This limited check measures marginal calibration under the simulator.
"""sbi NPE sobre SIR discreto, SBC marginal y ABC-SMC con mismo simulador."""
import numpy as np
import torch
from scipy.special import logsumexp
from sbi.inference import NPE
from sbi.neural_nets import posterior_nn
from sbi.utils import BoxUniform
import sbi
torch.set_num_threads(1);torch.manual_seed(27)
device='cuda' if torch.cuda.is_available() else 'cpu'
low=np.array([.6,.1]);high=np.array([1.8,.6])
def sir(theta):
# Euler dt=.1, proporciones, infectados en t=2,4,6,8,10.
theta=np.atleast_2d(theta);S=np.full(len(theta),.95);I=np.full(len(theta),.05);out=[]
for j in range(100):
inc=.1*theta[:,0]*S*I;rec=.1*theta[:,1]*I;S-=inc;I+=inc-rec
if (j+1)%20==0:out.append(I.copy())
return np.stack(out,axis=1)
def simulate(theta,rng):return sir(theta)+rng.normal(0,.02,(len(theta),5))
def abc_smc(obs,seed=40,n=150):
rng=np.random.default_rng(seed);theta=rng.uniform(low,high,(4000,2));d=np.sqrt(np.mean(((simulate(theta,rng)-obs)/.02)**2,axis=1));calls=4000
ix=np.argsort(d)[:n];theta=theta[ix];d=d[ix];weights=np.ones(n)/n;history=[(float(d.max()),calls)]
for _ in range(2):
eps=float(np.quantile(d,.6));C=2*np.cov(theta.T,aweights=weights)+1e-6*np.eye(2);L=np.linalg.cholesky(C);inv=np.linalg.inv(C);ld=np.linalg.slogdet(C)[1];new=[];newd=[]
for _ in range(1000):
idx=rng.choice(n,400,p=weights);p=theta[idx]+rng.normal(size=(400,2))@L.T
p=p[np.all((p>=low)&(p<=high),axis=1)];calls+=len(p)
if not len(p):continue
dd=np.sqrt(np.mean(((simulate(p,rng)-obs)/.02)**2,axis=1));ok=dd<=eps
new.extend(p[ok]);newd.extend(dd[ok])
if len(new)>=n:break
if len(new)<n:raise RuntimeError('insuficientes aceptaciones ABC')
new=np.array(new[:n]);d=np.array(newd[:n]);diff=new[:,None,:]-theta[None,:,:]
logk=-.5*np.einsum('nki,ij,nkj->nk',diff,inv,diff)-.5*(2*np.log(2*np.pi)+ld)
logw=-np.log(np.prod(high-low))-logsumexp(np.log(weights)[None,:]+logk,axis=1)
weights=np.exp(logw-logsumexp(logw));theta=new;history.append((eps,calls))
return theta,weights,history
rng=np.random.default_rng(27);ntrain=6000
theta=rng.uniform(low,high,(ntrain,2));x=simulate(theta,rng)
prior=BoxUniform(low=torch.tensor(low,dtype=torch.float32,device=device),high=torch.tensor(high,dtype=torch.float32,device=device),device=device)
inference=NPE(prior=prior,density_estimator=posterior_nn(model='maf',hidden_features=32,num_transforms=3),device=device)
inference.append_simulations(torch.tensor(theta,dtype=torch.float32),torch.tensor(x,dtype=torch.float32))
network=inference.train(training_batch_size=256,max_num_epochs=60,stop_after_epochs=10,show_train_summary=False)
posterior=inference.build_posterior(network)
print('sbi',sbi.__version__,'torch',torch.__version__,'device',device,'simulaciones NPE',ntrain)
true=np.array([[1.2,.3]]);obs=simulate(true,np.random.default_rng(41))[0]
post=posterior.sample((500,),x=torch.tensor(obs,dtype=torch.float32,device=device),show_progress_bars=False).cpu().numpy()
abc,w,history=abc_smc(obs);print('SIR observado',obs,'NPE media',post.mean(0),'ABC media',w@abc,'ABC tolerancia/simulaciones',history)
# Datos nuevos del prior, independientes del entrenamiento; rangos SBC marginales.
validation_theta=rng.uniform(low,high,(80,2));validation_x=simulate(validation_theta,rng);ranks=[];coverage=[]
for t,xx in zip(validation_theta,validation_x):
draw=posterior.sample((200,),x=torch.tensor(xx,dtype=torch.float32,device=device),show_progress_bars=False).cpu().numpy()
ranks.append(np.sum(draw<t,axis=0));lo,hi=np.quantile(draw,[.05,.95],axis=0);coverage.append((lo<=t)&(t<=hi))
ranks=np.asarray(ranks);coverage=np.asarray(coverage)
print('cobertura marginal 90%',coverage.mean(axis=0),'80 replicaciones')
for j in range(2):print('rangos SBC parámetro',j,np.histogram(ranks[:,j],bins=np.linspace(0,201,11))[0])npm run lab and open the connection link.Training a PFN
The full code is also available as pfn.py. It generates tasks online, each with up to six observations and a query distinct from the context points. The prior is an RBF GP with scale 0.7 and Gaussian noise of standard deviation 0.1 on 16 fixed inputs. The exact GP uses the same observations. There are 3907 steps with batch size 256, or 1 000 192 tasks. The program saves pfn.pt in the current directory. The recorded local run used an RTX 3060, so the timing pertains to that GPU.
"""PFN pequeño para regresión GP; 1 000 000 tareas simuladas en línea."""
import math
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
device='cuda' if torch.cuda.is_available() else 'cpu'
torch.manual_seed(27)
grid=torch.linspace(-2,2,16,device=device)
K=torch.exp(-.5*((grid[:,None]-grid[None,:])/.7)**2)
L=torch.linalg.cholesky(K+1e-5*torch.eye(16,device=device))
class PFN(nn.Module):
def __init__(self):
super().__init__();self.embed=nn.Linear(3,32)
layer=nn.TransformerEncoderLayer(32,4,64,dropout=0.,batch_first=True,activation='gelu')
self.transformer=nn.TransformerEncoder(layer,2,enable_nested_tensor=False)
self.head=nn.Sequential(nn.Linear(32,32),nn.GELU(),nn.Linear(32,2))
def forward(self,tokens,padding):
h=self.transformer(self.embed(tokens),src_key_padding_mask=padding)
out=self.head(h[:,-1]);return out[:,0],out[:,1].clamp(-3,2)
def batch(n):
# 16 GP evaluations plus independent observation noise; context can contain
# 0..6 points; the query is distinct from all sampled context indices.
f=torch.randn(n,16,device=device)@L.T
values=f+.1*torch.randn(n,16,device=device)
inds=torch.rand(n,16,device=device).argsort(dim=1)[:,:7]
cx=grid[inds[:,:6]];cy=values.gather(1,inds[:,:6]);tx=grid[inds[:,6]]
nctx=torch.randint(0,7,(n,),device=device)
pad=torch.arange(6,device=device)[None,:]>=nctx[:,None]
contexts=torch.stack((cx,cy,torch.ones_like(cx)),dim=-1)
query=torch.stack((tx,torch.zeros_like(tx),torch.zeros_like(tx)),dim=-1)[:,None,:]
tokens=torch.cat((contexts,query),dim=1)
padding=torch.cat((pad,torch.zeros((n,1),device=device,dtype=torch.bool)),dim=1)
target=values.gather(1,inds[:,6:7]).squeeze(1)
return tokens,padding,target,inds,nctx
def exact(tokens,padding):
# Variable-size posterior on the same discrete input grid.
mus=[];variances=[]
for tok,mask in zip(tokens,padding):
c=tok[:-1][~mask[:-1]];target=tok[-1,0]
if not len(c):mus.append(torch.tensor(0.,device=device));variances.append(torch.tensor(1.01,device=device));continue
A=torch.exp(-.5*((c[:,0,None]-c[None,:,0])/.7)**2)+.01*torch.eye(len(c),device=device)
k=torch.exp(-.5*((c[:,0]-target)/.7)**2)
sol=torch.linalg.solve(A,k);mus.append(c[:,1]@sol);variances.append(1.01-k@sol)
return torch.stack(mus),torch.stack(variances)
def train(steps=3907,batch_size=256):
model=PFN().to(device);opt=torch.optim.AdamW(model.parameters(),lr=.0006)
if device=='cuda':torch.cuda.reset_peak_memory_stats()
for step in range(steps):
tokens,padding,target,_,_=batch(batch_size);m,logsd=model(tokens,padding)
loss=(logsd+.5*((target-m)/logsd.exp())**2).mean()
opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
if (step+1)%1000==0:print('paso',step+1,'tareas',batch_size*(step+1),'NLL sin constante',float(loss.detach()),flush=True)
model.eval();torch.save(model.state_dict(),'pfn.pt')
with torch.no_grad():
tokens,padding,target,_,_=batch(512);m,logsd=model(tokens,padding);mg,vg=exact(tokens,padding)
print('tareas',steps*batch_size,'dispositivo',device,'memoria GPU máxima MB',torch.cuda.max_memory_allocated()/1e6 if device=='cuda' else 0)
print('RMSE media contra GP',float(torch.mean((m-mg)**2).sqrt()),'error medio varianza contra GP',float(torch.mean(abs(logsd.exp()**2-vg))))
print('NLL PFN',float(torch.mean(logsd+.5*((target-m)/logsd.exp())**2+.5*math.log(2*math.pi))),'NLL GP',float(torch.mean(.5*torch.log(2*math.pi*vg)+.5*(target-mg)**2/vg)))
return model
if __name__=='__main__':train()npm run lab and open the connection link.Exercises
Step 1 of 2. What factor multiplies the prior when you accept a ball of radius ε?
Step 1 of 2. How does expected −log q under p decompose?
weights(new, old, old_weights, prior_density, sigma) for a scalar parameter. Use a normal kernel with standard deviation sigma. Evaluate prior_density at new and divide by the kernel mixture centered at old, then normalize. Tests use positive densities and sigma > 0.def weights(new, old, old_weights, prior_density, sigma):
passSummary
- ABC trades off tolerance, cost, and information loss. SMC corrects for the proposal mixture.
- NPE amortizes inference, while NLE and NRE move some computation to each observation. SBC and coverage are diagnostics under the data generator.
- A PFN learns a predictive distribution over tasks and needs evaluation outside that task distribution. Neural samplers require checks for missed modes and unstable weights.