MCMC sampling

Wren currently provides two very simple samplers.

Results are stored as FlexiChain{VarName}; please see the FlexiChains documentation for more information.

using Wren, Wren.Distsy = [28, 8, -3, 7, -1, 1, 18, 12]sigma = [15, 10, 16, 11, 9, 11, 10, 18]J = 8@wren function eight_schools(y, sigma, J)    mu ~ Normal(0, 5)    tau ~ HalfCauchy(0, 5)    theta ~ MvNormalScale(fill(mu, J), tau * I)    for i in 1:J        @observe y[i] ~ Normal(theta[i], sigma[i])    end    return (mu=mu, tau=tau)endmodel = eight_schools(y, sigma, J)
Model eight_schools
├─ arguments
│  ├─ y => [28, 8, -3, 7, -1, 1, 18, 12]
│  ├─ sigma => [15, 10, 16, 11, 9, 11, 10, 18]
│  └─ J => 8
├─ conditioned (none)
└─ expressions
     mu ~ Normal(0, 5)
     tau ~ HalfCauchy(0, 5)
     theta ~ MvNormalScale(fill(mu, J), tau * I)
     for i = 1:J
         @observe y[i] ~ Normal(theta[i], sigma[i])
     end
     return (mu = mu, tau = tau)

Prior

This simply creates a chain with samples from the prior.

Wren.prior — Function
prior(
    [rng::Random.AbstractRNG=default_rng()],
    model::Model,
    niters::Integer,
    nchains::Integer=1;
    progress::Bool=true,
    track=AllQuantities(),
) -> FlexiChains.VNChain

Sample from the prior distribution of a Wren model.

By default, all tracked quantities will be included in the returned chain. To include only one or a selection of tracked quantities, pass a Symbol or a tuple of Symbols; to include none, pass track=false or an empty tuple.

source
using Wrenprior(model, 1000, 4; progress=false)
╭─FlexiChain (1000 iterations, 4 chains) ──────────────────────────────────────╮
│ ↓ iter  = 1:1000                                                             │
│ → chain = 1:4                                                                │
│                                                                              │
│ Parameters (3) ── VarName                                                    │
│  Float64          mu, tau                                                    │
│  Vector{Float64}  theta (8,)                                                 │
│                                                                              │
│ Extras (4)                                                                   │
│  @NamedTuple{mu::Float64, tau::Float64}  return_value                        │
│  Float64                                 logprior, loglikelihood, logjoint   │
╰──────────────────────────────────────────────────────────────────────────────╯

NUTS

Wren.nuts — Function
nuts(
    [rng::Random.AbstractRNG=default_rng()],
    model::Model,
    niters::Integer,
    nchains::Integer=1;
    adtype::DI.AbstractADType=DI.AutoEnzyme(; mode=Enzyme.Reverse),
    progress::Bool=true,
    reduce_copies::Bool=true,
    track=AllQuantities(),
    init=nothing,
    initial_stepsize::Union{Nothing,Real}=nothing,
    dynamichmc_kwargs...
) -> FlexiChains.VNChain

No U-Turn Sampler (NUTS) for a Wren model. All dynamichmc_kwargs are passed to DynamicHMC.mcmc_with_warmup, allowing you to customise the warmup and sampling behaviour.

Each chain starts from an independent prior draw by default. Use init to select an AbstractInitialization policy. Anything else passed as init, such as a VarNamedTuple or a latent source, is treated as FindFiniteDensity(init). initial_stepsize replaces the default initial step-size search.

reduce_copies is passed to VecModel: when sampling with Enzyme, it skips copies of model arguments that turn out not to be needed (see reduce_copies).

By default, all tracked quantities will be included in the returned chain. To include only one or a selection of tracked quantities, pass a Symbol or a tuple of Symbols; to include none, pass track=false or an empty tuple. Note that tracked quantities are not evaluated during the log-density step, but only once per iteration.

source
using Enzymeadtype = AutoEnzyme(; mode=Reverse)using Wrennuts(model, 1000, 4; adtype=adtype, progress=false)
╭─FlexiChain (1000 iterations, 4 chains) ──────────────────────────────────────╮
│ ↓ iter  = 1:1000                                                             │
│ → chain = 1:4                                                                │
│                                                                              │
│ Parameters (3) ── VarName                                                    │
│  Float64          mu, tau                                                    │
│  Vector{Float64}  theta (8,)                                                 │
│                                                                              │
│ Extras (10)                                                                  │
│  Float64                                 step_size, acceptance_rate          │
│                                          log_density, logprior               │
│                                          loglikelihood, logjoint             │
│  Int64                                   tree_depth                          │
│  Bool                                    is_divergent, is_max_depth          │
│  @NamedTuple{mu::Float64, tau::Float64}  return_value                        │
╰──────────────────────────────────────────────────────────────────────────────╯

Initialisation

The nuts function accepts an optional init argument, which controls how the initial parameter values for the MCMC chains are controlled.

init should be a subtype of AbstractInitialization. Currently, Wren only provides a single FindFiniteDensity, which attempts to find a point with finite probability density.

However, you can specify how that point is searched for by passing an AbstractLatentSource to the FindFiniteDensity constructor. As a shorthand, you can also pass a latent source (or a VarNamedTuple of values) directly as init; this is treated as FindFiniteDensity(init). For example, to replicate Stan's default behaviour of sampling from [-2, 2] in unconstrained space, you can pass:

init = FindFiniteDensity(FromUnconstrainedInterval(-2, 2))nuts(model, 1000, 4; adtype, init, progress=false)

In the future, we hope to provide more initialisation strategies (e.g. using Pathfinder).

Separate initialisation for different chains

Currently, the same initialisation strategy is used for all chains. This does not necessarily mean that all chains will start at the same point; it just means that the way the starting point is searched for is the same. For example, the four starting points may all be drawn from the prior, but that does not mean that they will all be the same point.

In the (near) future the API will be generalised to also accept a vector of initialisation strategies, one for each chain.

WrenCore.AbstractInitialization — Type
AbstractInitialization

An abstract type for ways to initialise MCMC samplers and optimisers.

Currently, only FindFiniteDensity is provided.

For convenience, other objects may be implicitly converted by Wren into an AbstractInitialization.

Specifically, AbstractLatentSources, or things that can be converted to them (such as Random.AbstractRNG or VarNamedTuple), are wrapped in FindFiniteDensity. The max_attempts keyword argument depends on what is passed in.

For sets of initial values without fallbacks, we use max_attempts=1 since it doesn't make sense to try the same parameters multiple times. For other sources, we use max_attempts=100 by default.

source
WrenCore.FindFiniteDensity — Type
FindFiniteDensity(source; max_attempts::Union{Nothing,Integer}=nothing)

Initialise a chain (or an optimisation) by drawing from source until its unconstrained coordinates and log-density are finite, trying at most max_attempts candidates per chain.

source can either be a WrenCore.AbstractLatentSource, or something that can be converted to it. In particular:

  • source::Random.AbstractRNG is shorthand for FromPrior(source), i.e., draw from the prior with the given RNG.
  • source::VarNamedTuple is shorthand for FromValues(source), i.e., use the given values (in model space) as the initial point.

To use Stan-style initialisation from a uniform interval, use source=FromUnconstrainedInterval([rng, ]lower, upper).

If max_attempts is not given, it is 1 for fixed values without a random fallback (since trying the same parameters again won't help), and 100 for other sources.

If initialisation fails after max_attempts, an error is thrown.

source