Guide

Basics

Introduction

A probabilistic program is Julia code wrapped in a @model macro. It can use arbitrary Julia code, but to ensure correctness of inference it should not have external effects or modify global state. Stack-allocated variables are safe, but mutable heap-allocated objects may lead to subtle bugs when using task copying. By default Libtask deepcopies Array and Dict objects when copying task to avoid bugs with data stored in mutable structure in Turing models.

To specify distributions of random variables, Turing programs should use the ~ notation:

x ~ distr where x is a symbol and distr is a distribution. If x is undefined in the model function, inside the probabilistic program, this puts a random variable named x, distributed according to distr, in the current scope. distr can be a value of any type that implements rand(distr), which samples a value from the distribution distr. If x is defined, this is used for conditioning in a style similar to Anglican (another PPL). In this case, x is an observed value, assumed to have been drawn from the distribution distr. The likelihood is computed using logpdf(distr,y). The observe statements should be arranged so that every possible run traverses all of them in exactly the same order. This is equivalent to demanding that they are not placed inside stochastic control flow.

Available inference methods include Importance Sampling (IS), Sequential Monte Carlo (SMC), Particle Gibbs (PG), Hamiltonian Monte Carlo (HMC), Hamiltonian Monte Carlo with Dual Averaging (HMCDA) and The No-U-Turn Sampler (NUTS).

Simple Gaussian Demo

Below is a simple Gaussian demo illustrate the basic usage of Turing.jl.

# Import packages.
using Turing
using StatsPlots

# Define a simple Normal model with unknown mean and variance.
@model function gdemo(x, y)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    x ~ Normal(m, sqrt(s²))
    return y ~ Normal(m, sqrt(s²))
end
gdemo (generic function with 2 methods)

Note: As a sanity check, the prior expectation of is mean(InverseGamma(2, 3)) = 3/(2 - 1) = 3 and the prior expectation of m is 0. This can be easily checked using Prior:

setprogress!(false)
p1 = sample(gdemo(missing, missing), Prior(), 100000)
Chains MCMC chain (100000×5×1 Array{Float64, 3}):

Iterations        = 1:1:100000
Number of chains  = 1
Samples per chain = 100000
Wall duration     = 1.96 seconds
Compute duration  = 1.96 seconds
parameters        = s², m, x, y
internals         = lp

Summary Statistics
  parameters      mean       std      mcse      ess_bulk      ess_tail      rh     Symbol   Float64   Float64   Float64       Float64       Float64   Float ⋯

          s²    2.9991    6.4798    0.0206    99739.9045    97925.9396    1.00 ⋯
           m    0.0138    1.7364    0.0055   100040.4369   100240.8390    1.00 ⋯
           x    0.0149    2.4591    0.0078   100119.4273    98862.4825    1.00 ⋯
           y    0.0131    2.4389    0.0077    99372.2894    98171.5650    1.00 ⋯
                                                               2 columns omitted

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

          s²    0.5427    1.1176    1.7989    3.1260   12.4277
           m   -3.3870   -0.8943    0.0050    0.9255    3.4182
           x   -4.8097   -1.2700    0.0113    1.3050    4.8151
           y   -4.8212   -1.2769    0.0109    1.2978    4.8325

We can perform inference by using the sample function, the first argument of which is our probabilistic program and the second of which is a sampler. More information on each sampler is located in the API.

#  Run sampler, collect results.
c1 = sample(gdemo(1.5, 2), SMC(), 1000)
c2 = sample(gdemo(1.5, 2), PG(10), 1000)
c3 = sample(gdemo(1.5, 2), HMC(0.1, 5), 1000)
c4 = sample(gdemo(1.5, 2), Gibbs(PG(10, :m), HMC(0.1, 5, :s²)), 1000)
c5 = sample(gdemo(1.5, 2), HMCDA(0.15, 0.65), 1000)
c6 = sample(gdemo(1.5, 2), NUTS(0.65), 1000)
┌ Info: Found initial step size
└   ϵ = 1.6
┌ Info: Found initial step size
└   ϵ = 0.8
Chains MCMC chain (1000×14×1 Array{Float64, 3}):

Iterations        = 501:1:1500
Number of chains  = 1
Samples per chain = 1000
Wall duration     = 1.94 seconds
Compute duration  = 1.94 seconds
parameters        = s², m
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

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

          s²    2.0085    1.7366    0.0811   392.9215   416.9046    0.9991     ⋯
           m    1.1888    0.8189    0.0366   532.1388   465.8591    1.0033     ⋯
                                                                1 column omitted

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

          s²    0.5035    0.9939    1.4626    2.3488    6.2069
           m   -0.5599    0.6986    1.1661    1.6448    3.0775

The MCMCChains module (which is re-exported by Turing) provides plotting tools for the Chain objects returned by a sample function. See the MCMCChains repository for more information on the suite of tools available for diagnosing MCMC chains.

# Summarise results
describe(c3)

# Plot results
plot(c3)
savefig("gdemo-plot.png")

The arguments for each sampler are:

  • SMC: number of particles.
  • PG: number of particles, number of iterations.
  • HMC: leapfrog step size, leapfrog step numbers.
  • Gibbs: component sampler 1, component sampler 2, …
  • HMCDA: total leapfrog length, target accept ratio.
  • NUTS: number of adaptation steps (optional), target accept ratio.

For detailed information on the samplers, please review Turing.jl’s API documentation.

Modelling Syntax Explained

Using this syntax, a probabilistic model is defined in Turing. The model function generated by Turing can then be used to condition the model onto data. Subsequently, the sample function can be used to generate samples from the posterior distribution.

In the following example, the defined model is conditioned to the data (arg1 = 1, arg2 = 2) by passing (1, 2) to the model function.

@model function model_name(arg_1, arg_2)
    return ...
end

The conditioned model can then be passed onto the sample function to run posterior inference.

model_func = model_name(1, 2)
chn = sample(model_func, HMC(..)) # Perform inference by sampling using HMC.

The returned chain contains samples of the variables in the model.

var_1 = mean(chn[:var_1]) # Taking the mean of a variable named var_1.

The key (:var_1) can be a Symbol or a String. For example, to fetch x[1], one can use chn[Symbol("x[1]")] or chn["x[1]"]. If you want to retrieve all parameters associated with a specific symbol, you can use group. As an example, if you have the parameters "x[1]", "x[2]", and "x[3]", calling group(chn, :x) or group(chn, "x") will return a new chain with only "x[1]", "x[2]", and "x[3]".

Turing does not have a declarative form. More generally, the order in which you place the lines of a @model macro matters. For example, the following example works:

# Define a simple Normal model with unknown mean and variance.
@model function model_function(y)
    s ~ Poisson(1)
    y ~ Normal(s, 1)
    return y
end

sample(model_function(10), SMC(), 100)
Chains MCMC chain (100×3×1 Array{Float64, 3}):

Log evidence      = -22.135183060983685
Iterations        = 1:1:100
Number of chains  = 1
Samples per chain = 100
Wall duration     = 1.84 seconds
Compute duration  = 1.84 seconds
parameters        = s
internals         = lp, weight

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

           s    3.9900    0.1000    0.0098   104.2535        NaN    1.0000     ⋯
                                                                1 column omitted

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

           s    4.0000    4.0000    4.0000    4.0000    4.0000

But if we switch the s ~ Poisson(1) and y ~ Normal(s, 1) lines, the model will no longer sample correctly:

# Define a simple Normal model with unknown mean and variance.
@model function model_function(y)
    y ~ Normal(s, 1)
    s ~ Poisson(1)
    return y
end

sample(model_function(10), SMC(), 100)

Sampling Multiple Chains

Turing supports distributed and threaded parallel sampling. To do so, call sample(model, sampler, parallel_type, n, n_chains), where parallel_type can be either MCMCThreads() or MCMCDistributed() for thread and parallel sampling, respectively.

Having multiple chains in the same object is valuable for evaluating convergence. Some diagnostic functions like gelmandiag require multiple chains.

If you do not want parallelism or are on an older version Julia, you can sample multiple chains with the mapreduce function:

# Replace num_chains below with however many chains you wish to sample.
chains = mapreduce(c -> sample(model_fun, sampler, 1000), chainscat, 1:num_chains)

The chains variable now contains a Chains object which can be indexed by chain. To pull out the first chain from the chains object, use chains[:,:,1]. The method is the same if you use either of the below parallel sampling methods.

Multithreaded sampling

If you wish to perform multithreaded sampling and are running Julia 1.3 or greater, you can call sample with the following signature:

using Turing

@model function gdemo(x)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))

    for i in eachindex(x)
        x[i] ~ Normal(m, sqrt(s²))
    end
end

model = gdemo([1.5, 2.0])

# Sample four chains using multiple threads, each with 1000 samples.
sample(model, NUTS(), MCMCThreads(), 1000, 4)

Be aware that Turing cannot add threads for you – you must have started your Julia instance with multiple threads to experience any kind of parallelism. See the Julia documentation for details on how to achieve this.

Distributed sampling

To perform distributed sampling (using multiple processes), you must first import Distributed.

Process parallel sampling can be done like so:

# Load Distributed to add processes and the @everywhere macro.
using Distributed

# Load Turing.
using Turing

# Add four processes to use for sampling.
addprocs(4; exeflags="--project=$(Base.active_project())")

# Initialize everything on all the processes.
# Note: Make sure to do this after you've already loaded Turing,
#       so each process does not have to precompile.
#       Parallel sampling may fail silently if you do not do this.
@everywhere using Turing

# Define a model on all processes.
@everywhere @model function gdemo(x)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))

    for i in eachindex(x)
        x[i] ~ Normal(m, sqrt(s²))
    end
end

# Declare the model instance everywhere.
@everywhere model = gdemo([1.5, 2.0])

# Sample four chains using multiple processes, each with 1000 samples.
sample(model, NUTS(), MCMCDistributed(), 1000, 4)

Sampling from an Unconditional Distribution (The Prior)

Turing allows you to sample from a declared model’s prior. If you wish to draw a chain from the prior to inspect your prior distributions, you can simply run

chain = sample(model, Prior(), n_samples)

You can also run your model (as if it were a function) from the prior distribution, by calling the model without specifying inputs or a sampler. In the below example, we specify a gdemo model which returns two variables, x and y. The model includes x and y as arguments, but calling the function without passing in x or y means that Turing’s compiler will assume they are missing values to draw from the relevant distribution. The return statement is necessary to retrieve the sampled x and y values. Assign the function with missing inputs to a variable, and Turing will produce a sample from the prior distribution.

@model function gdemo(x, y)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    x ~ Normal(m, sqrt(s²))
    y ~ Normal(m, sqrt(s²))
    return x, y
end
gdemo (generic function with 2 methods)

Assign the function with missing inputs to a variable, and Turing will produce a sample from the prior distribution.

# Samples from p(x,y)
g_prior_sample = gdemo(missing, missing)
g_prior_sample()
(-0.6703071517494347, -0.37418655781636645)

Sampling from a Conditional Distribution (The Posterior)

Treating observations as random variables

Inputs to the model that have a value missing are treated as parameters, aka random variables, to be estimated/sampled. This can be useful if you want to simulate draws for that parameter, or if you are sampling from a conditional distribution. Turing supports the following syntax:

@model function gdemo(x, ::Type{T}=Float64) where {T}
    if x === missing
        # Initialize `x` if missing
        x = Vector{T}(undef, 2)
    end
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    for i in eachindex(x)
        x[i] ~ Normal(m, sqrt(s²))
    end
end

# Construct a model with x = missing
model = gdemo(missing)
c = sample(model, HMC(0.01, 5), 500)
Chains MCMC chain (500×14×1 Array{Float64, 3}):

Iterations        = 1:1:500
Number of chains  = 1
Samples per chain = 500
Wall duration     = 3.4 seconds
Compute duration  = 3.4 seconds
parameters        = s², m, x[1], x[2]
internals         = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, numerical_error, step_size, nom_step_size

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

          s²    3.6830    1.1454    0.8320     2.0117    32.0853    1.5060     ⋯
           m    1.4748    0.3835    0.2447     2.7512    19.0751    1.3154     ⋯
        x[1]    0.7661    0.4169    0.2719     2.2606    20.5654    1.3851     ⋯
        x[2]    3.2074    0.2155    0.0738     9.7942    29.4308    1.2166     ⋯
                                                                1 column omitted

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

          s²    1.7982    2.6849    3.7196    4.5922    5.6651
           m    0.7023    1.2166    1.4502    1.7589    2.1379
        x[1]   -0.0530    0.4650    0.8063    1.0967    1.4671
        x[2]    2.8862    3.0448    3.1621    3.3477    3.6917

Note the need to initialize x when missing since we are iterating over its elements later in the model. The generated values for x can be extracted from the Chains object using c[:x].

Turing also supports mixed missing and non-missing values in x, where the missing ones will be treated as random variables to be sampled while the others get treated as observations. For example:

@model function gdemo(x)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    for i in eachindex(x)
        x[i] ~ Normal(m, sqrt(s²))
    end
end

# x[1] is a parameter, but x[2] is an observation
model = gdemo([missing, 2.4])
c = sample(model, HMC(0.01, 5), 500)
Chains MCMC chain (500×13×1 Array{Float64, 3}):

Iterations        = 1:1:500
Number of chains  = 1
Samples per chain = 500
Wall duration     = 2.05 seconds
Compute duration  = 2.05 seconds
parameters        = s², m, x[1]
internals         = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, numerical_error, step_size, nom_step_size

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

          s²    3.7031    1.7649    0.6928     8.5141    11.5123    1.0769     ⋯
           m    2.9200    0.2559    0.0962     7.1288    18.4957    1.0795     ⋯
        x[1]    7.4094    0.6143    0.2459     6.1685    10.8746    1.5162     ⋯
                                                                1 column omitted

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

          s²    1.7496    2.8203    3.2884    3.9300    9.3256
           m    2.4819    2.7358    2.8853    3.0848    3.4449
        x[1]    5.8563    7.0642    7.4267    7.9134    8.3528

Default Values

Arguments to Turing models can have default values much like how default values work in normal Julia functions. For instance, the following will assign missing to x and treat it as a random variable. If the default value is not missing, x will be assigned that value and will be treated as an observation instead.

using Turing

@model function generative(x=missing, ::Type{T}=Float64) where {T<:Real}
    if x === missing
        # Initialize x when missing
        x = Vector{T}(undef, 10)
    end
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    for i in 1:length(x)
        x[i] ~ Normal(m, sqrt(s²))
    end
    return s², m
end

m = generative()
chain = sample(m, HMC(0.01, 5), 1000)
Chains MCMC chain (1000×22×1 Array{Float64, 3}):

Iterations        = 1:1:1000
Number of chains  = 1
Samples per chain = 1000
Wall duration     = 2.9 seconds
Compute duration  = 2.9 seconds
parameters        = s², m, x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10]
internals         = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, numerical_error, step_size, nom_step_size

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

          s²    1.6017    0.6324    0.2167     9.4671    20.3858    1.0429     ⋯
           m    0.2348    0.4074    0.1728     5.7206    22.4118    1.1103     ⋯
        x[1]    1.7508    0.4417    0.2915     2.6805    20.4943    2.1014     ⋯
        x[2]   -0.8486    0.4873    0.1668     8.9670    12.6785    1.1068     ⋯
        x[3]    0.4671    0.2781    0.0902     9.9221    53.0234    1.0119     ⋯
        x[4]    0.5177    0.3427    0.1117     9.4191    24.4329    1.2191     ⋯
        x[5]    1.9000    0.4738    0.2504     4.5974    12.6703    1.1919     ⋯
        x[6]   -0.3454    0.7801    0.5214     2.6612    20.3312    2.0740     ⋯
        x[7]   -1.0074    0.4651    0.2016     5.5290    12.8354    1.2293     ⋯
        x[8]   -1.5335    0.4474    0.1529     8.7256    12.6340    1.1422     ⋯
        x[9]    0.1437    1.1843    0.7896     2.4499    13.2298    2.1059     ⋯
       x[10]    0.3433    0.6493    0.3286     4.0844    14.7590    1.2524     ⋯
                                                                1 column omitted

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

          s²    0.8096    1.0798    1.3965    2.0872    2.9376
           m   -0.5099   -0.0511    0.1953    0.6089    0.9185
        x[1]    1.0708    1.3729    1.6682    2.1295    2.5648
        x[2]   -1.6604   -1.2402   -0.8878   -0.5368    0.1488
        x[3]   -0.0031    0.2517    0.4681    0.6611    0.9872
        x[4]   -0.0903    0.2678    0.5257    0.7389    1.1547
        x[5]    0.8215    1.7357    2.0502    2.2272    2.5151
        x[6]   -1.6716   -0.9865   -0.5736    0.3839    0.9422
        x[7]   -2.0105   -1.3464   -0.9059   -0.6817   -0.2378
        x[8]   -2.3628   -1.8454   -1.4566   -1.2572   -0.5847
        x[9]   -1.3999   -0.9350   -0.2203    1.1729    2.2900
       x[10]   -0.8115   -0.1316    0.3616    0.7404    1.6316

Access Values inside Chain

You can access the values inside a chain several ways:

  1. Turn them into a DataFrame object
  2. Use their raw AxisArray form
  3. Create a three-dimensional Array object

For example, let c be a Chain:

  1. DataFrame(c) converts c to a DataFrame,
  2. c.value retrieves the values inside c as an AxisArray, and
  3. c.value.data retrieves the values inside c as a 3D Array.

Variable Types and Type Parameters

The element type of a vector (or matrix) of random variables should match the eltype of its prior distribution, <: Integer for discrete distributions and <: AbstractFloat for continuous distributions. Moreover, if the continuous random variable is to be sampled using a Hamiltonian sampler, the vector’s element type needs to either be:

  1. Real to enable auto-differentiation through the model which uses special number types that are sub-types of Real, or

  2. Some type parameter T defined in the model header using the type parameter syntax, e.g. function gdemo(x, ::Type{T} = Float64) where {T}.

Similarly, when using a particle sampler, the Julia variable used should either be:

  1. An Array, or

  2. An instance of some type parameter T defined in the model header using the type parameter syntax, e.g. function gdemo(x, ::Type{T} = Vector{Float64}) where {T}.

Querying Probabilities from Model or Chain

Turing offers three functions: loglikelihood, logprior, and logjoint to query the log-likelihood, log-prior, and log-joint probabilities of a model, respectively.

Let’s look at a simple model called gdemo:

@model function gdemo0()
    s ~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s))
    return x ~ Normal(m, sqrt(s))
end
gdemo0 (generic function with 2 methods)

If we observe x to be 1.0, we can condition the model on this datum using the condition syntax:

model = gdemo0() | (x=1.0,)
DynamicPPL.Model{typeof(gdemo0), (), (), (), Tuple{}, Tuple{}, DynamicPPL.ConditionContext{@NamedTuple{x::Float64}, DynamicPPL.DefaultContext}}(Main.Notebook.gdemo0, NamedTuple(), NamedTuple(), ConditionContext((x = 1.0,), DynamicPPL.DefaultContext()))

Now, let’s compute the log-likelihood of the observation given specific values of the model parameters, s and m:

loglikelihood(model, (s=1.0, m=1.0))
-0.9189385332046728

We can easily verify that value in this case:

logpdf(Normal(1.0, 1.0), 1.0)
-0.9189385332046728

We can also compute the log-prior probability of the model for the same values of s and m:

logprior(model, (s=1.0, m=1.0))
-2.221713955868453
logpdf(InverseGamma(2, 3), 1.0) + logpdf(Normal(0, sqrt(1.0)), 1.0)
-2.221713955868453

Finally, we can compute the log-joint probability of the model parameters and data:

logjoint(model, (s=1.0, m=1.0))
-3.1406524890731258
logpdf(Normal(1.0, 1.0), 1.0) +
logpdf(InverseGamma(2, 3), 1.0) +
logpdf(Normal(0, sqrt(1.0)), 1.0)
-3.1406524890731258

Querying with Chains object is easy as well:

chn = sample(model, Prior(), 10)
Chains MCMC chain (10×3×1 Array{Float64, 3}):

Iterations        = 1:1:10
Number of chains  = 1
Samples per chain = 10
Wall duration     = 0.02 seconds
Compute duration  = 0.02 seconds
parameters        = s, m
internals         = lp

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

           s    1.6883    0.7003    0.2782     7.9110    10.0000    1.2129     ⋯
           m   -0.9443    1.3897    0.7151     4.0204    10.0000    2.0820     ⋯
                                                                1 column omitted

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

           s    0.6512    1.1889    1.7690    2.1385    2.7409
           m   -2.8803   -1.9442   -0.8739   -0.0270    1.1863
loglikelihood(model, chn)
10×1 Matrix{Float64}:
 -5.825119352463151
 -3.408804354821764
 -2.5544800419787332
 -3.2130448804614398
 -3.9925314593022296
 -1.3532925261853788
 -2.4613050577537825
 -1.1290983283967444
 -1.3871083331174752
 -1.6230948613196645

Maximum likelihood and maximum a posterior estimates

Turing also has functions for estimating the maximum aposteriori and maximum likelihood parameters of a model. This can be done with

mle_estimate = maximum_likelihood(model)
map_estimate = maximum_a_posteriori(model)
UndefVarError: `maximum_likelihood` not defined
Stacktrace:
 [1] top-level scope
   @ ~/work/docs/docs/tutorials/docs-12-using-turing-guide/index.qmd:424

For more details see the mode estimation page.

Beyond the Basics

Compositional Sampling Using Gibbs

Turing.jl provides a Gibbs interface to combine different samplers. For example, one can combine an HMC sampler with a PG sampler to run inference for different parameters in a single model as below.

@model function simple_choice(xs)
    p ~ Beta(2, 2)
    z ~ Bernoulli(p)
    for i in 1:length(xs)
        if z == 1
            xs[i] ~ Normal(0, 1)
        else
            xs[i] ~ Normal(2, 1)
        end
    end
end

simple_choice_f = simple_choice([1.5, 2.0, 0.3])

chn = sample(simple_choice_f, Gibbs(HMC(0.2, 3, :p), PG(20, :z)), 1000)
Chains MCMC chain (1000×3×1 Array{Float64, 3}):

Iterations        = 1:1:1000
Number of chains  = 1
Samples per chain = 1000
Wall duration     = 12.83 seconds
Compute duration  = 12.83 seconds
parameters        = p, z
internals         = lp

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e     Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

           p    0.4279    0.2003    0.0195   102.0092   135.8129    1.0052     ⋯
           z    0.1480    0.3553    0.0144   608.6477        NaN    1.0022     ⋯
                                                                1 column omitted

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

           p    0.0598    0.2742    0.4272    0.5817    0.8107
           z    0.0000    0.0000    0.0000    0.0000    1.0000

The Gibbs sampler can be used to specify unique automatic differentiation backends for different variable spaces. Please see the Automatic Differentiation article for more.

For more details of compositional sampling in Turing.jl, please check the corresponding paper.

Working with filldist and arraydist

Turing provides filldist(dist::Distribution, n::Int) and arraydist(dists::AbstractVector{<:Distribution}) as a simplified interface to construct product distributions, e.g., to model a set of variables that share the same structure but vary by group.

Constructing product distributions with filldist

The function filldist provides a general interface to construct product distributions over distributions of the same type and parameterisation. Note that, in contrast to the product distribution interface provided by Distributions.jl (Product), filldist supports product distributions over univariate or multivariate distributions.

Example usage:

@model function demo(x, g)
    k = length(unique(g))
    a ~ filldist(Exponential(), k) # = Product(fill(Exponential(), k))
    mu = a[g]
    return x .~ Normal.(mu)
end
demo (generic function with 2 methods)

Constructing product distributions with arraydist

The function arraydist provides a general interface to construct product distributions over distributions of varying type and parameterisation. Note that in contrast to the product distribution interface provided by Distributions.jl (Product), arraydist supports product distributions over univariate or multivariate distributions.

Example usage:

@model function demo(x, g)
    k = length(unique(g))
    a ~ arraydist([Exponential(i) for i in 1:k])
    mu = a[g]
    return x .~ Normal.(mu)
end
demo (generic function with 2 methods)

Working with MCMCChains.jl

Turing.jl wraps its samples using MCMCChains.Chain so that all the functions working for MCMCChains.Chain can be re-used in Turing.jl. Two typical functions are MCMCChains.describe and MCMCChains.plot, which can be used as follows for an obtained chain chn. For more information on MCMCChains, please see the GitHub repository.

describe(chn) # Lists statistics of the samples.
plot(chn) # Plots statistics of the samples.

There are numerous functions in addition to describe and plot in the MCMCChains package, such as those used in convergence diagnostics. For more information on the package, please see the GitHub repository.

Changing Default Settings

Some of Turing.jl’s default settings can be changed for better usage.

AD Chunk Size

ForwardDiff (Turing’s default AD backend) uses forward-mode chunk-wise AD. The chunk size can be set manually by AutoForwardDiff(;chunksize=new_chunk_size).

AD Backend

Turing supports four automatic differentiation (AD) packages in the back end during sampling. The default AD backend is ForwardDiff for forward-mode AD. Three reverse-mode AD backends are also supported, namely Tracker, Zygote and ReverseDiff. Zygote and ReverseDiff are supported optionally if explicitly loaded by the user with using Zygote or using ReverseDiff next to using Turing.

For more information on Turing’s automatic differentiation backend, please see the Automatic Differentiation article.

Progress Logging

Turing.jl uses ProgressLogging.jl to log the sampling progress. Progress logging is enabled as default but might slow down inference. It can be turned on or off by setting the keyword argument progress of sample to true or false. Moreover, you can enable or disable progress logging globally by calling setprogress!(true) or setprogress!(false), respectively.

Turing uses heuristics to select an appropriate visualization backend. If you use Jupyter notebooks, the default backend is ConsoleProgressMonitor.jl. In all other cases, progress logs are displayed with TerminalLoggers.jl. Alternatively, if you provide a custom visualization backend, Turing uses it instead of the default backend.

Back to top