-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Approximation's sample method uses model contexts #7940
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
11
commits into
pymc-devs:main
Choose a base branch
from
zaxtax:removing_model_field_in_fit
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.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f50af8a
Approximation's sample method uses model contexts
zaxtax a044e76
Update rslice and sample_node
zaxtax adcdf90
Make tests pass
zaxtax 6a6b591
Vibe coded
zaxtax 41cfc20
Cleanup
zaxtax 2d05203
Cleanup
zaxtax 5c15eb5
Use model context everywhere
zaxtax 135d472
Remove caching logic
zaxtax ae6b9e1
Cleanup
zaxtax adeca86
Cleanup
zaxtax b4495b7
Add test that sampling with a different model works
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
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 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -12,6 +12,8 @@ | |||||||||||||
| # See the License for the specific language governing permissions and | ||||||||||||||
| # limitations under the License. | ||||||||||||||
|
|
||||||||||||||
| from functools import cached_property | ||||||||||||||
|
|
||||||||||||||
| import numpy as np | ||||||||||||||
| import pytensor | ||||||||||||||
|
|
||||||||||||||
|
|
@@ -32,7 +34,6 @@ | |||||||||||||
| Group, | ||||||||||||||
| NotImplementedInference, | ||||||||||||||
| _known_scan_ignored_inputs, | ||||||||||||||
| node_property, | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| __all__ = ["Empirical", "FullRank", "MeanField", "sample_approx"] | ||||||||||||||
|
|
@@ -52,20 +53,20 @@ class MeanFieldGroup(Group): | |||||||||||||
| short_name = "mean_field" | ||||||||||||||
| alias_names = frozenset(["mf"]) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def mean(self): | ||||||||||||||
| return self.params_dict["mu"] | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def rho(self): | ||||||||||||||
| return self.params_dict["rho"] | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def cov(self): | ||||||||||||||
| var = rho2sigma(self.rho) ** 2 | ||||||||||||||
| return pt.diag(var) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def std(self): | ||||||||||||||
| return rho2sigma(self.rho) | ||||||||||||||
|
|
||||||||||||||
|
|
@@ -85,6 +86,13 @@ def create_shared_params(self, start=None, start_sigma=None): | |||||||||||||
| # by `self.ordering`. In the cases I looked into these turn out to be the same, but there may be edge cases or | ||||||||||||||
| # future code changes that break this assumption. | ||||||||||||||
| start = self._prepare_start(start) | ||||||||||||||
| # Ensure start is a 1D array and matches ddim | ||||||||||||||
| start = np.asarray(start).flatten() | ||||||||||||||
| if start.size != self.ddim: | ||||||||||||||
| raise ValueError( | ||||||||||||||
| f"Start array size mismatch: got {start.size}, expected {self.ddim}. " | ||||||||||||||
| f"Start shape: {start.shape if hasattr(start, 'shape') else 'unknown'}" | ||||||||||||||
| ) | ||||||||||||||
|
Comment on lines
+89
to
+95
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. Move this check to |
||||||||||||||
| rho1 = np.zeros((self.ddim,)) | ||||||||||||||
|
|
||||||||||||||
| if start_sigma is not None: | ||||||||||||||
|
|
@@ -99,14 +107,14 @@ def create_shared_params(self, start=None, start_sigma=None): | |||||||||||||
| "rho": pytensor.shared(pm.floatX(rho), "rho"), | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def symbolic_random(self): | ||||||||||||||
| initial = self.symbolic_initial | ||||||||||||||
| sigma = self.std | ||||||||||||||
| mu = self.mean | ||||||||||||||
| return sigma * initial + mu | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def symbolic_logq_not_scaled(self): | ||||||||||||||
| z0 = self.symbolic_initial | ||||||||||||||
| std = rho2sigma(self.rho) | ||||||||||||||
|
|
@@ -139,28 +147,35 @@ def __init_group__(self, group): | |||||||||||||
|
|
||||||||||||||
| def create_shared_params(self, start=None): | ||||||||||||||
| start = self._prepare_start(start) | ||||||||||||||
| # Ensure start is a 1D array and matches ddim | ||||||||||||||
| start = np.asarray(start).flatten() | ||||||||||||||
| if start.size != self.ddim: | ||||||||||||||
| raise ValueError( | ||||||||||||||
| f"Start array size mismatch: got {start.size}, expected {self.ddim}. " | ||||||||||||||
| f"Start shape: {start.shape if hasattr(start, 'shape') else 'unknown'}" | ||||||||||||||
| ) | ||||||||||||||
| n = self.ddim | ||||||||||||||
| L_tril = np.eye(n)[np.tril_indices(n)].astype(pytensor.config.floatX) | ||||||||||||||
| return {"mu": pytensor.shared(start, "mu"), "L_tril": pytensor.shared(L_tril, "L_tril")} | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def L(self): | ||||||||||||||
| L = pt.zeros((self.ddim, self.ddim)) | ||||||||||||||
| L = pt.set_subtensor(L[self.tril_indices], self.params_dict["L_tril"]) | ||||||||||||||
| Ld = L[..., np.arange(self.ddim), np.arange(self.ddim)] | ||||||||||||||
| L = pt.set_subtensor(Ld, rho2sigma(Ld)) | ||||||||||||||
| return L | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def mean(self): | ||||||||||||||
| return self.params_dict["mu"] | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def cov(self): | ||||||||||||||
| L = self.L | ||||||||||||||
| return L.dot(L.T) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def std(self): | ||||||||||||||
| return pt.sqrt(pt.diag(self.cov)) | ||||||||||||||
|
|
||||||||||||||
|
|
@@ -173,7 +188,7 @@ def num_tril_entries(self): | |||||||||||||
| def tril_indices(self): | ||||||||||||||
| return np.tril_indices(self.ddim) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def symbolic_logq_not_scaled(self): | ||||||||||||||
| z0 = self.symbolic_initial | ||||||||||||||
| diag = pt.diagonal(self.L, 0, self.L.ndim - 2, self.L.ndim - 1) | ||||||||||||||
|
|
@@ -182,7 +197,7 @@ def symbolic_logq_not_scaled(self): | |||||||||||||
| logq = quaddist - logdet | ||||||||||||||
| return logq.sum(range(1, logq.ndim)) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def symbolic_random(self): | ||||||||||||||
| initial = self.symbolic_initial | ||||||||||||||
| L = self.L | ||||||||||||||
|
|
@@ -233,17 +248,19 @@ def create_shared_params(self, trace=None, size=None, jitter=1, start=None): | |||||||||||||
| return {"histogram": pytensor.shared(pm.floatX(histogram), "histogram")} | ||||||||||||||
|
|
||||||||||||||
| def _check_trace(self): | ||||||||||||||
| from pymc.model import modelcontext | ||||||||||||||
|
|
||||||||||||||
| trace = self._kwargs.get("trace", None) | ||||||||||||||
| if isinstance(trace, InferenceData): | ||||||||||||||
| raise NotImplementedError( | ||||||||||||||
| "The `Empirical` approximation does not yet support `InferenceData` inputs." | ||||||||||||||
| " Pass `pm.sample(return_inferencedata=False)` to get a `MultiTrace` to use with `Empirical`." | ||||||||||||||
| " Please help us to refactor: https://github.com/pymc-devs/pymc/issues/5884" | ||||||||||||||
| ) | ||||||||||||||
| elif trace is not None and not all( | ||||||||||||||
| self.model.rvs_to_values[var].name in trace.varnames for var in self.group | ||||||||||||||
| ): | ||||||||||||||
| raise ValueError("trace has not all free RVs in the group") | ||||||||||||||
| elif trace is not None: | ||||||||||||||
| model = modelcontext(None) | ||||||||||||||
| if not all(model.rvs_to_values[var].name in trace.varnames for var in self.group): | ||||||||||||||
| raise ValueError("trace has not all free RVs in the group") | ||||||||||||||
|
Comment on lines
+262
to
+263
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.
Suggested change
|
||||||||||||||
|
|
||||||||||||||
| def randidx(self, size=None): | ||||||||||||||
| if size is None: | ||||||||||||||
|
|
@@ -284,24 +301,24 @@ def _new_initial(self, size, deterministic, more_replacements=None): | |||||||||||||
| else: | ||||||||||||||
| return self.histogram[self.randidx(size)] | ||||||||||||||
|
|
||||||||||||||
| @property | ||||||||||||||
| @cached_property | ||||||||||||||
| def symbolic_random(self): | ||||||||||||||
| return self.symbolic_initial | ||||||||||||||
|
|
||||||||||||||
| @property | ||||||||||||||
| @cached_property | ||||||||||||||
| def histogram(self): | ||||||||||||||
| return self.params_dict["histogram"] | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def mean(self): | ||||||||||||||
| return self.histogram.mean(0) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def cov(self): | ||||||||||||||
| x = self.histogram - self.mean | ||||||||||||||
| return x.T.dot(x) / pm.floatX(self.histogram.shape[0]) | ||||||||||||||
|
|
||||||||||||||
| @node_property | ||||||||||||||
| @cached_property | ||||||||||||||
| def std(self): | ||||||||||||||
| return pt.sqrt(pt.diag(self.cov)) | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
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.
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.
these are all just dictionary lookups (or construction of symbolic variables). I don't think it's necessary to cache them