In WitDraw, a model is a joint probability distribution over all quantities of a problem. This includes the parameters we want to learn as well as the data we observe, all modeled as random variables. Once the joint distribution is written down, the model is used for generating samples, evaluating its density and, above all, conditioning it on the data we have observed. This guide develops these ideas on the classical example of Bayesian linear regression.
We want to model outcomes
Given the features
Each line contributes the distribution of its variable given the variables it
depends on. The first three lines define the prior distributions. They do not depend on the data. The last line describes how the outcomes
The same factorisation can be read as a recipe for generating data: draw
Every task in this guide is a question asked of this one joint distribution.
The two most basic questions are: what do draws from it look like, and what is
its density at given values of all variables? The most important question, however, starts from the outcomes
Let's see how to answer these questions in WitDraw.
We import dimwit, which provides the tensors and distributions, and WitDraw itself:
import dimwit.*
import dimwit.stats.*
import witdraw.*
import witdraw.inference.NUTS
import witdraw.inference.Summary.summaryEvery program that uses dimwit must initialise the dimwit runtime first:
dimwit.initialize()For each random variable we want to model, we declare a site.
The site is a singleton object that identifies the name of the variable and the type of its value. The type is a named DimWit tensor. Hence we have to
define for each axis of the tensor the label which this axis represents. In this example, we have two axes: Feature for the features and Sample for the samples.
trait Feature derives Label
trait Sample derives Label
object Alpha extends Site[Tensor0[Float32]] // intercept
object Beta extends Site[Tensor1[Feature, Float32]] // regression weights
object Sigma extends Site[Tensor0[Float32]] // noise scale (> 0)
object Y extends Site[Tensor1[Sample, Float32]] // outcomesLet's write the above model using the sites we defined.
A model in WitDraw is a method that takes a ProbContext as a parameter. The ProbContext is a context that is provided later on to interpret the model when it is run.
def model(x: Tensor2[Sample, Feature, Float32])(using ProbContext) =
val alpha = Alpha ~ Normal(0f, 10f)
val beta = Beta ~ Normal.isotropic(
Tensor1(x.extent(Axis[Feature])).fill(0f),
10f
)
val sigma = Sigma ~ HalfCauchy(0f, 5f)
val mu = x.dot(Axis[Feature])(beta) +! alpha
val y = Y ~ Normal.isotropic(mu, sigma)
(alpha = alpha, beta = beta, sigma = sigma, y = y)The line:
val beta = Beta ~ Normal.isotropic(...)reads "the site Beta is distributed according to this normal distribution".
It gives back a plain tensor of the site's type (Tensor1[Feature, Float32]),
which we can use in ordinary dimwit code. Which tensor depends on the
context the model runs in: a sampler draws one, a scorer uses a value we
give it.
Line by line, this is the model from the beginning: one ~ statement per
line, each with the distribution of its variable given the values computed
before it. The statements for Y is all y is a vector with one entry per sample, and
Normal.isotropic is the distribution of Normal(0f, 10f); and the mean mu is not a site, because it is not random:
values computed from other variables are ordinary code.
The model returns a named tuple of all its variables. This is what
ForwardSampler gives back, so naming the fields makes the samples easy to
use.
The model needs features to run: they are its inputs. We draw 100 samples of two features at random.
dimwit uses explicit random keys (as in JAX). We split one root key into independent keys, one for each use in this guide, so that no key is used twice:
val (featureKey, priorKey, fixedKey, dataKey, nutsKey, replicateKey) =
val ks = Key(42).split(6)
(ks(0), ks(1), ks(2), ks(3), ks(4), ks(5))
val sampleExtent = Axis[Sample] -> 100
val featureExtent = Axis[Feature] -> 2
// independent standard-normal features
val xData = Normal.standardNormal(Shape(sampleExtent, featureExtent)).sample(featureKey)The features are drawn independently on purpose. If one feature were a multiple of the other, only a combination of the weights could be learned from the data, and no inference algorithm could recover the weights.
As mentioned above, when the model is run, it needs a ProbContext to interpret the ~ statements. A context that gives the model a meaning in this way is called an
interpreter. The simplest one is ForwardSampler, which runs the generative recipe: it draws each variable in turn, given the values drawn before it. Each run is therefore one draw
val priorPredictive = ForwardSampler.sample(priorKey, 5)(model(xData))ForwardSampler.sample runs the model 5 times, each with its own key split
from priorKey; ForwardSampler.run(key)(model) runs it once.
The y values on their own are draws from the prior predictive distribution
Each sample is a named tuple, so we can print a short summary of each:
priorPredictive.foreach { s =>
println(f"alpha=${s.alpha.item}%7.2f sigma=${s.sigma.item}%7.2f mean(y)=${s.y.mean.item}%8.2f")
}
// alpha= 4.95 sigma= 73.70 mean(y)= 2.62
// alpha= 18.57 sigma= 2.84 mean(y)= 18.30
// alpha= -5.67 sigma= 2.53 mean(y)= -4.97
// alpha= 6.84 sigma= 11.85 mean(y)= 7.63
// alpha= 9.57 sigma= 2.96 mean(y)= 10.11The spread of these draws shows how vague our priors are.
Next we want to see what the model predicts for the outcomes observe, a handler: it sits between the model and the interpreter and changes what individual sites do.
observe runs a block of code with some sites fixed to given
values. Here we fix the noise scale to 1 and let everything else vary:
val withFixedSigma =
ForwardSampler.sample(fixedKey, 5):
observe(Sigma := Tensor0(1f)):
model(xData)withFixedSigma.foreach { s =>
println(f"sigma=${s.sigma.item}%4.2f mean(y)=${s.y.mean.item}%8.2f")
}
// sigma=1.00 mean(y)= 3.41
// sigma=1.00 mean(y)= -0.97
// sigma=1.00 mean(y)= 21.99
// sigma=1.00 mean(y)= 0.07
// sigma=1.00 mean(y)= -10.59These are draws from the conditional distribution
The same is not true for the data, because Y inside ForwardSampler would draw the parameters
from their priors, exactly as before, and merely skip drawing
So observe always means the same thing: this variable has this value.
Whether a computation turns that into the conditional distribution of the
other variables depends on the interpreter. ForwardSampler does so only when
the fixed variables depend on no free variable, as for
To check that inference works, we need data for which we know the answer. We
already have everything to make it: we fix all three parameters to chosen
"true" values and run the model forwards. The outcomes are then one draw from
val alphaTrue = Tensor0(0.5f)
val betaTrue = Tensor(Shape(featureExtent)).fromArray(Array(-1.5f, 2.0f))
val sigmaTrue = Tensor0(0.8f)
val yData =
ForwardSampler.run(dataKey):
observe(Alpha := alphaTrue, Beta := betaTrue, Sigma := sigmaTrue):
model(xData)
.yInstead of drawing from the model, we can ask for its density at given values of all variables. ModelScorer runs the model and returns the log-density of the joint distribution at the values we fix with observe. Here we fix the outcomes to the observed data and the parameters to their true values, and get the log-density of the joint distribution at these values:
val logDensity = ModelScorer.run:
observe(
Y := yData,
Alpha := alphaTrue,
Beta := betaTrue,
Sigma := sigmaTrue
):
model(xData)
.item
// logDensity: Float = -122.983185FFrom now on we pretend not to know the true values, and ask what the data
tells us about them. What we want is the posterior distribution: the distribution of the
parameters
The numerator is the joint density, with the outcomes fixed to the
observations. By the factorisation of our model it is the product of two
parts: the prior
As mentioned above, ModelScorer evaluates the joint log-density for any assignment of values to
all variables. The outcomes are given, so only the parameters are left to
choose, and for every
a function of the parameters alone. We can write it down directly, with
observe fixing all sites:
def logJoint(alpha: Float, beta: Array[Float], sigma: Float): Float =
ModelScorer.run:
observe(
Y := yData,
Alpha := Tensor0(alpha),
Beta := Tensor1(Axis[Feature]).fromArray(beta),
Sigma := Tensor0(sigma)
):
model(xData)
.itemAt the true parameters it is far higher than at, say,
logJoint(0.5f, Array(-1.5f, 2.0f), 0.8f)
// res3: Float = -122.983185F
logJoint(0f, Array(0f, 0f), 1f)
// res4: Float = -446.39734FAs every inference algorithm needs to evaluate the log-density at many values of the parameters, we turn this function into a first-class value. Latent does this: it takes a model with some sites observed and finds the latent sites.
val latent = Latent.discover:
observe(Y := yData):
model(xData)latent.sites.map(_.name)
// res5: Seq[String] = Vector("Alpha", "Beta", "Sigma")latent.logDensity is then the function above. Its argument has the type
latent.Params, made for this model: one value per latent site, in one
vector. To evaluate it, Latent fixes the latent sites to these values, so
that every site has a value, and runs ModelScorer.
How the values are laid out in the vector is an internal detail, so we do not
read it directly: latent.result(params) gives what the model returns at
given parameters, the same named tuple as the prior predictive draws above.
latent.init is a starting point for inference: the values of the traced
run, i.e. one draw of the parameters from the prior.
The latent is all an inference algorithm needs, and we hand it to NUTS next.
An MCMC method produces a sequence of draws
NUTS (the No-U-Turn Sampler) is such a method. It follows the gradient of the
log-density, which lets it take large steps through the parameter space. It
has tuning parameters, which NUTS.adapt sets in a warmup phase. The warmup
also moves the chain away from its starting point, so no draws need to be
discarded afterwards: adapted.sample continues where the warmup ended, and
returns the chain; samples gives the model's result at each draw, the same
named tuple as the prior predictive draws above.
val (warmupKey, sampleKey) = nutsKey.split2()
val adapted = NUTS.adapt(latent, warmupKey, latent.init, numSteps = 1000)
val nSamples = 2000
val nutsChain = adapted.sample(sampleKey, nSamples)
val samples = nutsChain.samplesFinally we summarise the posterior and compare it with the true values.
Summary.summary takes a sequence of chains, here just one, and picks the
quantities to summarise from the model's result at each draw, as a named
tuple. It gives one row per element of each quantity, with estimates from the
draws: the posterior mean, the posterior standard deviation and the 94%
highest density interval (HDI), the narrowest interval that holds 94% of the
draws. The HDI is a credible interval: given the data, the parameter lies in
it with probability 0.94. The last two columns are diagnostics, which we come
back to below.
println(summary(Seq(nutsChain))(s => (alpha = s.alpha, beta = s.beta, sigma = s.sigma)))
// parameter mean sd hdi 3% hdi 97% rhat ess
// alpha 0.408 0.074 0.259 0.544 1.000 2430
// beta[0] -1.495 0.080 -1.652 -1.351 1.000 2418
// beta[1] 1.978 0.075 1.832 2.112 1.000 2129
// sigma 0.743 0.055 0.643 0.843 1.000 1866
println(s"true values: alpha $alphaTrue, beta $betaTrue, sigma $sigmaTrue")
// true values: alpha 0.5, beta [-1.5 2. ], sigma 0.8All true values lie inside their 94% intervals. They do not match the posterior means exactly: with only 100 noisy observations, the data leaves some uncertainty about the parameters, and the standard deviations and intervals tell us how much.
Each draw also comes with diagnostic information from the sampler. A healthy run has no divergent transitions and a reasonably high acceptance rate:
val divergences = nutsChain.numDivergent
// divergences: Int = 0
val meanAcceptance = nutsChain.infos.map(_.acceptanceRate).sum / nutsChain.size
// meanAcceptance: Double = 0.910608547002077One chain cannot tell us whether it has explored the whole posterior. The
standard check is to run several chains from different starting points and
compare them. latent.initRandom draws a random starting point, as Stan
does. A chain is ordinary code: here a
warmup that tunes NUTS for this chain alone, followed by sampling.
def chain(key: Key, start: latent.Params) =
val (warmupKey, sampleKey) = key.split2()
val adapted = NUTS.adapt(latent, warmupKey, start)
adapted.sample(sampleKey, 1000)To run the chains at the same time, we run each in a Future:
import scala.concurrent.{Await, Future, blocking}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
val Seq(initKey, chainsKey) = nutsKey.split(2)
val starts = initKey.split(4).map(latent.initRandom(_))
val runs = chainsKey.split(4).zip(starts).map((key, start) => Future(blocking(chain(key, start))))
val chains = Await.result(Future.sequence(runs), Duration.Inf)The summary of all chains pools their draws. Its two diagnostic columns
compare the chains: rhat (R-hat) compares the variance between the chains
with the variance within them. Values close to 1 mean they agree, and values
above about 1.01 are a warning. ess, the effective sample size, estimates
how many independent draws the correlated draws of the chains are worth:
println(summary(chains)(s => (alpha = s.alpha, beta = s.beta, sigma = s.sigma)))
// parameter mean sd hdi 3% hdi 97% rhat ess
// alpha 0.408 0.074 0.271 0.550 1.000 4308
// beta[0] -1.496 0.080 -1.648 -1.347 1.000 4029
// beta[1] 1.982 0.078 1.837 2.133 0.999 4853
// sigma 0.744 0.054 0.637 0.838 0.999 3926The rows of beta are numbered by default; summary(chains, Axis[Feature].names(...))
names them. The diagnostics on their own, as tensors, are
Diagnostics.rhat and Diagnostics.ess, both in witdraw.inference.
NUTS is not the only inference method: MAP(latent) finds the posterior mode,
and Laplace(latent) approximates the posterior by a Gaussian around its mode
and is run like NUTS. Both are in witdraw.inference and take the same
latent.
The posterior draws are draws of
No new machinery is needed: this is the same model, the same observe and the
same ForwardSampler as in the prior predictive check. Only the values we fix
are different. Fixing the parameters is plain conditioning here, because they
are drawn before
val thinned = samples.grouped(10).map(_.head).toSeq
val replicated = replicateKey.split(thinned.size).zip(thinned).map { (key, s) =>
ForwardSampler.run(key):
observe(Alpha := s.alpha, Beta := s.beta, Sigma := s.sigma):
model(xData)
.y
}A posterior predictive check compares the replicated data sets with the
observed one. If the model describes the data well, the observed data should
look like a typical replication. We compare them through a statistic, here the
standard deviation of the outcomes,
As for the posterior mean, the fraction of replications for which this holds estimates this probability:
val replicatedSd = replicated.map(_.std.item)val observedSd = yData.std.item
// observedSd: Float = 2.5595632F
val pValue = replicatedSd.count(_ > observedSd).toFloat / replicatedSd.size
// pValue: Float = 0.56FA value close to 0 or 1 would mean that the observed spread is unusual under the model. Since we simulated the data from the model itself, we expect a value well away from both.
model above tells the whole story in one method. But the joint density has
two parts, the prior (using ProbContext) parameter, and calling it from another model runs it in
the same context.
The prior,
type Params = (alpha: Alpha.Value, beta: Beta.Value, sigma: Sigma.Value)
def prior(nFeatures: Int)(using ProbContext): Params =
val alpha = Alpha ~ Normal(0f, 10f)
val beta = Beta ~ Normal.isotropic(
Tensor1(Axis[Feature] -> nFeatures).fill(0f),
10f
)
val sigma = Sigma ~ HalfCauchy(0f, 5f)
(alpha = alpha, beta = beta, sigma = sigma)The likelihood,
def likelihood(
x: Tensor2[Sample, Feature, Float32],
params: Params
)(using ProbContext) =
val mu = x.dot(Axis[Feature])(params.beta) +! params.alpha
Y ~ Normal.isotropic(mu, params.sigma)The full model is their product, ProbProg[A], short for the
context function type ProbContext ?=> A. Writing prior inside the model
runs it, in the model's own context:
def regression(
x: Tensor2[Sample, Feature, Float32],
prior: ProbProg[Params]
)(using ProbContext) =
val params = prior
val y = likelihood(x, params)
(alpha = params.alpha, beta = params.beta, sigma = params.sigma, y = y)regression(xData, prior(nFeatures)) contains the same sites with the same
distributions as model(xData), so it can be used in exactly the same way,
from ForwardSampler to Latent.discover and NUTS. For example, both give
the same log-density at the true parameter values:
val nFeatures = xData.shape(Axis[Feature])
// nFeatures: Int = 2
def logDensityAtTruth(m: ProbProg[Any]): Float =
ModelScorer.run:
observe(Y := yData, Alpha := alphaTrue, Beta := betaTrue, Sigma := sigmaTrue):
m
.item
(logDensityAtTruth(model(xData)), logDensityAtTruth(regression(xData, prior(nFeatures))))
// res9: Tuple2[Float, Float] = (-122.983185F, -122.983185F)Because the prior is a parameter of regression, trying a different prior
does not touch the likelihood. Any program that yields Params fits,
for example one with tighter priors on the weights:
def tightPrior(nFeatures: Int)(using ProbContext): Params =
val alpha = Alpha ~ Normal(0f, 10f)
val beta = Beta ~ Normal.isotropic(
Tensor1(Axis[Feature] -> nFeatures).fill(0f),
1f
)
val sigma = Sigma ~ HalfCauchy(0f, 5f)
(alpha = alpha, beta = beta, sigma = sigma)
val tightSamples = priorKey.split(5).map { k =>
ForwardSampler.run(k)(regression(xData, tightPrior(nFeatures)))
}Two things to keep in mind when composing:
- A part that samples sites needs a
ProbContext, so it can only be called from a model, a handler or an interpreter. Calling it anywhere else is a compile error. - A site is identified by its object: two different objects are different sites, even if they share a name. Each site may be sampled only once per run when it is observed, traced or inferred; there, sampling it twice is an error.
Every step of this guide was a question asked of one joint distribution, and each has a direct counterpart in the code:
| Mathematics | Code |
|---|---|
| The joint distribution |
model(xData) |
| A draw |
ForwardSampler.run(key)(model(xData)) |
| A draw |
ForwardSampler.run(key)(observe(Alpha := …, …)(model(xData))) |
| The log-density |
ModelScorer.run(observe(Y := …, Alpha := …, …)(model(xData))) |
|
|
latent.logDensity, with latent = Latent.discover(observe(Y := yData)(model(xData)))
|
| Draws |
NUTS.adapt(latent, …).sample(…).samples |
| Posterior means, standard deviations, credible intervals | summary(chains)(…) |
| Draws |
ForwardSampler with observe of each posterior draw |
| Prior times likelihood, |
regression(xData, prior(nFeatures)), which runs prior, then likelihood
|