# 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 = 3.67 seconds
Compute duration = 3.67 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.2008 0.8827 0.1414 39.8970 43.4393 1.1049 ⋯
z[1] -1.3516 0.9407 0.1323 53.4236 143.8069 1.0486 ⋯
z[2] -0.1062 0.7323 0.0585 147.2589 201.1747 1.0051 ⋯
z[3] -0.1632 0.7114 0.0615 131.1338 217.7375 1.0227 ⋯
z[4] 0.8878 0.7907 0.0898 79.2287 189.5564 1.0278 ⋯
z[5] -1.6500 0.8869 0.1031 75.1115 158.8668 1.0477 ⋯
z[6] -0.5009 0.8031 0.0816 98.4141 164.7801 1.0135 ⋯
z[7] 0.5748 0.7782 0.0894 74.4541 118.0200 1.0804 ⋯
z[8] -0.0390 0.7957 0.0860 84.4884 174.9503 1.0106 ⋯
z[9] -0.1525 0.6810 0.0581 138.0675 162.1670 1.0215 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.5609 -0.3348 0.3016 0.7769 1.9365
z[1] -3.1808 -1.9899 -1.2590 -0.6542 0.2956
z[2] -1.6322 -0.6240 -0.0413 0.3162 1.3199
z[3] -1.5354 -0.6625 -0.1875 0.2927 1.2598
z[4] -0.5404 0.3248 0.8882 1.3839 2.4254
z[5] -3.6447 -2.1363 -1.5395 -0.9743 -0.2770
z[6] -2.2857 -0.9555 -0.5535 0.1269 0.9418
z[7] -0.9438 0.0766 0.5523 1.0848 2.1347
z[8] -1.8904 -0.5147 -0.0420 0.5012 1.3646
z[9] -1.3699 -0.7410 -0.1300 0.3582 1.1788
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 can use the library Pathfinder
2 (Pathfinder
’s GitHub) 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. You can see an example of how to use Pathfinder
with Turing in Pathfinder
’s docs.
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:05:59
ϵ: 2.618963339850589
L: 3.1622776601683795
dE/d: -0.017945981667290313
Tuning: 1%|▍ | ETA: 0:04:02
ϵ: 0.9081669496624556
L: 4.513736295674778
dE/d: 0.07490719412588583
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 0.9451379205728828
L: 401.2921135930397
dE/d: 0.013415481897950698
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 6.38 seconds
Compute duration = 6.38 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.0916 1.1250 0.0343 1106.0760 1015.7208 1.0006 ⋯
z[1] -1.1814 0.8886 0.0216 1757.9202 2358.4054 0.9999 ⋯
z[2] 0.0683 0.6380 0.0144 1984.5632 2440.2195 1.0063 ⋯
z[3] -0.1670 0.7176 0.0139 2704.6786 3369.9208 1.0160 ⋯
z[4] 0.9150 0.8369 0.0228 1395.7787 1861.2561 1.0006 ⋯
z[5] -1.4478 0.9730 0.0237 1716.9077 2621.4913 1.0000 ⋯
z[6] -0.4771 0.6885 0.0166 1791.6034 2103.1318 1.0017 ⋯
z[7] 0.6151 0.7084 0.0171 1815.6212 2259.6315 1.0001 ⋯
z[8] -0.0312 0.6634 0.0158 1803.2533 2229.2770 1.0018 ⋯
z[9] -0.1310 0.7550 0.0156 2379.9398 3019.5837 1.0005 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.4832 -0.8408 0.0182 0.7389 1.8549
z[1] -3.1451 -1.7390 -1.0992 -0.5187 0.2748
z[2] -1.1836 -0.3365 0.0570 0.4684 1.3673
z[3] -1.6436 -0.5951 -0.1416 0.2688 1.2740
z[4] -0.4906 0.2952 0.8074 1.4588 2.7277
z[5] -3.5282 -2.0937 -1.3586 -0.7006 0.1305
z[6] -2.0169 -0.8989 -0.4087 -0.0095 0.7281
z[7] -0.5766 0.1130 0.5405 1.0408 2.2024
z[8] -1.3929 -0.4268 -0.0251 0.3816 1.3076
z[9] -1.6889 -0.6143 -0.1106 0.3622 1.3583
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↩︎