# 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.86 seconds
Compute duration = 3.86 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.1039 0.8233 0.1152 52.7200 40.4563 1.1052 ⋯
z[1] 0.4009 0.7642 0.0656 135.4886 132.1802 1.0162 ⋯
z[2] 1.2911 0.8143 0.0996 65.4326 89.4628 1.0920 ⋯
z[3] -0.5136 0.8123 0.0823 96.0511 126.6859 1.0118 ⋯
z[4] -0.4554 0.7360 0.0729 100.4004 160.0387 1.0194 ⋯
z[5] -0.3054 0.7377 0.0717 108.1367 173.7354 1.0143 ⋯
z[6] 0.8334 0.8702 0.1114 61.6054 35.0235 1.0329 ⋯
z[7] -0.8152 0.7200 0.0636 127.3345 189.9595 1.0026 ⋯
z[8] 1.3125 0.9239 0.1141 65.9246 68.9438 1.0433 ⋯
z[9] 0.0740 0.6494 0.0694 84.1824 164.6589 1.0070 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.2737 -0.5173 0.1543 0.6695 1.6665
z[1] -1.1704 -0.1017 0.3973 0.8946 1.9832
z[2] -0.2149 0.6499 1.1938 1.8495 2.9585
z[3] -2.1857 -1.0909 -0.4970 0.0547 0.9868
z[4] -1.9230 -0.9931 -0.4120 0.0620 0.9032
z[5] -1.6395 -0.8596 -0.1925 0.1966 1.0531
z[6] -0.6250 0.2428 0.8336 1.4405 2.5269
z[7] -2.3287 -1.3537 -0.7791 -0.3042 0.4198
z[8] -0.2786 0.6732 1.0870 1.8953 3.3120
z[9] -1.2298 -0.3583 0.0453 0.4495 1.4104
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 will use the library Pathfinder
2 ((Pathfinder
’s GitHub)[https://github.com/mlcolab/Pathfinder.jl]) 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.
The code below shows this can be done in practice.
using AdvancedHMC, Pathfinder
# Running pathfinder
draws = 1_000
result_multi = multipathfinder(model, draws; nruns=8)
# Estimating the metric
inv_metric = result_multi.pathfinder_results[1].fit_distribution.Σ
metric = DenseEuclideanMetric(Matrix(inv_metric))
# Creating an AdvancedHMC NUTS sampler with the custom metric.
n_adapts = 1000 # Number of adaptation steps
tap = 0.9 # Large target acceptance probability to deal with the funnel structure of the posterior
nuts = AdvancedHMC.NUTS(tap; metric=metric)
# Sample
chain = sample(model, externalsampler(nuts), 10_000; n_adapts=1_000)
WARNING: Method definition size(Transducers.ProgressLoggingFoldable{T} where T) in module Transducers at /home/runner/.julia/packages/Transducers/txnl6/src/progress.jl:63 overwritten in module Pathfinder at /home/runner/.julia/packages/Pathfinder/02iSv/src/transducers.jl:15.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
UndefVarError: UndefVarError(:optim_function)
UndefVarError: `optim_function` not defined
Stacktrace:
[1] multipathfinder(model::DynamicPPL.Model{typeof(funnel), (), (), (), Tuple{}, Tuple{}, DynamicPPL.ConditionContext{@NamedTuple{x::Vector{Float64}}, DynamicPPL.DefaultContext}}, ndraws::Int64; rng::Random._GLOBAL_RNG, init_scale::Int64, init_sampler::Pathfinder.UniformSampler{Int64}, nruns::Int64, kwargs::@Kwargs{})
@ Pathfinder ~/.julia/packages/Pathfinder/02iSv/src/integration/turing.jl:150
[2] top-level scope
@ ~/work/docs/docs/tutorials/docs-16-using-turing-external-samplers/index.qmd:116
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:08:11
ϵ: 1.267584618877947
L: 3.1622776601683795
dE/d: -0.03211377196083518
Tuning: 1%|▍ | ETA: 0:04:11
ϵ: 0.8530898875330061
L: 4.182402269111954
dE/d: -0.10101984957848416
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 1.058706325311456
L: 431.99167930006774
dE/d: -0.04009357993313678
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 6.86 seconds
Compute duration = 6.86 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.0887 1.1269 0.0340 1116.8453 1090.8369 1.0035 ⋯
z[1] 0.3105 0.6557 0.0149 1977.4565 2229.0350 0.9999 ⋯
z[2] 1.2112 0.8815 0.0228 1558.4679 2205.9676 1.0008 ⋯
z[3] -0.5119 0.6911 0.0151 2162.4206 2720.3681 1.0001 ⋯
z[4] -0.3352 0.6927 0.0162 1867.0432 2264.5458 1.0067 ⋯
z[5] -0.2054 0.7148 0.0173 1757.1256 2071.8832 1.0041 ⋯
z[6] 0.7666 0.7713 0.0189 1755.4728 2167.9343 1.0007 ⋯
z[7] -0.7220 0.7479 0.0184 1736.6353 2176.8384 1.0000 ⋯
z[8] 1.3766 0.9541 0.0255 1426.9074 2190.5052 1.0006 ⋯
z[9] 0.0660 0.8024 0.0161 2503.2135 3264.3520 1.0032 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.4749 -0.8570 0.0148 0.7556 1.8318
z[1] -0.9333 -0.1060 0.2697 0.7041 1.7038
z[2] -0.2049 0.5435 1.1224 1.7962 3.0899
z[3] -2.0316 -0.9420 -0.4450 -0.0245 0.6937
z[4] -1.7943 -0.7720 -0.2848 0.1118 0.9583
z[5] -1.7506 -0.6096 -0.1829 0.2348 1.1818
z[6] -0.5282 0.2197 0.6906 1.2331 2.4774
z[7] -2.3603 -1.1843 -0.6387 -0.1882 0.5641
z[8] -0.1718 0.6486 1.2838 2.0181 3.4291
z[9] -1.5243 -0.4520 0.0456 0.5683 1.6938
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↩︎