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.
| Algorithm | What it returns | Typical use |
|---|---|---|
| NUTS (Hamiltonian Monte Carlo) | Draws from the full posterior | Default for final, publishable inference |
| L-BFGS optimization | Posterior mode or penalized maximum likelihood | Fast point estimates and initial values |
| Laplace approximation | Normal approximation around the mode | Quick uncertainty estimates for well-behaved models |
| Pathfinder | Approximate draws from a variational path | Initialization and rapid model exploration |
| ADVI | Mean-field or full-rank Gaussian approximation | Large models where sampling is too slow |
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.
| Block | Purpose | When it runs |
|---|---|---|
data | Declares observed inputs and their sizes | Once, when data are read |
transformed data | Precomputes constants from the data | Once, before sampling |
parameters | Declares unknowns the sampler explores | Every gradient evaluation |
transformed parameters | Derives quantities from parameters | Every gradient evaluation |
model | Adds priors and likelihood to the log density | Every gradient evaluation |
generated quantities | Produces predictions and simulated data | Once per saved draw |
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.
| Tool | Model definition | Main inference strength | Discrete parameters |
|---|---|---|---|
| Stan | Standalone typed language compiled to C++ | Robust NUTS with rich diagnostics | Must be marginalized out |
| PyMC | Python objects on a tensor backend | NUTS plus mixed samplers | Supported through compound steps |
| Pyro and NumPyro | Python functions on PyTorch or JAX | Stochastic variational inference and NUTS | Supported with enumeration |
| JAGS and BUGS | Declarative graphical model language | Gibbs sampling | Supported natively |
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.
| Symptom | Likely cause | Typical fix |
|---|---|---|
| Divergent transitions | Strong curvature, often a funnel in hierarchical models | Non-centered parameterization or higher adapt_delta |
| R-hat above 1.01 | Chains have not mixed or converged | Longer runs, better priors or reparameterization |
| Low effective sample size | High autocorrelation between draws | Rescale parameters or simplify the model |
| Maximum treedepth hits | Long trajectories in flat or correlated regions | Stronger priors or a different parameterization |
| Low E-BFMI | Poor exploration of the energy distribution | Reparameterize heavy-tailed parameters |
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.