Skip to main content

rustmc

Bayesian inference powered by Rust, with a Python API.

Project status: alpha. rustmc is suitable for research, evaluation, and controlled internal workflows. Its supported modeling surface is useful but still intentionally smaller than mature probabilistic programming systems. Validate every model on representative data before using its output for consequential decisions.

rustmc is a practical, general-purpose Bayesian toolkit. It combines graph-based automatic differentiation and NUTS/HMC with reusable compiled models, exact conjugate inference, and specialized state-space algorithms. A generic sampler is available when a model needs one, while focused methods can be added when a research or production problem benefits from them.

rustmc complements PyMC and Stan rather than trying to replace them. Its practical distinction is native Rust execution and Rayon-powered parallelism across chains and repeated-model workloads. That foundation can support fast forecasting, regression, and domain-specific models in biomedical research, engineering, science, finance, and other fields. The project aims to keep those implementations understandable enough to inspect, adapt, and extend for real work.

Why rustmc

  • General and specialized inference in one runtime. The model builder uses reverse-mode automatic differentiation with NUTS or HMC. Local-level, seasonal, and trend models use FFBS/Gibbs, while Gaussian AR(p) uses an exact Normal-Inverse-Gamma posterior.
  • Compile once, bind many. ModelBuilder.compile() separates immutable model structure from validated datasets, including datasets with different row counts.
  • Native execution. Sampling, state-space operations, and chain coordination execute in Rust outside the Python hot path.
  • Deterministic parallelism. Chains and repeated-model workloads use Rayon with stable per-chain seed derivation and ordered results.
  • A focused extension path. General inference and specialized model implementations share a small native core, allowing new domain methods to be added without pursuing feature parity with a mature probabilistic-programming language.
  • Bayesian workflow support. Prior predictive checks, posterior predictive draws, pointwise log likelihood, convergence diagnostics, and ArviZ export are available for the generic inference path.
  • Coherent uncertainty. Specialized forecasting APIs retain complete (chain, draw, horizon) paths so derived totals and other nonlinear quantities can be calculated draw by draw.

These are implementation capabilities, not a universal speed or accuracy claim. Performance and statistical quality depend on the model, data, tuning, and hardware.

Installation

Install the latest published Python package with:

pip install rustmc

To build the current source instead of installing a published wheel:

git clone https://github.com/tbosier/rustmc.git
cd rustmc
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip maturin numpy
maturin develop --manifest-path python_bindings/Cargo.toml --release

Python 3.9 through 3.13 are covered by source-install and wheel-install CI. NumPy is the only required Python runtime dependency. ArviZ and Matplotlib are optional:

pip install "rustmc[viz]"

The Python extension is the supported public package today. rustmc_core contains the Rust implementation, but its public API should still be considered unstable.

Quick start

This example fits a Bayesian linear regression with NUTS:

import numpy as np
import rustmc as rmc

rng = np.random.default_rng(42)
x = rng.normal(size=1_000)
y = 2.5 * x + rng.normal(size=1_000)

builder = rmc.ModelBuilder()
beta = builder.normal_prior("beta", mu=0.0, sigma=1.0)
builder.normal_likelihood(
    "obs",
    mu_expr=beta * "x",
    sigma=1.0,
    observed_key="y",
)

fit = rmc.sample(
    model_spec=builder.build(),
    data={"x": x, "y": y},
    chains=4,
    warmup=1_000,
    draws=1_000,
    seed=42,
)
print(fit.summary())

The same modeling surface supports scalar hierarchical priors, GLM-style expressions, and a vectorized beta @ "X" path backed by faer.

Reuse one model structure

When the structure is shared across datasets, compile it once and bind new data:

builder = rmc.ModelBuilder()
intercept = builder.normal_prior("intercept", mu=0.0, sigma=5.0)
slope = builder.normal_prior("slope", mu=0.0, sigma=2.0)
builder.normal_likelihood(
    "obs",
    mu_expr=intercept + slope * "x",
    sigma=1.0,
    observed_key="y",
)

compiled = builder.compile()
batch = compiled.sample_batch(
    [
        {"x": x_a, "y": y_a},
        {"x": x_b, "y": y_b},
    ],
    ids=["dataset-a", "dataset-b"],
    chains=4,
    warmup=500,
    draws=1_000,
    seed=42,
)

CompiledModel validates each binding against the same structural schema. The legacy sample() and batch_sample() entry points remain available.

Forecasting as an application

Forecasting is one application of rustmc's structure-aware inference rather than the definition of the library. Current specialized models include Bayesian local level, seasonal local level, local linear trend, and directly observed Gaussian AR(p), plus fixed-parameter linear Gaussian state-space filtering, smoothing, and a sum-to-zero seasonal constructor.

values = np.asarray(
    [101, 98, 103, 105, 102, 108, 111, 109, 114, 116, 113, 119,
     121, 118, 123, 126, 124, 129, 131, 128, 134, 136, 133, 139],
    dtype=float,
)

model = rmc.BayesianLocalLevel(
    process_variance_prior=rmc.InverseGammaPrior(shape=3.0, scale=20.0),
    observation_variance_prior=rmc.InverseGammaPrior(shape=3.0, scale=50.0),
    initial_mean=float(values[0]),
    initial_variance=100.0,
)
fit = model.fit(values, chains=4, warmup=500, draws=1_000, seed=42)
forecast = fit.forecast(steps=12, seed=43)

predictive_lower, predictive_upper = forecast.interval(0.95)
level_lower, level_upper = forecast.state_interval(0.95)

# Derived quantities are summarized after calculation within each joint draw.
six_period_totals = forecast.observation_samples[:, :, :6].sum(axis=2)
total_mean = six_period_totals.mean()
total_interval = np.quantile(six_period_totals, [0.025, 0.975])

The observation interval is posterior predictive; the latent-level interval is a credible interval for the expected level. Applications include demand, operations, sensor data, and financial series such as rebate accruals. Rebate payments are only an example: seasonal settlement timing, zeros, contract drivers, and positive support need careful priors and may need calendar, covariate, hurdle, or positive-valued models beyond the current Gaussian fitted APIs.

Forecasting examples:

Implemented surface

Area Current support
Generic inference NUTS with configurable target_accept, fixed-trajectory HMC, transformed continuous parameters, parallel chains
Continuous priors Normal, Student-t, HalfNormal, Exponential, LogNormal, Gamma, Beta, Uniform
Likelihoods Normal, Bernoulli-logit, Poisson-log, Exponential, LogNormal, Negative Binomial
Model structure Scalar hierarchical priors, scalar/vector regression expressions, automatic non-centering for supported scalar hierarchies
Diagnostics Rank-normalized folded split R-hat, rank-normalized bulk/tail ESS, MCSE, empirical 94% HDI, divergences and acceptance summaries
Predictive workflow Prior predictive, posterior predictive, pointwise log likelihood, ArviZ export
Repeated models In-memory compile/bind reuse and parallel batch sampling
Fixed state space Time-homogeneous linear-Gaussian models, Kalman filter, RTS smoother, missing observations, a seasonal constructor, joint and cumulative conditional forecasts
Specialized inference Bayesian local level, seasonal local level, local linear trend, and directly observed Gaussian AR(p)

Bernoulli and Poisson are exposed for prior-predictive use, but discrete latent parameters are not suitable for the current gradient-based samplers. Fitted AR(p) coefficient draws are not constrained to the stationary region; explosive draws are possible and are not silently discarded.

Validation and benchmarks

The repository includes finite-difference autodiff checks, analytic and synthetic posterior recovery, state-space reference tests, cross-thread determinism checks, Python API tests, and clean-wheel verification.

Run the core verification with:

cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --release
python -m pytest -q

Run python examples/run_benchmarks.py --help for the benchmark harness. This README does not publish a numeric cross-engine result because the repository does not retain a complete raw output, environment, and revision for one. Use benchmarks/RESULTS_TEMPLATE.md when publishing a result, and report statistical quality together with wall time.

Tests establish behavior on their stated reference cases. They do not prove that a new model is appropriate for a user's data or that its intervals are calibrated under misspecification.

Current limitations

  • The expression and distribution surface is deliberately finite; arbitrary user-defined probability functions and broad tensor algebra are not yet supported.
  • Vector-valued hierarchical priors, group indexing, named dimensions, and coordinates are incomplete.
  • Compile/bind artifacts are in-memory only and are not portable or versioned.
  • Initialization controls remain limited; BFMI and explicit termination reasons are not yet reported.
  • The generic state-space API accepts fixed system matrices rather than inferring them.
  • Specialized forecasting lacks covariates/calendar interventions, multiple seasonalities, positive/robust observations, hierarchical pooling, dated outputs, and rolling backtests.
  • Performance has not been established on a representative, retained benchmark corpus.

See ROADMAP.md for the ordered engineering plan and differentiated capability ideas.

Contributing

See CONTRIBUTING.md for development and evidence requirements. Bug reports are most useful when they include a minimal model, seed, environment, diagnostics, and expected result.

License

MIT

Release files for rustmc 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rustmc 0.9.0
File Size Uploaded
rustmc-0.9.0.tar.gz 152.5 kB Details

Built distributions (wheels)

Table of built distributions (wheels) for rustmc 0.9.0
File
rustmc-0.9.0-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details
rustmc-0.9.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.9 abi3 Linux glibc 2.17+ x86-64 Details
rustmc-0.9.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.9 abi3 Linux glibc 2.17+ ARM64 Details
rustmc-0.9.0-cp39-abi3-macosx_11_0_arm64.whl CPython 3.9 abi3 macOS 11.0+ ARM64 Details
rustmc-0.9.0-cp39-abi3-macosx_10_12_x86_64.whl CPython 3.9 abi3 macOS 10.12+ x86-64 Details

Total release size: 5.8 MB

Release files / rustmc-0.9.0.tar.gz

Download URL rustmc-0.9.0.tar.gz
Size 152.5 kB
Tags Source
SHA-256 checksum
How to use checksums
aea5aace53b338aea78ac8d3c21060ae1e0b4d5f3b7f6e71761aaef05569a649
BLAKE2b-256 checksum
How to use checksums
9532c959f8946ea899d1fc15c6f69f2fd630b266b94f02879469506542ac5dee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 2, 2026.

Transparency log

Release files / rustmc-0.9.0-cp39-abi3-win_amd64.whl

Download URL rustmc-0.9.0-cp39-abi3-win_amd64.whl
Size 988.1 kB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
b4fa6437fac30d5e414b9c6220bdafd6267efedc3f2bcb219b03aa0d14ab0d61
BLAKE2b-256 checksum
How to use checksums
782cc7f3b87c5f6ae6278e537ac201084218ad91178fe18e0b7f5dfd206a0d93
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 2, 2026.

Transparency log

Release files / rustmc-0.9.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL rustmc-0.9.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 1.3 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
0b51f003569841cd18ee72512b27f895b1f8c600c4dfc5a03760afd7497adf48
BLAKE2b-256 checksum
How to use checksums
85f49341f7bda2c087dd269ae14c6fe04b1820a3a655f5e4ec9f2eaee0ab1800
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 2, 2026.

Transparency log

Release files / rustmc-0.9.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL rustmc-0.9.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 1.2 MB
Tags CPython 3.9 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
6dd15c039e6aacc361de74212ae330d0ed7825a50bd751cf4b77636191c1d3fc
BLAKE2b-256 checksum
How to use checksums
b71ac4853de4d6adbd3c4bc93044ee2753f9f245f76240f93a8527bd74df5c7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 2, 2026.

Transparency log

Release files / rustmc-0.9.0-cp39-abi3-macosx_11_0_arm64.whl

Download URL rustmc-0.9.0-cp39-abi3-macosx_11_0_arm64.whl
Size 1.1 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
d924bb503528d3322e9815b6b2d331504a71813645d11f1f95a0a785d5fe75ee
BLAKE2b-256 checksum
How to use checksums
d26d71de500eadf2c7ca4b8aca7b98240828d26b84a5f07d57d6b2bfa68a97b5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 2, 2026.

Transparency log

Release files / rustmc-0.9.0-cp39-abi3-macosx_10_12_x86_64.whl

Download URL rustmc-0.9.0-cp39-abi3-macosx_10_12_x86_64.whl
Size 1.1 MB
Tags CPython 3.9 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
892685b7275444225faa7ce4f38631f27283a1f627695039deaaa30e1f361d0e
BLAKE2b-256 checksum
How to use checksums
9ec867a3009e20a786497bc1b8136461ad35c956906ab4c729519911e09192c1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 2, 2026.

Transparency log

Release history Release notifications | RSS feed

0.13.0

6 release files

0.12.0

6 release files

This release

0.9.0 This release

6 release files

0.8.0

6 release files

0.7.0

6 release files

0.6.0

6 release files

0.5.1

6 release files

0.4.0

5 release files

0.3.1

5 release files

0.3.0

5 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page