# Import libraries.
using Turing, Random, LinearAlgebra
= 10
d @model function funnel()
~ Truncated(Normal(0, 3), -3, 3)
θ ~ MvNormal(zeros(d - 1), exp(θ) * I)
z return x ~ MvNormal(z, I)
end
funnel (generic function with 2 methods)
Turing
provides several wrapped samplers from external sampling libraries, e.g., HMC samplers from AdvancedHMC
. These wrappers allow new users to seamlessly sample statistical models without leaving Turing
However, these wrappers might only sometimes be complete, missing some functionality from the wrapped sampling library. Moreover, users might want to use samplers currently not wrapped within Turing
.
For these reasons, Turing
also makes running external samplers on Turing models easy without any necessary modifications or wrapping! Throughout, we will use a 10-dimensional Neal’s funnel as a running example::
# Import libraries.
using Turing, Random, LinearAlgebra
d = 10
@model function funnel()
θ ~ Truncated(Normal(0, 3), -3, 3)
z ~ MvNormal(zeros(d - 1), exp(θ) * I)
return x ~ MvNormal(z, I)
end
funnel (generic function with 2 methods)
Now we sample the model to generate some observations, which we can then condition on.
Users can use any sampler algorithm to sample this model if it follows the AbstractMCMC
API. Before discussing how this is done in practice, giving a high-level description of the process is interesting. Imagine that we created an instance of an external sampler that we will call spl
such that typeof(spl)<:AbstractMCMC.AbstractSampler
. In order to avoid type ambiguity within Turing, at the moment it is necessary to declare spl
as an external sampler to Turing espl = externalsampler(spl)
, where externalsampler(s::AbstractMCMC.AbstractSampler)
is a Turing function that types our external sampler adequately.
An excellent point to start to show how this is done in practice is by looking at the sampling library AdvancedMH
(AdvancedMH
’s GitHub) for Metropolis-Hastings (MH) methods. Let’s say we want to use a random walk Metropolis-Hastings sampler without specifying the proposal distributions. The code below constructs an MH sampler using a multivariate Gaussian distribution with zero mean and unit variance in d
dimensions as a random walk proposal.
MetropolisHastings{RandomWalkProposal{false, ZeroMeanIsoNormal{Tuple{Base.OneTo{Int64}}}}}(RandomWalkProposal{false, ZeroMeanIsoNormal{Tuple{Base.OneTo{Int64}}}}(ZeroMeanIsoNormal(
dim: 10
μ: Zeros(10)
Σ: [1.0 0.0 … 0.0 0.0; 0.0 1.0 … 0.0 0.0; … ; 0.0 0.0 … 1.0 0.0; 0.0 0.0 … 0.0 1.0]
)
))
Sampling is then as easy as:
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 4.14 seconds
Compute duration = 4.14 seconds
parameters = θ, z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8], z[9]
internals = lp
Summary Statistics
parameters mean std mcse ess_bulk ess_tail rhat e ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯
θ -0.8854 1.2685 0.2691 23.9323 20.6522 1.3082 ⋯
z[1] 0.0515 0.5679 0.0646 64.1650 70.5929 1.2794 ⋯
z[2] -0.7360 0.6089 0.0937 50.3911 45.3167 1.5475 ⋯
z[3] 0.3182 0.6807 0.0972 54.5378 86.3896 1.1777 ⋯
z[4] 0.2409 0.5777 0.0720 61.2845 90.8608 1.2408 ⋯
z[5] 0.0210 0.5072 0.0562 77.8601 82.2737 1.3340 ⋯
z[6] -0.5651 0.7264 0.1294 28.4926 103.6509 1.2333 ⋯
z[7] -0.6210 0.6461 0.1032 40.0032 88.7816 1.1290 ⋯
z[8] -0.1350 0.6044 0.0807 79.0987 125.3019 1.1622 ⋯
z[9] 0.6129 0.9097 0.1729 25.7694 20.6522 1.4438 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.5615 -2.5615 -0.6481 0.1064 1.2751
z[1] -1.3939 -0.2085 0.2784 0.2784 1.0110
z[2] -2.2061 -0.9581 -0.4819 -0.4819 0.2741
z[3] -0.7046 0.0360 0.0360 0.7573 1.9232
z[4] -0.8419 0.0089 0.0089 0.4975 1.5032
z[5] -1.2013 -0.1527 0.1135 0.1581 1.2194
z[6] -2.4057 -0.9112 -0.4058 0.0821 0.0821
z[7] -2.2102 -0.9697 -0.5085 -0.1380 0.3462
z[8] -1.5415 -0.4917 0.2442 0.2442 0.6210
z[9] -0.3781 -0.3781 0.6582 1.0201 2.6431
As previously mentioned, the Turing wrappers can often limit the capabilities of the sampling libraries they wrap. AdvancedHMC
1 (AdvancedHMC
’s GitHub) is a clear example of this. A common practice when performing HMC is to provide an initial guess for the mass matrix. However, the native HMC sampler within Turing only allows the user to specify the type of the mass matrix despite the two options being possible within AdvancedHMC
. Thankfully, we can use Turing’s support for external samplers to define an HMC sampler with a custom mass matrix in AdvancedHMC
and then use it to sample our Turing model.
We will use the library Pathfinder
2 ((Pathfinder
’s GitHub)[https://github.com/mlcolab/Pathfinder.jl]) to construct our estimate of mass matrix. Pathfinder
is a variational inference algorithm that first finds the maximum a posteriori (MAP) estimate of a target posterior distribution and then uses the trace of the optimization to construct a sequence of multivariate normal approximations to the target distribution. In this process, Pathfinder
computes an estimate of the mass matrix the user can access.
The code below shows this can be done in practice.
using AdvancedHMC, Pathfinder
# Running pathfinder
draws = 1_000
result_multi = multipathfinder(model, draws; nruns=8)
# Estimating the metric
inv_metric = result_multi.pathfinder_results[1].fit_distribution.Σ
metric = DenseEuclideanMetric(Matrix(inv_metric))
# Creating an AdvancedHMC NUTS sampler with the custom metric.
n_adapts = 1000 # Number of adaptation steps
tap = 0.9 # Large target acceptance probability to deal with the funnel structure of the posterior
nuts = AdvancedHMC.NUTS(tap; metric=metric)
# Sample
chain = sample(model, externalsampler(nuts), 10_000; n_adapts=1_000)
[ Info: Found initial step size 9.5367431640625e-8
Chains MCMC chain (10000×23×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 6.1 seconds
Compute duration = 6.1 seconds
parameters = θ, z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8], z[9]
internals = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, max_hamiltonian_energy_error, tree_depth, numerical_error, step_size, nom_step_size, is_adapt
Summary Statistics
parameters mean std mcse ess_bulk ess_tail rhat ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯
θ -0.5882 1.0877 0.0274 1679.2040 1612.6627 1.0014 ⋯
z[1] -0.0653 0.6178 0.0056 12026.6288 6246.2413 1.0001 ⋯
z[2] -0.6454 0.7139 0.0160 1381.9872 255.1239 1.0005 ⋯
z[3] 0.3386 0.6631 0.0225 860.5725 224.2743 1.0021 ⋯
z[4] 0.2562 0.6532 0.0176 1758.9952 426.5806 1.0006 ⋯
z[5] -0.1074 0.6871 0.0291 907.8057 225.9690 1.0018 ⋯
z[6] -0.6332 0.7503 0.0273 685.1507 223.0935 1.0010 ⋯
z[7] -0.5677 0.6888 0.0087 6724.0470 6125.8555 1.0002 ⋯
z[8] -0.2521 0.6341 0.0072 7077.2070 6376.5319 1.0005 ⋯
z[9] 0.9499 0.8051 0.0128 4054.6214 5256.8280 1.0009 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.7595 -1.3582 -0.4979 0.2144 1.3308
z[1] -1.3408 -0.4254 -0.0624 0.3128 1.1640
z[2] -2.2136 -1.0945 -0.5498 -0.1348 0.4924
z[3] -0.9970 -0.0742 0.2871 0.7110 1.8058
z[4] -0.9534 -0.1642 0.1971 0.6271 1.6395
z[5] -1.7877 -0.4847 -0.0693 0.3095 1.2049
z[6] -2.3098 -1.0877 -0.5446 -0.1292 0.7377
z[7] -2.1272 -0.9667 -0.4760 -0.0914 0.5799
z[8] -1.6704 -0.6345 -0.2061 0.1592 0.9355
z[9] -0.2656 0.3428 0.8343 1.4421 2.8329
So far we have used Turing’s support for external samplers to go beyond the capabilities of the wrappers. We want to use this support to employ a sampler not supported within Turing’s ecosystem yet. We will use the recently developed Micro-Cannoncial Hamiltonian Monte Carlo (MCHMC) sampler to showcase this. MCHMC[3,4] ((MCHMC’s GitHub)[https://github.com/JaimeRZP/MicroCanonicalHMC.jl]) is HMC sampler that uses one single Hamiltonian energy level to explore the whole parameter space. This is achieved by simulating the dynamics of a microcanonical Hamiltonian with an additional noise term to ensure ergodicity.
Using this as well as other inference methods outside the Turing ecosystem is as simple as executing the code shown below:
using MicroCanonicalHMC
# Create MCHMC sampler
n_adapts = 1_000 # adaptation steps
tev = 0.01 # target energy variance
mchmc = MCHMC(n_adapts, tev; adaptive=true)
# Sample
chain = sample(model, externalsampler(mchmc), 10_000)
[ Info: Tuning eps ⏳
[ Info: Tuning L ⏳
[ Info: Tuning sigma ⏳
Tuning: 0%|▏ | ETA: 0:08:39
ϵ: 1.4845378455842602
L: 3.1622776601683795
dE/d: 0.004998231049967927
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 0.9532596426944614
L: 0.5924328257483777
dE/d: -0.011625940213059493
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 5.4 seconds
Compute duration = 5.4 seconds
parameters = θ, z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8], z[9]
internals = lp
Summary Statistics
parameters mean std mcse ess_bulk ess_tail rhat e ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯
θ -0.7349 1.1195 0.1342 71.6259 268.3805 1.0712 ⋯
z[1] -0.1193 0.5993 0.0436 192.0366 393.1157 1.0098 ⋯
z[2] -0.6004 0.6583 0.0647 110.0619 240.6098 1.0272 ⋯
z[3] 0.3275 0.5595 0.0448 171.0147 165.7693 1.0161 ⋯
z[4] 0.1522 0.5701 0.0331 296.2095 602.7333 1.0119 ⋯
z[5] -0.0966 0.5630 0.0401 210.2105 282.3144 1.0167 ⋯
z[6] -0.6651 0.7358 0.0916 75.2497 177.7069 1.0430 ⋯
z[7] -0.5700 0.6840 0.0600 145.2443 399.5230 1.0150 ⋯
z[8] -0.2182 0.6051 0.0392 248.2666 175.0463 1.0113 ⋯
z[9] 0.8338 0.7650 0.0951 69.4853 109.8273 1.0939 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.7076 -1.6007 -0.7204 0.0966 1.3405
z[1] -1.3759 -0.4700 -0.0986 0.2442 1.0902
z[2] -2.0899 -0.9845 -0.5278 -0.1346 0.4938
z[3] -0.6943 -0.0362 0.2720 0.6526 1.5751
z[4] -0.9741 -0.2113 0.1423 0.5135 1.3081
z[5] -1.2784 -0.4264 -0.0720 0.2532 0.9998
z[6] -2.3194 -1.0815 -0.5252 -0.1290 0.4359
z[7] -2.0857 -0.9698 -0.4760 -0.0958 0.5591
z[8] -1.5114 -0.5708 -0.1920 0.1545 0.9213
z[9] -0.3314 0.2784 0.7178 1.2591 2.6962
The only requirement to work with externalsampler
is that the provided sampler
must implement the AbstractMCMC.jl-interface [INSERT LINK] for a model
of type AbstractMCMC.LogDensityModel
[INSERT LINK].
As previously stated, in order to use external sampling libraries within Turing
they must follow the AbstractMCMC
API. In this section, we will briefly dwell on what this entails. First and foremost, the sampler should be a subtype of AbstractMCMC.AbstractSampler
. Second, the stepping function of the MCMC algorithm must be made defined using AbstractMCMC.step
and follow the structure below:
# First step
function AbstractMCMC.step{T<:AbstractMCMC.AbstractSampler}(
rng::Random.AbstractRNG,
model::AbstractMCMC.LogDensityModel,
spl::T;
kwargs...,
)
[...]
return transition, sample
end
# N+1 step
function AbstractMCMC.step{T<:AbstractMCMC.AbstractSampler}(
rng::Random.AbstractRNG,
model::AbstractMCMC.LogDensityModel,
sampler::T,
state;
kwargs...,
)
[...]
return transition, sample
end
There are several characteristics to note in these functions:
There must be two step
functions:
state
, which carries the initialization information.The functions must follow the displayed signatures.
The output of the functions must be a transition, the current state of the sampler, and a sample, what is saved to the MCMC chain.
The last requirement is that the transition must be structured with a field θ
, which contains the values of the parameters of the model for said transition. This allows Turing
to seamlessly extract the parameter values at each step of the chain when bundling the chains. Note that if the external sampler produces transitions that Turing cannot parse, the bundling of the samples will be different or fail.
For practical examples of how to adapt a sampling library to the AbstractMCMC
interface, the readers can consult the following libraries:
Xu et al., AdvancedHMC.jl: A robust, modular and efficient implementation of advanced HMC algorithms, 2019↩︎
Zhang et al., Pathfinder: Parallel quasi-Newton variational inference, 2021↩︎
Robnik et al, Microcanonical Hamiltonian Monte Carlo, 2022↩︎
Robnik and Seljak, Langevine Hamiltonian Monte Carlo, 2023↩︎