# 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.01 seconds
Compute duration = 4.01 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.3520 1.1875 0.2431 26.0081 23.7422 1.3582 ⋯
z[1] -0.2997 0.6906 0.0702 96.8197 153.8683 1.1832 ⋯
z[2] -0.8587 0.7267 0.1041 49.2515 165.0641 1.1222 ⋯
z[3] 1.2440 0.9018 0.1416 40.9505 96.7249 1.0477 ⋯
z[4] -0.0237 0.6034 0.0609 89.6946 126.1185 1.0359 ⋯
z[5] -0.1616 0.7123 0.1081 47.5303 113.5519 1.0805 ⋯
z[6] -0.2407 0.6677 0.0794 67.9583 119.5352 1.0467 ⋯
z[7] 1.1748 0.8840 0.1523 34.7660 25.1297 1.1315 ⋯
z[8] -0.3725 0.6970 0.0750 83.6220 138.4782 1.1687 ⋯
z[9] -0.8102 0.8099 0.1201 43.9191 61.3485 1.0396 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.2746 -1.6204 -0.0095 0.5655 1.6962
z[1] -1.7813 -0.6959 -0.1867 0.1208 0.8399
z[2] -2.4614 -1.3380 -0.7446 -0.2766 0.2612
z[3] 0.0765 0.4592 1.0319 1.8121 3.2375
z[4] -1.4241 -0.3142 -0.0513 0.3600 1.0633
z[5] -1.5251 -0.6776 -0.0425 0.3195 1.0186
z[6] -1.6031 -0.5301 -0.2078 0.2031 1.1262
z[7] 0.1060 0.2456 1.1747 1.6725 3.0703
z[8] -2.0091 -0.7963 -0.3633 0.1395 0.7237
z[9] -2.6567 -1.2987 -0.5437 -0.1560 0.1339
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:06:09
ϵ: 1.2677035953048792
L: 3.1622776601683795
dE/d: -0.02062268241886045
Tuning: 1%|▍ | ETA: 0:04:14
ϵ: 1.4328371486603444
L: 6.362065559261789
dE/d: 0.005162690876537113
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 1.5852115083770546
L: 651.0947707285515
dE/d: -0.01370794897740737
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 6.57 seconds
Compute duration = 6.57 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.3179 0.9213 0.0247 1533.5108 833.4134 1.0109 ⋯
z[1] -0.3445 0.7682 0.0167 2132.9659 2791.7059 1.0003 ⋯
z[2] -1.0995 0.8712 0.0180 2398.8450 3078.8268 1.0010 ⋯
z[3] 1.5688 0.9025 0.0190 2290.2073 3434.9540 1.0009 ⋯
z[4] -0.1002 0.7666 0.0123 3897.8155 5027.0916 1.0000 ⋯
z[5] -0.2357 0.6328 0.0118 2902.5568 3678.3525 1.0075 ⋯
z[6] -0.4141 0.7785 0.0153 2611.1922 3547.6539 1.0009 ⋯
z[7] 1.4881 0.9044 0.0176 2667.5098 3844.9609 1.0007 ⋯
z[8] -0.4986 0.8207 0.0171 2331.7688 3006.5198 1.0032 ⋯
z[9] -1.1416 0.8815 0.0186 2277.5427 3071.5949 1.0001 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.8218 -0.2048 0.4034 0.9421 1.9438
z[1] -1.9208 -0.8311 -0.3219 0.1585 1.1680
z[2] -2.9585 -1.6693 -1.0357 -0.4861 0.4601
z[3] -0.0176 0.9085 1.5184 2.1802 3.4129
z[4] -1.6955 -0.5672 -0.0849 0.3828 1.4091
z[5] -1.5545 -0.6140 -0.2149 0.1675 0.9779
z[6] -2.0079 -0.9212 -0.3795 0.1013 1.0786
z[7] -0.1223 0.8252 1.4366 2.0958 3.3503
z[8] -2.2326 -1.0122 -0.4626 0.0606 1.0067
z[9] -2.9896 -1.7296 -1.0859 -0.5078 0.4330
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↩︎