Why a sixth MCMC package: a portable GPU log-density kernel in R

R
MCMC
Bayesian
statistics
Rust
gpumetropolis
opensource
CRAN already ships five mature MCMC packages. The case for gpumetropolis rests on one empty niche, a log-density kernel generated once from an R formula and run on the CPU or on any GPU, and on a benchmark registered before it ran, which reports where the package loses as plainly as where it wins.
Author

Pedro Carvalho Brom

Published

June 10, 2026

Code repositorypcbrom/gpumetropolis

If you run MCMC in R, there is already a good package for most of what you need. MCMCpack gives canned samplers for common models, mcmc is a clean general-purpose random-walk Metropolis, nimble compiles model code and picks specialized samplers, BayesianTools wraps several modern algorithms, and Stan is the reference for gradient-based Hamiltonian Monte Carlo. Writing a new package when those exist is usually a mistake, so the justification for gpumetropolis has to be narrow, and it has to survive a benchmark designed to find where the new package loses.

The narrow case is this. Picture a model with many chains and a likelihood summed over a large data set, and a cluster whose GPUs may come from a different vendor next year. None of the five runs the heart of that computation, the log-density, on a GPU from any vendor, generated once from the model you wrote. CUDA-specific MCMC code exists, and kernels can be written by hand, but both tie the model to one vendor and to a code path someone has to maintain. That empty niche is what the package fills, and the rest of this post is about how it is built and how it was measured.

This post expands a LinkedIn Article of 10 June 2026: Why I built an MCMC sampler with a portable GPU kernel instead of using what CRAN already has.

From a formula to a kernel

A model is declared by writing its per-observation log-likelihood and its log-prior as ordinary one-sided R formulas, in the names of the parameters and the data. The example below is the Gaussian mean with known standard deviation, whose posterior has a closed form and therefore makes a clean correctness check.

library(gpumetropolis)
set.seed(1)
y <- rnorm(20000, mean = 3.4, sd = 2)

model <- gpum_model(
  loglik = ~ -((y - mu)^2) / 8,   # sigma = 2, so 0.5 / sigma^2 = 1 / 8
  params = "mu",
  data   = "y"
)

That formula is compiled once into a stack-machine bytecode, a flat sequence of instructions that pushes values and applies operations in order, and a single portable kernel interprets it. The kernel is written with CubeCL, which compiles that one kernel for CUDA, ROCm, Vulkan and a CPU back end. There is no runtime code generation and no hand-written CUDA. Interpreting rather than generating means the same model expression drives every back end, and a new model is new bytecode rather than a new kernel.

The sampler then advances many independent chains in one batched pass. That matters because Metropolis-Hastings (HASTINGS, 1970) has one stage that cannot be parallelized, the accept or reject step that moves each chain forward in time. Everything else splits along two data-parallel axes, across chains and across observations, and those are exactly the axes a GPU is good at. The repository describes the kernel as block per chain, with the sum of the log-density over the data done as a shared-memory reduction inside each block.

Correctness before speed

A GPU computation is only worth trusting if it matches the reference, so the package ships a distributional equivalence harness. It compares the GPU output with the CPU output through a two-sample Kolmogorov-Smirnov test and the split potential scale reduction factor, the split R-hat (GELMAN; RUBIN, 1992). The equivalence is distributional on purpose, because MCMC is stochastic and bit-exact agreement between CPU and GPU is not expected. The rule in the protocol is blunt. If R-hat shows systematic non-convergence, the defect is fixed before any speed is measured, because the speed of a sampler that has not converged is not a number worth reporting.

A benchmark registered before it ran

The benchmark protocol was frozen in a dated commit on 16 May 2026, before any cell of the registered benchmark was run. It fixes hypotheses that are allowed to fail, each with a prediction, a support condition and a refutation condition, and it states its objective as mapping the frontier of the advantage rather than demonstrating superiority. The factorial design crosses four target models with data sizes from 10² to 10⁷ observations and chain counts from 1 to 32,768, against MCMCpack, mcmc, nimble, BayesianTools and Stan.

  • M1, the Gaussian mean, with an exact closed-form posterior as ground truth.
  • M2, a separated bimodal posterior, which tests whether the sampler can represent two modes.
  • M3, a heavy-tailed Student-t location model, where the log-density is expensive to evaluate.
  • M4, an ill-conditioned three-dimensional Gaussian, a deliberately hard geometry.

The headline metric is effective sample size per second, effective draws after autocorrelation per second of wall-clock time, because a fast sampler that mixes poorly buys nothing. Decisions rest on bootstrap confidence intervals, not on point estimates. The protocol also records, before any result, what it will not claim. It will not claim that the package is the fastest MCMC, that any gain comes from the Rust language, or anything about high-dimensional targets. A later revision of the protocol adds a threat to validity that cuts against the best result of the package. Back ends whose log-density is an R callback pay interpreter overhead on every iteration, so part of any gap against them is an implementation artifact rather than an algorithmic result.

What the numbers say

The full per-cell results live in the repository, in benchmark/full_m1_cell_summary.csv and benchmark/full_m234_cell_summary.csv. Each ratio below divides the median effective sample size per second of the best gpumetropolis back end in a cell by that of the best competitor in the same cell, and each headline number is the best cell over data sizes, so the cell is named next to it.

Model Range at 64 chains, over data size N Headline cell Best competitor in the cell Ratio Time saved
M1 5.1x (N = 100,000) to 54x (N = 1,000) N = 1,000, 64 chains nimble 54x 98.1%
M2 29.7x (N = 100) to 78.5x (N = 1,000) N = 1,000, 64 chains MCMCpack 78.5x 98.7%
M3 124x (N = 100) to 227x (N = 10,000) N = 1,000, 64 chains mcmc 225x 99.6%
M3 N = 1,000, 512 chains mcmc 709x 99.9%
M3 N = 100, 64 chains nimble 124x 99.2%
M4 nimble leads in every cell N = 1 (no data), 64 chains nimble 0.06x none

M3 is the clearest win, and the competitor in the headline cells matters. At N = 1,000 and 64 chains the CUDA back end reaches 225 times the effective sample size per second of the best competitor, the same result in about 99.6% less time, and at N = 1,000 and 512 chains that rises to 709 times. In both cells the best competitor is mcmc, whose log-density is an R callback paid on every iteration, which is exactly the threat to validity recorded in the protocol, so part of those margins is an implementation artifact. The cleaner comparison is against nimble, which compiles its density. Where nimble is the best competitor, at N = 100 and 64 chains, the margin is 124 times. gpumetropolis is also the only back end that finishes the 4,096-chain cells at all, and with a single chain it still edges ahead on M3, by 1.8 to 3.0 times depending on the data size. A slightly elevated Kolmogorov-Smirnov rejection rate in an early M3 run was traced to a seed collision in the benchmark harness, not in the sampler, and fixing it changed neither the speed nor the per-run correctness.

M1 shows the same shape, less steep, because the Gaussian log-density is cheap and leaves less work per iteration for the GPU to absorb. At 64 chains the ratio runs from 5.1 times at N = 100,000, where Stan is the best competitor and the Vulkan back end leads (the CUDA back end alone reaches 3.3 times there), to 54 times at N = 1,000 against nimble, 98.1% less time, with R-hat at 1.00.

M2 is where a careless number would mislead. A single random-walk chain cannot cross between separated modes, so one chain never represents the posterior, which is a property of random-walk Metropolis and not a bug. The Kolmogorov-Smirnov pass rate against the exact bimodal reference is 0% with one chain and 84% with eight, and the per-chain R-hat stays high by design, because chains sitting in different modes disagree. Every back end, competitors included, is flagged by the convergence gate for that reason, and among them the CUDA and Vulkan back ends of gpumetropolis have the lowest rejection rate. So the 78.5 times at N = 1,000 and 64 chains, against MCMCpack, is real, but it is conditional on the many-chains strategy and should never be quoted without that condition. The fix that attacks the bimodal case directly came later, and it is the subject of the post on parallel tempering.

M4 is where the package loses, and the loss is the point. Correctness holds for every back end, but nimble detects that the target is exactly Gaussian, assigns a conjugate sampler and draws independent samples directly. At 64 chains it reaches about 3,500 times the effective sample size per second of the random walk in mcmc, and the best gpumetropolis back end gets 0.06 of what nimble does. A generic random-walk Metropolis does not beat a specialized algorithm on the target that algorithm was built for, and it does not claim to. M4 also sharpens the GPU caveat. With no data and a single chain, the CUDA back end is slower than the native CPU back end, because there is no data-parallel work to amortize the kernel launch.

The regime, stated as a rule

Across the four models the pattern is a statement about regime, not a ranking of packages. The GPU back end helps when there are many chains, or when the log-density is expensive to evaluate over a large data set, because that is where there is enough data-parallel work to fill the device. That is the profile of heavy simulation work. At the 225 times of the M3 headline cell, a day of sampling by the best competitor would become about 6.4 minutes, the difference between iterating on a model and abandoning it. The GPU back end does not help a small model with few chains. There the launch overhead is not amortized, and a plain CPU sampler, or a specialized algorithm such as the conjugate draw of nimble, wins.

What 0.1 did not do

Version 0.1.0 was explicitly experimental. Only the log-density evaluation goes to the GPU, so the speedup is bounded by how much of the total cost lives in that evaluation. The roadmap at the time named adaptive Metropolis, Differential Evolution MCMC and parallel tempering as the next tier, and the 0.4 release later turned the sampler into a fuller Bayesian toolkit. The package lives on R-universe rather than CRAN, because the vendored Rust dependency tree, dominated by the CUDA and Vulkan stacks, exceeds the CRAN tarball-size limit, a story told in the CRAN to R-universe post. It installs with a Rust toolchain present, the default build is CPU only, and the CUDA and Vulkan back ends are optional Cargo features that need the corresponding toolkit.

install.packages("gpumetropolis",
                 repos = c("https://pcbrom.r-universe.dev",
                           "https://cloud.r-project.org"))

Building a sixth package is justified only when the niche is empty, and the honest answer to build versus reuse needs a benchmark that reports the regime of loss as plainly as the regime of gain. So, in your own MCMC work, is the bottleneck the number of chains or the cost of the log-density?


References.

BROM, P. C. gpumetropolis: a GPU-portable, vendor-agnostic Metropolis-Hastings sampler. R-universe, 2026. Available at: https://pcbrom.r-universe.dev/gpumetropolis.

GELMAN, A.; RUBIN, D. B. Inference from iterative simulation using multiple sequences. Statistical Science, v. 7, n. 4, p. 457-472, 1992. DOI: 10.1214/ss/1177011136.

HASTINGS, W. K. Monte Carlo sampling methods using Markov chains and their applications. Biometrika, v. 57, n. 1, p. 97-109, 1970. DOI: 10.1093/biomet/57.1.97.

The source, the benchmark and its protocol are open on GitHub under the MIT license, github.com/pcbrom/gpumetropolis, and the package installs from pcbrom.r-universe.dev/gpumetropolis. I write about this kind of work, scientific method, statistics, and AI applied with rigor, on LinkedIn: linkedin.com/in/pcbrom.