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.48 seconds
Compute duration  = 3.48 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.7750    0.7504    0.1186    38.4975    31.1553    1.0060     ⋯
        z[1]    0.0495    0.6111    0.0731    73.5459   127.2069    1.0147     ⋯
        z[2]    0.0213    0.5269    0.0600    71.5341    47.4656    1.0133     ⋯
        z[3]    0.5984    0.6643    0.1001    44.8346    38.4570    1.0141     ⋯
        z[4]    0.5022    0.6226    0.0914    43.3093    79.7345    1.0448     ⋯
        z[5]   -0.1307    0.5952    0.0774    59.9811    84.6599    1.0215     ⋯
        z[6]   -0.0168    0.6413    0.0912    47.9506    63.3733    1.1175     ⋯
        z[7]   -0.4241    0.5910    0.0864    46.9540    94.6940    1.0037     ⋯
        z[8]   -0.3341    0.5981    0.0920    40.7560   144.9493    1.0296     ⋯
        z[9]    0.1484    0.5193    0.0730    47.0021    73.7463    1.0586     ⋯
                                                                1 column omitted

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

           θ   -2.1268   -1.3717   -0.7276   -0.3351    0.7887
        z[1]   -0.8977   -0.4271   -0.0622    0.5437    1.1751
        z[2]   -1.0740   -0.2440   -0.0250    0.3255    1.0781
        z[3]   -0.4505    0.2454    0.6150    0.8974    2.0159
        z[4]   -0.5137   -0.0088    0.4046    0.8012    2.0712
        z[5]   -1.5322   -0.5144   -0.1196    0.2095    1.0105
        z[6]   -1.4269   -0.5075    0.0719    0.3480    1.1626
        z[7]   -1.8347   -0.8374   -0.2203   -0.1155    0.6778
        z[8]   -1.5808   -0.6347   -0.3645    0.0865    0.6575
        z[9]   -0.7124   -0.2487    0.0722    0.5291    1.0794

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 can use the library Pathfinder2 (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.

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:30
      ϵ: 1.0979061983700957
      L: 3.1622776601683795
   dE/d: 0.011210766057140376








Tuning:   1%|▍                                          |  ETA: 0:04:09
      ϵ: 0.7887903384381623
      L: 3.667340576593098
   dE/d: 0.11154063556064742








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

Iterations        = 1:1:10000
Number of chains  = 1
Samples per chain = 10000
Wall duration     = 6.54 seconds
Compute duration  = 6.54 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.3324    1.1798    0.0377    906.8322   1051.0395    1.0002   ⋯
        z[1]    0.0967    0.5130    0.0129   1750.0075   1629.2643    1.0004   ⋯
        z[2]   -0.0317    0.5318    0.0146   1393.7726   1430.3529    1.0016   ⋯
        z[3]    0.4649    0.6586    0.0191   1620.2267   1176.5919    0.9999   ⋯
        z[4]    0.3753    0.5813    0.0156   1721.2097   1364.6060    1.0000   ⋯
        z[5]   -0.1369    0.4751    0.0105   2207.4553   1996.9028    1.0065   ⋯
        z[6]    0.0105    0.4325    0.0111   1675.5830   1563.0939    1.0005   ⋯
        z[7]   -0.3709    0.5995    0.0161   1657.5207   1345.5199    1.0000   ⋯
        z[8]   -0.3518    0.5853    0.0159   1627.1423   1402.0973    1.0052   ⋯
        z[9]    0.1967    0.4704    0.0124   1585.7195   1516.4384    1.0003   ⋯
                                                                1 column omitted

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

           θ   -2.9693   -2.3445   -1.4843   -0.4851    1.1033
        z[1]   -0.8673   -0.2004    0.0733    0.3593    1.2346
        z[2]   -1.1810   -0.3311   -0.0254    0.2775    1.0349
        z[3]   -0.4934    0.0375    0.3274    0.7489    2.2232
        z[4]   -0.5131   -0.0026    0.2688    0.6574    1.8185
        z[5]   -1.2307   -0.3813   -0.0978    0.1404    0.7540
        z[6]   -0.8884   -0.2173    0.0096    0.2366    0.9615
        z[7]   -1.8775   -0.6642   -0.2683    0.0194    0.5793
        z[8]   -1.8048   -0.6318   -0.2502    0.0384    0.5542
        z[9]   -0.6398   -0.0926    0.1425    0.4303    1.3057

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