Using External Samplers

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.88 seconds
Compute duration  = 3.88 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.9264    0.6140    0.0585   119.0781    82.5694    1.0009     ⋯
        z[1]    0.6612    0.7724    0.0717   118.5779   178.4398    1.0319     ⋯
        z[2]   -0.0080    0.8370    0.0809   110.6860   173.4552    1.0043     ⋯
        z[3]   -0.4514    0.8066    0.0669   146.0654   212.6612    1.0143     ⋯
        z[4]   -1.7583    0.8414    0.0920    81.9007   111.0115    1.0273     ⋯
        z[5]    2.2715    0.8622    0.0894    95.9043   197.5817    1.0032     ⋯
        z[6]   -0.0598    0.7841    0.0614   160.6928   155.1497    1.0031     ⋯
        z[7]    0.8957    0.8253    0.0676   154.3165   239.9771    1.0026     ⋯
        z[8]   -2.5790    0.8973    0.1078    69.3281   155.2039    1.0048     ⋯
        z[9]   -0.6353    0.7829    0.0644   147.6962   181.3845    1.0063     ⋯
                                                                1 column omitted

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

           θ   -0.5252    0.5149    0.9316    1.3449    2.0749
        z[1]   -0.7963    0.0697    0.6718    1.1875    2.1769
        z[2]   -1.9009   -0.5184    0.0216    0.6027    1.5897
        z[3]   -2.0123   -1.0084   -0.4415    0.1386    1.1082
        z[4]   -3.6289   -2.3445   -1.6652   -1.2400   -0.2874
        z[5]    0.7487    1.7268    2.3243    2.8719    3.9474
        z[6]   -1.5351   -0.6105   -0.0350    0.4457    1.5754
        z[7]   -0.5591    0.3563    0.8718    1.4141    2.5839
        z[8]   -4.3843   -3.1687   -2.5405   -2.0369   -0.5343
        z[9]   -2.3505   -1.1315   -0.6194   -0.1538    0.9901

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: Pareto shape k = 0.74 > 0.7. Resulting importance sampling estimates are likely to be unstable.
└ @ PSIS ~/.julia/packages/PSIS/fU76x/src/core.jl:364
[ Info: Found initial step size 0.8
Chains MCMC chain (10000×23×1 Array{Float64, 3}):

Iterations        = 1:1:10000
Number of chains  = 1
Samples per chain = 10000
Wall duration     = 5.8 seconds
Compute duration  = 5.8 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.8869    0.7524    0.0147    4356.1701   2310.2037    1.0000  ⋯
        z[1]    0.6551    0.8366    0.0079   11319.7280   7629.5344    1.0000  ⋯
        z[2]   -0.0127    0.8237    0.0072   13091.9387   7650.0905    1.0000  ⋯
        z[3]   -0.4417    0.8434    0.0076   12336.6258   7393.2199    0.9999  ⋯
        z[4]   -1.8052    0.9136    0.0099    8421.2618   4566.9553    1.0000  ⋯
        z[5]    2.1879    0.9524    0.0111    7202.3284   3861.0426    1.0003  ⋯
        z[6]    0.0190    0.8381    0.0076   12205.9131   7894.0347    1.0000  ⋯
        z[7]    0.7681    0.8497    0.0087    9569.6699   7919.5154    1.0003  ⋯
        z[8]   -2.5229    0.9895    0.0115    7124.7803   3079.1234    1.0001  ⋯
        z[9]   -0.5790    0.8434    0.0076   12217.2213   7944.0191    0.9999  ⋯
                                                                1 column omitted

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

           θ   -0.7030    0.4490    0.9166    1.3806    2.2612
        z[1]   -0.9594    0.0822    0.6437    1.2045    2.3153
        z[2]   -1.6380   -0.5479   -0.0143    0.5148    1.6524
        z[3]   -2.1395   -0.9969   -0.4242    0.1216    1.1852
        z[4]   -3.6146   -2.4272   -1.7949   -1.1602   -0.0812
        z[5]    0.3435    1.5433    2.1675    2.8132    4.1123
        z[6]   -1.6238   -0.5354    0.0150    0.5751    1.6811
        z[7]   -0.8444    0.1984    0.7448    1.3241    2.4888
        z[8]   -4.5015   -3.1984   -2.5031   -1.8468   -0.6189
        z[9]   -2.2544   -1.1394   -0.5636   -0.0166    1.0860

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:06:05
  ϵ:     1.1895469487199226
  L:     3.1622776601683795
  dE/d:  -0.034692248626156184


Tuning:   1%|▍                                          |  ETA: 0:04:14
  ϵ:     1.3608013131938246
  L:     6.654182401789463
  dE/d:  0.010563357763462377


Tuning: 100%|███████████████████████████████████████████| Time: 0:00:02
  ϵ:     2.252302063022756
  L:     954.2150049761135
  dE/d:  -0.014340325985904557
Chains MCMC chain (10000×11×1 Array{Float64, 3}):

Iterations        = 1:1:10000
Number of chains  = 1
Samples per chain = 10000
Wall duration     = 5.09 seconds
Compute duration  = 5.09 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.9568    0.7540    0.0169   2055.8121   1882.3516    1.0044   ⋯
        z[1]    0.6684    0.8394    0.0172   2394.1480   3325.6951    1.0003   ⋯
        z[2]   -0.0190    0.7472    0.0122   3766.2744   4949.7258    1.0372   ⋯
        z[3]   -0.4532    0.8389    0.0165   2613.2581   3633.3088    1.0023   ⋯
        z[4]   -1.8132    0.9175    0.0155   3541.1333   4387.8983    1.0001   ⋯
        z[5]    2.2142    1.0178    0.0200   2580.9428   3953.9982    1.0011   ⋯
        z[6]    0.0100    0.8429    0.0129   4259.2696   5828.5831    0.9999   ⋯
        z[7]    0.7738    0.8862    0.0183   2353.1778   3240.5408    1.0005   ⋯
        z[8]   -2.5711    1.0300    0.0201   2637.2177   3401.8526    1.0011   ⋯
        z[9]   -0.5933    0.8634    0.0145   3535.1486   4623.7053    1.0071   ⋯
                                                                1 column omitted

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

           θ   -0.6144    0.4886    0.9883    1.4784    2.3559
        z[1]   -1.0024    0.1322    0.6524    1.1905    2.4004
        z[2]   -1.5438   -0.4794   -0.0164    0.4465    1.5021
        z[3]   -2.1523   -0.9989   -0.4411    0.0962    1.1942
        z[4]   -3.6666   -2.4148   -1.7947   -1.1904   -0.0598
        z[5]    0.2409    1.5166    2.2035    2.8971    4.2161
        z[6]   -1.7359   -0.4890    0.0088    0.5034    1.7474
        z[7]   -0.8953    0.1732    0.7474    1.3645    2.5745
        z[8]   -4.6578   -3.2451   -2.5495   -1.8884   -0.5722
        z[9]   -2.3220   -1.1421   -0.5799   -0.0422    1.1384

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