Using External Sampler

Using External Samplers on Turing Models

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.

(; x) = rand(funnel() |=0,))
model = funnel() | (; x);

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.

# Importing the sampling library
using AdvancedMH
rwmh = AdvancedMH.RWMH(d)
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]
)
))
setprogress!(false)

Sampling is then as easy as:

chain = sample(model, externalsampler(rwmh), 10_000)
Chains MCMC chain (10000×11×1 Array{Float64, 3}):

Iterations        = 1:1:10000
Number of chains  = 1
Samples per chain = 10000
Wall duration     = 3.58 seconds
Compute duration  = 3.58 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.1630    1.0763    0.2102    30.5116    24.8561    1.0712     ⋯
        z[1]    0.2298    0.7515    0.0942    64.9420   136.5790    1.0000     ⋯
        z[2]    0.8685    0.7807    0.1041    61.1872   111.0589    1.0000     ⋯
        z[3]   -0.4350    0.7255    0.0914    61.6497   224.9555    1.0636     ⋯
        z[4]   -1.6141    1.0386    0.1617    40.0928    54.9201    1.0587     ⋯
        z[5]   -0.4978    0.7994    0.1158    48.7462    85.5420    1.0269     ⋯
        z[6]    0.5906    0.6864    0.0697    93.2805   153.1040    1.0000     ⋯
        z[7]   -0.7635    0.7713    0.1057    50.2478   170.4521    1.0328     ⋯
        z[8]   -0.3890    0.7220    0.0781    84.8619   187.4642    1.0357     ⋯
        z[9]    0.7536    0.7365    0.1027    51.2869   149.1702    1.0911     ⋯
                                                                1 column omitted

Quantiles
  parameters      2.5%     25.0%     50.0%     75.0%     97.5%
      Symbol   Float64   Float64   Float64   Float64   Float64

           θ   -1.7755   -1.2963   -0.0157    0.6603    1.7666
        z[1]   -1.0098   -0.1816    0.0759    0.6493    1.7971
        z[2]   -0.1493    0.2387    0.8203    1.3755    2.6352
        z[3]   -1.9803   -0.8255   -0.3761    0.0104    0.7546
        z[4]   -3.9860   -2.1594   -1.6272   -0.6642    0.2189
        z[5]   -2.4178   -0.9764   -0.3650    0.0433    0.6255
        z[6]   -0.8351    0.1450    0.6896    0.9286    2.0804
        z[7]   -2.5848   -1.0812   -0.7010   -0.2522    0.3656
        z[8]   -2.2052   -0.8442   -0.1504   -0.0019    0.9548
        z[9]   -0.2936    0.2234    0.4964    1.3344    2.5173

Going beyond the Turing API

As previously mentioned, the Turing wrappers can often limit the capabilities of the sampling libraries they wrap. AdvancedHMC1 (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 Pathfinder2 ((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

Using new inference methods

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:07:58
  ϵ:     1.8980650273792963
  L:     3.1622776601683795
  dE/d:  -0.028610448684361245


Tuning:   1%|▍                                          |  ETA: 0:04:00
  ϵ:     0.959043389027052
  L:     4.225929525781828
  dE/d:  -0.006381514598079363


Tuning: 100%|███████████████████████████████████████████| Time: 0:00:03
  ϵ:     1.6706982114713407
  L:     685.2609888420178
  dE/d:  -0.1125684252370867
Chains MCMC chain (10000×11×1 Array{Float64, 3}):

Iterations        = 1:1:10000
Number of chains  = 1
Samples per chain = 10000
Wall duration     = 6.57 seconds
Compute duration  = 6.57 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.3480    0.8402    0.0215   1648.8655   1306.8236    1.0010   ⋯
        z[1]    0.2428    0.7756    0.0129   3645.9714   4209.0244    1.0012   ⋯
        z[2]    1.0471    0.8392    0.0146   3366.8112   4088.8439    1.0001   ⋯
        z[3]   -0.5447    0.7717    0.0131   3577.7065   4157.0600    1.0003   ⋯
        z[4]   -1.8508    0.9487    0.0210   2054.7777   2830.9696    1.0008   ⋯
        z[5]   -0.5560    0.7731    0.0184   1785.9839   2307.5494    1.0008   ⋯
        z[6]    0.7439    0.8365    0.0177   2243.4187   3070.9742    1.0003   ⋯
        z[7]   -0.8874    0.8447    0.0181   2207.8256   3044.3597    1.0000   ⋯
        z[8]   -0.4121    0.6670    0.0111   3601.5396   4381.1506    1.0026   ⋯
        z[9]    1.0083    0.8337    0.0156   2887.7739   3649.0594    1.0006   ⋯
                                                                1 column omitted

Quantiles
  parameters      2.5%     25.0%     50.0%     75.0%     97.5%
      Symbol   Float64   Float64   Float64   Float64   Float64

           θ   -1.5469   -0.1510    0.4066    0.9133    1.8358
        z[1]   -1.2782   -0.2643    0.2365    0.7497    1.8281
        z[2]   -0.4825    0.4588    1.0083    1.5966    2.8042
        z[3]   -2.1185   -1.0192   -0.5148   -0.0469    0.9453
        z[4]   -3.8339   -2.4839   -1.8111   -1.1759   -0.1255
        z[5]   -2.1388   -1.0596   -0.5395   -0.0499    0.9531
        z[6]   -0.8234    0.1537    0.7136    1.3135    2.4310
        z[7]   -2.6345   -1.4522   -0.8453   -0.2887    0.6497
        z[8]   -1.7979   -0.8364   -0.3922    0.0256    0.8576
        z[9]   -0.5162    0.4179    0.9656    1.5657    2.7238

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:

    • A function that performs the first step and initializes the sampler.
    • A function that performs the following steps and takes an extra input, 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:

Back to top