Stan · probabilistic programming

On this page 8

Stan is an open-source probabilistic programming language and inference platform for specifying Bayesian statistical models and estimating them with Hamiltonian Monte Carlo, optimization and approximate variational methods. Among AI frameworks & tools, it occupies the niche of principled uncertainty quantification: instead of returning a single best prediction, a Stan model returns a full posterior distribution over every unknown parameter.

A user writes a model in a compact, statically typed language, and Stan compiles it to C++ with automatic differentiation built in. The same program can then be run from R, Python, Julia, the command line and other interfaces, which makes Stan a common reference implementation for applied Bayesian work in epidemiology, pharmacology, economics, ecology and the social sciences. Not to be confused with unrelated software or acronyms that share the name.

How Stan turns a model into posterior draws

Stan works by translating a declarative model into a log probability density function and then exploring that function with a sampler. The model code states how data arise from parameters, and Stan computes the unnormalized log posterior and its gradient for any parameter value.

The default algorithm is the No-U-Turn Sampler (NUTS), an adaptive form of Hamiltonian Monte Carlo. NUTS treats parameters as the position of a particle, uses the gradient of the log density to simulate its motion, and stops each trajectory automatically when it starts to double back. Gradients come from Stan’s reverse-mode automatic differentiation library, so users never derive them by hand.

Constrained parameters, such as a standard deviation that must be positive or a probability simplex, are transformed to unconstrained space behind the scenes, with the required Jacobian adjustment applied automatically. During a warmup phase, Stan tunes the step size and a mass matrix so that sampling proceeds efficiently afterward.

The table below summarizes the main inference engines that ship with Stan.

AlgorithmWhat it returnsTypical use
NUTS (Hamiltonian Monte Carlo)Draws from the full posteriorDefault for final, publishable inference
L-BFGS optimizationPosterior mode or penalized maximum likelihoodFast point estimates and initial values
Laplace approximationNormal approximation around the modeQuick uncertainty estimates for well-behaved models
PathfinderApproximate draws from a variational pathInitialization and rapid model exploration
ADVIMean-field or full-rank Gaussian approximationLarge models where sampling is too slow
Inference algorithms available in Stan

Structure of a Stan program

Every Stan program is organized into named blocks that execute at different times, which keeps data handling, parameter declarations and modeling logic clearly separated. Variables carry explicit types and constraints, for example real<lower=0> sigma;, so many specification errors are caught at compile time rather than during sampling.

BlockPurposeWhen it runs
dataDeclares observed inputs and their sizesOnce, when data are read
transformed dataPrecomputes constants from the dataOnce, before sampling
parametersDeclares unknowns the sampler exploresEvery gradient evaluation
transformed parametersDerives quantities from parametersEvery gradient evaluation
modelAdds priors and likelihood to the log densityEvery gradient evaluation
generated quantitiesProduces predictions and simulated dataOnce per saved draw
Program blocks and their roles

Statements such as y ~ normal(mu, sigma); add terms to the log density rather than draw random numbers, a point that often surprises newcomers. The generated quantities block is where posterior predictive checks and forecasts are written, because it runs only on accepted draws and does not affect the gradient.

Stan compared with other probabilistic programming tools

Stan differs from neighboring tools mainly in its dedicated modeling language and its focus on gradient-based sampling for continuous parameters. PyMC, Pyro and NumPyro embed models in Python code instead, which eases integration with deep learning pipelines but ties the model to one host language.

ToolModel definitionMain inference strengthDiscrete parameters
StanStandalone typed language compiled to C++Robust NUTS with rich diagnosticsMust be marginalized out
PyMCPython objects on a tensor backendNUTS plus mixed samplersSupported through compound steps
Pyro and NumPyroPython functions on PyTorch or JAXStochastic variational inference and NUTSSupported with enumeration
JAGS and BUGSDeclarative graphical model languageGibbs samplingSupported natively
Stan and related tools

The most consequential difference is that Stan cannot sample discrete parameters directly. Mixture models and change-point models must be rewritten so that discrete states are summed out of the likelihood, which is more work for the modeler but usually yields faster, more stable inference.

Interfaces, ecosystem and deployment

Stan is used through thin interfaces that call the same compiled core. CmdStan is the command-line foundation; CmdStanR and CmdStanPy wrap it for R and Python, while the older RStan and PyStan packages embed the engine in-process. Higher-level packages such as brms and rstanarm generate Stan code from familiar regression formulas, so analysts can fit multilevel models without writing Stan syntax.

Companion libraries cover the rest of the Bayesian workflow: ArviZ and the bayesplot and posterior packages handle diagnostics and visualization, and loo computes leave-one-out cross-validation for model comparison. Stan supports within-chain parallelism through the reduce_sum function and can run multiple chains on separate cores, and some linear algebra can be offloaded to GPUs through OpenCL.

Diagnosing and tuning Stan models

Stan reports convergence diagnostics by default, and reading them correctly is the core practical skill. Healthy runs typically use four chains with 1,000 warmup and 1,000 sampling iterations each, although harder models may need more.

SymptomLikely causeTypical fix
Divergent transitionsStrong curvature, often a funnel in hierarchical modelsNon-centered parameterization or higher adapt_delta
R-hat above 1.01Chains have not mixed or convergedLonger runs, better priors or reparameterization
Low effective sample sizeHigh autocorrelation between drawsRescale parameters or simplify the model
Maximum treedepth hitsLong trajectories in flat or correlated regionsStronger priors or a different parameterization
Low E-BFMIPoor exploration of the energy distributionReparameterize heavy-tailed parameters
Common warnings and remedies

A frequent mistake is to suppress divergences by raising `adapt_delta` alone. That only shrinks the step size; if the geometry is pathological, the posterior estimates remain biased, and the honest fix is to change the parameterization or the priors.

Strengths and limitations of Stan

Stan’s main strength is reliable, well-diagnosed inference for models with tens to tens of thousands of continuous parameters. Its limitations are equally clear and should guide tool choice.

  • No direct discrete sampling: discrete latent variables must be marginalized analytically.
  • Compilation overhead: each model change triggers a C++ build that can take tens of seconds.
  • Scaling limits: full MCMC becomes slow on millions of observations or very high-dimensional neural models.
  • Learning curve: effective use requires understanding priors, parameterization and diagnostics, not only syntax.

Stripped to the essentials

Stan is a tool for reasoning under uncertainty. You describe how you think your data came about. Stan then works backward. It finds every set of values that could plausibly explain what you saw.

Think of a detective who keeps a list of suspects with odds. Each new clue shifts the odds. Stan does the same with numbers. The result is not one answer but a range of answers with their probabilities. That range tells you how sure you can be.

Where it is applied

A public health team estimates vaccination coverage in 60 districts from household surveys. Some districts have 2,000 respondents, others only 40. Treating each district alone gives wildly unstable estimates for the small ones, while pooling everything hides real differences.

The analysts write a hierarchical logistic model in Stan with district-level intercepts drawn from a common distribution. The first run produces several hundred divergent transitions, so they switch to a non-centered parameterization. The second run shows no divergences and R-hat values below 1.01 for every parameter.

The result is partial pooling: small districts borrow strength from the regional average, and each estimate carries a 90 percent credible interval. The ministry uses those intervals to send outreach teams to the twelve districts most likely below target, rather than to the districts whose raw numbers merely looked worst.