On the surface, Wren’s syntax looks and feels similar to typical PPLs. Much of the underlying machinery has come directly from ideas which my colleagues and I came up with for the Turing.jl ecosystem. However, many of its components have been (re)built with the aim of improving performance, including AD via Enzyme.jl, and potential acceleration on GPUs via Reactant.jl. Wren also utilises a two-stage compilation process, heavily inspired by Tilde.jl, that enables some level of introspection and static analysis of models.
Some of this might understandably feel a little opaque. So, let’s walk through a fairly simple model, expanding on it as we go along in order to introduce some of the new functionality that Wren provides.
Setup
We’re going to write a Bayesian multinomial regression model for classifying the MNIST digits dataset.
Let’s set up our data first:
NoteA note about the MLDatasets version
As of the time of writing of this post, due to various compatibility conflicts involving JSON3.jl, the newest versions of MLDatasets and Reactant cannot be loaded together. This should hopefully be fixed soon, and we will update the blog post when this happens. However, in the meantime, this post uses a temporary fork of MLDatasets to circumvent this. If you are trying to run this code you should also use this fork.
usingMLDatasets: MNISTusingLinearAlgebra: svdX, y =let data =MNIST(split=:train)# N x 784 matrix of pixel values in [0, 1], one row per image X_full =Matrix(Float64.(reshape(data.features, 28*28, :))')# Reduce each image to its first 40 principal components D =40 Xc = X_full .-sum(X_full; dims=1) ./size(X_full, 1) X = Xc *svd(Xc).V[:, 1:D]# Convert labels from 0-9 to 1-10 for 1-based indexing in Julia y = data.targets .+1 X, yendsize(X), size(y)
((60000, 40), (60000,))
We can define our model in Wren with a function wrapped in the @wren macro. Random variables are written with ~, like most other PPLs. In multinomial regression, we need to have a ‘reference’ category against which the other categories are compared, whose logits (i.e. unnormalised log-probabilities) are set to zero. For this example, we use the digit ‘0’ as the reference category.
usingWren, Wren.DistsusingLogExpFunctions: softmax@wrenfunctionmnist_naive(X, y, C) N, D =size(X)@iid W ~Normal() size=(C-1, D) # Weights@iid b ~Normal() size=(C-1) # Biases nonref_logits = W * X'.+ b # (C-1) x N ref_logits =zeros(eltype(nonref_logits), 1, N) # 1 x N logits =vcat(ref_logits, nonref_logits) # C x N probabilities =softmax(logits; dims=1)for i in1:N y[i] ~Categorical(probabilities[:, i])endend
mnist_naive (generic function with 1 method)
We can now instantiate the model with our data. Note that (unlike in Turing.jl) passing y as an argument to mnist_naive alone does not make it an observation; it merely makes the values available to the model. So, we need to additionally condition the model on y using the | operator. Conditioning means that any y... ~ dist is treated as an observation in the model.
This returns a set of the parameters W and b, together with their associated log-probabilities; precisely the information we need to start performing inference. For example, we can feed this model to NUTS, using Enzyme.jl to calculate the necessary gradients of the log-density with respect to the parameters:
importEnzymenuts(model_naive, 1000, 4)
Wren returns a FlexiChain from its sampling routines, which has many useful tools for analysis and visualisation of the resulting data. Unfortunately, running this will almost certainly take a long time, if only because the model is very large! (We’ve omitted this output from the post because of this.) Of course, the question is then how can we make this faster!
To illustrate the changes in performance, we’ll use Wren’s benchmarking tools to help us measure the performance of our model.
Wren’s DEFAULT_AD is reverse-mode Enzyme, but you can also specify any AD backend you like as Wren uses DifferentiationInterface.jl under the hood. For example, to use Mooncake.jl:
importMooncake@bmodel model_naive AutoMooncake()
BenchmarkResult
├ model : mnist_naive
├ backend : ADTypes.AutoMooncake()
├ n_params : 369
├ lp : 4.106 ms (60020 allocs: 24.753 MiB)
├ lp_and_grad : 49.652 ms (240155 allocs: 57.298 MiB)
└ grad / lp : 12.09
Anyway, for NUTS we are most interested in the lp_and_grad field, which tells us the minimum time taken to evaluate the log-density and its gradient. One can profile this further, but it shouldn’t be a huge spoiler if I tell you that the bulk of the time is spent on the likelihood evaluation, because of the large dataset!
Handwritten likelihood
Traditionally, when faced with performance issues, one of the biggest tools that people reach for is to directly write out a mathematical expression for the likelihood, in the hope of stripping away the overhead of the PPL machinery. In particular, we might want to write a vectorised version of the likelihood so that we don’t loop over slices of probabilities one at a time.
In Wren, we can do that with the @addloglikelihood macro:
@wren function mnist_manual(X, y, C) # The rest of the model is unchanged from `mnist_naive`.- for i in 1:N- y[i] ~ Categorical(probabilities[:, i])- end+ @addloglikelihood sum(log, probabilities[y .+ C .* (0:(N-1))]) end
We can see here that there is a small decrease in the time required for the gradient. Furthermore, the number of allocations has also decreased substantially. This in turn means that the garbage collector has less work to do, and reduces the spikiness in the time taken to evaluate the log-density and its gradient.
This is all very good. Indeed, with modern LLMs it is quite easy to write such likelihoods out. However, in the process of doing this optimisation, we have also made the model less readable. It’s hard to see at a glance that this is indeed a multinomial regression model; imagine doing a presentation and having to show this to an audience. This rather defeats the purpose of using a PPL in the first place: if you wanted to just write a bare mathematical expression, you could have done that in a single function without needing the abstraction of a PPL!
Using @batch
This is where one of Wren’s features comes in: the @batch macro. We can simply annotate our original for loop with the macro, and Wren will attempt to vectorise the likelihood evaluation:
@wren function mnist_batch(X, y, C) # The rest of the model is unchanged from `mnist_naive`.- for i in 1:N+ @batch for i in 1:N y[i] ~ Categorical(probabilities[:, i]) end end
We see that this allows us to gain the same performance benefits as when we handwrote our likelihood, with no loss in readability!
In this case, the only gains really come from avoiding materialising intermediate arrays along with vectorisation. However, the @batch macro can also be used to automatically avoid redundant calculations. For example, if we instead had observations of the form y[i] ~ Normal(mu[i], sigma), the log(sigma) term can be calculated once and reused for all i, instead of being recomputed once per observation. @batchalso does such optimisations automatically for you.
Further acceleration with Reactant
Now, the small performance gain of ca. 15% above may seem slightly underwhelming. In fact, this is mainly because the bulk of the model’s work is in the large matrix multiplication W * X'; optimising the likelihood does not help us escape that bottleneck.
This is where Reactant.jl comes in! Reactant is a very powerful tool that takes a Julia function and generates highly optimised machine code which can be run on CPUs, GPUs, or TPUs. Wren provides a high-level interface to Reactant, so that you can use it without worrying too much about the details. On top of that, Wren’s own distributions (in the Wren.Dists submodule) are tested for compatibility with Reactant; this was a specific design goal because Distributions.jl is very much incompatible with Reactant.
To run a Wren model with Reactant, we just pass the AutoReactant AD type; this must itself wrap an Enzyme AD type, which controls whether the gradient is calculated using forward- or reverse-mode AD within Reactant.
NoteMaking models compatible with Reactant
Although Reactant is very impressive and is being actively improved on a daily basis, there are still a number of cases where Reactant either struggles to compile the model or produces code that is suboptimal. Much care has been put into Wren’s distributions to try to avoid these, but since Wren models may contain arbitrary user-defined code, Wren cannot make that work with Reactant automatically. Therefore you (or your LLM) should still be prepared to do some debugging to use Reactant effectively. For example, in the model above, passing eltype(nonref_logits) to zeros avoids triggering a scalar-indexing error.
We’ll now time our @batch model with Reactant. This blog post was rendered on a MacBook Pro, and Reactant is currently unable to work with Apple GPUs, so the following benchmark is actually being run on the CPU.
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1796003628.043092 15666843 cpp_gen_intrinsics.cc:81] Empty bitcode string provided for eigen. Optimizations relying on this IR will be disabled.
We see here that the time for a gradient evaluation has dropped by 4.5x, which is a massive improvement. However, we can do even better! I separately took the above model and ran it on an NVIDIA A100 GPU. The results here are hardcoded because they’re on a different system:
which is a further 3.6x improvement, for very little effort on our part.
We’ve only been demonstrating single evaluations of the model’s log-density and gradient here. In fact, each of these evaluations includes transferring the model parameters to the GPU, and transferring the results back to the CPU, which adds some non-trivial overhead. In particular, this overhead can actually make small models much slower.
However, in theory, it should eventually also be possible to use Reactant to accelerate the entire NUTS sampling process so as to (almost) entirely cut out this overhead. While we are not yet at that stage, this is a very exciting prospect for the future!
Static model analysis
While much of the post so far has focused on performance, another thing that I mentioned at the very beginning was Wren’s two-stage compilation process. To be precise, Wren first takes the model that you write and generates an intermediate representation: for example, x ~ dist is lowered to a struct that is conceptually like Sample(:x, :dist). The model itself stores this information and uses it to generate the actual evaluation function which contains calls to rand or logdensityof.
This is a very powerful feature, as it allows Wren to have full knowledge of the model structure. For example, in principle, this could be used to perform optimisations by simplifying the computation graph, which looks something like this:
flowchart LR
X[/"X"/] --> N["N, D"]
C[/"C"/] --> W
C --> b
N --> W(["W"])
N --> b(["b"])
W --> nonref["nonref_logits"]
b --> nonref
X --> nonref
N --> ref["ref_logits"]
nonref --> logits["logits"]
ref --> logits
logits --> probs["probabilities"]
probs --> y(["y"])
Wren doesn’t yet have the ability to do such optimisations (implementing this is very non-trivial!), but we can showcase a simpler version of this in the context of derived quantities. Derived quantities are not themselves model parameters, but are instead some other value that we might be interested in tracking as part of our probabilistic model. For example, we might be interested in calculating the accuracy of our predictions on the training data, i.e., the proportion of data points for which the largest probability matches the observed label:
accuracy =sum(map(argmax, eachcol(probabilities)) .== y) / N
Now, we definitely don’t want to calculate accuracy when evaluating gradients, as it isn’t necessary for the computation. If we were to naively write this as part of the model, it would, however, often be computed during the gradient evaluation.
NoteCan’t Julia optimise this away?
Julia’s compiler can sometimes eliminate unused code if the computation can be proven to have no effects, but this is often not guaranteed (as we will shortly see). In particular, if the computation has any chance of throwing an error, Julia will not remove it, since that can cause the error to no longer be thrown.
@wren function mnist_batch_derived(X, y, C) # The rest of the model is unchanged from `mnist_batch`. @batch for i in 1:N y[i] ~ Categorical(probabilities[:, i]) end+ accuracy = sum(map(argmax, eachcol(probabilities)) .== y) / N end
We’ll go back to benchmarking this with plain Enzyme (so the gradient benchmark we’re comparing against is mnist_batch’s 11.08 ms):
This 17% slowdown is very unfortunate, and classically means that you would have to write two models, one for inference and one for postprocessing.
In Wren, you can label such quantities with the @track macro. This tells Wren to elide these computations unless they are either (1) explicitly requested, or (2) actually needed for the model evaluation (for example, if it’s an intermediate calculation).
When performing inference with nuts, the @track-ed quantity will be included as part of the resulting chain. This is because at the end of each iteration we rerun the model a single time, during which we calculate these derived quantities and store them in the chain. However, during log-density and gradient evaluations, tracked quantities are omitted by default, meaning that inference is not slowed down by unnecessary calculations. We can see that the gradient time is now back to its normal value:
@wren function mnist_batch_tracked(X, y, C) # The rest of the model is unchanged from `mnist_batch`. @batch for i in 1:N y[i] ~ Categorical(probabilities[:, i]) end+ @track accuracy = sum(map(argmax, eachcol(probabilities)) .== y) / N end
Wren can do this because it can tell that the symbol accuracy is not used elsewhere in the model, meaning that if it’s not explicitly requested, it can be elided. This allows you to have just a single model which can be used for both inference and postprocessing, without any compromise in performance!
Conclusion
It’s worth emphasising that Wren is still very much a fledgling project. There are many features that are still missing, and in particular we have not done many tests on GPUs yet. This means that there is still a great deal of room for improvement, which we are acutely aware of. The best way to help us improve Wren is to try it out, report issues, let us know what’s still missing, and perhaps even contribute to the project!
Nevertheless, it should be obvious from this post that there is already a lot of functionality that is very usable. On top of that, we’ve put a lot of effort into writing documentation for users. That’s why we think it deserves to be made public! We’re very excited to both see where Wren goes in terms of future technical development, and also to develop it into a welcoming and inclusive community project.