# 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 = 2.94 seconds
Compute duration = 2.94 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.2739 0.8391 0.0972 76.8953 77.4001 1.0068 ⋯
z[1] 0.3751 0.8482 0.0826 100.5419 141.1046 1.0230 ⋯
z[2] 0.8406 0.8867 0.0813 121.4442 174.1092 1.0025 ⋯
z[3] 0.0707 0.7861 0.0660 146.0776 196.2744 1.0134 ⋯
z[4] 0.9596 0.8543 0.0811 109.9749 190.4704 1.0013 ⋯
z[5] -0.1931 0.8021 0.0815 96.9571 165.3821 1.0219 ⋯
z[6] 0.0338 0.8383 0.0744 125.8447 183.6257 1.0127 ⋯
z[7] 1.9040 0.9788 0.1180 70.1872 56.3309 1.0047 ⋯
z[8] 0.5686 0.8260 0.0725 125.1035 136.3779 1.0049 ⋯
z[9] -0.8472 0.8181 0.0789 108.1319 197.7111 1.0066 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.5000 -0.3730 0.3341 0.8701 1.8560
z[1] -1.3186 -0.1874 0.2707 0.8996 2.1230
z[2] -0.8689 0.2806 0.7866 1.3956 2.6674
z[3] -1.5954 -0.4502 0.0681 0.6112 1.5540
z[4] -0.6396 0.3509 0.8804 1.4654 2.6413
z[5] -1.8170 -0.7244 -0.1824 0.2666 1.4408
z[6] -1.5367 -0.5324 0.0961 0.5295 1.6088
z[7] 0.2631 1.1661 1.9290 2.5234 3.8310
z[8] -0.9067 0.0693 0.5115 1.0450 2.3849
z[9] -2.6100 -1.3351 -0.8122 -0.2281 0.4286
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)
┌ Warning: Pareto shape k = 0.83 > 0.7. Resulting importance sampling estimates are likely to be unstable.
└ @ PSIS ~/.julia/packages/PSIS/ArVs9/src/core.jl:314
[ Info: Found initial step size 0.8
Chains MCMC chain (10000×23×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 5.8 seconds
Compute duration = 5.8 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.1783 0.9932 0.0302 1456.9996 639.6569 1.0000 ⋯
z[1] 0.4036 0.7665 0.0072 11700.0675 6411.4291 0.9999 ⋯
z[2] 0.8412 0.8091 0.0097 7284.4144 7113.4498 0.9999 ⋯
z[3] -0.0052 0.7390 0.0063 13825.4703 7006.1351 1.0004 ⋯
z[4] 1.0152 0.8216 0.0110 5681.3956 7123.9693 1.0001 ⋯
z[5] -0.2201 0.7424 0.0067 12154.6326 6724.0560 1.0001 ⋯
z[6] 0.0793 0.7342 0.0063 13747.9829 7192.0324 1.0001 ⋯
z[7] 1.9517 1.0313 0.0209 2240.6733 1970.8940 1.0000 ⋯
z[8] 0.6980 0.7793 0.0087 8102.3713 7530.9252 0.9999 ⋯
z[9] -0.8896 0.8115 0.0113 5112.1450 6872.9389 1.0000 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.3203 -0.3463 0.3039 0.8447 1.8381
z[1] -1.0446 -0.0945 0.3662 0.8752 2.0375
z[2] -0.6036 0.2508 0.7826 1.3652 2.5496
z[3] -1.4803 -0.4783 -0.0026 0.4628 1.4724
z[4] -0.3989 0.4280 0.9508 1.5402 2.7784
z[5] -1.7766 -0.6897 -0.1965 0.2642 1.2143
z[6] -1.3939 -0.3886 0.0645 0.5465 1.5745
z[7] 0.1154 1.2033 1.9302 2.6580 4.0490
z[8] -0.7239 0.1533 0.6365 1.2130 2.3347
z[9] -2.5873 -1.4265 -0.8328 -0.3010 0.5356
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:07:14
ϵ: 1.4721677958463106
L: 3.1622776601683795
dE/d: -0.11116541769427499
Tuning: 1%|▍ | ETA: 0:03:54
ϵ: 0.8442600593206153
L: 3.769380298936006
dE/d: 7.466611030402249e-5
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 2.3072364042695592
L: 942.5155158331078
dE/d: -0.01811831361055525
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 4.7 seconds
Compute duration = 4.7 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 ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯
θ 0.3235 0.8862 0.0229 1596.3137 1243.8001 1.0029 ⋯
z[1] 0.4128 0.7341 0.0137 2914.4399 3624.0732 1.0266 ⋯
z[2] 0.8701 0.9012 0.0202 2000.3115 2816.6462 1.0098 ⋯
z[3] -0.0058 0.7358 0.0142 2746.5149 3530.6256 1.0090 ⋯
z[4] 1.0674 0.7760 0.0156 2525.8645 3303.8742 1.0037 ⋯
z[5] -0.2229 0.8489 0.0179 2250.8210 3235.4887 1.0005 ⋯
z[6] 0.0859 0.7854 0.0153 2687.9605 3402.4214 1.0039 ⋯
z[7] 2.0363 0.9765 0.0213 2099.6677 3056.6814 1.0002 ⋯
z[8] 0.7217 0.6981 0.0124 3258.1356 3904.5147 1.0083 ⋯
z[9] -0.9404 0.7431 0.0144 2705.4144 3586.4973 1.0000 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.6777 -0.2285 0.3949 0.9440 1.8483
z[1] -1.0068 -0.0665 0.3939 0.8674 1.9585
z[2] -0.7723 0.2324 0.8195 1.4781 2.6691
z[3] -1.4879 -0.4404 -0.0095 0.4211 1.5108
z[4] -0.3015 0.5198 1.0193 1.5697 2.7225
z[5] -1.9287 -0.7961 -0.2071 0.3617 1.4001
z[6] -1.5376 -0.3879 0.0791 0.5516 1.7071
z[7] 0.2125 1.3500 2.0236 2.6989 4.0087
z[8] -0.5585 0.2378 0.6838 1.1660 2.1965
z[9] -2.5620 -1.4000 -0.9005 -0.4451 0.4267
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↩︎