Skip to content

1. Your first model

Bayesian linear regression in QVR, the modeling language of quivers: declare the model, simulate data, fit it by stochastic variational inference (SVI) (Hoffman et al., 2013), and summarize the posterior. Each QVR program carries a typed signature, and the compiler checks the program before any tensor is evaluated.

Installation

pip install quivers

The following block compiles a one-line module and prints the class of the result:

from quivers.dsl import loads

src = """
object A : FinSet 3
morphism f : A -> A [role=parameter]
export f
"""
print(type(loads(src)).__name__)   # Program

The model

Let \(y_1, \dots, y_n\) be real responses, \(x_i\) a scalar predictor for response \(i\), \(\beta_0\) and \(\beta_1\) an intercept and a slope, and \(\sigma\) a noise scale:

\[ \beta_0 \sim \mathrm{Normal}(0, 5), \qquad \beta_1 \sim \mathrm{Normal}(0, 2), \qquad \sigma \sim \mathrm{HalfNormal}(1), \qquad y_i \sim \mathrm{Normal}(\beta_0 + \beta_1 x_i, \sigma). \]

QVR, PyMC, and NumPyro

object Item : FinSet 100

program regression : Item -> Item
    let sigma  <- sample HalfNormal(scale=1.0)
    let beta_0 <- sample Normal(loc=0.0, scale=5.0)
    let beta_1 <- sample Normal(loc=0.0, scale=2.0)
    let mu = beta_0 + beta_1 * x_design
    observe y : Item <- Normal(loc=mu, scale=sigma)
    return y

export regression

import pymc as pm

with pm.Model() as model:
    sigma  = pm.HalfNormal("sigma", 1.0)
    beta_0 = pm.Normal("beta_0", 0.0, 5.0)
    beta_1 = pm.Normal("beta_1", 0.0, 2.0)
    mu     = beta_0 + beta_1 * x_data
    y      = pm.Normal("y", mu, sigma, observed=y_data)

import numpyro
import numpyro.distributions as dist

def regression(x, y=None):
    sigma  = numpyro.sample("sigma", dist.HalfNormal(1.0))
    beta_0 = numpyro.sample("beta_0", dist.Normal(0.0, 5.0))
    beta_1 = numpyro.sample("beta_1", dist.Normal(0.0, 2.0))
    mu     = beta_0 + beta_1 * x
    numpyro.sample("y", dist.Normal(mu, sigma), obs=y)

The QVR declarations, in order:

Declaration Meaning
object Item : FinSet 100 A finite set Item of size 100 that indexes the rows of the data.
program regression : Item -> Item A probabilistic program with domain Item and codomain Item.
let sigma <- sample HalfNormal(scale=1.0) Draw a latent variable, as pm.HalfNormal(...) in PyMC or numpyro.sample(...) in NumPyro.
let mu = beta_0 + beta_1 * x_design A deterministic binding. x_design is bound nowhere in the program, so the compiler records it as a data input: a name the program reads but does not bind, given at run time with the observations (Stan's data block plays the same part).
observe y : Item <- Normal(loc=mu, scale=sigma) A vectorized observe statement, one draw for each element of Item. At inference time y takes its observed value, and the step adds its log likelihood to the program's log joint density.

Effect signatures

The compiler infers which of four effects a program body performs:

Effect Meaning Performed by
Pure no draws and no conditioning let only
Sample draws latent variables let v <- sample F(...)
Score conditions on observations observe v <- F(...)
Marginal sums out a discrete latent variable marginalize z : K <- ... with an indented body

An option [effects=[...]] on the program declaration states the set, and the compiler rejects a body that performs an effect outside it. With [effects=[Pure]] on regression, loads raises

CompileError: line 4, col 0: program 'regression' is declared as Pure but body uses effects ['Sample', 'Score']

and with [effects=[Sample]] it reports that the body uses Score. Pyro and NumPyro find such a mistake only when the model runs.

Data inputs and the observations dict

The model interface derives input names, types, and observation roles from the checked program. Model(source).bind(data) checks the given values before fitting; neither a guide nor an extra list of observed names is required. object Item : FinSet _ also permits the data to fix the number of rows, and optional typed parameters in the program header constrain external values.

The component-level workflow below constructs a guide and an optimizer explicitly to explain SVI. At this level, AutoNormalGuide still accepts observed_names, and each inference step receives an observations mapping. Both the response y and the covariate x_design belong in that mapping. For a complete example using the reusable interface, start with checked model fitting.

Compile and fit

loads returns a Program, a PyTorch nn.Module. Its morphism attribute is the compiled MonadicProgram, which the inference drivers in quivers.inference fit. Any PyTorch optimizer can also train its parameters directly.

import torch
from quivers.dsl import loads
from quivers.inference import AutoNormalGuide, ELBO, SVI

REGRESSION_SRC = """
object Item : FinSet 100

program regression : Item -> Item
    let sigma <- sample HalfNormal(scale=1.0)
    let beta_0 <- sample Normal(loc=0.0, scale=5.0)
    let beta_1 <- sample Normal(loc=0.0, scale=2.0)
    let mu = beta_0 + beta_1 * x_design
    observe y : Item <- Normal(loc=mu, scale=sigma)
    return y

export regression
"""

program = loads(REGRESSION_SRC)
model   = program.morphism                   # the compiled MonadicProgram

# Synthetic data.
torch.manual_seed(0)
x_data = torch.randn(100)
y_data = 1.5 + 2.7 * x_data + 0.3 * torch.randn(100)

# Variational inference. ``x_design`` is a free name in the model body;
# we hand it to the trace via ``observed_names`` and the observations dict.
guide     = AutoNormalGuide(model, observed_names={"y", "x_design"})
elbo      = ELBO(num_particles=1)
optimizer = torch.optim.Adam(
    list(model.parameters()) + list(guide.parameters()), lr=1e-2,
)
svi = SVI(model, guide, optimizer, elbo)

x_tensor = torch.zeros(1, 1)                  # one row: one run of the program
observations = {"x_design": x_data, "y": y_data}
for step in range(50):                        # bump to ~2000 for real fits
    loss = svi.step(x_tensor, observations)

The loop has Pyro's structure: a Guide holds the variational family, an Objective such as the evidence lower bound (ELBO) is the loss, and an SVI driver takes the gradient steps. x_tensor is the program's input. Each row of the input is one independent run of the program, and a program whose observations live on Item takes an input with one row (input rows are independent runs).

AutoNormalGuide is a mean-field Gaussian guide: each latent variable, mapped to an unconstrained scale, gets an independent Normal factor (Blei et al., 2017). SVI trains it with the reparameterization (pathwise) gradient (Kingma and Welling, 2014). A mean-field guide cannot represent posterior correlation between the intercept and the slope. A full-covariance guide can.

Inspect the posterior

Predictive draws from a trained Guide or an MCMCResult and returns a dict of (num_samples, ...) tensors, one for every latent variable and every observed response:

from quivers.inference import Predictive

predictive = Predictive(model, posterior=guide, num_samples=1000)
draws = predictive(x_tensor, {"x_design": x_data})
print("posterior mean beta_0 =", draws["beta_0"].mean().item())
print("posterior mean beta_1 =", draws["beta_1"].mean().item())
print("posterior mean sigma  =", draws["sigma"].mean().item())
print("predictive mean y[0] =", draws["y"][:, 0].mean().item())   # draws["y"]: (1000, 100, 1)

Predictive batches the draws, passes the same data inputs to every replicate, and returns posterior predictive draws of y in the same call. After the 50 steps above the guide is far from converged (the posterior mean of beta_1 is about 0.43 against a true slope of 2.7). Raise the step count to about 2000 for a usable fit.

Try this

Next

Chapter 2 replaces the Normal likelihood with Bernoulli and Poisson likelihoods: logistic and Poisson regression.

Cited sources

Matthew D. Hoffman, David M. Blei, Chong Wang, and John Paisley. Stochastic Variational Inference. Journal of Machine Learning Research, 14(40):1303–1347, 2013. URL: https://www.jmlr.org/papers/v14/hoffman13a.html.

David M. Blei, Alp Kucukelbir, and Jon D. McAuliffe. Variational Inference: A Review for Statisticians. Journal of the American Statistical Association, 112(518):859–877, 2017. URL: https://doi.org/10.1080/01621459.2017.1285773, doi:10.1080/01621459.2017.1285773.

Diederik P. Kingma and Max Welling. Auto-Encoding Variational Bayes. In International Conference on Learning Representations. 2014. Accepted conference paper; manuscript available as arXiv:1312.6114. URL: https://arxiv.org/abs/1312.6114, doi:10.48550/arXiv.1312.6114.