teddys-blackjax-utils
Functions for running MCMC with Blackjax.
The main aim is to provide a simple interface for running the NUTS sampler with blackJAX, much like Stan, PyMC or numpyro.
This approach is nice, in my opinion, as you don't have to learn a specialised probabilistic programming language. You 'just' have to write a JAX-compatible log density function.
Installation
teddys-blackjax-utils isn't on PyPI, so install it from GitHub:
pip install git+https://github.com/teddygroves/blackjax-utils.git
Or with uv:
uv add git+https://github.com/teddygroves/blackjax-utils.git
Quick start
import jax
import jax.numpy as jnp
from teddys_blackjax_utils import run_nuts
# Define a log-density to sample from (e.g. a standard normal)
def log_density(params):
return -0.5 * jnp.sum(params["x"] ** 2)
# Run 4 chains in parallel
key = jax.random.PRNGKey(42)
states, info = run_nuts(
key=key,
log_posterior=log_density,
init_params={"x": jnp.array([0.0])},
init_sd=1.0,
n_chain=4,
n_warmup=500,
n_sample=1000,
)
# states.position is a PyTree of samples with shape (n_chain, n_sample, ...)
samples = states.position["x"] # shape: (4, 1000, 1)
Multi-device parallelism
# Run with 4 CPU devices
JAX_NUM_CPU_DEVICES=4 python my_script.py
# pmap across all devices
states, info = run_nuts(
...,
n_chain=4,
chain_map=jax.pmap,
)
# Or use shard_map with a sub-mesh
from jax.experimental.shard_map import shard_map
from jax.sharding import Mesh, PartitionSpec
mesh = Mesh(jax.devices()[:2], axis_names=("chains",))
def chain_map(func, in_axes):
def wrapped(key, params):
key = key[0]
params = jax.tree.map(lambda x: x[0], params)
states, info = func(key, params)
states = jax.tree.map(lambda x: jnp.expand_dims(x, axis=0), states)
info = jax.tree.map(lambda x: jnp.expand_dims(x, axis=0), info)
return states, info
return shard_map(
wrapped,
mesh=mesh,
in_specs=(PartitionSpec("chains"), PartitionSpec("chains")),
out_specs=PartitionSpec("chains"),
)
states, info = run_nuts(..., n_chain=2, chain_map=chain_map)
Passing warmup and sampling kwargs
By default, **kwargs are forwarded to both warmup and sampling. Use
warmup_options and sampling_options to set or override values for a single
stage:
run_nuts(
...,
max_num_doublings=10, # goes to both warmup and sampling
warmup_options=dict(initial_step_size=0.1), # warmup only
sampling_options=dict(max_num_doublings=5), # sampling only
)
warmup_options is the only way to reach arguments that
blackjax.window_adaptation
accepts but blackjax.nuts rejects, since a plain **kwargs value is sent to
both stages and the NUTS kernel would raise TypeError. These are:
initial_step_sizetarget_acceptance_rateis_mass_matrix_diagonalinitial_inverse_mass_matriximm_shrinkage_to_previousadaptation_info_fn
Kernel parameters given only to warmup stay there: warmup_options=dict(max_num_doublings=1)
leaves sampling on the blackjax default rather than carrying the value over.
Using another sampler
run_nuts is an alias for run_sampler, which builds its warmup and its
sampling kernel through a sampler argument: a Sampler pair of factories,
defaulting to NUTS. Replace it and the same multi-chain, jittering,
flattening machinery runs a different sampler:
Sampler(make_warmup, make_kernel)
make_warmup(density, **warmup_kwargs) # -> .run(key, position, num_steps)
make_kernel(density, **params) # -> step(key, state) -> (state, info)
make_warmup's return must yield ((state, tuned_params), info), and
make_kernel receives the tuned parameters merged with the static ones. The
target density is called with whatever keyword arguments the sampler passes it,
so a sampler that threads extra state through the density — as
grapevine does with its guess — works
without teddys-blackjax-utils knowing anything about it:
from teddys_blackjax_utils import run_sampler
from grapevine import grapenuts
states, info = run_sampler(
key=key,
log_posterior=log_density, # (position, guess) -> (log_density, solution)
init_params=init_params,
n_chain=4,
sampler=grapenuts(default_guess),
)
Bind anything algorithm-specific into those two factories yourself, with
functools.partial, rather than passing it through warmup_kwargs: warmup
echoes its extra arguments back in tuned_params, which then reach the kernel
as per-step parameters.
Performance
teddys-blackjax-utils follows the blackjax speed-up guide. What it does for you:
- One
jax.jitper chain, wrapping warmup and sampling together, placed insidechain_mapso it composes correctly withvmap,pmapandshard_map. jax.lax.scanfor the sampling loop, with the NUTS kernel built once outside it.- A flat position.
run_nutsravels your position PyTree into a single 1-D array before it reaches blackjax and restores your structure in the returned samples, so a dict of parameters does not become one buffer per leaf in the scan carry. - Chain parallelism via
chain_map(see above).
Measured on one CPU device with an 8-leaf dict position (40 dimensions),
4 chains, 500 warmup and 500 sampling steps (median of the runs reported by
tests/test_benchmarks.py, see Benchmarks):
| position | median per call | |
|---|---|---|
run_nuts(flatten=False) |
PyTree | 1431ms |
run_nuts() |
flat | 696ms |
make_nuts_runner() (flatten=False) |
PyTree | 102ms |
make_nuts_runner() |
flat | 64ms |
run_nuts recompiles on every call, so its figures include compilation;
make_nuts_runner compiles once, so its figures are steady-state sampling
cost. Flattening is worth ~1.6x on its own and reusing the compiled sampler a
further ~10x.
Sampling repeatedly
run_nuts builds a fresh jax.jit on each call, so its compilation cache is
always empty and calling it in a loop recompiles every time. To sample the same
model more than once, build the sampler once with make_nuts_runner:
from teddys_blackjax_utils import make_nuts_runner
sample = make_nuts_runner(log_density, n_chain=4, n_warmup=500, n_sample=1000)
for key in jax.random.split(jax.random.PRNGKey(0), 10):
states, info = sample(key, init_params, 1.0) # compiles once, not ten times
It takes the same arguments as run_nuts apart from key, init_params and
init_sd, which move to the returned callable. Recompilation still happens if
the shape or dtype of init_params changes.
Flattening caveats
Pass flatten=False to keep your PyTree as the sampler position. Two reasons
you might need to:
- Every leaf must have a floating-point dtype. Integer leaves raise
TypeErrorrather than being silently rounded on the way back out. - Flattening is algebraically but not always bitwise identical to sampling the
PyTree directly, because XLA reassociates float operations differently on a
single array. Differences start at float rounding level (order 1e-7 in
float32) and could compound on an ill-conditioned target, so a fixed seed is
not guaranteed to reproduce
flatten=Falsenumbers exactly.
Flattening is a no-op when the position is already a single array, and gains little for two or three scalar leaves; it matters most for many leaves or large arrays.
Other tips from the guide
-
On GPU, prefer
float32(the JAX default -- leavejax_enable_x64off) and run more chains rather than fewer, since a single chain rarely saturates a GPU. -
Under
vmap, NUTS trajectory expansion is alax.while_loop, so all chains run in lockstep to the longest trajectory in the batch. With several devices available,chain_map=jax.pmapavoids that coupling. -
To profile, set
JAX_TRACE_DIRand run the trace test, then open the result in Perfetto or TensorBoard:JAX_TRACE_DIR=/tmp/jax-trace uv run pytest tests/test_benchmarks.py::test_write_jax_profile tensorboard --logdir /tmp/jax-trace
Benchmarks
tests/test_benchmarks.py uses
pytest-benchmark. Timings are
disabled by default, so a normal test run executes each benchmark body once as
a smoke test and reports nothing. To measure:
uv run pytest tests/test_benchmarks.py --benchmark-enable
Vary the problem size with environment variables, e.g.:
BENCH_N_LEAVES=16 BENCH_N_CHAIN=8 uv run pytest tests/test_benchmarks.py --benchmark-enable
Development
Clone and install with dev dependencies:
git clone https://github.com/teddygroves/blackjax-utils.git
cd blackjax-utils
uv sync
Running tests
uv run pytest
Multi-device tests require ≥ 4 CPU devices:
JAX_NUM_CPU_DEVICES=4 uv run pytest
Linting
uv run ruff check .
License
MIT
Metadata
Release files for teddys-blackjax-utils 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| teddys_blackjax_utils-0.2.1.tar.gz | 12.6 kB | With provenance | Details for teddys_blackjax_utils-0.2.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| teddys_blackjax_utils-0.2.1-py3-none-any.whl | Python 3 | none | any | Details for teddys_blackjax_utils-0.2.1-py3-none-any.whl |
Total release size: 26.0 kB
Release files / teddys_blackjax_utils-0.2.1.tar.gz
| Download URL | teddys_blackjax_utils-0.2.1.tar.gz |
|---|---|
| Size | 12.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
73223191ab7a413df14e08d9c11d8881c5985b0c4e3d987dd0d2069a17b90c2d
|
|
BLAKE2b-256 checksum How to use checksums |
c1405b74281fd50913131e7fd984ccffc9c9b880faaa499f096b346bf4fbbafb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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 Nov 13, 2026.
Transparency logRelease files / teddys_blackjax_utils-0.2.1-py3-none-any.whl
| Download URL | teddys_blackjax_utils-0.2.1-py3-none-any.whl |
|---|---|
| Size | 13.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f839fdc1bc0ddb962e17bc72015d4759b69bcf9711e563314bccd278fbd0136c
|
|
BLAKE2b-256 checksum How to use checksums |
08b171c05cb3327184707161a56209535eb1185eeaf904c98c7588726f1e5ac7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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 Nov 13, 2026.
Transparency logSecurity for teddys-blackjax-utils 0.2.1
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for teddys_blackjax_utils-0.2.1.tar.gz
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 Nov 13, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.