Working with Models

Once you have defined a model, you can use it to draw samples, calculate log-densities, and more.

This page describes Wren's high-level interface for running models and extracting information from them.

To begin, let's define a model with several of the features that Wren supports:

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_centred(y, sigma, J)    mu ~ Normal(0, 5)    tau ~ HalfCauchy(0, 5)    theta_trans ~ MvNormalScale(zeros(J), I)    @track theta = mu .+ tau .* theta_trans    for i in 1:J        @observe y[i] ~ Normal(theta[i], sigma[i])    end    return (mu=mu, tau=tau)endmodel = eight_schools_centred(y, sigma, J)
Model eight_schools_centred
├─ 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_trans ~ MvNormalScale(zeros(J), I)
     @track(theta = mu .+ tau .* theta_trans)
     for i = 1:J
         @observe y[i] ~ Normal(theta[i], sigma[i])
     end
     return (mu = mu, tau = tau)

The simulate family

The core function that Wren provides for drawing samples from a model is simulate.

Without any arguments, simulate will draw from the prior distribution of the model:

res = simulate(model)
ModelResult
├─ parameters => VarNamedTuple
│  ├─ mu => -1.121542749228379
│  ├─ tau => 7.194508811683692
│  └─ theta_trans => [0.389902951234577, 1.0025417917720483, -0.4857535119170005, 0.15237031068436377, -1.105624247984424, 0.23300139461696429, 0.7958225162280282, 0.5751491873009561]
├─ tracked_quantities => VarNamedTuple
│  └─ theta => [1.6836174691302623, 6.091253005756779, -4.616300671021539, -0.02531320637074197, -9.075966143763473, 0.5547878374779598, 4.604009356310458, 3.0163731468410644]
├─ return_value => (mu = -1.121542749228379, tau = 7.194508811683692)
├─ logprior => -14.916438923011304
└─ loglikelihood => -30.5122017137542

It returns a ModelResult object which has several fields. To extract these, it is recommended to use the following accessor functions:

For example:

parameters(res)
VarNamedTuple
├─ mu => -1.121542749228379
├─ tau => 7.194508811683692
└─ theta_trans => [0.389902951234577, 1.0025417917720483, -0.4857535119170005, 0.15237031068436377, -1.105624247984424, 0.23300139461696429, 0.7958225162280282, 0.5751491873009561]

This VarNamedTuple object can, roughly speaking, be thought of as a mapping from variable names (VarNames) to values. For example, indexing into it works:

parameters(res)[@vn(mu)]
-1.121542749228379

If you want to perform forward simulation but you only want the parameters, you can directly call parameters(model). This will be more performant than parameters(simulate(model)), because it avoids calculating the log-densities. (The other functions behave exactly the same way.)

parameters(model)
VarNamedTuple
├─ mu => 0.6806637138883689
├─ tau => 13.223065117729327
└─ theta_trans => [0.09544231515789006, -0.16166684390881522, -1.0293987192954208, 0.3596993195904812, -0.5247860356877773, -0.5436471346688289, -0.9206443077022715, 0.6188458268490312]

The functions parameters, tracked_quantities, return_value, logprior, loglikelihood, and logjoint can therefore be thought of in the following manner:

  • if you pass it a result of an evaluation, it will extract the corresponding field;
  • if you haven't yet evaluated the model, it will evaluate it and return the corresponding field.

Specifying input sources

While the above is useful for quickly drawing random samples, often we want to control exactly how these values are drawn.

For example, we might want to draw from the prior using a specific RNG seed. You can do this by passing a Random.AbstractRNG to simulate.

using Randomsimulate(model, Xoshiro(468))
ModelResult
├─ parameters => VarNamedTuple
│  ├─ mu => 0.3600443374866038
│  ├─ tau => 0.6128751220123403
│  └─ theta_trans => [0.3840556561560339, -1.1766071488765062, 1.0333255699367145, 1.2011302036474378, 0.4405173190617712, 0.5457297283900595, 0.2791271134487283, -0.6862761418225559]
├─ tracked_quantities => VarNamedTuple
│  └─ theta => [0.5954224946127624, -0.3610689124416767, 0.9933438722400388, 1.0961871575997344, 0.6300264431551359, 0.6945085113594229, 0.5311144011984456, -0.060557236667053316]
├─ return_value => (mu = 0.3600443374866038, tau = 0.6128751220123403)
├─ logprior => -14.499981833493008
└─ loglikelihood => -31.281397050916638
API intentionally differs from other Julia libraries

Please note that the RNG is passed as the second argument, not the first.

All the other derived functions (parameters, tracked_quantities, etc.) also behave the same way:

parameters(model, Xoshiro(468))
VarNamedTuple
├─ mu => 0.3600443374866038
├─ tau => 0.6128751220123403
└─ theta_trans => [0.3840556561560339, -1.1766071488765062, 1.0333255699367145, 1.2011302036474378, 0.4405173190617712, 0.5457297283900595, 0.2791271134487283, -0.6862761418225559]

Alternatively, you may want to evaluate the model at a specific set of values, rather than letting Wren draw them from the prior. This can be done by passing a VarNamedTuple to simulate:

pars = VarNamedTuple(mu=1.0, tau=2.0, theta_trans=randn(8))simulate(model, pars)
ModelResult
├─ parameters => VarNamedTuple
│  ├─ mu => 1.0
│  ├─ tau => 2.0
│  └─ theta_trans => [-1.2659913101663738, 2.0509929689894966, -1.2029515772903998, -2.374326979184465, -0.010583575573351664, 1.0931368005294195, -1.4054571275614864, -0.41135451787508925]
├─ tracked_quantities => VarNamedTuple
│  └─ theta => [-1.5319826203327476, 5.101985937978993, -1.4059031545807996, -3.74865395836893, 0.9788328488532967, 3.186273601058839, -1.8109142551229729, 0.1772909642498215]
├─ return_value => (mu = 1.0, tau = 2.0)
├─ logprior => -20.226030139709508
└─ loglikelihood => -32.00514440876618
General latent sources

From the above, one can see that the RNG seed, or the parameter values, both play the same role: they are sources of latent values for the model. Under the hood, Wren is actually converting these to an AbstractLatentSource object. Indeed, you can construct and pass one of these directly for even more control (for example, you might want to specify some parameters and sample others.)

This is the reason why Wren's API specifies the seed as the second argument: it's because the second argument can be thought of as 'a latent source or something that can be converted to one'.

VarName and VarNamedTuple

At Wren's core are two types: VarName and VarNamedTuple. (If you have used FlexiChains.jl, you may have seen these before.)

VarName is a representation of a variable or part of it, for example: x, x[1], or x.a.

vn1 = @vn(x)     # a variable named `x`vn2 = @vn(x[1])  # the first element of a variable named `x`(vn1, vn2)
(x, x[1])

A VarNamedTuple is a mapping of VarNames to values, which has a Dict-like interface. However, it is designed to be much more general and performant than a simple Dict or NamedTuple.

The most frequent operation you will encounter is indexing into it. Returning to our model above:

vnt = parameters(model)
VarNamedTuple
├─ mu => -1.6437250155343968
├─ tau => 2.4796024366334883
└─ theta_trans => [0.28007064070207477, -1.1510383235761368, -1.3166208548573242, -0.3423062759045783, -0.24564567282406216, -0.4319845227708845, -0.07853549013528824, -0.5208417787269386]

we can access not only the top-level variables

vnt[@vn(mu)], vnt[@vn(theta_trans)]
(-1.6437250155343968, [0.28007064070207477, -1.1510383235761368, -1.3166208548573242, -0.3423062759045783, -0.24564567282406216, -0.4319845227708845, -0.07853549013528824, -0.5208417787269386])

but also parts of variables:

vnt[@vn(theta_trans[1])]
0.28007064070207477

Notice here that @vn(...) describes what we want to access (sort of a 'path' into the data that we're interested in).

Constructing your own VarNamedTuple

Most often end-users who want to set specific values known in advance will want to construct a VarNamedTuple via the VarNames.@vnt macro. If you are writing an inference algorithm which has to work over arbitrary models, you should look at the lower-level interface, including VarNames.templated_setindex!!.

Usually, you will obtain VarNamedTuples from Wren's or FlexiChain's functions, so you will not need to think too much about how to construct them, unless you are writing custom inference algorithms. For this reason, although we would like to have more docs on this in the future, for now we defer a detailed discussion of VarNamedTuple to the VarNames.jl docs.

When does Wren copy arguments?

At this point, since we have been evaluating models a few times, it is an apposite time to discuss when Wren makes copies of the model arguments.

In general, for performance reasons, Wren tries to avoid copying its arguments as far as possible. This means that if you pass a mutable object to Wren, it may be modified in-place during evaluation of a model.

Notice how, for example, x[1] is different on each iteration of the following loop:

@wren function model_with_mutable_arg(x)    @info ("before", x[1])    x[1] ~ Normal(0, 1)    @info ("after", x[1])endmodel = model_with_mutable_arg([0.0])for i in 1:2    simulate(model)end
[ Info: ("before", 0.0)
[ Info: ("after", 0.6954773353756168)
[ Info: ("before", 0.6954773353756168)
[ Info: ("after", 0.11486634985921915)

What happens here is that when a sampling statement is encountered, the resulting value is stored back into x[1]. So the second time the model is evaluated, x[1] will have taken on the value that it was assigned in the first evaluation.

However, to try to minimise potential footguns, Wren will make a copy of arguments at model construction time. The reason why this is permissible is because you will only construct the model once (as opposed to evaluation, which happens many times in performance-sensitive code).

In the following example, we do the same as above, but we give the argument a name so that we can check whether it has been modified:

x_original = [0.0]model = model_with_mutable_arg(x_original)for i in 1:2    simulate(model)end
[ Info: ("before", 0.0)
[ Info: ("after", 0.7111351906324063)
[ Info: ("before", 0.7111351906324063)
[ Info: ("after", 1.0107043940315934)

The behaviour so far is unsurprisingly exactly the same as above, in that x[1] is modified in-place during model evaluation. However, if we check the original array passed into the model, we can see that it has not been modified, as Wren made a copy of it for the model:

x_original
1-element Vector{Float64}:
 0.0