Compilation model
One of Wren's features, inspired by Soss.jl and Tilde.jl, is that it uses staged computation to generate the evaluation functions for models. That sounds like a scary term, but it essentially means that the evaluation function is generated via a multi-stage pipeline:
(Note that this intermediate representation, or IR, has nothing to do with the IR that Julia uses in its own compilation pipeline; this is entirely within Wren.)
The model definition is what you write:
using Wren, Wren.Dists@wren function my_model(y) x ~ Normal() @observe y ~ Normal(x)endmodel = my_model(1.0)Model my_model
├─ arguments
│ └─ y => 1.0
├─ conditioned (none)
└─ expressions
x ~ Normal()
@observe(y ~ Normal(x))The probabilistic IR looks something like the following, but a bit more complicated:
[Sample(:x, :(Normal())), Observe(:y, :(Normal(:x)))]The actual IR
Although it's not really useful for the average user, you can view this if you want with
dump(model.stmts)Array{Union{LineNumberNode, WrenCore.Expressions.AbstractWrenExpr}}((5,))
1: LineNumberNode
line: Int64 19
file: Symbol compilation.md
2: LineNumberNode
line: Int64 20
file: Symbol compilation.md
3: WrenCore.Expressions.Sample{Symbol, WrenCore.Expressions.WrenExpr{Vector{Symbol}}}
name: Symbol x
lhs: Symbol x
rhs: WrenCore.Expressions.WrenExpr{Vector{Symbol}}
head: Symbol call
args: Array{Symbol}((1,))
1: Symbol Normal
lhs_top_level_symbol: Symbol x
lhs_is_reused: Bool true
4: LineNumberNode
line: Int64 21
file: Symbol compilation.md
5: WrenCore.Expressions.Observe{Symbol, WrenCore.Expressions.WrenExpr{Vector{Symbol}}}
name: Symbol y
lhs: Symbol y
rhs: WrenCore.Expressions.WrenExpr{Vector{Symbol}}
head: Symbol call
args: Array{Symbol}((2,))
1: Symbol Normal
2: Symbol xAnd the evaluation function is conceptually something like
function __mymodel_evaluate__(y, params, accs, ...) x = rand(Normal()) lp_x = logdensityof(Normal(), x) accs = add_logprior(accs, lp_x) lp_y = logdensityof(Normal(x), y) accs = add_loglikelihood(accs, lp_y) return accsendThe actual evaluation function
Again, although it's not really useful for the average user, you can view this with
using WrenCoreWrenCore.view_evaluation_fn(model):((var"##latent_source#204", var"##parameter_space#205", var"##accs#202", var"##model_args#199", var"##conditioned#203", var"##enzyme_copy_argnames#200", var"##ctx#201")->begin
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/model.jl:267 =#
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/model.jl:276 =#
begin
y = if (haskey)(var"##conditioned#203", :y)
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/model.jl:246 =#
(getproperty)(var"##conditioned#203", :y)
else
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/model.jl:248 =#
(WrenCore._maybe_dealias)(var"##ctx#201", var"##enzyme_copy_argnames#200", Val(:y), (var"##model_args#199").y)
end
var"##retval#206" = begin
#= compilation.md:19 =#
#= compilation.md:20 =#
begin
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:131 =#
var"##rhs#207" = Normal()
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:132 =#
var"##vn#212" = (VarName){:x}((VarNames.Iden)())
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:133 =#
if (WrenCore.is_submodel)(typeof(var"##rhs#207"))
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:134 =#
if var"##rhs#207" isa Model
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:136 =#
var"##scoped_args#215" = (WrenCore._scope_submodel)(var"##rhs#207", var"##latent_source#204", var"##parameter_space#205", var"##accs#202", var"##conditioned#203", var"##vn#212")
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:144 =#
(var"##val#208", var"##child_params#214", var"##child_accs#213") = (WrenCore._evaluate_scoped_submodel)(var"##rhs#207", var"##scoped_args#215"..., WrenCore.CollectSubmodelParams(), var"##ctx#201")
else
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:151 =#
(var"##val#208", var"##child_params#214", var"##child_accs#213") = (WrenCore.evaluate_submodel)(var"##rhs#207", var"##latent_source#204", var"##parameter_space#205", var"##accs#202", var"##conditioned#203", var"##vn#212", WrenCore.CollectSubmodelParams(), var"##ctx#201")
end
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:162 =#
x = var"##child_params#214"
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:163 =#
var"##accs#202" = (WrenCore.combine_from_scope)(var"##accs#202", var"##child_accs#213", var"##vn#212", nothing)
else
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:171 =#
if (haskey)(var"##conditioned#203", :x)
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:172 =#
var"##val#208" = (VarNames.getvalue)(var"##conditioned#203", var"##vn#212")
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:175 =#
x = var"##val#208"
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:179 =#
var"##accs#202" = (WrenCore.accumulate_observe!!)(var"##accs#202", var"##val#208", var"##vn#212", var"##rhs#207", x, Val{:x}())
else
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:188 =#
var"##init_tval#210" = (WrenCore.get_latent)(var"##latent_source#204", var"##vn#212", var"##rhs#207", Val{:x}())
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:189 =#
(var"##val#208", var"##tval#209", var"##logjac#211") = (WrenCore.apply_parameter_space)(var"##parameter_space#205", var"##init_tval#210", var"##vn#212", var"##rhs#207")
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:191 =#
x = var"##val#208"
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:192 =#
var"##accs#202" = (WrenCore.accumulate_assume!!)(var"##accs#202", var"##val#208", var"##tval#209", var"##vn#212", var"##rhs#207", var"##logjac#211", x, Val{:x}())
end
end
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:205 =#
var"##val#208"
end
#= compilation.md:21 =#
begin
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:765 =#
var"##val#217" = y
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:766 =#
var"##rhs#216" = Normal(x)
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:767 =#
var"##vn#218" = (VarName){:y}((VarNames.Iden)())
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:768 =#
var"##accs#202" = (WrenCore.accumulate_observe!!)(var"##accs#202", var"##val#217", var"##vn#218", var"##rhs#216", y, Val{:y}())
#= /home/runner/work/Wren.jl/Wren.jl/WrenCore/src/model/emit.jl:770 =#
var"##val#217"
end
end
return (var"##retval#206", var"##accs#202")
end
end)Why do this?
This pipeline does seem complicated. In particular, one might ask why we don't just generate the evaluation function directly from the model definition. (Indeed, a macro would do this quite easily, and that's more or less how DynamicPPL works, for example.)
The main motivation is that the intermediate representation (IR):
- gives Wren some information about the model which it can use to (more efficiently) generate the evaluation function;
- allows Wren to do some optimisations, for example elision of submodel parameter collection;
- allows for the programmatic generation of Wren models, in that a user can construct an IR and then generate a Wren model from it, instead of having to do some macro gymnastics to create the original model definition.
Example: tracked quantities
TODO: Should we use tracked quantities to illustrate staging or just leave this page as is?
This of course doesn't come for free. Besides the substantial extra complexity of the codebase, it also means that we have to use RuntimeGeneratedFunctions.jl in the second step (IR to evaluation function), which brings with it some limitations.
Soss and Tilde use GeneralizedGenerated.jl instead of RGF. GG is supposedly more powerful than RGF, but I haven't yet come across a use case where GG was absolutely necessary. Furthermore, RGF is actually maintained (for example it is used in ModelingToolkit.jl), and so it seems like a better choice for a dependency.
For example, model bodies cannot close over local variables (only global variables). This is surprisingly easy to trigger:
julia> for d in (Normal(), Exponential()) # d is a local variable... @wren function oops_closed_over_local() # ... but our model closes over it x ~ d end model = oops_closed_over_local() parameters(model) endERROR: UndefVarError: `d` not defined in `Main`Suggestion: check for spelling errors or missing imports.This can be worked around, for example by passing d into the model as an argument. However, it's still of course a limitation, and the error message isn't super helpful either.
IR and syntax design
Above we saw two of the 'special expressions' that Wren uses in its IR, namely Sample and Observe. These have a very unimaginative one-to-one mapping to the special nodes in Wren:
| Syntax | IR node |
|---|---|
a ~ b | Sample |
@observe a ~ b | Observe |
@iid size=N ... | IID |
@batch for ... | Batch |
@addloglikelihood ... | AddLogLikelihood |
@track ... | TrackedQuantity |
return ... | ReturnStatement |
As you can see, most of these are denoted by macros. As it turns out, none of these macros actually have a meaning outside of Wren model bodies: they don't actually expand into anything. They simply serve as syntax markers for the IR generation stage.
Why macros, though? To begin with, we are fundamentally limited by Julia syntax: we can't invent our own syntax, because it has to be parsed by a normal Julia macro (@wren). So we can't, for example, write [observe] a ~ b as that simply won't parse.
Then, we don't want to hijack any preexisting Julia syntax. This means that, for example, we don't want to parse a => b into something, because that usually means Pair(a, b) in Julia. Once we eliminate those, we are actually left with very few operators that aren't weird Unicode stuff that is impossible to type.
In principle, we could use any kind of function call to denote these. For example, we could say that sample(a, b) is what is now a ~ b, and iid(sample(a, b); size=N) is what is now @iid a ~ b size=N. However, this is a bit too understated: it looks just like a normal function call, and it's not obvious to the user that these have special semantics. On top of that, it actually stops the user from using any function named sample or iid in their model.
Macros are the best compromise between all of these. We aren't restricted to a fixed set of possibilities (as is the case with operators), but also to most Julia programmers it should be intuitive that macros have special effects! It does preclude the use of macros with the same name, but that is quite unlikely to be a problem as there are much fewer macros than functions in Julia.
Programmatic generation
The above claim that the IR allows for programmatic generation is very carefully worded: there is no meaningful API for this yet.
However, you can in principle do something like this:
using WrenCore.Expressions: Sample, Observe, AbstractWrenExprusing WrenCore: RuntimeGeneratedFunctionsstmts = AbstractWrenExpr[ Sample(:sample_x, :x, Normal(), :x, true), Observe(:observe_y, :y, :(Normal(x))),]RuntimeGeneratedFunctions.init(@__MODULE__)manual_model = Wren.Model(:my_model, (; y=1.0), stmts, @__MODULE__)Model my_model
├─ arguments
│ └─ y => 1.0
├─ conditioned (none)
└─ expressions
@sample(x ~ Normal{Float64, Float64}(0.0, 1.0), name = :sample_x)
@observe(y ~ Normal(x), name = :observe_y)Obviously, this leaks internal details of Wren, and is not exactly a user-friendly API. However, it does show that it should be possible to construct the stmts array programmatically, generate a Wren model from it, and then use that model:
parameters(manual_model)VarNamedTuple
└─ x => -0.40321475526667827