The challenge of truly probabilistic programming

Many years ago, Jouni and I wrote an unpublished paper called Fully Bayesian Computing:

A fully Bayesian computing environment calls for the possibility of defining vector and array objects that may contain both random and deterministic quantities, and syntax rules that allow treating these objects much like any variables or numeric arrays. Working within the statistical package R, we introduce a new object-oriented framework based on a new random variable data type that is implicitly represented by simulations.

A few years later we published an updated version of the paper under the title, Manipulating and summarizing posterior simulations using random variable objects. Here’s the background:

In the Bayesian paradigm, unknown quantities have probability distributions and are thus random variables. Observed values are just realizations of random variables, and constants may be thought of as random variables with point mass distributions. In mathematical notation, we deal with objects that are random variables, but in practice these objects are approximated by vectors of numbers, that is, simulations. Consequently, when programming for manipulating simulations of unknown quantities, we must write code to manipulate arrays of numeric constants.

And here’s the challenge:

Arrays of simulations are cumbersome objects to work with. Functions that work with vectors will not in general work with matrices, so special versions of the functions need to be written to accommodate matrices of simulations as arguments. For example, a scalar-valued random variable becomes a vector of simulations, and a random vector becomes a matrix of simulations. . . . The usual approach now is to use loops and vector-matrix computations to manipulate the matrix of posterior simulations. This approach is general but awkward and far from transparent . . .

As part of this effort, Jouni wrote a package in R called “rv” that allows direct manipulation of random variable objects, so for example if alpha and beta are random variables, each a vector of length J, and gamma is a scalar, then you can compute something like delta = (alpha + gamma)/beta, which would be a vector of length J. Internally, alpha, beta, and delta would be stored as S x K arrays, and gamma would be stored as an array of length S, where S is the number of simulation draws in your simulation frame, but the user would be able to work with these without having to keep track of that indexing; it would all be implicit.

The rv package was just a demonstration, but then more recently Paul Bürkner, Jonah Gabry, Matthew Kay, and Aki Vehtari implemented the idea in the “posterior” package in R. They call it rvar: The Random Variable Datatype. I still haven’t integrated rvar() into my Bayesian workflow, but I’d like to do it.

The point I want to make here is that this random variable datatype moves us closer to what I’d call “truly probabilistic programming.”

Here’s what I mean by that.

Stan (and Bugs, PyMC, etc.) are called “probabilistic programming languages,” characterized by Wikipedia as “based on the declarative specification of probabilistic models, for which inference is performed automatically.” Fair enough. In Stan, the variables defined in the parameters block, transformed parameters block, model block, and generated parameters block represent random variables with a joint density that is specified by the Stan program.

But, although this is called a probabilistic program as the term is used, it doesn’t fully feel like probabilistic programming in the sense of allowing me to grab random variables and work with them directly. I can do all that within the Stan program in the generated quantities block, but at a certain remove. Stan and other probabilistic programming languages are set up to run in batch mode: you specify a model and then the inference engine runs and spits out posterior simulations (or some other distributional summary).

To me, a truly probabilistic programming environment would allow me to interactively work with random variables, and to work with them as random variables, not as arrays of simulation draws. I want to be able to multiply two matrices without having to loop through the simulations. Part of this is about clean code, but more generally it’s about workflow. Any mathematical or graphical operations we can do on numbers, we should be able to do with random variables, with the simulations all hiding under the hood. Kind of by analogy to how we can do floating-point math on the computer without (usually) having to worry about how all these digits are being stored.

This will require tools such as rvar() and also some experience with the workflow. The payoff is . . . you could call it “better postprocessing of Bayesian simulations,” but I think that would understate the potential benefits of being able to work directl with uncertainty without that extra array dimension getting in your face at every step.

10 thoughts on “The challenge of truly probabilistic programming”

  1. I wonder if you’re familiar with work on functional probabilistic programming libraries like LazyPPL (http://lazyppl.org/)?
    This seems to be closer to the style you’re talking about, in terms of working with a random variable as a variable, manipulating it as if it was just a number, etc.
    But my sense is that there isn’t a huge amount of interaction between people working in this area and people doing practical statistics.

    • Closely related, see https://monad-bayes.netlify.app/ for similar examples. This kind of approach from programming langauge theory decouples the level of manipulating random variables from the interpretation as a sampler, which I think is exactly what you’re asking for. So for instance, one could write:

      x <- Normal 0 1
      y <- Normal 0 1
      z = x + y

      Here, z is a real random variable (or rather, a distribution) which you can manipulate directly, rather than a sample. In fact, this approach let's you have anything be random. One could even have a distribution over plots, as in the example in the above link.

  2. Having worked with brms, I’ve seen the rvar type in the wild a few times, and I knew after a few lines what this was about. It’s neat learning a bit of the history and the rationale behind this.
    For me, transparency means having all the draws in front of me if I have to operate with them, not abstracted away, but it’s a matter of taste.
    While the proposed concept is interesting, short of rerunning the model the draws are still static, so constants even if they stand for random variables. I still think from a workflow perspective it can be useful to treat them as a random vector instead of a static array.

  3. Andrew writes:

    Stan (and Bugs, PyMC, etc.) are called “probabilistic programming languages,” characterized by Wikipedia as “based on the declarative specification of probabilistic models, for which inference is performed automatically.” Fair enough.

    No! This is categorically wrong for Stan (and PyMC). Stan was designed as an imperative programming language, the polar opposite of a declarative language. For example, Stan requires every variable to be declared before it is used and it executes statements in the order they are written. BUGS is a declarative language. It defines a directed graphical model rather than defining operations. The reason the Church crowd, who built the tools from which LazyPPL descended, say that Stan is not a probabilistic programming language.

    What I mean when I say that Stan is a probabilistic programming language is that you can interpret its variables as random variables, exactly what Andrew is asking for. Andrew notes you can do this in the generated quantities block, but this holds throughout. We have observed random variables input as data, such as the y in a regression. We have transformed random variables such as expectations defined by regressions, such as the alpha + beta * x in a regression. We also have posterior predictive random variables, which can be defined much more efficiently in the generated quantities block because posterior predictive inference is neatly factored, for example, sampling parameters alpha, beta, and sigma conditional on data according to the model, then for a new x, generating normal_rng(alpha + beta * x_new, sigma) for posterior predictive simulation for y_new which you would do to make a forecast.

    There’s also an issue with how you do things jointly and keep everything in synch—all the random variables need to have the same number of draws that respect their joint distribution.

    Now what we don’t do with Stan is carry all of this over into R. You can try to do what you’re trying to do, but I would urge you to think through the design. If I define a random variable alpha ~ normal(0, 5), and that alpha is part of the aforementioned regression model, we are going to observe some (x, y) pairs and then update alpha. I’m not sure how that would work. I think some of these languages let you just say observe(x, y). But now everything is super stateful. You have prior alpha then you destructively update it. Or, if you don’t destructively update it, then you have a new random variable alpha_cond_xy that is conditioned on x and y and somehow related to alpha. Maybe I’m missing something here, but I’ve never been able to figure it out.

    A fully Bayesian computing environment calls for the possibility of defining vector and array objects that may contain both random and deterministic quantities, and syntax rules that allow treating these objects much like any variables or numeric arrays.

    Setting aside that Andrew explicitly concluded the post by asking for random variables “without that extra array dimension getting in your face at every step,” there’s an important reason we don’t do this in Stan. It’s the same reason that IEEE arithmetic does not have an NA value. Shoehorning concrete values (integer and floating point values) and NAs into a single containers is both a huge programming burden and very inefficient. It turns everything into a list and means every time you deal with a number, you have to check if it’s NA and do something different, which is really really really slow.

    It does buy you convenience. Stan will let you assign a concrete value to a random variable in a vector or array. To avoid the slowdown and complication of heterogeneous containers, Stan promotes data to essentially be a random variable with a fixed value (more concretely, an autodiff variable, which does incur some autodiff overhead). But the real problem is that it’s fussy to code. You have to define an N1-vector of observed value in the data block and then an N2-vector of missing values in the parameters block, then you need to weave them together based on a data declaration of missingness pattern in transformed parameters. Ben Goodrich had a really clever way of doing this, but I think it would still qualify as “getting in your face every step” up until the point where you want to use them. If you have a controlled system like brms, you could code this all up behind the scenes and just consume R’s inefficient mixed primitive/NA types as input and then code in Stan internals. We never figured out how to do this more elegantly at the level of generality required for Stan, where we don’t have control over the context. I’m also sorry to be the bearer of bad news that JAX is not going to make this easier as it also follows the natural and more efficient underlying coding like Stan, C++, and Python itself.

  4. The R package `rvec` implements the idea that any mathematical operation we can do on numbers, we should be able to do with random variables, at least to the extent that the basic design of R allows. For instance, `log(x)` or `df |> count(region, wt = x)` both work when `x` is an ordinary numeric vector and when `x` is an `rvec` holding draws from a distribution.

    For the `posterior` package’s `rvar` objects, `mean(x)` translates as “take the mean across draws, within each element of `x`”, while for `rvec` objects it means “take the mean across elements of `x`, within each draw”.

  5. This doesn’t get you as far as you’d like, but I think working in Julia has some benefits in this direction. I haven’t seriously used it in a few years – I’ve been in StanLand at work – but the general idea is that you can declare distributions in your code, e.g.

    “`
    using Distributions
    dist = Normal(0, 1)
    “`

    And then do things with these distributions, e.g. plot them:

    “`
    using StatsPlots
    plot(dist)
    “`

    and you’ll get a nice plot of the pdf. you can also sample from them:

    “`
    rand(dist)
    “`

    or use them in a Turing.jl model:

    “`
    using Turing # this example from the turing.jl [homepage](https://turinglang.org)

    @model function linear_regression(x)
    # Priors
    α ~ Normal(0, 1) # this Normal(0, 1) uses the same distributions machinery as the previous code blocks!
    β ~ Normal(0, 1)
    σ² ~ truncated(Cauchy(0, 3); lower=0)

    # Likelihood
    μ = α .+ β .* x
    y ~ MvNormal(μ, σ² * I)
    end

    posterior = linear_regression(x) | (; y = y) # note the very, very nice conditioning syntax that, in more complicated contexts,
    # [allows you to condition on different parts of the model](https://turinglang.org/DynamicPPL.jl/stable/conditionfix/)
    “`

    you can also compose turing models with other packages that also use Distributions.jl types, e.g. in this [hmm tutorial](https://turinglang.org/docs/tutorials/hidden-markov-models/#efficient-inference-with-the-forward-algorithm), which gives you a super concise hmm defined as:

    “`
    # I think Stan has nice enumeration functions now too (hmm_marginal), this is not an attempt to flex on Stan!
    # but it’s notable that the hmm machinery here was just another Julia package, not something intended to work with Turing.
    # disclosure: I wrote this tutorial
    @model function BayesHmm2(y, K)
    m ~ Bijectors.ordered(MvNormal([1.0, 2.0, 3.0], 0.5I))
    T ~ filldist(Dirichlet(fill(1/K, K)), K)

    hmm = HMM(softmax(ones(K)), copy(T’), [Normal(m[i], 0.1) for i in 1:K]) # note the use of distributions to define an HMM here
    @addlogprob! logdensityof(hmm, y) # which you can do things like query the logdensity of.
    end
    “`

    Now, this is missing the main thing I think you care about – algebra on the rvs – but this is pretty fussy for the reasons Bob Carpenter mentions. juggling that state in a repl also seems like a recipe for disaster. I actually think that the above setup solves a lot of the workflow problems here though … I’ve got probably way too much utility out of just `plot(dist)` for prior setting, and the fact that Turing models don’t pay the compilation cost that Stan models do is great for interactive use. Many models can sample (including compilation) in under a second or two, so you can iterate quickly through different prior parameterizations or whatever you want to test. The massive caveat here is that the MCMCChains output format is (was?) pretty rough to work with. I think I bizarrely spent 90+% of my time in some experiments just dim juggling, which is partially a function of how fast it is to specify a model. So:

    > “a truly probabilistic programming environment would allow me to interactively work with random variables, and to work with them as random variables, not as arrays of simulation draws. I want to be able to multiply two matrices without having to loop through the simulations.”

    only applies to the prior building block distributions* you put on the rhs of a `~`. Building up some helpers that go from draws arrays -> plots of quantities of interest + avoiding compiling an outside binary does really help here, though.

    The main issue with Julia is probably a type of Lisp disease … I mentioned Turing, Valentin above mentions RxInfer, there’s also, like, the [Soss / Tilde / MeasureTheory.jl universe](https://github.com/JuliaMath/MeasureTheory.jl) … maybe that’s dead now … and ofc you can use Stan w Julia too. In the past this has lead to some frustrating ecosystem correctness issues …

    —

    *the big caveat here is that it’s been a few years. looking at the work the Turing team has been doing, there’s all this stuff like defining and conditioning models:

    “`
    cond_model = model | observations
    “`

    and then apparently sampling from the prior of this model etc:

    “`
    rand(cond_model)
    loglikelihood(cond_model, parameters)
    “`

    I also see some stuff about [compositional models](https://turinglang.org/docs/usage/submodels/), e.g.

    “`
    @model function inner()
    a ~ Normal()
    return a + 100
    end

    @model function outer()
    x ~ to_submodel(inner())
    b ~ Normal(x)
    end

    # seems like you could do some cools stuff with this + epidemic models …
    “`

    I’m not sure how far you can take this stuff, but I could be really underselling the state of ppls in julia in 2026. rv composition doesn’t seem to exist, but this stuff is kinda adjacent from a workflow perspective, and seems very cool.

Leave a Reply

Your email address will not be published. Required fields are marked *