One Stan chain across RDMA-connected Macs
An earlier tutorial showed how to hand-code a gradient in C++, and then how to spread one chain’s gradient over the cores of one machine. This one carries the same idea across machines: Macs joined by Thunderbolt 5 cables and RDMA, where a chain’s parameters and gradients cross from one Mac’s memory to another’s in a fraction of a millisecond.
From the cores of one Mac to several Macs
The earlier tutorial has two sections on threading a single chain: one with reduce_sum and one with raw TBB. Both rest on one observation. A chain’s steps are sequential, but the work inside one step is a sum: the log likelihood adds a term for every observation, and so does its gradient. So we cut the observations into slices, each core evaluates a slice, and we add the partial sums. The chain is still one chain. Each of its gradients arrives sooner.
That idea stops at the edge of the machine only because threads do. The sum itself has no such limit. A slice of the observations can be evaluated by a core in the same Mac or by a core in the Mac next to it, as long as that Mac has the data, receives the current parameter values, and returns its partial sum.
The exchange has to be fast, because it happens at every gradient, and a chain computes hundreds of thousands of them. Recent Macs make it so. Two Macs joined by a Thunderbolt 5 cable can use RDMA, remote direct memory access, in which the network hardware moves bytes straight from one program’s memory into the other’s with very little help from the operating system. On my cable the 107,000 parameters of the example go out and their gradient comes back in 0.2 to 0.4 ms.
This matters because the other use of a second machine, more chains, does nothing for the length of one chain. Four Macs run four chains in the time one Mac runs one. Each chain still starts every step from the end of its last one, and its warmup cannot be divided. A model in development often needs one chain that finishes sooner, so we can see whether a change worked. A production fit has the same need four times over: each of its four chains can be shared across the Macs, so that all four finish sooner than any one Mac could run them.
I wrote a small C++ library, coeval, that shares a gradient between Macs in this way, and this tutorial walks through a complete example with it. The Macs need not match. A new Mac Studio M5 Ultra can be paired with a second one, or helped by the older machines already on the desk: on mine, the example’s kernel takes 29 ms per gradient on the M5 Ultra alone, 18.6 ms when an M3 Ultra on a Thunderbolt 5 cable computes part of it, and 15.7 ms when an M2 Ultra on Ethernet joins as well.
The idea
We’ll call the process that needs the answer the root. In our case the root is the Stan model, running one chain. A helper is a small program on another Mac that waits for requests. Both load the same data at start, so the data never travels.
At each gradient the root sends every helper the current parameter values, as plain doubles. The root evaluates the first rows of the data and each helper the next, all at the same time and each with all of its own cores. Each helper sends back its part of the log likelihood and of the gradient, and the root adds the parts.
Illustrative. One chain runs on the root. Each helper evaluates its share of the rows with its own cores and returns its part of every sum; the faster the Mac, the larger its share.
In the example the message out is the $P$ player abilities and two more parameters, and the message back is the gradient for each of them and the log likelihood.
The time for one gradient is then that of the slowest part, plus the exchange. For 107,000 parameters the exchange is 856 kB each way, which costs between 0.2 and 2 ms depending on the link. We judge whether sharing pays from that number, and return to it under Timings.
The library is not specific to Stan. It is given a function that takes an array of doubles and returns an array of doubles, each element a sum over rows. A Stan likelihood with a hand-coded gradient happens to be such a function.
Assumptions
You have a likelihood written as a C++ function on doubles that returns its value and its gradient, as in the earlier tutorial. You have CmdStan and cmdstanr, and you are comfortable in a terminal.
The library runs on macOS. It has two ways to carry messages. On a Thunderbolt 5 cable between two Macs that both support it, it uses RDMA. On every other link (older Thunderbolt, Ethernet, or one Mac talking to itself) it uses TCP. You can follow every step of this tutorial on one Mac; the speed-up needs two.
The example model
The example is a choice model with enough structure to be slow. In each of $M$ choice sets, one of $J$ players is chosen. Player $p$ has an ability $\theta_p = \sigma z_p$, and each offered player $j$ in set $m$ comes with a covariate $x_{mj}$. The slope on the covariate varies from set to set, $\beta + \tau \varepsilon_m$ with $\varepsilon_m \sim \mathrm{normal}(0, 1)$, and we integrate $\varepsilon_m$ out with $G$ Gauss-Hermite nodes $n_g$ and weights $w_g$. With the chosen player listed first, the utility of player $j$ at node $g$ is
$$u_{gj} = \theta_{\text{player}[m, j]} + (\beta + \tau n_g)\, x_{mj},$$
and the log likelihood of set $m$ is
$$\ell_m = \log \sum_{g=1}^{G} w_g \, \frac{\exp(u_{g1})}{\sum_{j=1}^{J} \exp(u_{gj})}.$$
In plain Stan the whole model fits on a page:
parameters {
vector[P] z; // standardised player ability
real<lower=0> sigma; // sd of player ability
real beta; // mean slope on the covariate
real<lower=0> tau; // sd of the slope across choice sets
}
model {
z ~ std_normal();
sigma ~ normal(0, 1);
beta ~ normal(0, 1);
tau ~ normal(0, 1);
for (m in 1:M) {
vector[J] theta = sigma * z[player[m]];
vector[G] a;
for (g in 1:G) {
a[g] = logw[g] + categorical_logit_lpmf(1 | theta + (beta + tau * node[g]) * x[m]);
}
target += log_sum_exp(a);
}
}
We keep this file. It is the model in its most readable form, and every faster version is checked against it. It is the reference for correctness only. The loop over choice sets is a sum of independent terms, so plain Stan can thread it with reduce_sum, as the earlier tutorial shows, and a hand-coded kernel is faster again. Every timing below starts from that end point: the hand-coded kernel already running on every core of one Mac.
The timing data have 524,288 choice sets of 30 players each, 107,000 players and 15 nodes, so one gradient computes 236 million exponentials. The version we fit replaces the loop with one external function and keeps the parameters and priors in Stan:
functions {
// Log likelihood of every choice set, summed, at player abilities sigma * z.
real choice_ll(vector z, real sigma, real beta, real tau);
}
...
model {
z ~ std_normal();
sigma ~ normal(0, 1);
beta ~ normal(0, 1);
tau ~ normal(0, 1);
target += choice_ll(z, sigma, beta, tau);
}
A kernel that evaluates a range of rows
We’ll call the C++ function that does the arithmetic the kernel. The earlier tutorial’s functions evaluated every observation. To share the work, the kernel needs one more ability: to evaluate the rows from $r_0$ up to $r_1$ and return their part of every sum. In the example a row is a choice set, and the kernel’s two entry points are
Plan make_plan(const Data& d, int64_t m0, int64_t m1); // prepare the sets m0 .. m1 - 1
double eval(Plan& pl, const double* theta, double beta, double tau,
double* grad, double* g_beta, double* g_tau); // their log likelihood and its partials
Three properties make such a kernel safe to share.
Every output is a sum over rows. The log likelihood is one by definition. The gradient with respect to a player’s ability is too: it adds a term for each choice set the player appears in, so the root’s part and the helper’s part of that one number simply add.
The order of summation is fixed. The kernel works through the sets in blocks of 256, adds within a block in set order, and adds the blocks in block order, whatever the number of threads. A range always starts on a block boundary. The result then depends only on where the rows are cut between machines, so a run with the same seed and the same shares repeats exactly.
The arithmetic is the same in every build. Stan compiles a model with fused multiply-add turned off (-ffp-contract=off), and a program you compile yourself has it on by default, which changes the last bits of a result. The kernel states its own choice with #pragma clang fp contract(on) at the top of its function, so the Stan model and the helper compute identical numbers from identical code.
Three pieces of code
Everything the library asks of you fits in three small pieces.
The kernel as the library sees it
The library defines an interface with seven questions, and you answer them for your kernel. Here is the whole answer for the choice model:
class Kernel : public coeval::Kernel {
public:
explicit Kernel(const std::string& path) : d_(load_data(path)) {}
const Data& data() const { return d_; }
int64_t rows() const override { return d_.M; } // rows the sum runs over
int64_t block() const override { return choice::block; } // a range starts on a multiple of this
int inputs() const override { return int(d_.P + 2); } // theta[P], beta, tau
int outputs() const override { return int(d_.P + 3); } // gradient[P], d beta, d tau, lp
uint64_t data_id() const override { return d_.id; } // a hash of the data
void range(int64_t r0, int64_t r1) override { plan_ = make_plan(d_, r0, r1); }
void eval(const double* in, double* out) override {
const int64_t P = d_.P;
out[P + 2] = choice::eval(plan_, in, in[P], in[P + 1], out, &out[P], &out[P + 1]);
}
private:
Data d_;
Plan plan_;
};
inputs() and outputs() are the lengths of the two arrays that travel. range() is called once at start with the rows this process was given. eval() is called at every gradient. data_id() is a hash of every array in the data file, which the root and the helper compare before any work is done; the library provides coeval::hash() to compute it.
The helper program
The helper is the same kernel with a different main:
#include "../cpp/choice_coeval.hpp"
#include <tbb/global_control.h>
int main(int argc, char** argv) {
if (argc != 4) {
std::fprintf(stderr, "usage: choice_helper DATA THREADS WIRE\n");
return 3;
}
tbb::global_control threads(tbb::global_control::max_allowed_parallelism, std::atoi(argv[2]));
try {
choice::Kernel kernel(argv[1]);
return coeval::helper_main(kernel, argv[3]);
} catch (const std::exception& e) {
std::fprintf(stderr, "choice_helper: %s\n", e.what());
return 1;
}
}
It loads the data, sets its thread count, and hands the kernel to coeval::helper_main with the address it should listen on. That function answers requests until the root tells it to stop, until the root is gone, or until fifteen minutes pass without a request.
The call from Stan
In the earlier tutorial, the Stan-facing function stripped the var wrappers, called the arithmetic on doubles, and returned a make_callback_var. That shape stays. One line changes: where the function called the kernel, it now calls the link.
struct Shared {
Kernel kernel;
coeval::Link link;
explicit Shared(const char* path) : kernel(path), link(kernel) {}
};
A coeval::Link is the root’s end. We build one, once, at the model’s first evaluation, from the data file named in an environment variable. From then on, the body of the gradient function reads
// in: theta = sigma * z, then beta and tau, as doubles
tbb::parallel_for(tbb::blocked_range<int64_t>(0, P, 4096), [&](const tbb::blocked_range<int64_t>& r) {
for (int64_t i = r.begin(); i < r.end(); ++i) {
vi[i] = z(i).vi_;
in[i] = sd * z(i).val();
}
});
in[P] = beta.val(), in[P + 1] = tau.val();
s.link.evaluate(in, gr); // every Mac's rows, added: gradient[P], d beta, d tau, lp
// chain rule from theta back to z and sigma, then one node for Stan
...
return stan::math::make_callback_var(lp, [vi, gr, P](auto& out) { ... });
link.evaluate(in, out) returns the same numbers the kernel would return for every row. When no helper is configured it calls the kernel in this process and touches no network, so one executable serves both cases.
The scaling theta = sigma * z happens here, in doubles, spread over the root’s cores. This is the same care a threaded Stan model takes when it builds each slice’s abilities inside its reduce_sum function: a sigma * z written once for all 107,000 players at the top of the model block would be built on one core at every gradient. The chain rule back to z and sigma takes two lines: $\partial \ell / \partial z_i = \sigma g_i$ and $\partial \ell / \partial \sigma = \sum_i g_i z_i$, where $g$ is the kernel’s gradient with respect to $\theta$.
One detail is specific to Stan. If the link cannot be set up (a helper is unreachable, or it has other data), the header prints the reason and ends the process. An exception thrown there would reach Stan during its first evaluation, where Stan logs it and carries on trying initial values.
Building
Each Mac compiles its own programs from the same sources. The example’s build script does this on whichever Mac it runs:
Rscript examples/choice/R/build.R # the root: the helper, a bench program and the Stan model
Rscript examples/choice/R/build.R tools # a Mac that only helps: the helper and the bench program
Two things in it are worth reading. Before compiling, it calls coeval_build_id(), which writes a small header with a number computed from the kernel’s sources, the library’s sources and the compiler’s version. The root and each helper compare that number at start, so a helper compiled from an older edit of the kernel is refused. And the Stan model is compiled with the header as a user header, plus Apple’s RDMA library on the link line:
mod <- cmdstanr::cmdstan_model(
"choice.stan",
user_header = "cpp/choice_ext.hpp",
cpp_options = list(stan_threads = TRUE, LDLIBS_OS = "-lrdma"),
dir = out
)
The example simulates its own data. A small set for checking and the large one for timing:
Rscript examples/choice/R/make_data.R tiny 2048 8 300 7 # M J P G
Rscript examples/choice/R/make_data.R full 524288 30 107000 15
A first run on one Mac
It helps to do by hand, once, what the launcher will do later. Open two terminals in examples/choice. In the first, start a helper with two threads, listening on TCP port 25001. The last number is a token of our choosing that the root must repeat, so a helper only answers the run that started it.
build/<host>/choice_helper data/tiny.bin 2 tcp:-:25001:4242
In the second, run the bench program, which calls the kernel through a link fifty times, and tell it about the helper. The setting reads: give half of the rows to the helper at this address.
COEVAL_HELPERS=0.5@tcp:127.0.0.1:25001:4242 build/<host>/choice_bench data/tiny.bin 2 50 --check
coeval helper 1 check: within 0
coeval helpers=1 wires=tcp cuts=1024 rows=2048 evals=50 ms_total=0.6450 ms_send=0.0491 ms_local=0.3986 ms_wait=0.1974 ms_helper=0.4078
choice_bench threads=2 reps=50 helpers=1 ms_min=0.2435 ms_median=0.5146 ms_max=2.2648 lp=-4469.584074039466
choice_bench check: largest relative difference from one process 6.21e-16: PASS
The first line is a check the library makes on its own, described below. The second is the link’s summary, printed when it ends. cuts=1024 says the root took rows 0 to 1023 and the helper the rest. The four timers are averages per evaluation: the whole evaluation, handing the inputs to the network, the root’s own rows, and the wait from the end of the root’s work until the helper’s reply was in. ms_helper is the helper’s own work, as the helper measured it. The last line comes from --check: the bench program evaluated every row in one process and compared.
The helper’s terminal has returned to its prompt. The root told it to stop.
This run is no faster than one process, since both halves share one Mac’s cores. It shows that the pieces work.
Two Macs
For two Macs, three things have to be true.
Both Macs see the project at the same path. A folder shared from one of them is the simplest way, and it gives both the same data file and a common place for the helper’s log.
The root can start a program on the helper through ssh with no password prompt.
The ssh name the root uses resolves to the helper’s address on the link the messages should take. A Mac often has several routes to another (Wi-Fi, Ethernet, a Thunderbolt cable), and the library uses the one the name points at. An entry in ~/.ssh/config settles it:
Host m3-studio
HostName 10.10.0.1
where 10.10.0.2 is the helper’s address on the Thunderbolt cable.
The library’s R file starts and stops helpers. A complete launcher for one chain is short:
library(cmdstanr)
source("R/coeval.R") # from the library's folder
here <- "/path/both/Macs/see/coeval/examples/choice"
mod <- cmdstan_model(exe_file = file.path(here, "build/<root host>/choice"))
helper <- list(
host = "m3-studio", # the ssh name
share = 0.38, # the part of the rows it evaluates
command = c(file.path(here, "build/<helper host>/choice_helper"), file.path(here, "data/full.bin"), "32")
)
job <- coeval_start(list(helper), log_dir = file.path(here, "logs"))
Sys.setenv(CHOICE_DATA = file.path(here, "data/full.bin"),
COEVAL_HELPERS = sub("^COEVAL_HELPERS=", "", job$env))
fit <- mod$sample(data = file.path(here, "data/full.json"), chains = 1, threads_per_chain = 36)
coeval_stop(job) # returns anything the helper printed
coeval_start() looks at the link between the two Macs. When both ends have an active RDMA device on it, which is the case for a Thunderbolt 5 cable between two Macs that support it, the messages go by RDMA; otherwise by TCP. It picks a port and a token for this run, starts the helper through ssh, and returns the setting the root needs. A list with several entries starts several helpers; the root takes the first rows and each helper the next.
The share is the one number you choose. Time the kernel alone on each Mac, with the bench program and no helper. The best share for a helper is its speed over the sum of the speeds. My M5 Ultra takes 29 ms for the kernel and the M3 Ultra 47 ms, so the M3 Ultra’s share is $(1/47) / (1/29 + 1/47) = 0.38$, and the two together should take about $1 / (1/29 + 1/47) = 17.9$ ms. They took 18.6. An older Mac is given less to do, in proportion, and every share finishes at about the same moment.
A link serves one chain, and a helper serves one link. A fit of four chains is therefore four of these jobs side by side: each chain is its own root with its own helpers, started by its own call to coeval_start(), and the chains divide each Mac’s cores among them as they would on one machine.
Checks before any number is trusted
A shared gradient that is subtly wrong would be worse than a slow one, because the sampler would run and produce numbers. Three layers of checks stand between a mistake and a posterior.
The first is yours, and it is the one the earlier tutorial ended on: the C++ model against the plain Stan model, at the same point. With BridgeStan,
library(bridgestan)
Sys.setenv(CHOICE_DATA = "data/tiny.bin")
kernel <- StanModel$new("build/<host>/twin/choice_model.so", "data/tiny_ref.json", 1)
plain <- StanModel$new("build/<host>/twin/choice_ref_model.so", "data/tiny_ref.json", 1)
point <- rnorm(kernel$param_unc_num(), 0, 0.5)
a <- kernel$log_density_gradient(point)
b <- plain$log_density_gradient(point)
c(a$val, b$val) # -4144.278 -4144.278
max(abs(a$gradient - b$gradient)) # 5.8e-13
This check involves no helper. It establishes that the kernel computes the model.
The second layer runs when the link starts. Each helper must report the same sizes, the same data hash and the same build number as the root. A helper with yesterday’s data file or last week’s kernel is refused, with a message that says which.
The third runs at the first evaluation. The root computes every helper’s rows itself, once, and compares them with what each helper returned; they must agree to $10^{-10}$. That is the line coeval helper 1 check: within 0 above. A helper that somehow computes something else stops the run at its first gradient. After that, every reply carries the number of the evaluation it answers, so a late or repeated message cannot be taken for a current one.
Machines also fail in mid-run. When a helper dies, the root notices within a fraction of a second; when a helper hangs, the root gives up after COEVAL_TIMEOUT seconds (120 unless you set it). In both cases the link raises an error and never returns a partial sum. Stan ends the chain and closes its output file, so the draws written up to that point are kept. I tested both by killing and by freezing a helper during sampling.
Timings
The timings are of the kernel, in milliseconds per gradient, on the large data set (107,000 parameters), with the machines otherwise idle. The baseline in each comparison is one Mac running the threaded kernel on all of its cores, which is the best that Mac can do alone with this code. No row compares against plain Stan or against a single core.
| Macs | Link to the root | Share of the rows | Kernel, ms per gradient |
|---|---|---|---|
| M5 Ultra alone (36 cores) | 29 | ||
| M3 Ultra alone (32 cores) | 47 | ||
| M2 Ultra alone (24 cores) | 76 | ||
| M5 Ultra and M3 Ultra | Thunderbolt 5, RDMA | 62% and 38% | 18.6 |
| M5 Ultra and M3 Ultra | Thunderbolt 5, TCP | 62% and 38% | 19.1 |
| M5 Ultra, M3 Ultra and M2 Ultra | Thunderbolt 5, RDMA; 10 Gb Ethernet, TCP | 51.5%, 32% and 16.5% | 15.7 |
For the owner of the M5 Ultra, an M3 Ultra on a cable makes the kernel 1.6 times as fast, and an M2 Ultra on Ethernet brings that to 1.8. Seen from the M3 Ultra the same pairing is worth 2.5 times. A second M5 Ultra would take half of the rows, so by the same arithmetic as for the shares the pair should take about 15 ms; I have one M5 Ultra and have not measured that.
Inside the sampler each gradient costs a little more than the kernel. On the M3 Ultra, Stan’s own work on 107,000 parameters added about 1.9 ms: the priors, the sampler’s vector arithmetic, the output. That part stays on the root and is not shared, which is one reason to root the chain on the fastest Mac.
The exchange is the price of sharing, and it grows with the number of parameters, since the parameters go out and the gradient comes back at every evaluation:
| Parameters | Message each way | RDMA, Thunderbolt 5 | TCP, Thunderbolt 5 | TCP, 10 Gb Ethernet |
|---|---|---|---|---|
| 107,000 | 0.86 MB | 0.2 to 0.4 ms | 0.7 to 0.9 ms | 2.1 ms |
| 600,000 | 4.8 MB | 1.3 ms | 2.6 ms | 9.2 ms |
| 2,000,000 | 16 MB | 4.3 ms | 7.2 ms | 29 ms |
The cases where sharing pays
Sharing pays when the kernel’s time is large beside the exchange. A gradient of 50 ms with 100,000 parameters loses less than one percent to a Thunderbolt 5 cable. A gradient of 2 ms loses everything, on any link.
It pays in a mixed set of machines. Shares follow speed, so an older Mac contributes what it can and slows nobody: the M2 Ultra, at 38 percent of the M5 Ultra’s speed and on the slowest link, still took the kernel from 18.6 ms with two Macs to 15.7 ms with three.
It pays whenever the wall time of a chain is the limit, with one chain or with four. Sharing adds no computing power: two equal Macs that each run two chains produce about as many draws per hour as the same two Macs sharing all four. The gain is in how the power is spread. With one chain in development, every Mac works on it. With four chains on Macs of different speeds, a chain left alone on the slowest Mac sets the time of the whole fit, and sharing gives each chain a part of every Mac, so the four should finish together.
And it pays only for the part that is a sum over rows in a C++ kernel. Whatever else the model does stays on the root, on Stan’s tape, at the root’s speed. If that remainder is large, the earlier tutorial is the place to start.
Summary
The recipe for sharing one chain’s gradient between Macs:
- Begin with a hand-coded kernel on doubles that is already checked against the plain Stan model.
- Give the kernel a range of rows to evaluate, with a fixed order of summation, so that every output is a sum of parts.
- Describe it to the library in one small class, write the four-line helper, and replace the kernel call in the Stan header with
link.evaluate(). - Build on each Mac, run both ends on one Mac with a tiny data set, and read the checks.
- Time the kernel alone on each Mac, root the chain on the fastest, set the shares from the speeds, and start the helpers from the launcher.
The earlier tutorial ended on a trade: hand-coded gradients are more work to write, verify and maintain, and they are worth it for the functions that earn it. This step asks for much less. The kernel is the hard part, and it is already written. It gains, for one chain, the use of every Mac within reach of a cable, the older ones included.