Probabilistic programming

Also known as: probabilistic programming language · PPL

On this page 7

Probabilistic programming is a paradigm in which a statistical model is written as an ordinary program that draws random variables, conditions them on observed data, and passes the result to a general-purpose inference engine that computes the posterior distribution automatically. Within probabilistic models, a branch of artificial intelligence, it separates two jobs that were once tangled together: describing the generative story of the data and implementing the algorithm that inverts that story.

A system that offers this capability is called a probabilistic programming language (PPL). Well-known examples include Stan, PyMC, Pyro, NumPyro, Turing.jl, Gen and the TensorFlow Probability library. The practical promise is that a modeler can change an assumption in one line and rerun Bayesian inference without deriving new update equations by hand.

How a probabilistic program describes a model

A probabilistic program is a generative model expressed in code: it states how latent quantities are drawn from their prior distributions and how observations are produced from those quantities. Two primitives carry the meaning. A sample statement introduces a random variable, and an observe or condition statement ties a random variable to a measured value.

Formally, the program defines a joint density over latent variables and data. Running it forward simulates synthetic data; conditioning on real data turns the same program into a question about the posterior distribution, that is, which latent values are plausible given what was observed. The engine never needs to know what the program means in domain terms; it only needs to evaluate or explore the joint density.

The table below lists the core building blocks that most PPLs share, even when their syntax differs.

ConstructRole in the modelTypical syntax
SampleDeclares a latent random variable with a priortheta ~ normal(0, 1)
ObserveConditions a variable on measured datay ~ normal(theta, sigma) with y given
FactorAdds an arbitrary term to the log densitytarget += log_weight
PlateMarks conditionally independent repetitionswith plate("data", N):
GuideDefines an approximating family for variational inferenceSeparate program with matching sites
Core constructs of a probabilistic program

Inference engines behind the language

The value of a PPL lies in its automatic inference backend, which turns a model description into posterior samples or an approximate distribution. Most engines rely on automatic differentiation to compute gradients of the log joint density, which makes gradient-based samplers and optimizers available for any differentiable model.

Different engines suit different model shapes. The following table compares the main families and their trade-offs.

MethodOutputStrengthsLimitations
Hamiltonian Monte Carlo with NUTSAsymptotically exact samplesRobust default for continuous modelsCannot handle discrete latents directly
Stochastic variational inferenceOptimized approximate posteriorScales to large data with mini-batchesUnderestimates variance; family choice matters
Sequential Monte CarloWeighted particle setsHandles time series and model evidenceWeight degeneracy in high dimensions
Gibbs and Metropolis-HastingsCorrelated samplesWorks with discrete variablesSlow mixing in correlated posteriors
Laplace approximationGaussian around the modeVery fastPoor for skewed or multimodal posteriors
Main inference methods used in probabilistic programming

Many systems also apply automatic transformations behind the scenes: constrained parameters such as variances are mapped to an unconstrained space, discrete variables may be marginalized out by enumeration, and conjugate structures can be detected and solved in closed form.

Types of probabilistic programming languages

PPLs differ mainly in how much program structure they allow and therefore in which inference methods they can guarantee. A key distinction separates languages with a fixed model structure from universal PPLs, whose programs may use unbounded recursion and stochastic control flow so that the number of random variables changes from run to run.

Design choiceExample systemsMain consequence
Standalone modeling languageStanCompiled, fast and well diagnosed, but less flexible
Embedded in PythonPyMC, Pyro, NumPyroIntegrates with data science and deep learning tools
Embedded in JuliaTuring.jl, GenComposable inference and native speed
Universal PPLPyro, Gen, AnglicanStochastic recursion; inference is harder to tune
Deep PPLPyro, TensorFlow ProbabilityNeural networks inside models; amortized inference
Design choices among probabilistic programming languages

Deep probabilistic programming combines neural networks with explicit random variables. A variational autoencoder, for example, can be written as a model program plus a neural guide, with amortized inference learning to map each observation to its approximate posterior in a single forward pass.

Probabilistic programming is broader than a probabilistic graphical model and more flexible than hand-written inference code. A Bayesian network fixes its structure as a graph, whereas a program can express loops, conditionals and data-dependent structure. Hand-derived samplers can be faster for one specific model, but every change of assumption forces new derivations.

  • Graphical models express conditional independence clearly but struggle with dynamic structure.
  • Custom inference code can be optimal for one model yet is costly to maintain and verify.
  • Classical machine learning libraries return point estimates, while a PPL returns a full posterior with uncertainty.
  • Simulation-based inference tools treat the simulator as a black box, whereas a PPL usually exposes the likelihood.

Practical workflow, limitations and common mistakes

Productive use follows a Bayesian workflow: simulate from the prior to check that assumptions produce plausible data, fit the model, inspect convergence diagnostics, and compare posterior predictions with held-out observations. Automating inference does not automate judgment, so the modeler remains responsible for prior choice, identifiability and model criticism.

The most frequent problems and their remedies are summarized below.

SymptomLikely causeRemedy
Divergent transitions in HMCFunnel geometry in hierarchical modelsUse a non-centered parameterization
R-hat above about 1.01Chains have not mixedRun longer, reparameterize or tighten priors
Low effective sample sizeStrong posterior correlationsRescale or decorrelate parameters
Overconfident variational posteriorMean-field family too restrictiveUse a richer guide or switch to MCMC
Prior predictive data are implausiblePriors too wide or mis-scaledChoose weakly informative priors
Typical problems in probabilistic programs

Performance remains the main limitation. MCMC on millions of observations can take hours, discrete latent structure often forces slower samplers, and universal programs may defeat general engines. A model that compiles is not necessarily a correct model: silent misspecification is a greater risk than a crash.

In simple terms

Probabilistic programming lets a person describe how data might have been produced and let the computer work backward. The description is written as code. It says which quantities are unknown and how they create the measurements.

The computer then finds which values of the unknowns fit the measurements best. It also reports how sure it is about each answer. Think of a detective who writes down every possible story, and a tireless assistant who checks every story against the evidence. The key idea is simple: the modeler writes the story, and the engine does the math.

A practical example

A regional hospital network wants to compare infection rates across 40 wards, some of which report only a handful of cases per month. Raw percentages from small wards swing wildly, so a quality analyst writes a hierarchical model in a Python-embedded PPL: each ward has its own rate, and all ward rates are drawn from a shared network-wide distribution.

The model takes about 30 lines of code. The NUTS sampler runs four chains of 2,000 draws in a few minutes, all R-hat values stay below 1.01, and posterior predictive checks match last year’s data. The result is a set of shrunken, uncertainty-aware ward estimates: two small wards that looked alarming are pulled toward the average, while one larger ward is flagged with a 95 percent credible interval clearly above the target. The infection control team focuses its audit on that ward instead of chasing noise.