Vectorisation
Wren models can be converted into a vectorised form, i.e., one where the parameters are supplied as a vector rather than a VarNamedTuple. This allows Wren models to be used with a wide range of other Julia packages which expect a vectorised interface (i.e., LogDensityProblems.jl).
We begin by setting up our now-familiar eight schools model.
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) @batch 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)
@batch(name = Symbol("##batch#648"), for i = 1:J
@observe y[i] ~ Normal(theta[i], sigma[i])
end)
return (mu = mu, tau = tau)Introduction
Conceptually, vectorising a model requires two things:
- a mapping from the original model's parameters to ranges of indices in a vector; and
- transformation from the original model's parameter space to an unconstrained space (i.e., a space where all parameters can take any value in ℝ^n).
The latter is technically not mandatory, but in practice often desirable due to the fact that many inference algorithms work best in unconstrained space.
Vectorisation is done with the VecModel constructor, which takes a model and an ADTypes.AbstractADType object, constructs the above mapping, and stores it. The latter allows you to calculate gradients of the log-density with respect to the vectorised parameters.
using Enzyme# DEFAULT_AD is AutoEnzyme(; mode=Reverse)).vecmodel = VecModel(model, Wren.DEFAULT_AD)VecModel eight_schools
├─ adtype => AutoEnzyme(mode=EnzymeCore.ReverseMode{false, false, false, EnzymeCore.FFIABI, false, false}())
├─ dimension => 10
├─ parameter space => UnconstrainedSpace()
└─ 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)
@batch(name = Symbol("##batch#648"), for i = 1:J
@observe y[i] ~ Normal(theta[i], sigma[i])
end)
return (mu = mu, tau = tau)Automatic differentiation
Wren's 'default' AD backend is reverse-mode Enzyme: in general we recommend this for performance.
However, Wren does also use DifferentiationInterface.jl under the hood, so you can pass any AD backend which is supported by DI. These include (but are not limited to) the following. All of the following are re-exported by Wren:
AutoEnzyme(; mode=Forward)orAutoEnzyme(; mode=Reverse)using Enzyme.jl;AutoMooncakeForward()orAutoMooncake()using Mooncake.jl.AutoForwardDiff()using ForwardDiff.jl;AutoReverseDiff()using ReverseDiff.jl;
Because AD functionality is implemented in the form of Julia package extensions, you must explicitly load the AD backend you want to use before creating a VecModel. Wren does not automatically load any AD backend, because this would require Wren to incur a dependency on them.
You can also use AutoReactant to further accelerate the model evaluation using Reactant.jl. Please see the Working with Reactant page for more information.
If you are only interested in vectorisation and not AD, you can pass nothing as the second argument:
noad_vecmodel = VecModel(model, nothing)VecModel eight_schools
├─ adtype => nothing
├─ dimension => 10
├─ parameter space => UnconstrainedSpace()
└─ 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)
@batch(name = Symbol("##batch#648"), for i = 1:J
@observe y[i] ~ Normal(theta[i], sigma[i])
end)
return (mu = mu, tau = tau)Interacting with VecModel
This is mostly useful when you want to hand off a Wren model to a different library which expects a vector interface. In particular, VecModels obey the LogDensityProblems.jl interface, and thus can be used with a wide range of other Julia packages that expect this.
Probably the first thing to do is to draw a vectorised sample from a VecModel with vector_parameters. This draws from the prior of the underlying model:
v = vector_parameters(vecmodel)10-element Vector{Float64}:
0.5417212426297761
2.950305705424619
10.141494481265697
-6.718125732637892
2.320009449724219
-9.434116293971929
-17.51023427398454
8.053835705561188
14.484410803863417
-10.37356655249208This is exactly analogous to calling parameters(model). For example, you can also pass as the second argument a Random.AbstractRNG to control the random number generation; or pass a VarNamedTuple to evaluate the model at a specific set of values. The latter can be thought of as a way of converting the VarNamedTuple into a vectorised form.
ps = parameters(model) # This is a VarNamedTuple in original model space.v = vector_parameters(vecmodel, ps) # Convert it to vectorised (and unconstrained) form.10-element Vector{Float64}:
-7.381075059339993
0.6431823790350153
-5.825564372053846
-8.59367188144861
-10.749022292711743
-5.608011901427876
-10.018996806281482
-7.7836139415072365
-6.736252902339699
-6.042769854213139Once you have a vectorised sample, you can call simulate and its derivatives to evaluate the model at that point:
simulate(vecmodel, v)ModelResult
├─ parameters => VarNamedTuple
│ ├─ mu => -7.381075059339993
│ ├─ tau => 1.9025258138303194
│ └─ theta => [-5.825564372053846, -8.59367188144861, -10.749022292711743, -5.608011901427876, -10.018996806281482, -7.7836139415072365, -6.736252902339699, -6.042769854213139]
├─ tracked_quantities => VarNamedTuple()
├─ return_value => (mu = -7.381075059339993, tau = 1.9025258138303194)
├─ logprior => -22.138171861273
└─ loglikelihood => -36.39691127113428When calling simulate, the log-prior returned does not include log-Jacobian terms, even if the VecModel was constructed with a transformation to unconstrained space.
Log-densities
In addition to the above interface, VecModels also have a privileged notion of a log-density. That is, unlike the underlying model which tracks each probability component separately and does not emphasise one over the other, VecModels have a single type of log-density which it knows how to calculate.
By default, this log-density is the transformed log-joint: that is, the log-prior plus the log-likelihood, minus the log-Jacobian of the transformation from the original parameter space to the unconstrained space. This is precisely the log-density that is required by many inference algorithms which run in unconstrained space.
The reason for having this single notion of a log-density is to satisfy the LogDensityProblems.jl interface, which expects a mapping from $\mathbb{R}^n$ (parameters) to $\mathbb{R}$ (a single log-density value). If you have a vector of parameters, you can calculate the log-density of these vectorised parameters, and their gradient:
import LogDensityProblems as LDPLDP.logdensity(vecmodel, v) # Works without an adtype.LDP.logdensity_and_gradient(vecmodel, v) # Requires an adtype.(-57.89190075337226, [-0.3427558438932161, 0.40102617350803943, -0.2794101980571473, 0.5009448202220986, 0.9607434474894528, -0.38565152888458315, 0.8401329330948392, 0.18380258807543562, 0.0692153966677424, -0.31405040743389956])Wren in fact exports shorter functions for these, namely lp and lp_and_grad, which are directly equivalent to the above. Additionally, Wren provides an in-place gradient lp_and_grad! function, which may be useful for squeezing every last bit of performance out. Note that LogDensityProblems.jl does not provide a corresponding interface function for lp_and_grad! (but if you have a good usecase for it, please consider adding a comment on this issue!).
If you need to access the log-density components separately when evaluating a VecModel, it is recommended to either use simulate (less efficient) or directly call WrenCore.evaluate with the appropriate accumulators. Documentation on this will be forthcoming but for now please see the source code.
By default, VecModels are always run in UnconstrainedSpace(): that is, all parameters are transformed into a form where they can take any value in ℝ^n. As mentioned above, the log-density calculation will then include the log-Jacobian term corresponding to this transformation. If this is not desired, you can specify a different parameter space, or a different log-density calculation function as a keyword argument to the VecModel constructor: please see its docstring for more info.
If you have a use for higher-order derivatives like Hessians, please open an issue!
Mutation semantics
Note that, for performance reasons, Wren retains the right to mutate the input vector passed into simulate, logdensity, and other functions. This is subject to the same considerations as outlined in Working with Models.
It's probably worth illustrating this with a simple example. The easiest way to trigger this behaviour is if your model explicitly mutates arrays (e.g. writing x[1] += 1 if x is a parameter).
@wren function with_mutation() x ~ MvNormalScale(zeros(2), I) x[1] += 1.0 @info xendvm = VecModel(with_mutation(), nothing)VecModel with_mutation
├─ adtype => nothing
├─ dimension => 2
├─ parameter space => UnconstrainedSpace()
└─ Model with_mutation
├─ arguments (none)
├─ conditioned (none)
└─ expressions
x ~ MvNormalScale(zeros(2), I)
x[1] += 1.0
#= vecmodel.md:152 =# @info(x)for i in 1:2 vector_parameters(vm)end[ Info: [0.09354449600870329, -0.03345913845552166]
[ Info: [3.062120168665267, 0.015823685575548477]Each time we run the model, we get a new value of x, and mutate it inside the model. So far, this looks reasonable. However, the following can be quite surprising:
p = [2.0, 3.0]LDP.logdensity(vm, p)p2-element Vector{Float64}:
3.0
3.0The vector p has been mutated in-place by the x[1] += 1.0 statement.
There isn't a correctness issue here at all: the log-density is always calculated with respect to the values that are passed in. The slightly surprising thing is that the values that are passed in are themselves mutated.
The reason for this is because lp is a model evaluation, and as discussed in Working with Models, Wren makes no promises to copy anything during model evaluation.
However, it is still always guaranteed that at model construction time the arguments to the model will be copied. This holds true for VecModels as well (if only because to make a VecModel you must first make a Model). The parameter vector p above does not fall into this category: it does not exist at model construction time.
Restrictions
Vectorisation places certain restrictions on the structure of the model. In particular, it is not valid for a model to have a varying dimension. This can be caused either by parameters which have varying sizes:
x ~ Poisson(3.0)y ~ MvNormalScale(zeros(x), I) # dimension of `y` is not constantor models which simply have a varying number of parameters:
if x > 4 z ~ Normal() # existence of `z` is not constantendWren contains some code for handling cases where the names of parameters vary but their number is constant, but this is not an official guarantee right now.