# 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.69 seconds Compute duration = 3.69 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.6459 0.7825 0.1363 35.7511 54.1209 1.1942 ⋯ z[1] -0.0574 0.5722 0.0580 85.5473 150.4166 1.3798 ⋯ z[2] 0.2526 0.6075 0.0721 70.1326 162.7076 1.0905 ⋯ z[3] -0.1789 0.5634 0.0483 119.6478 128.3053 1.1229 ⋯ z[4] -0.9774 0.7283 0.1056 51.2386 160.2304 1.3298 ⋯ z[5] 0.2061 0.6717 0.1038 42.9356 29.5714 1.2433 ⋯ z[6] 0.1707 0.6657 0.1035 46.0443 55.1253 1.1153 ⋯ z[7] 0.0228 0.6094 0.0710 62.7656 134.6670 1.1501 ⋯ z[8] -0.2600 0.7492 0.1124 59.3519 85.3190 1.1054 ⋯ z[9] -0.3914 0.6194 0.0875 47.0785 121.6926 1.2750 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 θ -1.9718 -1.0157 -1.0157 -0.0292 1.0383 z[1] -1.5693 -0.2407 -0.0925 0.3393 1.0006 z[2] -0.7260 -0.1641 0.2989 0.5835 1.5934 z[3] -1.4574 -0.3797 -0.0218 0.0371 0.9717 z[4] -2.5359 -1.4752 -0.9565 -0.7222 0.3457 z[5] -0.6656 -0.0918 -0.0918 0.6985 1.7131 z[6] -1.1219 -0.3108 0.1756 0.7116 1.3077 z[7] -1.4000 -0.2297 0.1437 0.1809 1.4450 z[8] -1.9374 -0.6622 0.0254 0.3319 0.6313 z[9] -1.9782 -0.7552 -0.2513 -0.0611 0.6026
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:15 ϵ: 1.1211431281687394 L: 3.1622776601683795 dE/d: 0.2873684742006947 Tuning: 1%|▍ | ETA: 0:04:11 ϵ: 1.1180881895805668 L: 4.9681388589581115 dE/d: -0.05297200795334014 Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02 ϵ: 1.6455784977623267 L: 722.6731043981233 dE/d: 0.03674927677086863
Chains MCMC chain (10000×11×1 Array{Float64, 3}): Iterations = 1:1:10000 Number of chains = 1 Samples per chain = 10000 Wall duration = 6.62 seconds Compute duration = 6.62 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.2839 1.1508 0.0346 1019.7196 1175.2540 1.0023 ⋯ z[1] -0.0448 0.4704 0.0103 2270.0669 2031.4763 1.0018 ⋯ z[2] 0.2540 0.5188 0.0117 2200.2796 1960.4706 1.0000 ⋯ z[3] -0.1770 0.5285 0.0127 1902.6487 1757.5428 1.0001 ⋯ z[4] -0.5809 0.6883 0.0182 1684.0695 1608.1568 1.0004 ⋯ z[5] 0.2084 0.5244 0.0123 1979.5546 1887.5345 1.0019 ⋯ z[6] 0.0757 0.4740 0.0104 2226.0634 2024.4460 1.0025 ⋯ z[7] 0.0338 0.4856 0.0107 2201.8193 2139.1764 1.0007 ⋯ z[8] -0.2980 0.5927 0.0152 1760.9426 1581.6438 1.0001 ⋯ z[9] -0.3629 0.6062 0.0155 1838.5696 1584.9624 1.0028 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 θ -2.9252 -2.2596 -1.3963 -0.4392 1.0872 z[1] -1.0704 -0.2919 -0.0302 0.2103 0.8817 z[2] -0.6360 -0.0657 0.1880 0.5114 1.4782 z[3] -1.4028 -0.4573 -0.1323 0.1504 0.7720 z[4] -2.2608 -0.9588 -0.4403 -0.1010 0.4653 z[5] -0.7512 -0.1068 0.1582 0.4789 1.4049 z[6] -0.8617 -0.1935 0.0536 0.3189 1.1343 z[7] -0.9684 -0.2383 0.0244 0.2948 1.0533 z[8] -1.7721 -0.5814 -0.2097 0.0757 0.6830 z[9] -1.8408 -0.6499 -0.2620 0.0283 0.6065
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↩︎