-
Notifications
You must be signed in to change notification settings - Fork 91
New ADVI API #635
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
Merged
Merged
New ADVI API #635
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
14ebc23
Add ADVI fit API with compiled SVI step and optimizers
ricardoV94 0921355
Use same backend for deterministics
ricardoV94 b7141c2
Use exp unconstraining in the ADVI guides
ricardoV94 f463675
Rework ADVI training around a single Trainer object
zaxtax b3f44ad
Let the ADVI Trainer own its training state
ricardoV94 30cb921
Rebuild the ADVI notebook around the new Trainer API
ricardoV94 d14cb71
Drop early stopping and make schedules follow the global step
ricardoV94 380120a
Remove learning_rate and clip_norm from Trainer, move defaults to opt…
zaxtax File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import numpy as np | ||
| import xarray as xr | ||
|
|
||
| from pymc import Model, modelcontext | ||
| from xarray import DataTree | ||
|
|
||
| from pymc_extras.inference.advi.optimizers import GradientTransformation | ||
| from pymc_extras.inference.advi.training import Trainer | ||
|
|
||
|
|
||
| def fit_advi( | ||
| model: Model | None = None, | ||
| *, | ||
| n_steps: int = 10_000, | ||
| n_particles: int = 1, | ||
| draws: int = 1_000, | ||
| optimizer: GradientTransformation | None = None, | ||
| path_derivative_gradient: bool = True, | ||
| random_seed=None, | ||
| backend: str | None = None, | ||
| compile_kwargs: dict | None = None, | ||
| ) -> DataTree: | ||
| """Fit a model with automatic differentiation variational inference (ADVI). | ||
|
|
||
| Fits a mean-field normal approximation to the model posterior in the unconstrained | ||
| space, then returns posterior draws from the fitted guide. A one-shot wrapper around | ||
| :class:`~pymc_extras.inference.advi.training.Trainer` with its default guide; use the | ||
| trainer directly to keep training, change the optimizer between runs, or sample | ||
| more than once. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Model, optional | ||
| The PyMC model to fit. If None, the model is inferred from context. | ||
| n_steps : int, optional | ||
| Number of optimization steps, by default 10_000. | ||
| n_particles : int, optional | ||
| Number of guide draws per step used to estimate the ELBO gradient, by default 1. | ||
| draws : int, optional | ||
| Number of posterior draws to sample from the fitted guide, by default 1_000. | ||
| optimizer : GradientTransformation, optional | ||
| An optax-like optimizer (actual optax optimizers are compatible). By default, | ||
| :func:`clipped_adam` is used. | ||
| path_derivative_gradient : bool, optional | ||
| Whether to use the lower-variance path-derivative ("sticking the landing") | ||
| gradient estimator, by default True. It is an unbiased variance reduction (it changes | ||
| only the gradient, not the ELBO); numpyro's ``Trace_ELBO`` does not offer it. | ||
| random_seed : optional | ||
| Seed for the guide initialization, the training draws, and the posterior draws. | ||
| backend : str, optional | ||
| PyTensor backend to compile the training and sampling functions with | ||
| (e.g. "numba", "jax", "c"). Mutually exclusive with ``compile_kwargs["mode"]``. | ||
| compile_kwargs : dict, optional | ||
| Additional kwargs passed to pytensor compilation. | ||
|
|
||
| Returns | ||
| ------- | ||
| DataTree | ||
| Posterior draws from the fitted guide, with the negative loss history in the | ||
| ``fit`` group (as ``elbo``). | ||
| """ | ||
| model = modelcontext(model) | ||
|
|
||
| if random_seed is not None: | ||
| rng = np.random.default_rng(random_seed) | ||
| init_seed, train_seed, sampling_seed = (int(s) for s in rng.integers(2**30, size=3)) | ||
| else: | ||
| init_seed = train_seed = sampling_seed = None | ||
|
|
||
| trainer = Trainer( | ||
| optimizer=optimizer, | ||
| n_particles=n_particles, | ||
| path_derivative_gradient=path_derivative_gradient, | ||
| model=model, | ||
| backend=backend, | ||
| compile_kwargs=compile_kwargs, | ||
| random_seed=init_seed, | ||
| ) | ||
| state = trainer.fit(n_steps, random_seed=train_seed) | ||
| idata = trainer.sample_posterior(draws, random_seed=sampling_seed) | ||
| idata["fit"] = DataTree(dataset=xr.Dataset({"elbo": ("step", -state.loss_history)})) | ||
| return idata |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We had it with softplus since that's what numpyro does? Why change?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
2x faster, logdet becomes -scale, instead of log(softplus)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's not a sure choice, just something I'm exploring