Wednesday, March 22, 2023

A really first conceptual introduction to Hamiltonian Monte Carlo

Why a very (that means: VERY!) first conceptual introduction to Hamiltonian Monte Carlo (HMC) on this weblog?

Nicely, in our endeavor to characteristic the varied capabilities of TensorFlow Chance (TFP) / tfprobability, we began displaying examples of tips on how to match hierarchical fashions, utilizing one in every of TFP’s joint distribution courses and HMC. The technical points being advanced sufficient in themselves, we by no means gave an introduction to the “math facet of issues.” Right here we try to make up for this.

Seeing how it’s not possible, in a brief weblog submit, to offer an introduction to Bayesian modeling and Markov Chain Monte Carlo on the whole, and the way there are such a lot of glorious texts doing this already, we’ll presuppose some prior data. Our particular focus then is on the newest and biggest, the magic buzzwords, the well-known incantations: Hamiltonian Monte Carlo, leapfrog steps, NUTS – as at all times, making an attempt to demystify, to make issues as comprehensible as potential.
In that spirit, welcome to a “glossary with a story.”

So what’s it for?

Sampling, or Monte Carlo, strategies on the whole are used once we need to produce samples from, or statistically describe a distribution we don’t have a closed-form formulation of. Typically, we would actually have an interest within the samples; generally we simply need them so we will compute, for instance, the imply and variance of the distribution.

What distribution? In the kind of functions we’re speaking about, we have now a mannequin, a joint distribution, which is meant to explain some actuality. Ranging from probably the most fundamental situation, it’d appear to be this:

x sim mathcal{Poisson}(lambda)

This “joint distribution” solely has a single member, a Poisson distribution, that’s imagined to mannequin, say, the variety of feedback in a code assessment. We even have knowledge on precise code opinions, like this, say:

We now need to decide the parameter, (lambda), of the Poisson that make these knowledge most doubtless. To date, we’re not even being Bayesian but: There isn’t a prior on this parameter. However in fact, we need to be Bayesian, so we add one – think about mounted priors on its parameters:

x sim mathcal{Poisson}(lambda)
lambda sim gamma(alpha, beta)
alpha sim […]
beta sim […]

This being a joint distribution, we have now three parameters to find out: (lambda), (alpha) and (beta).
And what we’re enthusiastic about is the posterior distribution of the parameters given the info.

Now, relying on the distributions concerned, we normally can’t calculate the posterior distributions in closed type. As a substitute, we have now to make use of sampling strategies to find out these parameters. What we’d wish to level out as an alternative is the next: Within the upcoming discussions of sampling, HMC & co., it’s very easy to overlook what’s it that we’re sampling. Attempt to at all times understand that what we’re sampling isn’t the info, it’s parameters: the parameters of the posterior distributions we’re enthusiastic about.


Sampling strategies on the whole include two steps: producing a pattern (“proposal”) and deciding whether or not to maintain it or to throw it away (“acceptance”). Intuitively, in our given situation – the place we have now measured one thing and at the moment are searching for a mechanism that explains these measurements – the latter needs to be simpler: We “simply” want to find out the probability of the info below these hypothetical mannequin parameters. However how can we give you strategies to start out with?

In principle, simple(-ish) strategies exist that could possibly be used to generate samples from an unknown (in closed type) distribution – so long as their unnormalized chances might be evaluated, and the issue is (very) low-dimensional. (For concise portraits of these strategies, comparable to uniform sampling, significance sampling, and rejection sampling, see(MacKay 2002).) These should not utilized in MCMC software program although, for lack of effectivity and non-suitability in excessive dimensions. Earlier than HMC grew to become the dominant algorithm in such software program, the Metropolis and Gibbs strategies had been the algorithms of alternative. Each are properly and understandably defined – within the case of Metropolis, usually exemplified by good tales –, and we refer the reader to the go-to references, comparable to (McElreath 2016) and (Kruschke 2010). Each had been proven to be much less environment friendly than HMC, the primary subject of this submit, as a result of their random-walk habits: Each proposal is predicated on the present place in state house, that means that samples could also be extremely correlated and state house exploration proceeds slowly.


So HMC is common as a result of in comparison with random-walk-based algorithms, it’s a lot extra environment friendly. Sadly, additionally it is much more troublesome to “get.” As mentioned in Math, code, ideas: A 3rd highway to deep studying, there appear to be (no less than) three languages to specific an algorithm: Math; code (together with pseudo-code, which can or might not be on the verge to math notation); and one I name conceptual which spans the entire vary from very summary to very concrete, even visible. To me personally, HMC is totally different from most different instances in that regardless that I discover the conceptual explanations fascinating, they end in much less “perceived understanding” than both the equations or the code. For folks with backgrounds in physics, statistical mechanics and/or differential geometry this can in all probability be totally different!

In any case, bodily analogies make for the perfect begin.

Bodily analogies

The basic bodily analogy is given within the reference article, Radford Neal’s “MCMC utilizing Hamiltonian dynamics” (Neal 2012), and properly defined in a video by Ben Lambert.

So there’s this “factor” we need to maximize, the loglikelihood of the info below the mannequin parameters. Alternatively we will say, we need to decrease the adverse loglikelihood (like loss in a neural community). This “factor” to be optimized can then be visualized as an object sliding over a panorama with hills and valleys, and like with gradient descent in deep studying, we wish it to finish up deep down in some valley.

In Neal’s personal phrases

In two dimensions, we will visualize the dynamics as that of a frictionless puck that slides over a floor of various top. The state of this method consists of the place of the puck, given by a 2D vector q, and the momentum of the puck (its mass occasions its velocity), given by a 2D vector p.

Now while you hear “momentum” (and provided that I’ve primed you to think about deep studying) chances are you’ll really feel that sounds acquainted, however regardless that the respective analogies are associated the affiliation doesn’t assist that a lot. In deep studying, momentum is often praised for its avoidance of ineffective oscillations in imbalanced optimization landscapes.
With HMC nonetheless, the main focus is on the idea of vitality.

In statistical mechanics, the chance of being in some state (i) is inverse-exponentially associated to its vitality. (Right here (T) is the temperature; we received’t give attention to this so simply think about it being set to 1 on this and subsequent equations.)

[P(E_i) sim e^{frac{-E_i}{T}} ]

As you may or may not keep in mind from college physics, vitality is available in two types: potential vitality and kinetic vitality. Within the sliding-object situation, the item’s potential vitality corresponds to its top (place), whereas its kinetic vitality is expounded to its momentum, (m), by the formulation

[K(m) = frac{m^2}{2 * mass} ]

Now with out kinetic vitality, the item would slide downhill at all times, and as quickly because the panorama slopes up once more, would come to a halt. By its momentum although, it is ready to proceed uphill for some time, simply as if, going downhill in your bike, you choose up pace chances are you’ll make it over the following (brief) hill with out pedaling.

In order that’s kinetic vitality. The opposite half, potential vitality, corresponds to the factor we actually need to know – the adverse log posterior of the parameters we’re actually after:

[U(theta) sim – log (P(x | theta) P(theta))]

So the “trick” of HMC is augmenting the state house of curiosity – the vector of posterior parameters – by a momentum vector, to enhance optimization effectivity. After we’re completed, the momentum half is simply thrown away. (This facet is very properly defined in Ben Lambert’s video.)

Following his exposition and notation, right here we have now the vitality of a state of parameter and momentum vectors, equaling a sum of potential and kinetic energies:

[E(theta, m) = U(theta) + K(m)]

The corresponding chance, as per the connection given above, then is

[P(E) sim e^{frac{-E}{T}} = e^{frac{- U(theta)}{T}} e^{frac{- K(m)}{T}}]

We now substitute into this equation, assuming a temperature (T) of 1 and a mass of 1:

[P(E) sim P(x | theta) P(theta) e^{frac{- m^2}{2}}]

Now on this formulation, the distribution of momentum is simply a regular regular ((e^{frac{- m^2}{2}}))! Thus, we will simply combine out the momentum and take (P(theta)) as samples from the posterior distribution:

& P(theta) =
int ! P(theta, m) mathrm{d}m = frac{1}{Z} int ! P(x | theta) P(theta) mathcal{N}(m|0,1) mathrm{d}m
& P(theta) = frac{1}{Z} int ! P(x | theta) P(theta)

How does this work in follow? At each step, we

  • pattern a brand new momentum worth from its marginal distribution (which is identical because the conditional distribution given (U), as they’re impartial), and
  • resolve for the trail of the particle. That is the place Hamilton’s equations come into play.

Hamilton’s equations (equations of movement)

For the sake of much less confusion, must you resolve to learn the paper, right here we change to Radford Neal’s notation.

Hamiltonian dynamics operates on a d-dimensional place vector, (q), and a d-dimensional momentum vector, (p). The state house is described by the Hamiltonian, a operate of (p) and (q):

[H(q, p) =U(q) +K(p)]

Right here (U(q)) is the potential vitality (known as (U(theta)) above), and (Okay(p)) is the kinetic vitality as a operate of momentum (known as (Okay(m)) above).

The partial derivatives of the Hamiltonian decide how (p) and (q) change over time, (t), in line with Hamilton’s equations:

& frac{dq}{dt} = frac{partial H}{partial p}
& frac{dp}{dt} = – frac{partial H}{partial q}

How can we resolve this method of partial differential equations? The fundamental workhorse in numerical integration is Euler’s methodology, the place time (or the impartial variable, on the whole) is superior by a step of measurement (epsilon), and a brand new worth of the dependent variable is computed by taking the (partial) spinoff and including it to its present worth. For the Hamiltonian system, doing this one equation after the opposite appears like this:

& p(t+epsilon) = p(t) + epsilon frac{dp}{dt}(t) = p(t) − epsilon frac{partial U}{partial q}(q(t))
& q(t+epsilon) = q(t) + epsilon frac{dq}{dt}(t) = q(t) + epsilon frac{p(t)}{m})

Right here first a brand new place is computed for time (t + 1), making use of the present momentum at time (t); then a brand new momentum is computed, additionally for time (t + 1), making use of the present place at time (t).

This course of might be improved if in step 2, we make use of the new place we simply freshly computed in step 1; however let’s instantly go to what’s really utilized in modern software program, the leapfrog methodology.

Leapfrog algorithm

So after Hamiltonian, we’ve hit the second magic phrase: leapfrog. Not like Hamiltonian nonetheless, there may be much less thriller right here. The leapfrog methodology is “simply” a extra environment friendly technique to carry out the numerical integration.

It consists of three steps, mainly splitting up the Euler step 1 into two components, earlier than and after the momentum replace:

& p(t+frac{epsilon}{2}) = p(t) − frac{epsilon}{2} frac{partial U}{partial q}(q(t))
& q(t+epsilon) = q(t) + epsilon frac{p(t + frac{epsilon}{2})}{m}
& p(t+ epsilon) = p(t+frac{epsilon}{2}) − frac{epsilon}{2} frac{partial U}{partial q}(q(t + epsilon))

As you possibly can see, every step makes use of the corresponding variable-to-differentiate’s worth computed within the previous step. In follow, a number of leapfrog steps are executed earlier than a proposal is made; so steps 3 and 1 (of the next iteration) are mixed.

Proposal – this key phrase brings us again to the higher-level “plan.” All this – Hamiltonian equations, leapfrog integration – served to generate a proposal for a brand new worth of the parameters, which might be accepted or not. The best way that call is taken will not be specific to HMC and defined intimately within the above-mentioned expositions on the Metropolis algorithm, so we simply cowl it briefly.

Acceptance: Metropolis algorithm

Underneath the Metropolis algorithm, proposed new vectors (q*) and (p*) are accepted with chance

min(1, exp(−H(q∗, p∗) +H(q, p)))

That’s, if the proposed parameters yield a better probability, they’re accepted; if not, they’re accepted solely with a sure chance that will depend on the ratio between outdated and new likelihoods.
In principle, vitality staying fixed in a Hamiltonian system, proposals ought to at all times be accepted; in follow, lack of precision as a result of numerical integration could yield an acceptance charge lower than 1.

HMC in just a few strains of code

We’ve talked about ideas, and we’ve seen the maths, however between analogies and equations, it’s simple to lose monitor of the general algorithm. Properly, Radford Neal’s paper (Neal 2012) has some code, too! Right here it’s reproduced, with only a few extra feedback added (many feedback had been preexisting):

# U is a operate that returns the potential vitality given q
# grad_U returns the respective partial derivatives
# epsilon stepsize
# L variety of leapfrog steps
# current_q present place

# kinetic vitality is assumed to be sum(p^2/2) (mass == 1)
HMC <- operate (U, grad_U, epsilon, L, current_q) {
  q <- current_q
  # impartial customary regular variates
  p <- rnorm(size(q), 0, 1)  
  # Make a half step for momentum firstly
  current_p <- p 
  # Alternate full steps for place and momentum
  p <- p - epsilon * grad_U(q) / 2 
  for (i in 1:L) {
    # Make a full step for the place
    q <- q + epsilon * p
    # Make a full step for the momentum, besides at finish of trajectory
    if (i != L) p <- p - epsilon * grad_U(q)
  # Make a half step for momentum on the finish
  p <- p - epsilon * grad_U(q) / 2
  # Negate momentum at finish of trajectory to make the proposal symmetric
  p <- -p
  # Consider potential and kinetic energies at begin and finish of trajectory 
  current_U <- U(current_q)
  current_K <- sum(current_p^2) / 2
  proposed_U <- U(q)
  proposed_K <- sum(p^2) / 2
  # Settle for or reject the state at finish of trajectory, returning both
  # the place on the finish of the trajectory or the preliminary place
  if (runif(1) < exp(current_U-proposed_U+current_K-proposed_K)) {
    return (q)  # settle for
  } else {
    return (current_q)  # reject

Hopefully, you discover this piece of code as useful as I do. Are we by but? Nicely, to date we haven’t encountered the final magic phrase: NUTS. What, or who, is NUTS?


NUTS, added to Stan in 2011 and a few month in the past, to TensorFlow Chance’s grasp department, is an algorithm that goals to bypass one of many sensible difficulties in utilizing HMC: The selection of variety of leapfrog steps to carry out earlier than making a proposal. The acronym stands for No-U-Flip Sampler, alluding to the avoidance of U-turn-shaped curves within the optimization panorama when the variety of leapfrog steps is chosen too excessive.

The reference paper by Hoffman & Gelman (Hoffman and Gelman 2011) additionally describes an answer to a associated issue: selecting the step measurement (epsilon). The respective algorithm, twin averaging, was additionally lately added to TFP.

NUTS being extra of algorithm within the pc science utilization of the phrase than a factor to elucidate conceptually, we’ll depart it at that, and ask the reader to learn the paper – and even, seek the advice of the TFP documentation to see how NUTS is applied there. As a substitute, we’ll spherical up with one other conceptual analogy, Michael Bétancourts crashing (or not!) satellite tv for pc (Betancourt 2017).

Find out how to keep away from crashes

Bétancourt’s article is an superior learn, and a paragraph specializing in a single level made within the paper might be nothing than a “teaser” (which is why we’ll have an image, too!).

To introduce the upcoming analogy, the issue begins with excessive dimensionality, which is a given in most real-world issues. In excessive dimensions, as traditional, the density operate has a mode (the place the place it’s maximal), however essentially, there can’t be a lot quantity round it – identical to with k-nearest neighbors, the extra dimensions you add, the farther your nearest neighbor will likely be.
A product of quantity and density, the one vital chance mass resides within the so-called typical set, which turns into an increasing number of slender in excessive dimensions.

So, the everyday set is what we need to discover, nevertheless it will get an increasing number of troublesome to search out it (and keep there). Now as we noticed above, HMC makes use of gradient data to get close to the mode, but when it simply adopted the gradient of the log chance (the place) it will depart the everyday set and cease on the mode.

That is the place momentum is available in – it counteracts the gradient, and each collectively be sure that the Markov chain stays on the everyday set. Now right here’s the satellite tv for pc analogy, in Bétancourt’s personal phrases:

For instance, as an alternative of making an attempt to motive a few mode, a gradient, and a typical set, we will equivalently motive a few planet, a gravitational area, and an orbit (Determine 14). The probabilistic endeavor of exploring the everyday set then turns into a bodily endeavor of inserting a satellite tv for pc in a secure orbit across the hypothetical planet. As a result of these are simply two totally different views of the identical mathematical system, they’ll undergo from the identical pathologies. Certainly, if we place a satellite tv for pc at relaxation out in house it is going to fall within the gravitational area and crash into the floor of the planet, simply as naive gradient-driven trajectories crash into the mode (Determine 15). From both the probabilistic or bodily perspective we’re left with a catastrophic consequence.

The bodily image, nonetheless, supplies a right away answer: though objects at relaxation will crash into the planet, we will keep a secure orbit by endowing our satellite tv for pc with sufficient momentum to counteract the gravitational attraction. We’ve got to watch out, nonetheless, in how precisely we add momentum to our satellite tv for pc. If we add too little momentum transverse to the gravitational area, for instance, then the gravitational attraction will likely be too robust and the satellite tv for pc will nonetheless crash into the planet (Determine 16a). Then again, if we add an excessive amount of momentum then the gravitational attraction will likely be too weak to seize the satellite tv for pc in any respect and it’ll as an alternative fly out into the depths of house (Determine 16b).

And right here’s the image I promised (Determine 16 from the paper):

And with this, we conclude. Hopefully, you’ll have discovered this useful – except you knew all of it (or extra) beforehand, wherein case you in all probability wouldn’t have learn this submit 🙂

Thanks for studying!

Betancourt, Michael. 2017. A Conceptual Introduction to Hamiltonian Monte Carlo.” arXiv e-Prints, January, arXiv:1701.02434.
Blei, David M., Alp Kucukelbir, and Jon D. McAuliffe. 2017. “Variational Inference: A Evaluation for Statisticians.” Journal of the American Statistical Affiliation 112 (518): 859–77.
Hoffman, Matthew D., and Andrew Gelman. 2011. “The No-u-Flip Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo.”

Kruschke, John Okay. 2010. Doing Bayesian Knowledge Evaluation: A Tutorial with r and BUGS. 1st ed. Orlando, FL, USA: Educational Press, Inc.

MacKay, David J. C. 2002. Data Concept, Inference & Studying Algorithms. New York, NY, USA: Cambridge College Press.

McElreath, Richard. 2016. Statistical Rethinking: A Bayesian Course with Examples in r and Stan. CRC Press. http://xcelab.internet/rm/statistical-rethinking/.
Neal, Radford M. 2012. MCMC utilizing Hamiltonian dynamics.” arXiv e-Prints, June, arXiv:1206.1901.

Related Articles


Please enter your comment!
Please enter your name here

Latest Articles

Microsoft launches Loop, its Notion competitor, in public preview

Microsoft Loop, a Notion-like hub for managing duties and initiatives that sync throughout Microsoft 365 apps and companies, launched in public preview right...

8 finest enterprise accounting software program for 2023

Gone are the times of the spreadsheet for preserving tabs on essential enterprise...

See Rockset’s Rollups for Streaming Information at Kafka Summit

Occasion stream processing has these days turn into the most-requested function amongst knowledge practitioners, who're ever being pushed by their enterprise counterparts for...

Posit AI Weblog: Ideas in object detection

A couple of weeks in the past, we supplied an introduction to the duty of naming and finding objects in photos. Crucially, we confined...

Nice Information for American Drone Producers, Drone Supply Updates, Police Drones for Search and Rescue

Our first story is especially heartening for American drone producers. Will the addition of 5 new producers to the Blue sUAS checklist ease...