High-performance Bayesian inference engine written in Rust
Project description
rustmc
Bayesian inference engine written in Rust. Python API via PyO3.
rustmc runs the entire sampling loop in compiled Rust, with no Python in the inner loop. Chains are parallelized across threads using Rayon. The result is fast enough to fit thousands of independent Bayesian models in a single call.
Why rustmc
PyMC, Stan, and other Bayesian frameworks are built for single-model workflows. You define one model, fit it, and analyze it. This works well for research but falls apart when you need to fit the same model structure to thousands of datasets -- per-store demand models, per-SKU pricing models, per-patient dosing models.
rustmc is designed for that use case. It provides a batch inference API that runs 10,000 independent NUTS chains through a single Rayon thread pool, sharing compute across all available cores with zero serialization overhead.
10,000 Bayesian demand models in 70 seconds, with full posterior uncertainty.
Fitting those same 10,000 models sequentially with ARIMA takes ~160 seconds. With Prophet, ~28 minutes. Neither gives you credible intervals for free.
Benchmark
10 parameters, 100,000 observations, 8 chains, 2,000 draws:
| Method | Time | Speedup |
|---|---|---|
| rustmc (NUTS) | 72s | 5.3x |
| PyMC (NUTS) | 383s | 1.0x |
Batch inference, 10,000 independent 3-parameter models:
| Method | Total time | Per model | Uncertainty |
|---|---|---|---|
| rustmc (batch NUTS) | 70s | 7ms | Yes (full posterior) |
| ARIMA (sequential) | 160s | 16ms | No |
| Prophet (sequential) | 28min | 170ms | Partial |
Quick start
pip install maturin
git clone https://github.com/tbosier/rustmc.git
cd rustmc
python -m venv .venv && source .venv/bin/activate
pip install numpy maturin
maturin develop --manifest-path python_bindings/Cargo.toml --release
or if you prefer, I have made this publically downloadable via pip
pip install rustmc
Single model
import numpy as np
import rustmc as rmc
np.random.seed(42)
x = np.random.randn(1000)
y = 2.5 * x + np.random.randn(1000)
builder = rmc.ModelBuilder()
beta = builder.normal_prior("beta", mu=0.0, sigma=1.0)
mu_expr = beta * "x"
builder.normal_likelihood("obs", mu_expr=mu_expr, sigma=1.0, observed_key="y")
model = builder.build()
fit = rmc.sample(model_spec=model, data={"x": x, "y": y}, chains=4, draws=1000)
print(fit.summary())
Output:
4 chains x 1000 draws per chain
Parameter mean std hdi_3% hdi_97% ess_bulk ess_tail r_hat mcse_mean
-----------------------------------------------------------------------------------------------
beta 2.4575 0.0313 2.3982 2.5133 2638 2966 1.0055 0.000610
-----------------------------------------------------------------------------------------------
Mean accept rate: 0.94 | Divergences: 0
Batch inference (10,000 models)
import rustmc as rmc
import numpy as np
models = []
for i in range(10_000):
builder = rmc.ModelBuilder()
intercept = builder.normal_prior("intercept", mu=0.0, sigma=200.0)
trend = builder.normal_prior("trend", mu=0.0, sigma=20.0)
mu_expr = intercept + trend * "t"
builder.normal_likelihood("obs", mu_expr=mu_expr, sigma=5.0, observed_key="y")
model = builder.build()
t = np.arange(52, dtype=np.float64) / 52
y = some_data[i] # your per-SKU time series
models.append((model, {"t": t, "y": y}))
results = rmc.batch_sample(models, draws=500, warmup=300)
# Each result has .mean(), .std(), .get_samples()
for r in results[:5]:
print(r)
What is implemented
Sampling
- NUTS (No-U-Turn Sampler) with multinomial candidate selection, generalized U-turn criterion, and divergence detection. Follows Hoffman and Gelman (2014) and Betancourt (2017).
- HMC with fixed leapfrog steps, available as a fallback via
sampler="hmc". - Diagonal mass matrix adaptation with 3-phase warmup (step-size only, mass matrix estimation, final step-size tuning).
- Auto step-size initialization via binary search.
- Deterministic per-chain RNG (ChaCha8) for reproducible results.
- Multithreaded chains via Rayon. Batch inference shares the thread pool across all models.
Distributions
| Distribution | Support | Transform | Status |
|---|---|---|---|
| Normal | (-inf, inf) | None | Working |
| StudentT | (-inf, inf) | None | Working |
| HalfNormal | (0, inf) | log | Working |
| Gamma | (0, inf) | log | Working |
| Beta | (0, 1) | logit | Working |
| Uniform | (a, b) | logit | Working |
| Bernoulli | {0, 1} | None | Discrete, limited |
| Poisson | {0, 1, 2, ...} | None | Discrete, limited |
Constrained distributions are automatically sampled in unconstrained space via log/logit transforms with Jacobian corrections. Samples are back-transformed before being returned to the user.
Computation
- Computational graph with reverse-mode automatic differentiation.
- Fused linear combination op for regression models. Replaces N separate multiply-add passes with a single cache-friendly loop over the data.
- Zero-allocation evaluator. All vector intermediates are pre-allocated in a flat buffer and reused across gradient evaluations. No heap allocation in the sampling loop.
Diagnostics
- Split R-hat with rank normalization (Vehtari et al. 2021).
- Bulk and tail effective sample size (ESS).
- Monte Carlo standard error (MCSE).
- 94% highest density interval.
- Per-chain acceptance rates, step sizes, and divergence counts.
- Automatic warnings for convergence issues.
Available via fit.summary() for a formatted table or fit.diagnostics() for programmatic access.
Progress reporting
Live progress bar rendered from Rust at 10 Hz using atomic counters, with no GIL involvement:
Sampling 8 chains ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% | 24.0k/24.0k | 0 divergences | 384.0k grad evals | 6.7s
Architecture
Python (orchestration only)
|
v GIL released
Rust Core
+-- Graph Computational DAG, nodes, ops, data storage
+-- Autodiff Forward evaluation + reverse-mode gradient
+-- Distributions 8 distributions with automatic transforms
+-- NUTS Multinomial tree-building, U-turn detection
+-- HMC Fixed-step leapfrog (fallback)
+-- Sampler Multi-chain parallel runner, batch inference
+-- Diagnostics R-hat, ESS, MCSE, HDI
+-- Progress Atomic counters, background render thread
Design principles:
- Model graph is built once and shared read-only across chains.
- Sampler accepts any log-probability + gradient function derived from a Graph.
- No global state. All state is explicit and owned.
- Deterministic RNG per chain (ChaCha8 seeded from base_seed + chain_index).
- Parameter transforms and Jacobian corrections are handled in the graph, not the sampler.
Data structures (Rust vs JAX)
The hot path uses plain Rust types only: the graph is Vec<Node> and Vec<Op>, parameters and gradients are Vec<f64>, and the autodiff evaluator uses contiguous vec_buf / adj_vec_buf (flat Vec<f64>) for all vector intermediates. There is no ndarray or external array library in the inner loop; ndarray appears only in the Python bindings when building the 2D sample array to return to NumPy. Benefits of this layout:
- Cache-friendly: One pass over the graph touches sequential memory; vector slots are in a single allocation.
- Zero allocation in the loop: Buffers are allocated once per chain and reused for every gradient evaluation.
- No Python or FFI in the inner loop: The entire NUTS/HMC step runs in Rust; Python is only used to build the model and consume results.
- Fixed graph traversal: The same DAG is walked every time; there is no tracing or recompilation per model or per step.
JAX, by contrast, traces Python and compiles to XLA. That gives flexibility and GPU support but adds per-model compilation and dispatch overhead. For many small, independent models (e.g. 10,000 SKUs), rustmc's "compile once, run fixed graph over contiguous buffers" approach often wins on CPU because there is no per-model JAX trace/compile and no Python in the inner loop. Nutpie (JAX-based) is faster than default PyMC for a single model; the batch example compares rustmc's batch NUTS against PyMC+nutpie run in a loop over the same number of models.
Roadmap
Near term:
- Hierarchical priors (parameter as hyperparameter of another parameter's prior)
- Link functions and GLMs
- Custom likelihood functions
- Prior and posterior predictive sampling
- LOO-CV (Pareto-smoothed importance sampling)
- Trace plots and visual diagnostics
- PyPI package (
pip install rustmc)
Medium term:
- Sufficient statistics optimization for linear-Normal models
- MAP estimation (L-BFGS)
- Laplace approximation
- Sparse indicator variable support
- Stochastic gradient MCMC (SGLD/SGHMC) for large datasets
- Model serialization (compile once, deploy without Python)
Long term:
- Variational inference (ADVI)
- GPU-accelerated log-probability via wgpu
- WASM compilation for browser/edge inference
- Distributed posterior aggregation
- Automatic reparameterization for funnel geometries
- C FFI for embedding in non-Python systems
License
MIT
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file rustmc-0.4.0-cp312-cp312-win_amd64.whl.
File metadata
- Download URL: rustmc-0.4.0-cp312-cp312-win_amd64.whl
- Upload date:
- Size: 539.3 kB
- Tags: CPython 3.12, Windows x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
375a0be83cb9b8ab75815fa1f92736c752b430aefcc2504b55529225e20902ff
|
|
| MD5 |
85e81f1d85c0bfdb429b5a91cac93264
|
|
| BLAKE2b-256 |
18c28edfd5f98e59a29c3f298f052ecf76862acca6f087d96f7fc4842b81e124
|
Provenance
The following attestation bundles were made for rustmc-0.4.0-cp312-cp312-win_amd64.whl:
Publisher:
ci.yml on tbosier/rustmc
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
rustmc-0.4.0-cp312-cp312-win_amd64.whl -
Subject digest:
375a0be83cb9b8ab75815fa1f92736c752b430aefcc2504b55529225e20902ff - Sigstore transparency entry: 1012346903
- Sigstore integration time:
-
Permalink:
tbosier/rustmc@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Branch / Tag:
refs/tags/v0.4.0 - Owner: https://github.com/tbosier
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file rustmc-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: rustmc-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 780.8 kB
- Tags: CPython 3.12, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1dc9e10d281928fae7e3ba70c799004dbc5d01c5d959714127be7d0def3319e2
|
|
| MD5 |
faaede147bd70f44a5ae8485488f6d27
|
|
| BLAKE2b-256 |
e295548eda5800eca6fc6f443cd5cd1dc1d760cfeff4693c1441539204e3f404
|
Provenance
The following attestation bundles were made for rustmc-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:
Publisher:
ci.yml on tbosier/rustmc
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
rustmc-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl -
Subject digest:
1dc9e10d281928fae7e3ba70c799004dbc5d01c5d959714127be7d0def3319e2 - Sigstore transparency entry: 1012346731
- Sigstore integration time:
-
Permalink:
tbosier/rustmc@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Branch / Tag:
refs/tags/v0.4.0 - Owner: https://github.com/tbosier
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file rustmc-0.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.
File metadata
- Download URL: rustmc-0.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
- Upload date:
- Size: 726.0 kB
- Tags: CPython 3.12, manylinux: glibc 2.17+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bf60af7055deafd911ec12b197080debb10048db5da5eddfdb3477e021457ba9
|
|
| MD5 |
e4b14ed9210ebd29ee1c1ee315063564
|
|
| BLAKE2b-256 |
22c209b7f536c3c8a6517eb10c63aa770910c9e0c4fc56695ee922c8206d93be
|
Provenance
The following attestation bundles were made for rustmc-0.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:
Publisher:
ci.yml on tbosier/rustmc
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
rustmc-0.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl -
Subject digest:
bf60af7055deafd911ec12b197080debb10048db5da5eddfdb3477e021457ba9 - Sigstore transparency entry: 1012346830
- Sigstore integration time:
-
Permalink:
tbosier/rustmc@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Branch / Tag:
refs/tags/v0.4.0 - Owner: https://github.com/tbosier
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file rustmc-0.4.0-cp312-cp312-macosx_11_0_arm64.whl.
File metadata
- Download URL: rustmc-0.4.0-cp312-cp312-macosx_11_0_arm64.whl
- Upload date:
- Size: 618.4 kB
- Tags: CPython 3.12, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
21b53d7a1fca7656a56fede112159f4cf09256f3e62606a425b20a3ca9c12915
|
|
| MD5 |
0754728d1598ab215123fa1873849afe
|
|
| BLAKE2b-256 |
68968b4f62827977528b3a61696ce55911b199e28af9df859f8ab75e9701416a
|
Provenance
The following attestation bundles were made for rustmc-0.4.0-cp312-cp312-macosx_11_0_arm64.whl:
Publisher:
ci.yml on tbosier/rustmc
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
rustmc-0.4.0-cp312-cp312-macosx_11_0_arm64.whl -
Subject digest:
21b53d7a1fca7656a56fede112159f4cf09256f3e62606a425b20a3ca9c12915 - Sigstore transparency entry: 1012346864
- Sigstore integration time:
-
Permalink:
tbosier/rustmc@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Branch / Tag:
refs/tags/v0.4.0 - Owner: https://github.com/tbosier
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file rustmc-0.4.0-cp312-cp312-macosx_10_12_x86_64.whl.
File metadata
- Download URL: rustmc-0.4.0-cp312-cp312-macosx_10_12_x86_64.whl
- Upload date:
- Size: 672.3 kB
- Tags: CPython 3.12, macOS 10.12+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
671dd4c7eeacc26b81a9b9d6a44a5fb993e39f4049aeb3eedc84f41f2a024795
|
|
| MD5 |
cb272ccab768de82193f4e0b9834e70e
|
|
| BLAKE2b-256 |
95aaf80787c818591afb663aa56b26b1b724d7f897b54c93f6397d220db6c5c0
|
Provenance
The following attestation bundles were made for rustmc-0.4.0-cp312-cp312-macosx_10_12_x86_64.whl:
Publisher:
ci.yml on tbosier/rustmc
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
rustmc-0.4.0-cp312-cp312-macosx_10_12_x86_64.whl -
Subject digest:
671dd4c7eeacc26b81a9b9d6a44a5fb993e39f4049aeb3eedc84f41f2a024795 - Sigstore transparency entry: 1012346785
- Sigstore integration time:
-
Permalink:
tbosier/rustmc@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Branch / Tag:
refs/tags/v0.4.0 - Owner: https://github.com/tbosier
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yml@ef9e8069e213bc740921c9ef71ca35197ffd9bf9 -
Trigger Event:
push
-
Statement type: