# 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.08 seconds
Compute duration = 4.08 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.0792 0.8151 0.1204 45.5604 37.6941 1.0060 ⋯
z[1] 0.5610 0.7449 0.0933 64.8288 126.8726 1.0058 ⋯
z[2] 0.3612 0.6890 0.0597 124.4392 206.7558 1.0133 ⋯
z[3] 0.7044 0.7482 0.0767 95.4292 155.1933 1.0082 ⋯
z[4] 0.2318 0.6911 0.0788 75.8781 139.4351 1.0186 ⋯
z[5] -0.1766 0.7446 0.0751 92.2116 83.0047 1.0219 ⋯
z[6] -0.8205 0.7650 0.0944 62.0074 104.7053 1.0353 ⋯
z[7] 1.1050 0.7907 0.0940 71.6256 71.1584 1.0022 ⋯
z[8] 0.9779 0.7800 0.1013 57.6048 106.3557 1.0457 ⋯
z[9] 0.7700 0.7400 0.0953 63.2703 122.5273 1.0410 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -1.6445 -0.6787 -0.1105 0.3835 1.6178
z[1] -0.8654 0.0237 0.6924 1.0917 1.9525
z[2] -1.0652 -0.0830 0.4410 0.7220 1.6860
z[3] -0.6129 0.1749 0.6547 0.9859 2.6049
z[4] -1.2204 -0.1001 0.1960 0.6364 1.5910
z[5] -1.4776 -0.7024 -0.2506 0.2121 1.4434
z[6] -2.5053 -1.2989 -0.6657 -0.2739 0.6728
z[7] -0.4411 0.5558 1.1549 1.6075 2.6111
z[8] -0.4518 0.4798 0.8798 1.4188 2.7179
z[9] -0.3270 0.1658 0.6706 1.3029 2.2946
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: Pareto shape k = 0.72 > 0.7. Resulting importance sampling estimates are likely to be unstable.
└ @ PSIS ~/.julia/packages/PSIS/jwznT/src/core.jl:314
[ Info: Found initial step size 5.960464477539063e-9
Chains MCMC chain (10000×23×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 6.02 seconds
Compute duration = 6.02 seconds
parameters = θ, z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8], z[9]
internals = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, max_hamiltonian_energy_error, tree_depth, numerical_error, step_size, nom_step_size, is_adapt
Summary Statistics
parameters mean std mcse ess_bulk ess_tail rhat ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯
θ -0.3508 1.0678 0.0307 1302.0586 791.9230 1.0003 ⋯
z[1] 0.4732 0.7173 0.0217 996.3905 209.9091 1.0019 ⋯
z[2] 0.2997 0.6886 0.0170 1485.8466 219.5798 1.0006 ⋯
z[3] 0.6457 0.7266 0.0091 6528.7701 6522.9936 1.0006 ⋯
z[4] 0.2293 0.6612 0.0062 10916.6391 6670.9476 1.0003 ⋯
z[5] 0.1077 0.6890 0.0252 1027.5614 214.8401 1.0015 ⋯
z[6] -0.7339 0.7870 0.0255 820.0466 206.2429 1.0010 ⋯
z[7] 0.9339 0.8044 0.0136 3593.1983 6329.7335 1.0002 ⋯
z[8] 0.8033 0.7722 0.0121 4364.2473 6030.0162 1.0000 ⋯
z[9] 0.6968 0.7553 0.0132 3477.7623 6992.1926 1.0004 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.6536 -1.0407 -0.2384 0.4190 1.4740
z[1] -0.9230 -0.0055 0.4020 0.9100 2.0454
z[2] -0.9415 -0.1379 0.2592 0.7142 1.7754
z[3] -0.5857 0.1428 0.5699 1.0837 2.2475
z[4] -1.0377 -0.1916 0.1879 0.6259 1.6388
z[5] -1.2229 -0.3209 0.0777 0.5003 1.7559
z[6] -2.4780 -1.2229 -0.6541 -0.1838 0.7437
z[7] -0.3425 0.3305 0.8328 1.4389 2.7236
z[8] -0.4458 0.2494 0.7056 1.2786 2.5420
z[9] -0.5354 0.1414 0.6048 1.1817 2.3684
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:39
ϵ: 0.6362485600475346
L: 3.1622776601683795
dE/d: -0.07510782204273454
Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
ϵ: 1.3661322692887936
L: 0.8983048842005218
dE/d: 0.0018555340631152717
Chains MCMC chain (10000×11×1 Array{Float64, 3}):
Iterations = 1:1:10000
Number of chains = 1
Samples per chain = 10000
Wall duration = 5.33 seconds
Compute duration = 5.33 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.4354 1.1091 0.1065 107.5045 88.8800 1.0250 ⋯
z[1] 0.4975 0.6794 0.0352 371.1418 869.7823 1.0002 ⋯
z[2] 0.3414 0.6715 0.0310 486.9585 748.9885 1.0021 ⋯
z[3] 0.6253 0.7420 0.0454 280.7704 480.2087 1.0026 ⋯
z[4] 0.1686 0.6419 0.0303 457.1670 606.0290 1.0018 ⋯
z[5] 0.0624 0.6588 0.0292 535.4506 571.5948 1.0091 ⋯
z[6] -0.7558 0.7688 0.0475 279.0248 542.7749 1.0079 ⋯
z[7] 0.8457 0.7871 0.0434 350.3150 761.9883 1.0031 ⋯
z[8] 0.7751 0.7844 0.0423 368.1900 891.6664 1.0062 ⋯
z[9] 0.7005 0.7730 0.0499 272.5664 507.6777 1.0125 ⋯
1 column omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
θ -2.7414 -1.1973 -0.3533 0.3835 1.5146
z[1] -0.7172 0.0425 0.4401 0.9027 1.9881
z[2] -0.9288 -0.0857 0.2942 0.7320 1.8138
z[3] -0.6653 0.1307 0.5304 1.0469 2.3217
z[4] -1.0494 -0.2539 0.1530 0.5608 1.5029
z[5] -1.2536 -0.3330 0.0462 0.4408 1.4567
z[6] -2.5225 -1.2219 -0.6419 -0.2073 0.4957
z[7] -0.4023 0.2681 0.7364 1.3181 2.6505
z[8] -0.4948 0.2230 0.6715 1.2472 2.5333
z[9] -0.5581 0.1466 0.5893 1.1618 2.5109
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↩︎