API reference

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
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
WrenCore.ADTestResult — Type
ADTestResult

The correctness results returned by test_ad.

  • vecmodel::VecModel: The vectorised model that was tested. The parameters used are in vecmodel.sample.

  • lp_expected::Any: The expected log-density value, or nothing if it was not checked.

  • grad_expected::Any: The expected gradient of the log-density, or nothing if it was not checked.

  • lp_actual::Any: The actual log-density value returned by the AD backend.

  • grad_actual::Any: The actual gradient of the log-density returned by the AD backend.

  • atol::Real: The absolute tolerance used for correctness checking.

  • rtol::Real: The relative tolerance used for correctness checking.

source
WrenCore.AbstractAccumulator — Type
AbstractAccumulator

An abstract type for accumulators.

An accumulator is an object that may change its value at every tilde_assume!! or tilde_observe!! call based on the random variable in question. The obvious examples of accumulators are the log prior and log likelihood. Other examples might be a variable that counts the number of observations in a trace, or a list of the names of random variables seen so far.

An accumulator type T <: AbstractAccumulator must implement the following methods:

  • accumulator_name(acc::T) or accumulator_name(::Type{T})
  • accumulate_observe!!(acc::T, val, vn, dist, template, ::Val{sitename})
  • accumulate_assume!!(acc::T, val, tval, vn, dist, logjac, template, ::Val{sitename})
  • reset(acc::T)
  • Base.copy(acc::T)
  • combine_from_scope(parent::T, child::T, vn, template), if the accumulator is to be used in models that contain submodels

In these functions:

  • val is the new value of the random variable supplied by a latent source (always in the distribution's original space), or the value on the left-hand side of an observe statement.
  • tval is the TransformedValue produced by interpreting the value supplied by the latent source in the selected parameter space.
  • dist is the distribution on the RHS of the tilde statement.
  • logjac is the forward log absolute determinant of the Jacobian for the transform from the distribution's original space to the representation selected by the parameter space.
  • vn is the VarName that is on the left-hand side of the tilde-statement. If the tilde-statement is a literal observation like 0.0 ~ Normal(), then vn is nothing.
  • template is a value that conveys the shape of the top-level symbol in vn, and is used specifically for accumulators that carry VarNamedTuples.
  • sitename is a compile-time Val{::Symbol} identifying the sampling site in the model source code. It defaults to the left-hand side and can be overridden with name=:site. Site names need not be unique; use vn to distinguish parameters that share a name.

See the documentation for each of these functions for more details.

source
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.AbstractLatentSource — Type
AbstractLatentSource

An abstract type representing somewhere from which the values of latent variables can be obtained.

Wren provides several subtypes of AbstractLatentSource:

  • FromPrior: samples latent variables from their prior distributions
  • FromValues: provides latent variables in a VarNamedTuple
  • FromUnconstrainedInterval: samples latent variables uniformly from an interval in unconstrained space
  • FromVector: provides a vector of flattened latent variables, together with information about how to convert them back into the original space

Custom subtypes of this can be created to customise model execution. To be a valid AbstractLatentSource, a type must implement

  • get_latent(source, vn, dist) to obtain a latent variable from the source, and
  • scope to obtain a latent source that applies only to a subset of variables. This is used in submodel evaluation: if a model contains a ~ submodel(), then the latent source used to evaluate submodel is obtained by calling scope(source, @vn(a)).
source
WrenCore.AbstractParameterSpace — Type
AbstractParameterSpace

The coordinate space in which latent parameters and their density are represented.

An AbstractParameterSpace can be thought of as a collection of AbstractTransforms, one for each latent variable in a model. However, while AbstractTransforms represent information that has already been decided (i.e., it is irrevocably tied to the value stored in a TransformedValue), an AbstractParameterSpace more resembles an upfront specification of how one wants to evaluate a model.

When evaluating a model with a given AbstractParameterSpace, the model's latent variables will be transformed into the representation that it specifies (using target_transform). The log-Jacobian that is accumulated, and hence the log-density, will be with respect to the coordinate space specified by the AbstractParameterSpace.

There are two built-in AbstractParameterSpaces:

  • UnconstrainedSpace: all latent variables are represented in unconstrained, vectorised space. This is the default for Wren's vectorised models, particularly because this is most suitable for gradient-based inference methods and automatic differentiation.

  • OriginalSpace: all latent variables are represented in their original space.

source
WrenCore.AbstractTransform — Type
AbstractTransform

A specification of how to transform a variable's value back into its original space. Note that this might not necessarily contain the actual transformation function: in particular, AsUnconstrainedVec and AsVec are just markers that indicate that the transform function should be derived from the distribution.

Wren provides a few built-in transform types; it is unlikely that you will need to define your own (if you do, please get in touch and let us know!)

source
WrenCore.AccumulatorTuple — Type
AccumulatorTuple{N,T<:NamedTuple}

A collection of accumulators, stored as a NamedTuple of length N

This is defined as a separate type to be able to dispatch on it cleanly and without method ambiguities or conflicts with other NamedTuple types. We also use this type to enforce the constraint that the name in the tuple for each accumulator acc must be accumulator_name(acc), and these names must be unique.

The constructor can be called with a tuple or a VarArgs of AbstractAccumulators. The names will be generated automatically. One can also call the constructor with a NamedTuple but the names in the argument will be discarded in favour of the generated ones.

source
WrenCore.AsOriginal — Type
AsOriginal <: AbstractTransform

Indicates a value that is already in its original space. No transformation is necessary.

source
WrenCore.AsUnconstrainedVec — Type
AsUnconstrainedVec <: AbstractTransform

Indicate that a value is an unconstrained, vectorised value. The appropriate transformation function is Plaice.from_unconstrained_vec(dist), where dist is the prior distribution of the variable.

source
WrenCore.AsVec — Type
AsVec <: AbstractTransform

Indicate that a value is a vectorised value. The appropriate transformation function is Plaice.from_vec(dist), where dist is the prior distribution of the variable.

source
WrenCore.BenchmarkResult — Type
BenchmarkResult

The benchmark results returned by benchmark_model and @bmodel. Each benchmark is the fastest Chairmarks.Sample for the function it is named after.

  • vecmodel::VecModel: The vectorised model that was benchmarked. The parameters used are in vecmodel.sample.

  • parameters_bench::Union{Nothing, Chairmarks.Sample}: Benchmark for drawing a sample from the model with parameters, or nothing if extras=false.

  • logjoint_bench::Union{Nothing, Chairmarks.Sample}: Benchmark for evaluating the log-joint density with logjoint, or nothing if extras=false.

  • lp_bench::Chairmarks.Sample: Benchmark for evaluating the vectorised log-density with lp.

  • lp_and_grad_bench::Union{Nothing, Chairmarks.Sample}: Benchmark for lp_and_grad, or nothing if no AD backend was given.

source
WrenCore.CollectOrDiscardSubmodelParams — Type
CollectOrDiscardSubmodelParams

Internal types used to denote whether the parameters of a submodel should be collected as a top-level variable in the parent model. For example, in

@wren function f()    retval = x ~ submodel    y ~ x[@vn(a)]end

we need x to contain a VarNamedTuple of the submodel's parameters, otherwise the next line will fail. However, if x is never used again in the model body, then we can avoid collecting the submodel's parameters. This makes performance better in hot paths that don't use ParamsAccumulator, such as VecModel (and probably also improves type stability).

source
WrenCore.EvalContext — Type
EvalContext{Enzyme}

Information about how a model is being evaluated. It is passed to the model's evaluation function, and from there on to any submodels, so that they are evaluated in the same way.

EnzymeCopies is a Bool that says whether we are running under Enzyme AD. In such a case, the arguments in the model's enzyme_copy_argnames should be copied on evaluation (see _maybe_dealias).

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
WrenCore.FromPrior — Type
FromPrior([rng::AbstractRNG=Random.default_rng()]) <: AbstractLatentSource

Sample latent values from their prior distributions, optionally with a given random number generator.

source
WrenCore.FromUnconstrainedInterval — Type
FromUnconstrainedInterval(
    [rng::AbstractRNG=Random.default_rng()],
    [lower::Real=-2.0, upper::Real=2.0]
) <: AbstractLatentSource

Generate latent values by first transforming the prior distribution of each variable to unconstrained space, and then sampling each element of the unconstrained vector uniformly from the interval [lower, upper].

If lower and upper are not given, they default to -2 and 2, which mimics Stan's default initialisation strategy (see the Stan reference manual page on initialisation for more details).

Requires that lower <= upper.

source
WrenCore.FromValues — Type
FromValues(
    values::VarNamedTuple,
    fallback::AbstractLatentSource=Void()
) <: AbstractLatentSource

Take latent values from the given VarNamedTuple. If the VarNamedTuple does not contain a value for a variable, then the fallback source is used. The default fallback, Void(), throws an error.

source
WrenCore.FromVector — Type
FromVector(
    params::AbstractVector,
    vecinfo::VecInfo
) <: AbstractLatentSource

Provide latent values from a vector of flattened parameters, together with a VecInfo that provides information on how to recover the values in their original space.

source
WrenCore.Indexed — Type
Indexed{D,N,T}

Marker struct to indicate that the argument is an object indexed by the batch loop index.

D is the dimension that contains the loop index, and N is the number of indices that was passed to the indexing expression.

source
WrenCore.LogJacobianAccumulator — Type
LogJacobianAccumulator{T<:Number} <: LogProbAccumulator{T}

An accumulator that tracks the cumulative forward log absolute determinant of the Jacobian from the distribution's original space to the representation selected by the parameter space.

Note

With OriginalSpace, the log-Jacobian is zero. With UnconstrainedSpace, it is the forward log-Jacobian from original space to unconstrained vector space.

In general, for the forward Jacobian $\mathbf{J}$ corresponding to the function $\mathbf{y} = f(\mathbf{x})$,

\[\log(q(\mathbf{y})) = \log(p(\mathbf{x})) - \log (|\mathbf{J}|)\]

and correspondingly:

logjoint_transformed(accs) = logjoint(accs) - logjac(accs)

Fields

  • logjac::Number: the forward log absolute determinant of the selected transform Jacobian
source
WrenCore.LogPriorAccumulator — Type
LogPriorAccumulator{T<:Number} <: LogProbAccumulator{T}

An accumulator that tracks the cumulative log prior during model execution.

The log prior is always calculated from the raw value in the distribution's original space, so it is independent of the parameter space.

Fields

  • logp::Number: the scalar log prior value
source
WrenCore.LogProbAccumulator — Type
LogProbAccumulator{T} <: AbstractAccumulator

An abstract type for accumulators that hold a single scalar log probability value.

Every subtype of LogProbAccumulator must implement

  • A method for logp that returns the scalar log probability value that defines it.
  • A single-argument constructor that takes a logp value.
  • accumulator_name, accumulate_assume!!, and accumulate_observe!! methods like any other accumulator.

LogProbAccumulator provides implementations for other common functions, like convenience constructors, copy, show, ==, isequal, hash, reset, and combine_from_scope.

This type has no great conceptual significance, it just reduces code duplication between types like LogPriorAccumulator, LogJacobianAccumulator, and LogLikelihoodAccumulator.

source
WrenCore.LogProbType — Type
LogProbType

The default type used for log-probabilities in Wren.jl. This is a compile-time constant that can be set via set_logprob_type!, which under the hood uses Preferences.jl.

Note that this does not prevent computations within the model from promoting the log-probability to a different type. In essence, LogProbType specifies the lowest possible type that log-probabilities can be, and Wren promises to not insert any extra operations that would cause this to be promoted to a higher type. However, Wren cannot guard against user code inside models.

For example, in:

@wren f() = x ~ Normal(0.0, 1.0)

the log-probability of the model will always be promoted to Float64, regardless of the value of LogProbType, because the logpdf of Normal(0.0, 1.0) is a Float64. On the other hand, in:

@wren f() = x ~ Normal(0.0f0, 1.0f0)

the log-probability of the model will be Float32 if LogProbType is Float32 or lower.

source
WrenCore.Model — Type
WrenCore.Model

A Wren model.

  • name::Symbol: Name of the function declared with @wren

  • args::NamedTuple: Positional and keyword arguments passed to the model.

  • stmts::Vector{Union{LineNumberNode, WrenCore.Expressions.AbstractWrenExpr}}: The model's AST, stored as Wren's probabilistic IR

  • mod::Module: Module that the model was defined in. Required to make RGF resolve globals / functions defined in that module.

  • conditioned::NamedTuple: The set of variables that the model is conditioned on.

  • evaluation_fn::Any: The cached evaluation function.

  • enzyme_copy_argnames::Val: The names of the arguments which are copied on every evaluation when differentiating with Enzyme. This must be a Val of a tuple of symbols (preferably sorted to deduplicate compilation).

    Whether they are actually copied is decided by the [EvalContext](@ref) that the model is
    evaluated with. That struct allows us to differentiate code being run with Enzyme (where
    the copy is needed) from other code (where the copy is not needed).
source
WrenCore.NoLogProb — Type
NoLogProb <: Real

Singleton type that represents the absence of a log probability value. This is used as the default type parameter for LogProbAccumulator when no log probability value is needed, to avoid defining a concrete type such as Float64 that would cause unwanted type promotion when accumulating log probabilities of other types (e.g., Float32).

Adding anything to NoLogProb() returns the other thing. In other words, NoLogProb is a true additive identity which additionally preserves types.

source
WrenCore.PointEstimate — Type
PointEstimate

The result of optimize, MAP, or MLE.

Fields

  • lp_function: the objective that was maximised, e.g. logjoint for MAP or loglikelihood for MLE.

  • parameters: a VarNamedTuple of the fitted parameters, in model space (i.e. not in unconstrained coordinates, even though the optimisation itself is carried out in unconstrained coordinates). To access this we recommend using parameters(::PointEstimate) rather than accessing the field, but both are equivalent.

  • lp: the value of lp_function at parameters. This is the actual log-density, not the negated value that the solver minimises.

  • vecmodel: the VecModel used to evaluate the objective. It should hold that p.lp ≈ lp(p.vecmodel, p.solution.u) for a p::PointEstimate.

  • solution: the solution object returned by Optimization.solve. Check p.solution.retcode to see whether the solver converged.

source
WrenCore.SitenameCountAccumulator — Type
SitenameCountAccumulator

Accumulator that identifies sampling sites hit exactly once during model evaluation.

After evaluating a model, the entries field should contain a mapping of (maybe-prefixed) sitenames to (maybe-prefixed) VarNames.

For example, take the model

@wren function model(x)    @sample name=:sna a ~ Normal()    for i in eachindex(x)        @sample name=:snxi x[i] ~ Normal()    endend

Here, the sna site is only hit once during model evaluation, but snx is hit more than once (as long as x has length 2 or more). Thus, after evaluating the model with a SitenameCountAccumulator, it should contain the mappings @vn(sna) => @vn(a) and @vn(snx) => SeenMultipleTimes().

On the first hit of a sitename, its VarName is stored in a VarNamedTuple under the key VarName{sitename}(). On any subsequent hit, the entry is replaced with SeenMultipleTimes so it is never re-added.

Submodel handling

In the following example:

@wren function inner()    @sample name=:sna a ~ Normal()end@wren function outer()    @sample name=:snx x ~ inner()end

After evaluating outer(), the entries field of the SitenameCountAccumulator should contain a mapping of @vn(x.sna) => @vn(x.a). Note: the prefixed sitename is prefixed with the parent VarName, not the parent sitename (snx). The rationale for this is explained in VecInfo.

source
WrenCore.TransformedValue — Type
TransformedValue(value, transform::AbstractTransform)

A transformed value together with a description of its current representation. The stored transform describes how to recover the untransformed value (in its original space).

source
WrenCore.UnconstrainedSpace — Type
UnconstrainedSpace <: AbstractParameterSpace

Evaluate the model in a space where all latent variables are represented as unconstrained vectors.

source
WrenCore.VNTAccumulator — Type
VNTAccumulator{AccName}(f::F, values::VarNamedTuple=VarNamedTuple()) where {AccName,F}
VNTAccumulator{AccName,KeepEmptySubmodels}(f::F, values::VarNamedTuple=VarNamedTuple())

A generic accumulator that applies a function f to values seen during model execution and stores the results in a VarNamedTuple.

AccName is the name of the accumulator, and is exposed to allow users to define and use multiple forms of VNTAccumulator within the same set of accumulators. In theory, each VNTAccumulator with the same function f should use the same accumulator name. This is not enforced.

KeepEmptySubmodels controls what combine_from_scope does with a submodel that accumulated nothing (i.e., a key @vn(a) => VarNamedTuple() in the parent accumulator). When false (the default), the empty VNT is dropped from the parent, meaning that @vn(a) will not even be a key in the parent. When true the empty VNT is retained. In the absence of submodels, this option has no effect.

The function f should have the signature:

f(val, tval, vn, dist, logjac) -> value_to_store

where the arguments have their usual meanings in accumulate_assume!!. If a value does not need to be accumulated, this can be signalled by returning DoNotAccumulate() from f.

If f is a struct (and not a function), you also need to define Base.copy on f.

source
WrenCore.VecInfo — Type
VecInfo

All the information needed to derive a vectorised form of a model.

The fundamental information that we need to do this is a mapping from VarNames, on the left-hand side of tilde-statements, to RangeAndTransforms that describe:

  • which slice of the vectorised parameters correspond to that variable, and
  • how to transform that slice into the original space of the variable.

The naive way to store this information is in a direct key-value map, i.e., a VarNamedTuple mapping (lhs VarName) => RangeAndTransform. Then, when we encounter a vn ~ dist statement during model evaluation, we can look up the RangeAndTransform for vn.

However, this can become very slow for VarNames that contain large integer vectors, e.g., x[1:100000], due to PartialArray and ArrayLikeBlock checks. This motivates a fast path which relies on a mapping from sitename => Pair(cache_key, RangeAndTransform). The idea behind this is that sitenames often have a one-to-one correspondence with lhs VarNames, and thus we can collect this mapping one time during VecModel construction, and then reuse it during the hot path of model evaluation.

Sitenames that are encountered more than once during model evaluation are not stored in this mapping (technically, their values are stored as SeenMultipleTimes; this could in theory be removed). Lookups for those sampling sites will thus fall back to the slower VarNamedTuple lookup.

The cache_key is an additional piece of information that allows us to handle cases where the sitename is constant, but the lhs VarName is not. See, e.g. https://github.com/JuliaBayes/Wren.jl/issues/155 for an example of this. In order to hit the fast path, two things must be true:

  • the sitename must only be encountered once during model evaluation (otherwise it will be stored as SeenMultipleTimes and the fast path will be disabled);

  • the lhs VarName must be hashed into a cache_key that is equal to the cached key stored in the mapping.

Submodel handling

The first VNT handles VarNames exactly as they appear in the lhs of tilde-statements. Note that sitenames of submodels are prefixed by the VarName of the submodel site, rather than the sitename of the submodel site. For example, if we have

@wren function inner()    @sample name=:norm x ~ Normal()end@wren function outer()    @sample name=:myinner a ~ inner()end

then the first VNT stores @vn(a.x) => RangeAndTransform(...), and the second VNT stores @vn(a.norm) => (@vn(x) => RangeAndTransform(...)), not @vn(myinner.norm). The cached name is local to the submodel, so it can be compared without its prefix during evaluation. This design allows us to:

  • avoid passing the submodel site name into functions such as scope, which would pollute the signature with something that is only relevant for Wren (i.e., making it harder to use submodels from other sources), and

  • handle cases where a submodel contains a slow variable (e.g. x[1:10000]) but is sampled in a loop. For example

    @wren function inner()    x = zeros(N)    x[1:N] ~ distend@wren function outer()    a = Vector{Any}(undef, M)    for i in 1:M        a[i] ~ inner()    endend

    Prefixing with the submodel site would cause all the submodels' x variables to have the same prefixed sampling site, whereas prefixing with the VarName allows each submodel's x to have a different entry.

The main inner constructor takes a VarNamedTuple and a SitenameCountAccumulator. This guarantees that the two maps are consistent.

source
WrenCore.VecModel — Type
VecModel(
    model::Model,
    adtype::Union{ADTypes.AbstractADType,Nothing};
    lp_function=logjoint_transformed,
    latent_source=FromPrior(),
    parameter_space=UnconstrainedSpace(),
    reduce_copies=true,
)

A vectorised form of model, which is designed to take a single vector of parameters as input, and returns a scalar log-density.

Overview

This is accomplished by storing the original model, together with a set of ranges and transforms which map segments of the parameter vector to the latent variables' values in original space. For example, consider

@wren function my_model()    x ~ Normal()    y ~ Normal()end

The mapping from params, a vector of length 2 to the latent variables takes the form:

x_info = mapping[@vn(x)] # This is a `RangeAndTransform` object.x = x_info.transform(params[x_info.range])y_info = mapping[@vn(y)]y = y_info.transform(params[y_info.range])

where x_info.range might be 1:1 and y_info.range might be 2:2.

In order for this to work reliably, the model must have a fixed set of latent variables and fixed dimension. If these conditions are not adhered to, it is very likely that results obtained will be meaningless. Models with varying parameter order can be safely vectorised since the mapping is invariant to the order in which the latent variables are encountered.

Positional arguments

  • model::Model: The model to vectorise.

  • adtype::Union{ADTypes.AbstractADType,Nothing}: The automatic differentiation backend to use for gradient calculations. You can pass nothing to construct a log-density-only model that is not capable of computing gradients.

    In Wren, we recommend using reverse-mode Enzyme as the default backend as that offers the most performance. This can be specified with AutoEnzyme(; mode=Reverse) (these identifiers are re-exported by Wren).

    However, in some cases you may find that Enzyme errors. In such a case, please do open an issue: we want to help fix this! In such cases you can use a different AD backend. Wren is backed by DifferentiationInterface.jl so you can plug in any AbstractADType.

Keyword arguments

  • latent_source::AbstractLatentSource: when preparing a VecModel, Wren requires information about the model's latent variables in order to construct the mapping from vector to latent variables. This is obtained by running the model once with an AbstractLatentSource, which you can pass here. If you want to control the RNG with which these parameters are drawn, you can use FromPrior(rng). If you have a VarNamedTuple of values, wrap it in FromValues.

    If you have already run the model once, you can avoid reevaluation entirely by calling the positional constructor with a VecInfo and a parameter vector. This is mostly intended for advanced usage, please see the Wren source code for examples of how to do this.

  • lp_function: When the model is evaluated, it will return a set of accumulators, which must then be collapsed into a single scalar log-density. This function is responsible for that (i.e., it must have the signature f(accs::AccumulatorTuple) -> Number). The default is logjoint_transformed, which evaluates the log joint density in transformed space. This is virtually always what you want, but you can also use logprior, loglikelihood, or logjoint, or write your own.

  • parameter_space::AbstractParameterSpace: The parameter space in which the vectorised model is defined. The default is UnconstrainedSpace, which is almost always what you want (again this is mostly for compatibility with gradient-based inference algorithms).

  • reduce_copies::Bool: When differentiating with Enzyme, Wren copies some of the model's arguments on every evaluation (see the docs). If this is true, reduce_copies is first called on the model to find out which of these copies can be skipped. This has no effect for other AD backends, which never make the copies. The default is true.

    In very pathological cases, reduce_copies may skip a copy that is actually needed (e.g. when there is parameter-dependent control flow which (1) in turn causes a change in Enzyme's behaviour, and (2) is not caught by the random testing in reduce_copies). This is very unlikely, but if you are concerned about this, you can disable this option.

source
WrenCore.VecSampleAccumulator — Type
VecSampleAccumulator

An accumulator that holds a full AbstractVector, the eventual result of vector_parameters(vecmodel) or similar. This is filled in chunk-by-chunk during model evaluation.

source
WrenCore.Void — Type
Void

A latent source that provides no values (it errors when asked for any).

source
WrenCore.WithBackend — Type
WithBackend(adtype=AutoForwardDiff())

Check correctness against the log density and gradient produced by another AD backend.

source
WrenCore.WithExpectedResult — Type
WithExpectedResult(lp, grad)

Check correctness against a known log density and gradient. Either can be left as nothing to skip testing.

source
WrenCore._VecModelLP — Type
_VecModelLP

Callable struct that is used for AD backends that require a closure (i.e. compiled ReverseDiff). This is equivalent to _vecmodel_lp but with the inactive arguments stored in the struct.

source
Base.copy — Function
Base.copy(acc::AbstractAccumulator)

Create a new accumulator that is a copy of acc, without aliasing (i.e., this should behave conceptually like a deepcopy).

source
StatsAPI.loglikelihood — Method
loglikelihood(model::Model, latents)

Return the log-likelihood of model evaluated at the given latent values.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
VarNames.parameters — Method
parameters(model::Model)::VarNamedTuple
parameters(model::Model, latents)::VarNamedTuple

Obtain the model's parameters in original space, calculated with a given set of latent values. If no latent values are provided, they are drawn from the prior distribution.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

This is equivalent to parameters(simulate(model)), but is more efficient than simulate because it does not compute the log-density terms.

source
VarNames.parameters — Method
VarNames.parameters(vecmodel::VecModel, params::AbstractVector)::VarNamedTuple

Return the model-space parameters of vecmodel at params.

source
WrenCore.MAP — Method
MAP(model, solver; kwargs...)

Find the original-space maximum a posteriori estimate of a model.

All arguments are forwarded to optimize but with the objective function set to logjoint. Please see its documentation for details.

source
WrenCore.MLE — Method
MLE(model, solver; kwargs...)

Find the original-space maximum likelihood estimate of a model.

All arguments are forwarded to optimize but with the objective function set to logjoint. Please see its documentation for details.

source
WrenCore.ParamsAccumulator — Method
ParamsAccumulator() <: AbstractAccumulator

An accumulator that keeps tracks of the model parameters exactly as they are seen in the model.

source
WrenCore.VectorisedParamsAccumulator — Method
VectorisedParamsAccumulator()

An accumulator that collects parameter values as TransformedValue{<:AbstractVector} objects.

Values already represented as vectors are stored unchanged. Values represented by AsOriginal are vectorised using Plaice.from_vec and stored as AsVec. Thus, the stored transform agrees with the selected parameter space while every stored value has a uniform vector representation.

source
WrenCore._copied_args — Method
_copied_args(::Model)

Get the set of argument names that are marked for copying. NOTE: This is for internal use only. Be careful interpreting the results of this function! For example, even if _copied_args(model) returns a nonempty set, this does not mean that the model's arguments are actually copied. Outside of Enzyme contexts (i.e., in normal evaluation like parameters(model), the copies are always disabled. This includes AD with non-Enzyme backends. And with Enzyme, it's very possible that reduce_copies will prune this set of arguments down.

source
WrenCore._copy_for_thread — Method
_copy_for_thread(model::Model)

Return the same model with its own copies of the arguments and conditioned values, so that evaluations on different threads cannot write into each other's data. Outside Enzyme, evaluation does not copy arguments (see _maybe_dealias). Models passed as arguments are copied too. This reuses the evaluation function, so no new code is generated.

source
WrenCore._dealias — Method
_dealias

Create a copy of a model argument that has the same contents, but avoids aliasing the user's data.

This is called on model construction, as well as on model evaluation (unless the argument has been proven or annotated to not require copying). See the docs for why this matters.

source
WrenCore._eval_context — Method
_eval_context(adtype)

The EvalContext that a VecModel with the given AD backend should evaluate its model with. Only Enzyme needs model arguments to be copied on evaluation (see the docs); other AD backends can track gradients through writes into model arguments, so the copies can be skipped.

source
WrenCore._maybe_dealias — Method
_maybe_dealias(::EvalContext, ::Val{S}, ::Val{name}, v)

Return _dealias(v) if the following all hold true:

  • EvalContext tells us that we are running under Enzyme AD, which is the only situation where copies need to be made for correctness;
  • name is in S, the set of argument names which must be copied (S can be pruned either through Wren's dataflow analysis, or by reduce_copies); and
  • v is a type that needs copying (see _needs_copy).

Otherwise, returns v.

The decision only depends on types, so should be resolvable at compile-time.

Apparently, making this a generated function means that it's impossible for e.g. extensions to overload _needs_copy, as the generated function only has access to the methods of _needs_copy that were present at the compilation world age.

source
WrenCore._needs_copy — Method
_needs_copy(::Type{T})

Whether a model argument of type T needs to be copied on every evaluation, assuming that the dataflow analysis (or the user) has not ruled it out. The only reason for these copies is to stop differentiable data being written into the model's arguments (see _dealias), so types that can't hold differentiable data, or that _dealias returns unchanged anyway, are never copied.

Note that this is separate from the copy made when the model is constructed, which protects the user's data and always uses _dealias.

source
WrenCore._with_copied_args — Method
_with_copied_args(model::Model, copy_argnames)

Return the same model, but with copy_argnames (an iterable of symbols) as its enzyme_copy_argnames. This reuses the evaluation function, so no new code is generated. The names are sorted so that the same set of arguments always gives the same type (as in the @wren macro).

source
WrenCore.accumulator_name — Method
accumulator_name(acc::AbstractAccumulator)

Return a Symbol which can be used as a name for acc.

The name has to be unique in the sense that an AccumulatorTuple can only have one accumulator for each name. The most typical case, and the default implementation, is that the name only depends on the type of acc, not on its value.

source
WrenCore.apply_parameter_space — Method
apply_parameter_space(
    parameter_space::AbstractParameterSpace,
    tval::TransformedValue,
    vn::VarName,
    dist,
)

Convert a latent value into the representation specified by parameter_space.

Given a parameter_space which says how a latent variable should be represented, and a TransformedValue which contains a value and its current representation (derived from the AbstractLatentSource), returns a tuple of:

  • the value in original model space,
  • the value in the target representation (a TransformedValue), and
  • the forward log absolute determinant of the Jacobian from original space to the target representation.

Note that when evaluating a model, even if the values are already supplied in unconstrained space and the target representation is also unconstrained, we still have to perform the inverse transform to original space for two reasons:

  • Calculation of the log-Jacobian.
  • The left-hand side of the tilde-statement contains a variable, and we must assign the value in original space to that variable.
source
WrenCore.benchmark_model — Function
benchmark_model(
    model::Model,
    adtype::Union{Nothing,DI.AbstractADType}=nothing;
    lp_function=logjoint_transformed,
    latent_source::AbstractLatentSource=FromPrior(Xoshiro(468)),
    parameter_space::AbstractParameterSpace=UnconstrainedSpace(),
    seconds::Real=1,
    extras::Bool=false,
) -> BenchmarkResult

Benchmark a model. By default this benchmarks:

  • lp (log-density of the vectorised model), and
  • if adtype is given, lp_and_grad (log-density and its gradient).

If extras=true, it also benchmarks parameters (sampling from the prior) and logjoint (log-joint density evaluation without vectorisation).

Note that if adtype is given, the corresponding backend package must be loaded first.

The lp_function, latent_source, and parameter_space keywords are forwarded to VecModel. lp_function and parameter_space have the same defaults as for VecModel. latent_source instead defaults to drawing from the prior with a fixed seed, so that every call benchmarks at the same parameters. (The time taken can depend on the parameter values, so random parameters make results vary between calls.)

seconds is the approximate time spent on each of the benchmarks.

See also @bmodel.

source
WrenCore.combine_from_scope — Function
combine_from_scope(parent, child, vn, template)

Embed the contents of child beneath vn, then combine it with parent.

This is the counterpart of scope: scope narrows the accumulators before a submodel is evaluated, and combine_from_scope merges the submodel's results back into the parent model's accumulators.

source
WrenCore.condition — Method
condition(model::Model, values::NamedTuple)::Model

Condition model on the values in values, returning a new model. The original model is not modified. Each key conditions a whole variable, including every indexed or field tilde-statement on that variable. Partial conditioning is not supported.

For a submodel, the value under its namespace is a NamedTuple of the child's conditioned variables, for example model | (child=(y=data,),). Values replace existing keys as in merge(::NamedTuple, ::NamedTuple), including a nested submodel namespace. Nested values are not merged recursively.

source
WrenCore.decondition — Method
decondition(model::Model, vars::Union{Symbol,VarName}...)::Model

Remove whole variables from this model's conditioning, returning a new model. Use symbols for top-level names, for example decondition(model, :y), and qualified VarNames for child variables, for example decondition(model, @vn(child.y)) or decondition(model, @vn(children[1].y)). With no selectors, all conditioning is removed.

Removing a parent override does not remove a child model's own conditioning. Components of an ordinary observed array or record cannot be made latent individually.

Variables observed with @observe are part of the model's structure rather than its conditioning, and are unaffected.

source
WrenCore.evaluate — Function
evaluate(model, latent_source, parameter_space, accs, ctx[, conditioned])

Evaluate model in three stages for every latent variable:

  1. latent_source supplies a TransformedValue.
  2. parameter_space determines the model-space value, target representation, and forward log-Jacobian.
  3. accs accumulate the resulting information.

All three components are required. Higher-level interfaces may choose defaults, but this method keeps the evaluation pipeline explicit.

ctx is an EvalContext, which says whether to make the copies of model arguments that Enzyme needs. Unless the model is being differentiated with Enzyme, this should be EvalContext{false}().

conditioned defaults to conditioned(model). A parent model passes other values when it evaluates a submodel.

source
WrenCore.evaluate_submodel — Method
evaluate_submodel(
    rhs,
    latent_source::AbstractLatentSource,
    parameter_space::AbstractParameterSpace,
    accs::AccumulatorTuple,
    conditioned::NamedTuple,
    vn::VarName,
    collect_params::CollectOrDiscardSubmodelParams,
    ctx::EvalContext,
)

Evaluate a tilde-statement of the form vn ~ rhs, where rhs is a submodel. conditioned holds the parent model's conditioned values. The values under vn take precedence over the submodel's own. The collect_params argument indicates whether the parent model might require access to the parameters of the submodel as a top-level variable. ctx is the parent model's EvalContext, which should be passed on when evaluating the submodel.

source
WrenCore.get_latent — Function
get_latent(
    source::AbstractLatentSource,
    vn::VarName,
    dist,
    ::Val{sitename}
) where {sitename} -> TransformedValue

Obtain a value for the latent variable vn from source.

dist is the prior distribution of the variable, which occurs on the right-hand side of the model's tilde-statement. sitename is a compile-time Symbol identifying the sampling site in the model source code.

This function should return a TransformedValue which specifies both the value as well as the way to convert the value back to the model's original space. Note that this allows for lazy evaluation of the transformation, and thus get_latent should be as lazy as possible, and avoid performing any transformations on the value before returning it.

source
WrenCore.get_latent — Method
get_latent(source::FromVector, ...)

When evaluating a model with FromVector, Wren checks sitename_to_rat for a matching key. Otherwise it uses the potentially slower VarNamedTuple lookup.

The implicit assumption here is that if sitename was only encountered once during the construction of the VecInfo, then it will only be encountered once during every model evaluation. This is true of essentially any model that is amenable to vectorisation.

An interesting case to ponder is a model like this. In the absence of this fast path (i.e., if there was only VNT-based lookup like DynamicPPL), this is compatible with vectorisation as long as dist1 and dist2 have the same Plaice.unconstrained_vec_size, because the resulting RangeAndTransform will be a constant:

if something    x ~ dist1else    x ~ dist2end

With the fast path, it's quite possible that the sitename for the if branch will be stored, and the sitename for the else branch won't. This means that during model evaluation, the fast path will only work if we hit the same branch. However, even if we hit the other branch, the slow path will still work (because x's RangeAndTransform will still be stored in the VNT!)

source
WrenCore.iid — Method
iid(dist, dims::Dims)

Return independent draws from dist in an array of shape (size(dist)..., dims...). The distribution is stored once. @batch uses this when the distribution does not depend on the loop index.

@wren function f(N)    x ~ iid(Normal(), (N,))   # length N    W ~ iid(Normal(), (3, N)) # 3 × Nend

Inside @wren, @iid y ~ dist is shorthand for y ~ iid(dist, size(y)).

When the lhs is undefined, as is typically the case when setting up priors, use the size keyword to set its shape @iid mu ~ dist size=k where k may be either a tuple or an integer.

The fallback is independent(Fill(dist, dims)); backends may add specialised methods.

source
WrenCore.independent — Function
independent(dists::AbstractArray)

Return a distribution over arrays with the same shape as dists, where each entry is independently drawn from dists[i].

Used by @batch for indexed distributions without a specialised batched method. Backends (e.g. the Distributions and ProbabilityMeasures extensions) add methods for their own distribution types.

source
WrenCore.internal_values_as_vector — Method
internal_values_as_vector(values::VarNamedTuple)

Concatenate the internal vectors of the TransformedValues in values. An error is thrown if any stored value is not a vector.

source
WrenCore.is_submodel — Method
is_submodel(::Type{T}) where {T}

Return true if objects of T should be interpreted as submodels when used on the right-hand side of tilde expressions.

For a custom object t to be used as a submodel, is_submodel(typeof(t)) must return true, and evaluate_submodel must be overloaded for that type.`

source
WrenCore.logjac — Method
logjac(accs::AccumulatorTuple)::Number

Return the accumulated log-absolute determinant of the Jacobian of the transformation from original to the space that the model was evaluated in. If the model is evaluated in original space, this will be zero. However, if the model was evaluated in transformed space, then this is J_f(x) where f is the forward transformation into the evaluation space.

Consequently, the log-joint density in transformed space is given by

logjoint_transformed(accs) = logjoint(accs) - logjac(accs)

(note the minus sign).

source
WrenCore.logjoint — Method
logjoint(model::Model, latents)

Return the log-joint probability of model evaluated at the given latent values, in original space.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
WrenCore.logprior — Method
logprior(accs::AccumulatorTuple)::Number

Return the accumulated log-prior.

This number is always in original coordinates, even if the model was evaluated in transformed coordinates. If you want the log-prior density in transformed coordinates, you can compute it as logprior(accs) - logjac(accs).

source
WrenCore.logprior — Method
logprior(model::Model, latents)

Return the log-prior probability of model evaluated at the given latent values, in original space.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
WrenCore.lp — Method
lp(vecmodel::VecModel, params::AbstractVector)

Calculate the log-density of vecmodel at params.

Warning

params is not copied, and the model may receive views into it. A model that writes into a latent variable (e.g. x ~ MvNormal(...); x[1] += 1) is therefore not supported: it may change params and give inconsistent results.

source
WrenCore.lp_and_grad! — Method
lp_and_grad!(grad::AbstractVector, vecmodel::VecModel, params::AbstractVector)

Calculate the log-density and its gradient with respect to params, writing the gradient into grad. Returns a tuple (log_density, grad).

Warning

params is not copied, and the model may receive views into it. A model that writes into a latent variable (e.g. x ~ MvNormal(...); x[1] += 1) is therefore not supported: it may change params and give inconsistent results.

source
WrenCore.lp_and_grad — Method
lp_and_grad(vecmodel::VecModel, params::AbstractVector)

Returns a tuple (logdensity, grad) where `logdensityis the log-density ofvecmodelandgradis its gradient atparams`.

Warning

params is not copied, and the model may receive views into it. A model that writes into a latent variable (e.g. x ~ MvNormal(...); x[1] += 1) is therefore not supported: it may change params and give inconsistent results.

source
WrenCore.map_sitenames_to_rats — Method
map_sitenames_to_rats(sca::SitenameCountAccumulator, varnames_to_ranges::VarNamedTuple)

sca.entries contains a mapping of sitenames visited only once, to the corresponding VarNames. Then varnames_to_ranges contains a mapping of VarNames to the corresponding RangeAndTransform structs.

This function joins the two and returns a VarNamedTuple that maps sitenames (visited only once) to the corresponding RangeAndTransform structs.

Resolve each VarName tracked by tracker against vnt, returning a VarNamedTuple that maps sitename-paths to the corresponding values in vnt. SeenMultipleTimes sites are left as SeenMultipleTimes.

source
WrenCore.optimize — Function
optimize(
    model,
    solver;
    adtype=DEFAULT_AD,
    init=FromPrior(),
    lp_function=logjoint,
    reduce_copies=true,
    solve_kwargs...
)

Find a maximum a posteriori (MAP) estimate with an Optimization.jl solver. Requires Optimization.jl and the selected AD backend to be loaded.

Returns a PointEstimate, which contains the fitted model-space parameters, the value of the objective there, and the native Optimization solution (including its convergence status). The solver minimises the negative original-space log-density in unconstrained coordinates.

The starting point is chosen by init, which should be an AbstractInitialization or anything that can be implicitly converted to one. The default is to attempt drawing from the prior.

Other keywords are forwarded to Optimization.solve, although passing u0 is not allowed (you should use init instead).

source
WrenCore.reduce_copies — Method
reduce_copies(
    model::Model,
    adtype::DI.AbstractADType;
    n_points::Int=10,
    rng::AbstractRNG=Xoshiro(468),
    atol::Real=100 * eps(),
    rtol::Real=sqrt(eps()),
    lp_function=logjoint_transformed,
    latent_source::AbstractLatentSource=FromPrior(),
    parameter_space::AbstractParameterSpace=UnconstrainedSpace(),
    verbose::Bool=true,
) -> Model

Return a copy of model which skips copying any arguments whose copies turn out not to affect the log density or gradient computed with adtype.

The copies are only made when differentiating with Enzyme (see the docs), so for any other adtype this returns model unchanged.

source
WrenCore.replace_loop_idx_with_iters — Method
replace_loop_idx_with_iters(expr, loop_idx::Symbol, loop_iters, is_indexing_arg)::BatchedExpr

Replace all occurrences of loop_idx in expr with loop_iters and broadcast where necessary.

is_indexing_arg indicates whether expr is an argument to an indexing expression (i.e., foo[expr]).

source
WrenCore.reset — Function
reset(acc::AbstractAccumulator)

Return a new accumulator like acc, but with its contents reset to the state that they should be at the beginning of model evaluation.

This is also used to create the accumulators for a submodel, which are then merged back into the parent model's accumulators using combine_from_scope.

source
WrenCore.return_value — Method
return_value(model::Model)
return_value(model::Model, latents)

Obtain the model's return value calculated with a given set of latent values. If no latent values are provided, they are drawn from the prior distribution.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

This is equivalent to return_value(simulate(model)), but is more efficient than simulate because it does not compute the log-density terms or store the parameters.

source
WrenCore.return_value — Method
return_value(vecmodel::VecModel, params::AbstractVector)

Obtain the return value of the model of vecmodel at the parameter vector params, which is in the parameter space of vecmodel.

source
WrenCore.scope — Function
scope(source::AbstractLatentSource, vn::VarName) -> AbstractLatentSource

Restrict source such that it only provides values for sub-variables of vn. This is used when evaluating submodels with a prefix vn.

This is best explained through an example. Suppose you have a model with

@wren function inner()    x ~ Normal(0, 1)end@wren function outer()    a ~ inner()end

When evaluating outer, the latent source may contain a value for the variable a.x. For example, you might have FromValues(VarNamedTuple(a=VarNamedTuple(x=1.0))). However, when evaluating inner, the submodel does not know about the prefix a: Wren will call scope to obtain a subsetted latent source which only contains the variable x.

source
WrenCore.set_auto_runtime_activity! — Method
WrenCore.set_auto_runtime_activity!(val::Union{Bool,Nothing})

Set Wren's automatic runtime activity behaviour.

When using Enzyme as the AD backend, depending on how the model is constructed, it may be necessary to enable runtime activity. This can often allow more expressive models to be differentiated, but comes at a performance cost.

Wren recommends using reverse-mode Enzyme, i.e., AutoEnzyme(; mode=Reverse) as the AD backend, which does not enable runtime activity. By default, Wren will automatically enable runtime activity if Enzyme requires it.

If you would rather have Wren raise an error, set

WrenCore.set_auto_runtime_activity!(false)

Or if you want an info message instead of an error, set

WrenCore.set_auto_runtime_activity!(nothing)

To restore the default behaviour (silently enabling runtime activity), set

WrenCore.set_auto_runtime_activity!(true)
source
WrenCore.set_logprob_type! — Method
set_logprob_type!(::Type{T}) where {T}

Set the log probability type for Wren.jl, WrenCore.LogProbType, to T. Permitted values are Float64, Float32, Float16, and NoLogProb. The default in Wren is Float64.

NoLogProb is a special type that is the "lowest" possible float type. This means that the log probability will be promoted to whatever type the model dictates. This is a totally unintrusive option, which can be useful if you do not know in advance what log probability type you are targeting, or want to troubleshoot a model to see what type the log probability is being promoted to. However, this can also cause type stability issues and performance degradations, so we generally recommend setting a specific log probability type if you know what type you want to target.

This function uses Preferences.jl to set a compile-time constant, so you will need to restart your Julia session for the change to take effect.

source
WrenCore.setacc!! — Method
setacc!!(at::AccumulatorTuple, acc::AbstractAccumulator)

Add acc to at. Returns a new AccumulatorTuple.

If an AbstractAccumulator with the same accumulator_name already exists in at it is replaced. at will never be mutated, but the name has the !! for consistency with the corresponding function for AbstractVarInfo.

source
WrenCore.simulate — Method
simulate(model::Model; track=AllQuantities())
simulate(model::Model, latents; track=AllQuantities())

Draw a sample from model, using the given latent source. If one is not provided, draws from the prior distribution.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

Returns the params, tracked quantities selected by track, return value, log-prior, and log-likelihood of the model packaged in a ModelResult.

By default, all tracked quantities will be included in the result. 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. If you are using simulate in a performance-sensitive loop, you should instead pass one of AllQuantities, SomeQuantities, or NoQuantities.

source
WrenCore.simulate — Method
simulate(vecmodel::VecModel, params::AbstractVector; track=AllQuantities())::ModelResult

Evaluate the model of vecmodel at the parameter vector params, which is in the parameter space of vecmodel. The log-prior and log-likelihood in the result are in original space.

By default, all tracked quantities will be included in the result. 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. If you are using simulate in a performance-sensitive loop, you should instead pass one of AllQuantities, SomeQuantities, or NoQuantities.

source
WrenCore.test_ad — Method
test_ad(
    model::Model,
    adtype::DI.AbstractADType;
    reference::AbstractADCorrectnessTestSetting=WithBackend(),
    atol::Real=100 * eps(),
    rtol::Real=sqrt(eps()),
    lp_function=logjoint_transformed,
    latent_source::AbstractLatentSource=FromPrior(),
    parameter_space::AbstractParameterSpace=UnconstrainedSpace(),
    verbose::Bool=(!isinteractive()),
) -> ADTestResult

Check that the log-density and gradient computed by adtype on model are correct, and throw an ADIncorrectException if not.

Note that the corresponding backend package for adtype must be loaded first.

reference determines what the results are compared against: either another backend (WithBackend) or known values (WithExpectedResult).

The lp_function, latent_source, and parameter_space keywords are forwarded to VecModel, and have the same defaults.

source
WrenCore.to_latent_source — Method
to_latent_source(x)::AbstractLatentSource

Convert x into an AbstractLatentSource. Functions that take a latent source, such as simulate, call this on their argument, so they also accept:

  • an AbstractRNG, which becomes FromPrior(rng), i.e. latent variables are drawn from the prior using rng;
  • a VarNamedTuple, which becomes FromValues(values). There is no fallback, so it must contain every latent variable of the model.

An AbstractLatentSource is returned unchanged.

source
WrenCore.tracked_quantities — Method
tracked_quantities(model::Model; track=AllQuantities())
tracked_quantities(model::Model, latents; track=AllQuantities())

Obtain the tracked quantities selected by track, calculated with a given set of latent values. If no latent values are provided, they are drawn from the prior distribution.

By default, all tracked quantities will be included. 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. If you are using tracked_quantities in a performance-sensitive loop, you should instead pass one of AllQuantities, SomeQuantities, or NoQuantities.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

This is equivalent to tracked_quantities(simulate(model, latents; track)), but is more efficient than simulate because it does not compute the log-density terms or store the parameters.

source
WrenCore.vector_parameters — Method
vector_parameters(vecmodel::VecModel)::AbstractVector
vector_parameters(vecmodel::VecModel, latents)::AbstractVector

Obtain the model's parameters from latents and return them as a vector compatible with vecmodel. If no latent values are provided, they are drawn from the prior distribution.

The vector is in the parameter space of vecmodel (usually unconstrained), not in original space; parameters(vecmodel, v) converts it back.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
WrenCore.@_issue_error — Macro
@_issue_error msg

Throw an internal Wren error, including the source location and a request to report the issue.

source
WrenCore.@bmodel — Macro
@bmodel model [key=value ...]
@bmodel model adtype [key=value ...]

Benchmark a model; shorthand for benchmark_model. The one-argument form benchmarks lp only. The two-argument form also benchmarks lp_and_grad with the given AD backend.

Two keyword arguments are accepted, and passed on to benchmark_model:

  • seconds=5 to run each benchmark for roughly 5 seconds
  • extras=true to also benchmark parameters and logjoint

For the other keyword arguments, use benchmark_model directly.

source
WrenCore.@track — Macro
@track name = expr
@track name

Record the value of expr as the tracked quantity name in a @wren model. @track name is short for @track name = name. name must be a single symbol.

@track must be a statement of the model body. It is not supported inside @batch or inside functions defined in the model; we discourage using it inside @submodel.

If name is used later in the model body, expr is also assigned to name and runs on every evaluation of the model. If name is used only by later tracked quantities, it is assigned only when one of those tracked quantities is requested. Otherwise name is not defined in the model body.

Warning

If name is not used later in the model body and the tracked quantity is not requested, expr is not run at all. Note that this means side effects in expr do not happen!

Relatedly, if expr assigns to a variable defined elsewhere in the model body, that assignment happens only when name is requested.

source
WrenCore.Expressions.AbstractWrenExpr — Type
AbstractWrenExpr

Wren's probabilistic intermediate representation. This is for the most part a copy of Julia's Expr type, but with a few additional node types for probabilistic statements, namely Sample, Observe, IID, and Batch.

The ReturnStatement type is used as a convenient wrapper around Expr(:return, ...) to allow for dispatch, but has the same meaning.

TODO: I think we should create WrenExpr types for every Julia expression type that we handle, so that we can dispatch on them, but also so that users can create models more easily without dealing with Julia's Expr internals.

source
WrenCore.Expressions.AddLogLikelihood — Type
AddLogLikelihood

Representation of @addloglikelihood [name=NAME] EXPR. Manually adds the value of EXPR to the log-likelihood accumulator.

name must be a single Symbol. If not specified, a gensym'd name is used. The name is intended for use with pointwise log-likelihoods.

source
WrenCore.Expressions.Batch — Type
Batch

Representation of

@batch [name=NAME] [size=SIZE] for LOOP_IDX in LOOP_ITERS    BODYend

name must be a single Symbol. If not specified, a gensym'd name is used. If size is not specified, it will be nothing.

source
WrenCore.Expressions.IID — Type
IID

Representation of @iid lhs ~ rhs (wrapping a Sample), or of @iid @observe lhs ~ rhs / @observe @iid lhs ~ rhs (wrapping an Observe).

The wrapped tilde-statement is stored as written; the meaning lhs ~ iid(rhs, size(lhs)) is only given to it at the second stage of lowering, in emit_model_expr.

source
WrenCore.Expressions.Observe — Type
Observe

Representation of @observe lhs ~ rhs. Note that Sample statements that are conditioned on do become observations, but do not become Observe nodes in the AST. The same model can be evaluated with different sets of whole variables conditioned on.

source
WrenCore.Expressions.OtherStatement — Type
OtherStatement

Any other statement without special probabilistic meaning. (Note, by statement, we mean a top-level expression – things like for loops, etc. become WrenExpr nodes. This might be changed in the future.)

source
WrenCore.Expressions.TrackedQuantity — Type
TrackedQuantity

Represents @track name = expr, or @track name (short for @track name = name). name must be a single Symbol.

always_evaluated and tqs_triggering_evaluation are set by dataflow analysis. If an expr is always_evaluated, we know its name appears in a later statement (other than a different TQ that is not always_evaluated), and expr needs to be evaluated on every model evaluation. Otherwise expr is evaluated only when the quantity or one of the tracked quantities in tqs_triggering_evaluation is requested.

source
WrenCore.Expressions.lower_to_wren — Function
lower_wren_expr(expr, mod::Module, statement_position::Bool=false)

The actual function that handles part 1 of lowering, i.e., transforming the user's model into Wren's IR.

source
WrenCore.tracked_quantities — Method
tracked_quantities(
    model::WrenCore.Model,
    chain::FlexiChains.VNChain;
    rng::Random.AbstractRNG=Random.default_rng(),
    track=WrenCore.AllQuantities(),
) -> FlexiChains.VNChain

Re-evaluate model at each iteration of chain and return a chain holding the tracked quantities requested with track. If a parameter required by model is not stored in chain, that parameter will be drawn from the prior distribution using rng.

See also: TrackedQuantitySpec

source
WrenCore.simulate — Method
simulate(
    model::WrenCore.Model,
    chain::FlexiChains.VNChain;
    rng::Random.AbstractRNG=Random.default_rng(),
    track=AllQuantities(),
) -> FlexiChains.VNChain

Simulate from model using the parameters at each iteration of chain. If a parameter required by model is not stored in chain, that parameter will be drawn from the prior distribution using rng.

The returned FlexiChain will contain all the simulated variables, the tracked quantities selected by track (see TrackedQuantitySpec), as well as the variables already present in the input chain, which implies that:

  • variables that are in the chain are fixed to their respective values;
  • variables that arent in the chain are resampled according to the model;
  • variables that are @observed are never included.

To move a variable from the first into the second category, subset chain to exclude that variable (more about subsetting chains here).

The returned chain will also contain log-probabilities corresponding to the re-evaluation of the model. In particular, the log probability for the newly simulated variables are now considered as prior terms. However, note that the log-prior of the returned chain will also contain the log-prior terms of the parameters already present in the input chain. Thus, if you want to obtain the log-probability of the simulated variables only, you can subtract the two log-prior terms.

source
WrenCore.logjoint — Function
logjoint(accs::AccumulatorTuple)::Number

Return the log joint density in original coordinates, i.e. the sum of the log-prior and log-likelihood.

source
logjoint(result::ModelResult)

Get the log-joint (log-prior plus log-likelihood) from a ModelResult.

source
logjoint(model::Model, latents)

Return the log-joint probability of model evaluated at the given latent values, in original space.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
logjoint(
    model::WrenCore.Model,
    chain::FlexiChains.VNChain
) -> DimensionalData.DimMatrix

Return the log-joint (log-prior plus log-likelihood) of model at each iteration of chain. All variables required by model must be stored in chain.

source
StatsAPI.loglikelihood — Function
StatsAPI.loglikelihood(accs::AccumulatorTuple)::Number

Return the accumulated log-likelihood.

source
loglikelihood(result::ModelResult)

Get the log-likelihood from a ModelResult.

source
loglikelihood(model::Model, latents)

Return the log-likelihood of model evaluated at the given latent values.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
loglikelihood(
    model::WrenCore.Model,
    chain::FlexiChains.VNChain
) -> DimensionalData.DimMatrix

Return the log-likelihood of model at each iteration of chain. All variables required by model must be stored in chain.

source
WrenCore.logprior — Function
logprior(accs::AccumulatorTuple)::Number

Return the accumulated log-prior.

This number is always in original coordinates, even if the model was evaluated in transformed coordinates. If you want the log-prior density in transformed coordinates, you can compute it as logprior(accs) - logjac(accs).

source
logprior(result::ModelResult)

Get the log-prior from a ModelResult.

source
logprior(model::Model, latents)

Return the log-prior probability of model evaluated at the given latent values, in original space.

latents is converted to a latent source with to_latent_source, so it can also be an AbstractRNG (to draw from the prior) or a VarNamedTuple of values.

source
logprior(
    model::WrenCore.Model,
    chain::FlexiChains.VNChain
) -> DimensionalData.DimMatrix

Return the log-prior of model at each iteration of chain. All variables required by model must be stored in chain.

source
Pathfinder.pathfinder — Method
Pathfinder.pathfinder(
    model::Model;
    rng=Random.default_rng(),
    init_scale=2,
    init_sampler=FromUnconstrainedInterval(rng, -init_scale, init_scale),
    init=init_sampler,
    adtype=DEFAULT_AD,
    pathfinder_kwargs...
)

Run single-path Pathfinder on a Wren posterior in unconstrained coordinates.

Arguments

All arguments are passed to Pathfinder.pathfinder, but Wren overrides Pathfinder's init and init_sampler arguments to use Wren types instead.

In Pathfinder's original API, init is used to provide the initial point of the optimisation, and init_sampler is used to provide new starting points when an optimisation run fails. These must both be vectors of unconstrained parameters; however, this is difficult to generate with Wren as you need to use low-level APIs.

Wren instead allows you to pass an AbstractLatentSource to init and init_sampler, which is then converted into the appropriate vectors internally.

As in upstream Pathfinder, init_sampler defaults to drawing each unconstrained coordinate uniformly from [-init_scale, init_scale], with init_scale=2. init_scale must be positive, and cannot be combined with an explicit init_sampler.

Finally, if init is not given, the starting point is also drawn from init_sampler.

Note that only ntasks=1 is allowed due to Pathfinder not supporting thread-unsafe log-densities.

Returns

Returns a Pathfinder.PathfinderResult. This struct contains several fields which are documented in Pathfinder's own docs (see previous link), but in particular we note here that:

  • each column of the draws field contains one vectorised draw in unconstrained coordinates, and

  • the draws_transformed field contains a FlexiChains.VNChain of draws which have been transformed back to model space.

For example, in

using Wren, Pathfinder, Wren.Dists, Enzyme@wren f() = x ~ Beta(2, 2); model = f()result = pathfinder(model; ndraws=1000)

result.draws will be a 1×1000 Matrix of unconstrained draws, and result.draws_transformed[@vn(x)] will be a 1000×1 DimArray of constrained draws.

source
Pathfinder.multipathfinder — Method
Pathfinder.multipathfinder(
    model::Model,
    ndraws::Integer;
    rng=Random.default_rng(),
    init_scale=2,
    init_sampler=FromUnconstrainedInterval(rng, -init_scale, init_scale),
    init=nothing,
    nruns=4,
    multipathfinder_kwargs...
)

Run multi-path Pathfinder on a Wren posterior.

Fit nruns Gaussian mixture components and, by default, use Pareto-smoothed importance resampling to obtain ndraws draws.

Arguments

init_sampler specifies where new starting points come from when an optimisation run fails and Pathfinder retries. It is a single value that is shared by all runs (this mimics Pathfinder's API), and accepts the same types as init in Pathfinder.pathfinder.

init_scale works as in Pathfinder itself.

init sets the optimisers' starting points. If it is nothing, each of the nruns fits starts from a draw from init_sampler. Otherwise, it must be a collection with one entry per fit, and its length determines the number of fits instead of nruns. Each entry can be anything accepted by init in Pathfinder.pathfinder.

Only ntasks=1 and ntasks_per_run=1 are allowed due to Pathfinder not supporting thread-unsafe log-densities.

All other options are forwarded to Pathfinder.multipathfinder.

Return value

Returns a Pathfinder.MultiPathfinderResult struct. As with single-path Pathfinder, the draws field contains unconstrained draws, and draws_transformed contains a FlexiChains.VNChain of draws which have been transformed back to model space. For the other fields, please see the Pathfinder docs.

source