- Introduced by
- Matthew D. Hoffman & Andrew Gelman
- Year
- 2014
- Type
- Sampling algorithm (MCMC)
What does it do?
The No-U-Turn Sampler (NUTS) is an adaptive Markov chain Monte Carlo algorithm, introduced by Hoffman and Gelman (2014), that extends Hamiltonian Monte Carlo (HMC) by choosing the number of leapfrog steps automatically.
This removes the trajectory-length setting that is most sensitive to user choice in plain HMC. NUTS is the default sampler in Stan and PyMC, which makes posterior inference for continuous models with many parameters practical without manual trajectory tuning.
The intuition behind the method
Hamiltonian Monte Carlo works by giving a particle (representing the parameter vector) a random kick of momentum and then letting it roll through the posterior landscape under simulated physics, moving efficiently along ridges and around curves without random-walk back-tracking. The weakness of plain HMC is that the user must choose how many steps to simulate before stopping; too few steps waste the trajectory, and too many make the particle double back on itself. NUTS addresses this by checking whether the trajectory has started to turn back, a 'U-turn', and stopping automatically just before that happens. The sampler therefore chooses a trajectory length adaptively at each iteration, adapts its step size by dual averaging during warm-up, and returns samples without the user setting either quantity by hand.
History
Hamiltonian Monte Carlo originates in physics as 'Hybrid Monte Carlo', introduced by Duane et al. (1987), and Radford Neal developed its use for Bayesian inference, culminating in his 2011 handbook chapter. The main practical limitation of HMC, the need to set the number of leapfrog steps L by hand, was addressed by Hoffman and Gelman (2014) in the Journal of Machine Learning Research. They introduced the No-U-Turn criterion together with dual averaging for step-size adaptation, and reported performance comparable to or better than carefully hand-tuned HMC on the benchmarks they examined. NUTS was adopted as the core sampler in Stan, and PyMC also uses it as the default sampler for continuous variables. Extensions addressing its limitations, including variants for discrete spaces, Riemannian geometry and stochastic gradients, remain an active research area.
When to use it
Choose NUTS for posterior sampling when the parameters are continuous and the log-posterior is differentiable with respect to them, with gradients supplied by automatic differentiation (as in Stan or PyMC) or by analytic gradients in a custom implementation. It is well suited to models with many correlated parameters, such as hierarchical and latent-variable models, where random-walk Metropolis-Hastings mixes slowly. It is not directly applicable when the model has discrete parameters that cannot be marginalised out, because gradients do not exist for them. For models with few parameters and very cheap likelihoods, a simpler sampler is often adequate, since the extra gradient cost per iteration may not be offset.
Limitations and considerations
- Requires a continuous, differentiable log-posterior; discrete parameters cannot be sampled directly and must be marginalised out or handled by a separate sampler.
- Each leapfrog step needs a full gradient of the log-posterior, so an iteration costs more than a Metropolis step; the extra cost pays off only when the posterior is hard enough for random-walk moves to mix poorly.
- Warm-up is needed to adapt the step size, and the adapted quantities are not used for inference, so warm-up draws are discarded before posterior summaries are computed.
- Posteriors with strongly varying curvature, such as funnel-shaped hierarchical geometries, can still challenge the sampler, and reparameterisation (for example a non-centred parameterisation) is often needed.
- Diagnosing failures requires interpreting energy diagnostics and divergent transitions, which is more demanding than checking a simple Metropolis chain.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Removes the trajectory-length parameter L that plain HMC requires, through the No-U-Turn stopping rule, so the user does not have to choose the number of leapfrog steps.
- Adapts the leapfrog step size during warm-up by dual averaging, so no manual step-size calibration is needed for a new model.
- Explores correlated, high-dimensional posteriors more efficiently than random-walk Metropolis, because trajectories follow the posterior geometry rather than taking small random steps.
- Is the default production sampler in Stan and PyMC, which provide built-in diagnostics such as R-hat, effective sample size and energy diagnostics.
- Scales to many parameters, so hierarchical and latent-variable models that are impractical with simpler MCMC become feasible.
Applications
- Fitting hierarchical and multilevel Bayesian models in psychology, education, ecology and epidemiology.
- Bayesian regression and generalised linear models where full posterior uncertainty is needed rather than point estimates.
- Structural equation and latent-variable models in the social sciences, where the posterior over latent factors is high-dimensional.
- Bayesian time-series and state-space models.
- Pharmacokinetic and pharmacodynamic (PK/PD) modelling in clinical trials.
- Astrophysical parameter estimation and cosmological inference.
- Any continuous Bayesian model written in Stan or PyMC where posterior sampling is the inferential objective.
How it works
How it works
NUTS operates on the augmented space of model parameters θ and auxiliary momentum variables r. The Hamiltonian H(θ, r) is the sum of the negative log-posterior (potential energy) and a kinetic energy term determined by the mass matrix M. At each iteration, r is resampled from a zero-mean Gaussian, and the joint (θ, r) state evolves along a Hamiltonian trajectory that leaves the joint density exactly invariant. In common implementations, such as Stan and PyMC, the mass matrix M is also adapted during warm-up, using the variability of the warm-up draws. It is usually diagonal and sometimes dense. This rescales the momentum to suit the posterior geometry but does not change the target distribution.
Formula
H(\theta, r) = -\log p(\theta \mid y) + \tfrac{1}{2}\,r^\top M^{-1} rThe trajectory is simulated using the leapfrog integrator, a symplectic, time-reversible, volume-preserving numerical scheme. Each leapfrog step updates the momentum by a half-step using the gradient of the log-posterior, advances the position by a full step, then completes the momentum update with another half-step. This preserves the Hamiltonian approximately and keeps the acceptance rate high even with large step sizes.
Formula
r_{t+\varepsilon/2} = r_t + \tfrac{\varepsilon}{2}\,\nabla_\theta \log p(\theta_t \mid y), \quad \theta_{t+\varepsilon} = \theta_t + \varepsilon\, M^{-1} r_{t+\varepsilon/2}, \quad r_{t+\varepsilon} = r_{t+\varepsilon/2} + \tfrac{\varepsilon}{2}\,\nabla_\theta \log p(\theta_{t+\varepsilon} \mid y)NUTS builds the trajectory by repeatedly doubling the number of leapfrog steps, in one direction or the other, to form a binary tree of candidate points. Doubling stops when the displacement vector (θ⁺ − θ⁻) starts to point against the momentum at either end of the tree, that is, when either (θ⁺ − θ⁻)·r⁺ or (θ⁺ − θ⁻)·r⁻ becomes negative. This is the No-U-Turn condition: it signals that the trajectory would begin to retrace itself, so the simulation ends without a user-specified step count L. The criterion is also checked on subtrees as the tree is built, not only at its two ends. In practice, implementations cap the tree depth, which bounds the trajectory length. Reaching that cap is reported as a diagnostic warning and is not a convergence result. The next state is then drawn from the tree using a biased progressive sampling scheme.
Formula
(\theta^+ - \theta^-)\cdot r^+ \geq 0 \quad \text{and} \quad (\theta^+ - \theta^-)\cdot r^- \geq 0During warm-up, NUTS uses Nesterov's dual averaging to adapt the leapfrog step size ε so that the average Metropolis acceptance probability approaches a target δ (typically 0.8). The log step size is driven toward μ = log(10ε₀), while the running average H̄ₘ accumulates the gap between the target and the realised acceptance rate. After warm-up, the step size is fixed at a value derived from the adaptation phase and is not updated further during sampling.
Formula
\bar{H}_m = \left(1 - \tfrac{1}{m+t_0}\right)\bar{H}_{m-1} + \tfrac{1}{m+t_0}\left(\delta - \alpha_m\right), \quad \log\varepsilon_m = \mu - \tfrac{\sqrt{m}}{\gamma}\bar{H}_mCommon pitfalls
- Ignoring divergent transitions: a divergence means the leapfrog integrator lost accuracy, typically in a region of high curvature, so samples from that region may be biased. Remedies are reparameterisation or raising the target acceptance rate, which reduces the step size and improves integration accuracy; lowering the target acceptance rate enlarges the step size and tends to make divergences more likely.
- Treating warm-up samples as posterior draws: warm-up iterations serve only for adaptation and must be discarded before inference.
- Skipping convergence diagnostics: R-hat above 1.01, or low bulk or tail effective sample size, indicates that the chains have not mixed, and estimates from them are unreliable however long the chains run.
- Neglecting posterior predictive checks: a well-mixing sampler can still fit a misspecified model, so simulated data from the posterior should be compared with the observed data.
- Assuming NUTS needs no model-specific work: deep hierarchical models often need a non-centred reparameterisation before NUTS can sample them efficiently.
Frequently asked questions
What is the difference between NUTS and plain Hamiltonian Monte Carlo?
Standard HMC requires the user to specify two parameters: the leapfrog step size ε and the number of leapfrog steps L. Choosing L poorly leads either to slow mixing (too few steps) or to wasted computation when the trajectory doubles back (too many steps). NUTS replaces the fixed L with the No-U-Turn stopping criterion: it doubles the trajectory until it detects a U-turn and then selects a point from the resulting tree, so L is set automatically. Step size is handled by dual averaging during warm-up. Users therefore do not need to tune L, and in the benchmarks reported by Hoffman and Gelman (2014) the performance was competitive with carefully tuned HMC.
What are divergent transitions and why do they matter?
A divergent transition occurs when the leapfrog integrator becomes inaccurate, typically in a region of high curvature, so that the simulated Hamiltonian departs substantially from its starting value. The sampler has then entered a region it cannot integrate reliably, and samples from that region can be biased. Stan and PyMC flag divergences explicitly. Even a small number of divergences should be investigated and reported rather than dismissed. The usual remedies are reparameterising the model, for example from a centred to a non-centred parameterisation for hierarchical models, or raising the target acceptance rate, which reduces the step size and improves integration accuracy.
How should I assess NUTS convergence?
Run several chains from dispersed starting values and check the following: R-hat below 1.01 for all parameters, since larger values indicate that the chains have not converged to a common distribution; adequate bulk and tail effective sample size, where tail quantiles usually need more effective draws than the mean; near-zero divergent transitions after reparameterisation; energy diagnostics without warning signs; and trace plots that mix well, with no trends or stuck regions.
Can NUTS sample discrete parameters?
No. NUTS requires gradients of the log-posterior with respect to the parameters, which are undefined for discrete quantities. Models with discrete parameters must either marginalise those parameters out analytically, as Stan requires, or handle them with a separate sampler. PyMC supports some compound samplers that pair NUTS for continuous parameters with Metropolis-Hastings steps for discrete ones, but mixing can be slow when discrete and continuous parameters are strongly dependent.
Related methods
Sources
Hoffman, M. D., & Gelman, A. (2014). The No-U-Turn Sampler: Adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47), 1593–1623.
Open publication referenceNeal, R. M. (2011). MCMC using Hamiltonian dynamics. In S. Brooks, A. Gelman, G. L. Jones, & X.-L. Meng (Eds.), Handbook of Markov Chain Monte Carlo (pp. 113–162). CRC Press.
Open DOI referenceGelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian Data Analysis (3rd ed.). CRC Press.
ISBN: 978-1-4398-4095-5