# 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.74 seconds Compute duration = 3.74 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 ⋯ θ 1.0295 0.6704 0.0768 79.5976 99.2420 1.0353 ⋯ z[1] -1.7839 0.8410 0.0853 99.1516 203.4430 1.0349 ⋯ z[2] 1.3141 0.9263 0.0736 155.4912 200.7325 1.0088 ⋯ z[3] -1.8258 0.9986 0.1179 70.9013 85.0898 1.0433 ⋯ z[4] 0.4134 0.7947 0.0771 108.1984 191.6275 1.0253 ⋯ z[5] 0.1195 0.7768 0.0686 131.8665 262.0959 1.0046 ⋯ z[6] -1.1304 0.8793 0.0814 118.8239 272.6334 1.0039 ⋯ z[7] -2.1086 0.9862 0.0979 104.6358 184.0345 1.0006 ⋯ z[8] -1.4013 0.8032 0.0747 121.8452 161.4809 1.0251 ⋯ z[9] 1.4257 0.9100 0.0988 85.4115 181.4439 1.0190 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 θ -0.2723 0.6063 1.0173 1.4933 2.3036 z[1] -3.3750 -2.3001 -1.8228 -1.1658 -0.1481 z[2] -0.3958 0.5771 1.3293 1.9913 3.3513 z[3] -3.8340 -2.5101 -1.8364 -1.0045 -0.1269 z[4] -1.1355 -0.1048 0.4295 0.8805 2.1200 z[5] -1.3287 -0.3917 0.0780 0.6160 1.7374 z[6] -2.9448 -1.7366 -1.0498 -0.5464 0.3793 z[7] -4.1953 -2.8202 -2.0599 -1.3654 -0.3806 z[8] -3.1216 -1.8689 -1.3923 -0.9055 0.2863 z[9] -0.1266 0.7816 1.4362 2.0177 3.2510
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:28 ϵ: 0.9663153935263795 L: 3.1622776601683795 dE/d: 0.01385281196933832 Tuning: 1%|▍ | ETA: 0:04:06 ϵ: 0.7335283643772573 L: 3.361728211706576 dE/d: 0.010276439197631503 Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02 ϵ: 1.4340709894696084 L: 577.6115904742026 dE/d: -0.022485246888096454
Chains MCMC chain (10000×11×1 Array{Float64, 3}): Iterations = 1:1:10000 Number of chains = 1 Samples per chain = 10000 Wall duration = 6.53 seconds Compute duration = 6.53 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 ⋯ θ 1.0819 0.7674 0.0164 2153.7807 2302.5120 1.0000 ⋯ z[1] -1.7906 0.9279 0.0195 2274.0761 3268.4851 1.0005 ⋯ z[2] 1.3388 0.9081 0.0152 3573.7467 4485.9638 1.0000 ⋯ z[3] -1.8984 0.9463 0.0206 2112.0355 3058.9001 1.0034 ⋯ z[4] 0.5383 0.7603 0.0142 2870.9171 3684.6057 1.0036 ⋯ z[5] 0.2591 1.0101 0.0215 2202.2646 3225.7499 1.0000 ⋯ z[6] -1.1873 0.8334 0.0169 2435.1032 3291.7450 1.0009 ⋯ z[7] -2.1175 0.9856 0.0177 3110.0458 4052.3545 1.0021 ⋯ z[8] -1.4094 0.8252 0.0165 2529.0586 3715.3712 1.0028 ⋯ z[9] 1.5147 0.9006 0.0190 2259.8390 3059.9302 1.0001 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 θ -0.5695 0.5865 1.1302 1.6313 2.4259 z[1] -3.7049 -2.3840 -1.7635 -1.1605 -0.0354 z[2] -0.3719 0.7113 1.3150 1.9481 3.1658 z[3] -3.8284 -2.5246 -1.8573 -1.2398 -0.1400 z[4] -0.9304 0.0382 0.5323 1.0256 2.0970 z[5] -1.7860 -0.3917 0.2609 0.9282 2.2109 z[6] -2.9149 -1.7246 -1.1691 -0.6341 0.3973 z[7] -4.1107 -2.7533 -2.1046 -1.4631 -0.2099 z[8] -3.0836 -1.9513 -1.3752 -0.8428 0.1114 z[9] -0.1995 0.8953 1.4847 2.0996 3.3574
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↩︎