Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for numpyro and blackjax PyMC samplers #526

Merged
merged 18 commits into from
Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 47 additions & 21 deletions bambi/backend/pymc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import numpy as np
import pymc as pm
import pymc.sampling_jax
markgoodhead marked this conversation as resolved.
Show resolved Hide resolved

import aesara.tensor as at

Expand Down Expand Up @@ -83,6 +84,7 @@ def run(
chains=None,
cores=None,
random_seed=None,
sampler_backend="default",
**kwargs,
):
"""Run PyMC sampler."""
Expand All @@ -99,6 +101,7 @@ def run(
chains,
cores,
random_seed,
sampler_backend,
**kwargs,
)
elif method.lower() == "vi":
Expand Down Expand Up @@ -209,40 +212,63 @@ def _run_mcmc(
chains=None,
cores=None,
random_seed=None,
sampler_backend="default",
**kwargs,
):
with self.model:
try:
idata = pm.sample(
draws=draws,
tune=tune,
discard_tuned_samples=discard_tuned_samples,
init=init,
n_init=n_init,
chains=chains,
cores=cores,
random_seed=random_seed,
**kwargs,
)
except (RuntimeError, ValueError):
if "ValueError: Mass matrix contains" in traceback.format_exc() and init == "auto":
_log.info(
"\nThe default initialization using init='auto' has failed, trying to "
"recover by switching to init='adapt_diag'",
)
if sampler_backend == "default":
try:
idata = pm.sample(
draws=draws,
tune=tune,
discard_tuned_samples=discard_tuned_samples,
init="adapt_diag",
init=init,
n_init=n_init,
chains=chains,
cores=cores,
random_seed=random_seed,
**kwargs,
)
else:
raise
except (RuntimeError, ValueError):
if "ValueError: Mass matrix contains" in traceback.format_exc() and init == "auto":
_log.info(
"\nThe default initialization using init='auto' has failed, trying to "
"recover by switching to init='adapt_diag'",
)
idata = pm.sample(
draws=draws,
tune=tune,
discard_tuned_samples=discard_tuned_samples,
init="adapt_diag",
n_init=n_init,
chains=chains,
cores=cores,
random_seed=random_seed,
**kwargs,
)
else:
raise
Copy link
Collaborator

@canyon289 canyon289 Jun 9, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please raise a specific exception with a helpful message

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah this was the code before I changed this function, it's just been moved around. To be honest I wondered about removing this whole error handling because I've seen pymc do the same thing internally anyway but I thought that might be out of scope for this PR - I'll do whatever is the consensus here 😄

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If youre willing editing here would be helpful, but youre right if you just moved the code it can be out of scope! My ask is just open an issue ticket to track and reference this discussion :)

elif sampler_backend == "numpyro":
idata = pm.sampling_jax.sample_numpyro_nuts(
draws=draws,
tune=tune,
chains=chains,
random_seed=random_seed,
**kwargs,
)
elif sampler_backend == "blackjax":
idata = pm.sampling_jax.sample_blackjax_nuts(
draws=draws,
tune=tune,
chains=chains,
random_seed=random_seed,
**kwargs,
)
else:
raise ValueError(
f'sampler_backend value {sampler_backend} is not valid. Please choose one of'
f'``default``, ``numpyro`` or ``blackjax``'
)

idata = self._clean_mcmc_results(idata, omit_offsets, include_mean)
return idata
Expand Down
18 changes: 18 additions & 0 deletions bambi/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ def fit(
chains=None,
cores=None,
random_seed=None,
sampler_backend="default",
**kwargs,
):
"""Fit the model using PyMC.
Expand Down Expand Up @@ -239,6 +240,17 @@ def fit(
in the system unless there are more than 4 CPUs, in which case it is set to 4.
random_seed : int or list of ints
A list is accepted if cores is greater than one.
sampler_backend: str
markgoodhead marked this conversation as resolved.
Show resolved Hide resolved
If ``default`` uses the standard PyMC fit() method. Is only valid if method == "mcmc".
markgoodhead marked this conversation as resolved.
Show resolved Hide resolved
Other valid sampling methods are ``numpyro`` and ``blackjax`` which both use JAX (see
https://www.pymc.io/blog/v4_announcement.html#new-jax-backend-for-faster-sampling)
and which offers both performance improvements on the CPU due to JIT compilation
and also GPU use (which will happen automatically if a GPU is detected - see the
JAX documentation https://jax.readthedocs.io/en/latest/index.html). Also, both
markgoodhead marked this conversation as resolved.
Show resolved Hide resolved
non-default methods will only work if you can use NUTS sampling, so your model must
be differentiable. It is also strongly recommended, if using ``numpyro`` or
``blackjax``, to set the kwarg of ``chain_method`` to either ``parallel`` or
``vectorized`` for optimal performance.
**kwargs:
For other kwargs see the documentation for ``PyMC.sample()``.

Expand All @@ -248,6 +260,11 @@ def fit(
An ``Approximation`` object if ``"vi"`` and a dictionary if ``"laplace"``.
"""

if sampler_backend != "default" and method != "mcmc":
raise ValueError(
f"Non-default sampler_backend {sampler_backend} can only be used with method 'mcmc'"
)

if not self.built:
self.build()

Expand All @@ -271,6 +288,7 @@ def fit(
chains=chains,
cores=cores,
random_seed=random_seed,
sampler_backend=sampler_backend,
**kwargs,
)

Expand Down