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 7 commits
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
2 changes: 0 additions & 2 deletions bambi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import logging

from pymc import math
aloctavodia marked this conversation as resolved.
Show resolved Hide resolved

from .data import clear_data_home, load_data
from .families import Family, Likelihood, Link
from .models import Model
Expand Down
74 changes: 52 additions & 22 deletions bambi/backend/pymc.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def run(
):
"""Run PyMC sampler."""
# NOTE: Methods return different types of objects (idata, approximation, and dictionary)
if method.lower() == "mcmc":
if method.lower() in ["mcmc", "nuts_numpyro", "nuts_blackjax"]:
result = self._run_mcmc(
draws,
tune,
Expand All @@ -99,6 +99,7 @@ def run(
chains,
cores,
random_seed,
method.lower(),
**kwargs,
)
elif method.lower() == "vi":
Expand Down Expand Up @@ -209,40 +210,69 @@ def _run_mcmc(
chains=None,
cores=None,
random_seed=None,
sampler_backend="mcmc",
aloctavodia marked this conversation as resolved.
Show resolved Hide resolved
**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 == "mcmc":
aloctavodia marked this conversation as resolved.
Show resolved Hide resolved
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 == "nuts_numpyro":
import pymc.sampling_jax # Lazy import to not force users to install Jax
if not chains:
chains = 4 # sample_numpyro_nuts does not handle chains = None like pm.sample does
idata = pm.sampling_jax.sample_numpyro_nuts(
draws=draws,
tune=tune,
chains=chains,
random_seed=random_seed,
**kwargs,
)
elif sampler_backend == "nuts_blackjax":
import pymc.sampling_jax # Lazy import to not force users to install Jax
if not chains:
chains = 4 # sample_blackjax_nuts does not handle chains = None like pm.sample does
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'``mcmc``, ``nuts_numpyro`` or ``nuts_blackjax``'
)

idata = self._clean_mcmc_results(idata, omit_offsets, include_mean)
return idata
Expand Down
5 changes: 5 additions & 0 deletions bambi/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,11 @@ def fit(
using the ``fit`` function.
Finally, ``"laplace"``, in which case a Laplace approximation is used and is not
recommended other than for pedagogical use.
To use the PyMC numpyro and blackjax samplers, use ``nuts_numpyro`` or ``nuts_blackjax``
respectively. Both methods will only work if you can use NUTS sampling, so your model must
be differentiable. It is also recommended, if using ``nuts_numpyro`` or
``nuts_blackjax``, to set the kwarg of ``chain_method`` to either ``parallel`` or
``vectorized`` for optimal performance.
init: str
Initialization method. Defaults to ``"auto"``. The available methods are:
* auto: Use ``"jitter+adapt_diag"`` and if this method fails it uses ``"adapt_diag"``.
Expand Down