# 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.12 seconds Compute duration = 3.12 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.8768 0.7372 0.1288 32.1743 32.1949 1.0098 ⋯ z[1] 0.2721 0.5376 0.0742 46.7907 53.6520 1.0349 ⋯ z[2] 0.5545 0.5350 0.0616 70.2416 131.2876 1.0928 ⋯ z[3] 0.3594 0.6519 0.0946 47.9609 94.3743 1.0000 ⋯ z[4] 0.0425 0.5740 0.0738 58.9362 36.8095 1.1466 ⋯ z[5] -0.4332 0.5841 0.0678 70.4664 86.8225 1.0414 ⋯ z[6] -0.1634 0.6074 0.0841 51.1635 79.9729 1.0528 ⋯ z[7] -0.0033 0.5698 0.0647 66.9222 83.9645 1.0622 ⋯ z[8] -0.1531 0.5520 0.0597 71.0186 131.1553 1.0027 ⋯ z[9] -0.2253 0.5547 0.0688 62.6980 136.0659 1.0079 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 θ -1.9832 -1.5462 -1.0479 -0.3519 0.7212 z[1] -0.5705 -0.0787 0.2618 0.5047 1.3736 z[2] -0.3682 0.2280 0.5592 0.7784 1.7392 z[3] -0.7917 -0.1209 0.2560 0.7384 1.7989 z[4] -0.9613 -0.3058 0.1328 0.3264 1.0686 z[5] -1.7526 -0.7296 -0.3559 -0.0796 0.6972 z[6] -1.6250 -0.5355 0.0006 0.1096 0.8869 z[7] -1.2270 -0.3688 0.1066 0.3122 1.1739 z[8] -1.1622 -0.4514 -0.1613 0.1761 1.3080 z[9] -1.4330 -0.5922 -0.2255 0.2412 0.7280
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:21 ϵ: 0.7226029210395422 L: 3.1622776601683795 dE/d: 21.918269327110437 Tuning: 1%|▍ | ETA: 0:04:08 ϵ: 0.4953919107976624 L: 2.1802648728472844 dE/d: 0.003818969483821988 Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02 ϵ: 1.4183092594078262 L: 612.7407745828053 dE/d: -0.03096302591328559
Chains MCMC chain (10000×11×1 Array{Float64, 3}): Iterations = 1:1:10000 Number of chains = 1 Samples per chain = 10000 Wall duration = 6.96 seconds Compute duration = 6.96 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.4830 1.0225 0.0298 1080.1036 1125.0593 0.9999 ⋯ z[1] 0.1214 0.5009 0.0109 2205.1146 2187.4821 1.0009 ⋯ z[2] 0.3292 0.5398 0.0135 1916.0331 1460.6257 1.0002 ⋯ z[3] 0.2816 0.5369 0.0114 2472.2469 1936.6785 1.0047 ⋯ z[4] -0.0343 0.4575 0.0114 1762.9507 1669.0377 1.0017 ⋯ z[5] -0.3336 0.5229 0.0135 1769.6885 1327.3704 1.0022 ⋯ z[6] -0.1221 0.4505 0.0102 2089.4682 1881.4212 1.0046 ⋯ z[7] -0.0248 0.4631 0.0114 1771.8764 1812.7748 1.0061 ⋯ z[8] -0.0113 0.4676 0.0106 2093.3132 2031.6112 1.0034 ⋯ z[9] -0.2123 0.5044 0.0128 1769.5037 1338.5555 1.0005 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 θ -2.9460 -2.3406 -1.5927 -0.7797 0.6932 z[1] -0.8284 -0.1794 0.0999 0.4057 1.1834 z[2] -0.5459 -0.0253 0.2504 0.5989 1.6547 z[3] -0.6166 -0.0651 0.2166 0.5584 1.5402 z[4] -1.0286 -0.2793 -0.0234 0.2254 0.8893 z[5] -1.6073 -0.5928 -0.2513 0.0073 0.5036 z[6] -1.1236 -0.3579 -0.0976 0.1408 0.7444 z[7] -0.9951 -0.2800 -0.0217 0.2327 0.9377 z[8] -1.0039 -0.2753 -0.0078 0.2569 0.9434 z[9] -1.4478 -0.4562 -0.1554 0.0892 0.6741
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↩︎