-
Notifications
You must be signed in to change notification settings - Fork 88
Reworking Minibatching for ADVI #713
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
Open
zaxtax
wants to merge
18
commits into
pymc-devs:main
Choose a base branch
from
zaxtax:advi-minibatch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+5,554
−307
Open
Changes from 6 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
e99b62d
Add ADVI fit API with compiled SVI step and optimizers
ricardoV94 173a57f
Rework ADVI training around a single Trainer object
zaxtax 27ed6ba
Use same backend for deterministics
ricardoV94 3750535
Stream minibatches through Trainer.fit with likelihood rescaling
zaxtax 7472c32
Add minibatch-iterator ADVI notebook and fix pm.Data auto-rescaling
zaxtax 35f01d6
Use model.logp(sum=False) with dot-product for logp scalings
zaxtax 7ae09aa
Clean up minor nits from review
zaxtax 1e8b359
Remove tests flagged by review: test_fit_advi_random_seed_jax and tes…
zaxtax d240539
Remove learning_rate and clip_norm from Trainer, move defaults to opt…
zaxtax 2f43182
Move optimizer updates into PyTensor graph via GradientTransformation…
zaxtax 3afdcb3
Extract early stopping into a Callback system
zaxtax 7e88329
Remove banner comment from test_optimizers.py
zaxtax a40d74c
Remove callback system and early stopping
zaxtax 3d71de6
Add built-in rmsprop optimizer, update notebooks for API drift
zaxtax 8e2726f
sample_posterior: add model kwarg, always use user model context
zaxtax 1d508c8
Remove self.model from Trainer, use modelcontext throughout
zaxtax 1b2918d
Update notebooks: remove model= from Trainer, pass to fit/sample_post…
zaxtax d64a1b6
Rename _resolve_guide to _build_guide, return guide instead of mutating
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.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| 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, | ||
| convergence_window: int | None = 200, | ||
| relative_tolerance: float = 1e-3, | ||
| 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 thin wrapper around | ||
| :class:`~pymc_extras.inference.advi.training.Trainer` with its default guide. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Model, optional | ||
| The PyMC model to fit. If None, the model is inferred from context. | ||
| n_steps : int, optional | ||
| Maximum number of optimization steps, by default 10_000. Training may stop | ||
| earlier, controlled by ``convergence_window`` and ``relative_tolerance``. | ||
| 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, | ||
| clipped Adam on a :func:`linear_onecycle_schedule` peaking at 0.008 over | ||
| ``n_steps`` is compiled *into* the step function (fast path); passing an explicit | ||
| optimizer uses the Python-side update loop instead. | ||
| 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. | ||
| convergence_window : int, optional | ||
| Number of steps per convergence window, by default 200. Set to None to always | ||
| run for ``n_steps``. | ||
| relative_tolerance : float, optional | ||
| Relative loss change between consecutive windows under which training stops, | ||
| by default 1e-3. | ||
| 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, | ||
| convergence_window=convergence_window, | ||
| relative_tolerance=relative_tolerance, | ||
| 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", -np.asarray(state.loss_history, dtype=float))}) | ||
| ) | ||
| return idata | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.