-
Notifications
You must be signed in to change notification settings - Fork 69
PyMC/PyTensor Implementation of Pathfinder VI #387
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
fonnesbeck
merged 27 commits into
pymc-devs:main
from
aphc14:pathfinder_w_pytensor_symbolic
Jan 27, 2025
Merged
Changes from 25 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
4540b84
renamed samples argument name and pathfinder variables to avoid confu…
aphc14 0c880d2
Minor changes made to the `fit_pathfinder` function and added test
aphc14 8835cd5
extract additional pathfinder objects from high level API for debugging
aphc14 663a60a
changed pathfinder samples argument to num_draws
aphc14 05aeeaf
Merge branch 'replicate_pathfinder_w_pytensor' into scipy_lbfgs
aphc14 0db91fe
feat(pathfinder): add PyMC-based Pathfinder VI implementation
aphc14 cb4436c
Multipath Pathfinder VI implementation in pymc-experimental
aphc14 2efb511
Added type hints and epsilon parameter to fit_pathfinder
aphc14 fdc3f38
Removed initial point values (l=0) to reduce iterations. Simplified …
aphc14 1fd7a11
Added placeholder/reminder to remove jax dependency when converting t…
aphc14 ef2956f
Sync updates with draft PR #386. \n- Added pytensor.function for bfgs…
aphc14 8b134b7
Reduced size of compute graph with pathfinder_body_fn
aphc14 6484b3d
- Added TODO comments for implementing Taylor approximation methods: …
aphc14 aa765fb
fix: correct posterior approximations in Pathfinder VI
aphc14 4299a58
feat: Add dense BFGS sampling for Pathfinder VI
aphc14 f1a54c6
feat: improve Pathfinder performance and compatibility
aphc14 ea802fc
minor: improve error handling in Pathfinder VI
aphc14 a77f2c8
Progress bar and other minor changes
aphc14 9faaa72
set maxcor to max(5, floor(N / 1.9)). max=1 will cause error
aphc14 2815c4f
Merge branch 'main' into pathfinder_w_pytensor_symbolic
aphc14 e4b8996
Refactor Pathfinder VI: Default to PSIS, Add Concurrency, and Improve…
aphc14 885afaa
Improvements to Importance Sampling and InferenceData shape
aphc14 ba85587
Display summary of results, Improve error handling, General improvements
aphc14 382aeb7
Merge branch 'main' into pathfinder_w_pytensor_symbolic
aphc14 baad3d9
Move pathfinder module to pymc_extras
aphc14 862627e
Improve pathfinder error handling and type hints
aphc14 03e9dd0
fix: Use typing_extensions.Self for Python 3.10 compatibility
aphc14 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
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 was deleted.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from pymc_extras.inference.pathfinder.pathfinder import fit_pathfinder | ||
|
||
__all__ = ["fit_pathfinder"] |
139 changes: 139 additions & 0 deletions
139
pymc_extras/inference/pathfinder/importance_sampling.py
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,139 @@ | ||
import logging | ||
import warnings | ||
|
||
from dataclasses import dataclass, field | ||
from typing import Literal | ||
|
||
import arviz as az | ||
import numpy as np | ||
|
||
from numpy.typing import NDArray | ||
from scipy.special import logsumexp | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
@dataclass(frozen=True) | ||
class ImportanceSamplingResult: | ||
"""container for importance sampling results""" | ||
|
||
samples: NDArray | ||
pareto_k: float | None = None | ||
warnings: list[str] = field(default_factory=list) | ||
method: str = "none" | ||
|
||
|
||
def importance_sampling( | ||
samples: NDArray, | ||
logP: NDArray, | ||
logQ: NDArray, | ||
num_draws: int, | ||
method: Literal["psis", "psir", "identity", "none"] | None, | ||
random_seed: int | None = None, | ||
): | ||
"""Pareto Smoothed Importance Resampling (PSIR) | ||
This implements the Pareto Smooth Importance Resampling (PSIR) method, as described in Algorithm 5 of Zhang et al. (2022). The PSIR follows a similar approach to Algorithm 1 PSIS diagnostic from Yao et al., (2018). However, before computing the the importance ratio r_s, the logP and logQ are adjusted to account for the number multiple estimators (or paths). The process involves resampling from the original sample with replacement, with probabilities proportional to the computed importance weights from PSIS. | ||
|
||
Parameters | ||
---------- | ||
samples : NDArray | ||
samples from proposal distribution, shape (L, M, N) | ||
logP : NDArray | ||
log probability values of target distribution, shape (L, M) | ||
logQ : NDArray | ||
log probability values of proposal distribution, shape (L, M) | ||
num_draws : int | ||
number of draws to return where num_draws <= samples.shape[0] | ||
method : str, optional | ||
importance sampling method to use. Options are "psis" (default), "psir", "identity", "none. Pareto Smoothed Importance Sampling (psis) is recommended in many cases for more stable results than Pareto Smoothed Importance Resampling (psir). identity applies the log importance weights directly without resampling. none applies no importance sampling weights and returns the samples as is of size num_draws_per_path * num_paths. | ||
random_seed : int | None | ||
|
||
Returns | ||
------- | ||
NDArray | ||
importance sampled draws | ||
|
||
Future work! | ||
---------- | ||
- Implement the 3 sampling approaches and 5 weighting functions from Elvira et al. (2019) | ||
- Implement Algorithm 2 VSBC marginal diagnostics from Yao et al. (2018) | ||
- Incorporate these various diagnostics, sampling approaches and weighting functions into VI algorithms. | ||
|
||
References | ||
---------- | ||
Elvira, V., Martino, L., Luengo, D., & Bugallo, M. F. (2019). Generalized Multiple Importance Sampling. Statistical Science, 34(1), 129-155. https://doi.org/10.1214/18-STS668 | ||
|
||
Yao, Y., Vehtari, A., Simpson, D., & Gelman, A. (2018). Yes, but Did It Work?: Evaluating Variational Inference. arXiv:1802.02538 [Stat]. http://arxiv.org/abs/1802.02538 | ||
|
||
Zhang, L., Carpenter, B., Gelman, A., & Vehtari, A. (2022). Pathfinder: Parallel quasi-Newton variational inference. Journal of Machine Learning Research, 23(306), 1-49. | ||
""" | ||
|
||
warning_msgs = [] | ||
num_paths, _, N = samples.shape | ||
|
||
if method == "none": | ||
warning_msgs.append( | ||
"Importance sampling is disabled. The samples are returned as is which may include samples from failed paths with non-finite logP or logQ values. It is recommended to use importance_sampling='psis' for better stability." | ||
) | ||
return ImportanceSamplingResult(samples=samples, warnings=warning_msgs) | ||
else: | ||
samples = samples.reshape(-1, N) | ||
logP = logP.ravel() | ||
logQ = logQ.ravel() | ||
|
||
# adjust log densities | ||
log_I = np.log(num_paths) | ||
logP -= log_I | ||
logQ -= log_I | ||
logiw = logP - logQ | ||
|
||
with warnings.catch_warnings(): | ||
warnings.filterwarnings( | ||
"ignore", category=RuntimeWarning, message="overflow encountered in exp" | ||
) | ||
if method == "psis": | ||
replace = False | ||
logiw, pareto_k = az.psislw(logiw) | ||
elif method == "psir": | ||
replace = True | ||
logiw, pareto_k = az.psislw(logiw) | ||
elif method == "identity": | ||
replace = False | ||
pareto_k = None | ||
else: | ||
raise ValueError(f"Invalid importance sampling method: {method}") | ||
|
||
# NOTE: Pareto k is normally bad for Pathfinder even when the posterior is close to the NUTS posterior or closer to NUTS than ADVI. | ||
# Pareto k may not be a good diagnostic for Pathfinder. | ||
# TODO: Find replacement diagnostics for Pathfinder. | ||
|
||
p = np.exp(logiw - logsumexp(logiw)) | ||
rng = np.random.default_rng(random_seed) | ||
|
||
try: | ||
resampled = rng.choice(samples, size=num_draws, replace=replace, p=p, shuffle=False, axis=0) | ||
return ImportanceSamplingResult( | ||
samples=resampled, pareto_k=pareto_k, warnings=warning_msgs, method=method | ||
) | ||
except ValueError as e1: | ||
if "Fewer non-zero entries in p than size" in str(e1): | ||
num_nonzero = np.where(np.nonzero(p)[0], 1, 0).sum() | ||
warning_msgs.append( | ||
f"Not enough valid samples: {num_nonzero} available out of {num_draws} requested. Switching to psir importance sampling." | ||
) | ||
try: | ||
resampled = rng.choice( | ||
samples, size=num_draws, replace=True, p=p, shuffle=False, axis=0 | ||
) | ||
return ImportanceSamplingResult( | ||
samples=resampled, pareto_k=pareto_k, warnings=warning_msgs, method=method | ||
) | ||
except ValueError as e2: | ||
logger.error( | ||
"Importance sampling failed even with psir importance sampling. " | ||
"This might indicate invalid probability weights or insufficient valid samples." | ||
) | ||
raise ValueError( | ||
"Importance sampling failed with both with and without replacement" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: "... for both with and ..." There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
) from e2 | ||
raise |
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.
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.
Add return typehint:
) -> ImportanceSamplingResult:
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.
type hints are now added for all function outputs. Let me know if there is any more I've missed