What makes an MCMC sampler GPU-friendly?

(This post is by Charles)

Art Owen (Stanford) read our paper on nesting Rhat to assess convergence in the many-short-chains regime of MCMC. He made a lot of great comments and asked some clarification questions. Notably:

It wasn’t clear to me what makes an MCMC GPU-friendly.  Is there a canonical reference?  E.g., maybe the Lao paper.

I’m not sure there is a canonical reference with an entirely satisfactory exposition. Lao et al (2020) present the main ideas from an engineering perspective and discuss why it is difficult to implement NUTS on a GPU. Meanwhile, Hoffman et al (2021) present ChEES-HMC, a GPU-friendly alternative to NUTS. (This paper inspired the design of other GPU-friendly samplers: see Sountsov and Hoffman (2022), Hoffman and Sountsov (2022), and Riou-Durand et al (2022).)

A key ingredient to make a sampler GPU-friendly is that each Markov chain requires the same operations, albeit with different inputs. Then each operation can be executed in parallel on single-instruction-multiple-data (SIMD) hardware. For example, in HMC, the gradients of the log density for all chains are evaluated in parallel and this calculation of many gradients is efficient. This is to be contrasted with more traditional implementations of parallel MCMC where each chain runs asynchronously on its own processing unit, and so there is no parallel evaluation of the gradients. The latter approach is less efficient than SIMD, which to me is one of the more subtle points made by Junpeng Lao and colleagues.

With this in mind, NUTS is not GPU-friendly because at each iteration, each chain simulates a Hamiltonian trajectory with a different length, meaning each chain requires a different number of operations. So we end up waiting for the slowest chain at each iteration or trying to anticipate the longest trajectory. This is likely a challenge, not only for NUTS, but for many locally adaptive methods (although not all).
 

Additional input from Matt

I’ve discussed the topic many times with Matt and Bob, and sought them out for additional insight.

Matt sends me the draft of an article which dives into the topic. The article is unpublished and currently being reviewed, so I cannot share it. But I believe it will become the canonical reference Art was asking for.

The paper carefully explains that using SIMD only works well when separate chains perform the same computation at the same time. This can be violated if a sampler is adaptive or has a control flow that makes the chains differ in the amount of computation they perform. Matt points to some results, which show that NUTS has a heavy control flow, meaning it spends a lot of computation beyond evaluating and differentiating the target log density (remember, calculating gradients on SIMD is efficient). For those more familiar with the NUTS paper, these operations include managing the internal tree proposal stack, which will incur a number of operations unique to each chain.

Matt adds:

Although raggedness (different chains running for different numbers of leapfrog steps or whatever) is a serious issue, I think it may actually be secondary to NUTS’s other overheads (switching back and forth between states at either end of the trajectory, other control flow stuff). Alexey Radul tried to implement a version of NUTS that deals with raggedness by syncing on every gradient call, which allows for chains to have different numbers of samples at different times, but IIRC the overhead of the virtual machine he created (in TensorFlow!!!) to solve the problem incurred more overhead than it was worth.

Additional input from Bob

To shed more light on why NUTS’s overhead, and more generally why control flow is a problem, Bob points to this blog post he wrote. I highly recommend reading it. The post discusses SIMD, memory management, vectorization, and branch-point prediction. A heavy control flow leads to a more difficult memory management and branch-point predictions, both of which are harder on a GPU than a CPU. A GPU-friendly sampler would avoid both, as much as possible.

(On the same email thread, Bob Carpenter and I also started a discussion on how certain likelihoods can be difficult to evaluate, for example when the likelihood is based on a system of differential equations. I’m not including this here, because this post seems long enough and I will visit this topic in another post.)

15 thoughts on “What makes an MCMC sampler GPU-friendly?”

  1. It is important to understand how MASSIVE the overhead may be from synchronizing across multiple chains of the NUTS sampler.

    Consider running 32 chains of NUTS and generating 1000 samples per chain. This example is done with Blackjax, a Bayesian inference library in JAX, here: https://github.com/blackjax-devs/blackjax/issues/251.

    When required to *synchronize* SIMD instructions (using JAX vmap), this takes 2 minutes. When running on multiple CPU cores and *not* required to synchronize (using JAX pmap), this takes 3 seconds!

    This is an ENORMOUS difference (43x faster!!!) and motivates samplers like Chees, Meads, and others.

    An amazing introduction to these considerations in JAX can be found in the Blackjax tutorial here: https://blackjax-devs.github.io/blackjax/examples/howto_sample_multiple_chains.html.

    Note: running each NUTS chain on its own CPU/GPU core may get around the synchronization issue, but is not scaleable! Many machines (even powerful ones) are made with < 32 cores so we will rarely be able to run e.g. 1024 chains. (Can we instead do this with different threads? Not easily in Python with the GIL lock but maybe in other languages? Not really sure here…)

    Would love to hear any thoughts about this.

    • I think the only thing I want to add is that JAX is a combination of a frontend language (essentially + numpy I guess) plus a “backend” (or middle) that translates JAX code to Google’s XLA HLO. This stack has been mostly optimized for TPUs rather than GPUs, and for large neural networks rather than anything with control flow.

      And as far as I can tell, basically all the GPU MCMC implementations are currently on top of JAX? I think there’s a lot of uncertainty about how much performance one could get by going down to CUDA or similar, although of course this is a ton more work.

      • rif, reading your comment, I’m realizing that I should’ve mentioned that all the examples of GPU-friendly samplers also work well on TPUs. (Especially with JAX which makes it seamless to use a TPU—something anyone can try on Google Colab: https://colab.research.google.com/)

        Are there any comparisons between GPU and TPU for parallel MCMC?

        > And as far as I can tell, basically all the GPU MCMC implementations are currently on top of JAX? I think there’s a lot of uncertainty about how much performance one could get by going down to CUDA or similar, although of course this is a ton more work.

        I’m not sure either. Thanks for raising the question, maybe someone will step in to answer.

    • Thanks Gilad for the input and pointing to the excellent benchmark comparison.

      Some clusters do give you access to hundreds of CPU cores, and this is something our colleagues at the Flatiron Institute Center for Computational Biology take advantage of. I think there are problems that justify this type of computation. But it seems expensive, and I don’t know how much this type of compute power will continue to grow.

  2. This is a bit off topic, but can someone point me to papers that use large Bayesian models to answer scientific questions (preferably social science)?

    I always wonder on what problems people work on that they need 1000 chains.

    • My guess is that these 1000 chains are each a small number of samples, like maybe you just take the last one. Then you have essentially 1000 samples one per chain.

      The hard part about sampling is moving through the distribution from one place to another. Converging to some location with the right lp value is much easier. If you start from a widely distributed set of initial positions, and converge to a location in the high probability region, then you may not be guaranteed a good sample, but it might often be a good sample, and if you can converge 1000 chains in parallel on a GPU, then you might get there in the time it takes to do 1 sample.

    • Daniel Lakeland is right. The samplers from Matt et al. and the convergence monitoring work by Charles et al. are based on the assumption that you will run a large number of chains through warmup, then take only one (or very few) draws per chain. Matt was suggesting 100 parallel chains when I saw him give a talk about this a couple of weeks ago. If you’re roughly stationary after warmup, you get an ESS of 1 per chain by construction. It costs a huge number of flops, but if you can do those in parallel, you’ll reduce wall time. It also changes the equation about how much you want to adapt/precondition each chain—in this regime of one draw per chain, you want to optimize time to stationarity, not optimize mixing once you get there.

      • Bob, rather than running N chains independently and taking the last one of each chain, we can conceptualize it as run one chain on an ensemble of N draws. The lp of the ensemble would be the sum of the lp of the individual points, and each lp could be calculated in parallel. Furthermore, we can run parallel tempering on a second ensemble, and in between diffusive samples we can do exchange samples. We really don’t need to calculate gradients at all here. The parallel tempering could be something like my white box sampler idea. Using piecewise deterministic dynamics and traveling in straight lines just to ensure points are widespread so the ensemble can be a mixture of points throughout the high probability region.

  3. Based on how active the explorations are in this space, I assume the answer currently is no, but is there a current front runner for MCMC on GPU? It seems there’s an acceptance that to scale along with hardware, there needs to be an adoption of GPU/other accelerators, but as a practitioners I’m not totally sure what I should be paying attention to.

    Or, relatedly, are there alternatives to MCMC that are perhaps more promising for probabilistic modeling?

    • Hi Anonymous! All very good questions.

      Al lot of this work is still experimental and it is not quite as user-friendly as more established methods implemented in probabilistic software such as Stan. The short answer is there is no clear front runner. The long answer is… longer. My sense is that ChEES-HMC is more battle-tested, but SNAPER-HMC (https://arxiv.org/abs/2110.11576) does provide an improvement. MALT is very interesting and empirically it’s less memory intensive (https://arxiv.org/abs/2210.12200).

      > Or, relatedly, are there alternatives to MCMC that are perhaps more promising for probabilistic modeling?

      Deep topic! I don’t know about *more* promising, but certainly worth considering. The one approach I would like to study more is Sequential Monte Carlo, whose design screams “parallelization!”

      I’ve also done quite a bit of work on variational inference (VI): sometimes it works very well, and sometimes it really doesn’t, and we’re doing a lot of work to characterize the problems VI is suited for. What is promising is the use of VI with richer families of approximation, at least for problems with a moderate dimension.

  4. Another way of thinking about it is, can higher variance in worse individual results that are easy to calculate be cancelled out by massively parallel repetitions? One way of looking at deep neural networks is that they produce many low quality pattern representations that get ensembled together for a higher quality average result. This is made architecturally explicit in “mixture of experts” models.

    In an MCMC like setting, ignoring the adaptation phase control flow would get you something like a quadrature method. The level of parallelism can’t keep up with the dimensionality and you don’t get good inference. In the post warmup phase once chains have reached the typical set, you can get a high effective sample size by running lots of short parallel chains, but at that point usually even a very small sample size is fine so the algorithm is already fast anyways. The trick is to how can to find and fill the typical set by averaging an enormous number of shitty guesses, something like a classical particle swarm simulation optimized for GPUs.

  5. From the article it sounds like the research really wants to explore synchronizing multiple chains together. Does that seem necessary for more advanced algorithms right now?

    Maybe I missed this in the article, but to my knowledge the benefit of the sync is that you can do multiple gradients at the same time. If done cleverly that allows you to turn things like matrix * vector multiplies into matrix * matrix multiplies or other higher tensor operations. Matrix / tensor operations are nice because you may keep memory much more local (using the same memory over and over)

    Has anyone ever looked at waiting for just a few chains to do the gradient calculation instead of all of them at once? i.e. if I have 1000 chains then instead of waiting for all 1000 to do a gradient calculation I just wait for like 3 or 4. For large enough models it feels like you could just swamp the memory transfer speeds with just a hand full of chains

Leave a Reply

Your email address will not be published. Required fields are marked *