# 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.98 seconds
Compute duration = 3.98 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.1957 1.0898 0.2114 28.0606 22.2989 1.2898 ⋯
z[1] -0.1067 0.6979 0.0646 115.2730 143.5981 1.1031 ⋯
z[2] -1.1414 1.0486 0.1734 35.7951 124.5009 1.1125 ⋯
z[3] -0.5404 0.6600 0.0538 143.0447 242.9044 1.2333 ⋯
z[4] -0.4860 0.8083 0.1090 54.9182 192.0313 1.0680 ⋯
z[5] 0.3920 0.7993 0.1128 53.1496 176.4117 1.1785 ⋯
z[6] -0.4337 0.6994 0.0635 122.6504 122.7533 1.1803 ⋯
z[7] 0.6603 0.6633 0.0545 143.6583 198.8838 1.2512 ⋯
z[8] -0.1069 0.7423 0.0794 88.7173 129.9076 1.0502 ⋯
z[9] -1.3959 1.0289 0.1746 33.9874 56.0401 1.1870 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.9668 -1.3178 -0.0579 0.6011 1.7673
z[1] -1.4539 -0.5467 -0.0428 0.3969 1.2499
z[2] -3.4887 -1.8344 -0.9636 -0.0517 0.0185
z[3] -2.0201 -0.7925 -0.4765 -0.2481 0.6559
z[4] -2.4023 -0.9924 -0.1521 0.0350 0.6634
z[5] -0.8231 -0.0571 0.1527 0.8227 2.1676
z[6] -1.9636 -0.7352 -0.4058 -0.0343 1.0178
z[7] -0.6276 0.3058 0.5124 1.0592 2.1457
z[8] -1.8569 -0.3900 -0.2266 0.2735 1.4391
z[9] -3.6599 -2.0917 -1.3097 -0.3653 0.0642
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:05
ϵ: 1.585906187150271
L: 3.1622776601683795
dE/d: -0.09065680864888392
Tuning: 1%|▍ | ETA: 0:04:10
ϵ: 0.9541745062071615
L: 4.525343573938768
dE/d: -0.013809934786513978
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 0.6737241228913299
L: 281.7193713424354
dE/d: 0.002206183801634154
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 6.47 seconds
Compute duration = 6.47 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.2356 1.1516 0.0358 1076.1617 926.1186 1.0007 ⋯
z[1] -0.2545 0.7621 0.0197 1523.9266 1939.2599 1.0001 ⋯
z[2] -1.4109 0.9785 0.0253 1521.3065 2127.3443 1.0006 ⋯
z[3] -0.5316 0.7474 0.0182 1729.0010 2162.0184 1.0009 ⋯
z[4] -0.7924 0.8068 0.0216 1435.4892 1929.3430 1.0009 ⋯
z[5] 0.6729 0.7219 0.0191 1448.9305 1964.9167 1.0006 ⋯
z[6] -0.5137 0.6955 0.0188 1400.1944 1736.1802 1.0179 ⋯
z[7] 0.6401 0.7277 0.0199 1370.2796 1835.5533 1.0006 ⋯
z[8] -0.1258 0.6628 0.0175 1461.2481 1938.2502 1.0033 ⋯
z[9] -1.7840 1.1003 0.0275 1619.0936 2485.6935 1.0085 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.4412 -0.4640 0.3613 1.0713 2.1619
z[1] -1.8674 -0.7269 -0.2131 0.2532 1.1601
z[2] -3.4682 -2.0575 -1.3747 -0.6823 0.2653
z[3] -2.1727 -0.9854 -0.4789 -0.0266 0.8386
z[4] -2.5785 -1.2785 -0.7222 -0.2190 0.6088
z[5] -0.6559 0.1864 0.6299 1.1150 2.2042
z[6] -2.0398 -0.9113 -0.4586 -0.0623 0.7764
z[7] -0.6554 0.1407 0.5753 1.1022 2.2039
z[8] -1.4647 -0.5297 -0.1102 0.2735 1.2292
z[9] -4.0619 -2.4993 -1.7265 -0.9743 0.1260
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↩︎