-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Derive probability for broadcasting operations #6808
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
+235
−2
Merged
Changes from all commits
Commits
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
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,137 @@ | ||
| # Copyright 2024 - present The PyMC Developers | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import numpy as np | ||
| import pytensor.tensor as pt | ||
|
|
||
| from pytensor.graph.rewriting.basic import node_rewriter | ||
| from pytensor.tensor.basic import Alloc | ||
|
|
||
| from pymc.logprob.abstract import MeasurableOp, _logprob, _logprob_helper | ||
| from pymc.logprob.rewriting import measurable_ir_rewrites_db | ||
| from pymc.logprob.utils import ( | ||
| check_potential_measurability, | ||
| filter_measurable_variables, | ||
| get_related_valued_nodes, | ||
| ) | ||
|
|
||
|
|
||
| class MeasurableBroadcast(MeasurableOp, Alloc): | ||
| """A placeholder used to specify a log-likelihood for a broadcast sub-graph.""" | ||
|
|
||
|
|
||
| @_logprob.register(MeasurableBroadcast) | ||
| def broadcast_logprob(op, values, rv, *shape, **kwargs): | ||
| """Log-probability expression for (statically-)broadcasted RV. | ||
| The probability is the same as the base RV, if no broadcasting had happened. | ||
| The broadcast dimensions are degenerate copies of the base entries, so they are | ||
| consumed like support dimensions and disappear from the logp: | ||
| ``logp(broadcast_to(normal(size=(3, 1)), (2, 3, 4)), zeros((2, 3, 4))) == logp(normal(size=(3,)), zeros((3,)))`` | ||
| And zero if the value couldn't have possibly originated via broadcasting: | ||
| ``logp(broadcast_to(normal(size=(1,)), (3,)), [1, 2, 3]) == -np.inf`` | ||
| The consistency check is elementwise over the base variable's batch dimensions, | ||
| so entries that were not broadcast from each other keep their own logp. | ||
| """ | ||
| [value] = values | ||
|
|
||
| n_new_dims = len(shape) - rv.ndim | ||
| assert n_new_dims >= 0 | ||
|
|
||
| # Enumerate broadcasted dims | ||
|
Member
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. Trying to follow along here, this comment is more for "mental scribbles". rv = pt.random.normal(size=(3, 1))
x = pt.broadcast_to(rv, (5, 2, 3, 4)) # a bit more than your example above
# rv.broadcastable = (False, False, False, False)
n_new_dims = 2 # 4 - 2
expanded_dims = (0, 1)
value.broadcastable[n_new_dims:] = (False, False) # (3, 4)
rv.broadcastable = (False, True) # (3, 1)
# condition is True only: if (not v_bcast) and rv_bcast = if (not False) and True
# condition is True only if v_bast is False and rv_bcast is True
broadcast_dims = (3,) # (0 + 2, 1 + 2) but conditions are (False, True)? |
||
| expanded_dims = tuple(range(n_new_dims)) | ||
| broadcast_dims = tuple( | ||
| i + n_new_dims | ||
| for i, (v_bcast, rv_bcast) in enumerate( | ||
| zip(value.broadcastable[n_new_dims:], rv.broadcastable) | ||
| ) | ||
| if (not v_bcast) and rv_bcast | ||
| ) | ||
|
larryshamalama marked this conversation as resolved.
|
||
|
|
||
| # "Unbroadcast" value via indexing. | ||
| # All entries in the broadcasted dimensions should be the same, so we simply select | ||
| # the first of each. Broadcast dims are re-inserted with expand_dims (rather than | ||
| # sliced with `0:1`) so they are statically known to be broadcastable. | ||
| indices = [] | ||
| for i in range(value.ndim): | ||
| # Remove expanded and broadcasted (but not expanded) dims | ||
| if i in expanded_dims or i in broadcast_dims: | ||
| indices.append(0) | ||
| else: | ||
| indices.append(slice(None)) | ||
|
|
||
| unbroadcast_value = value[tuple(indices)] | ||
| # The base variable still carries the broadcast dims (with length 1); they are | ||
| # re-inserted with expand_dims so they are statically known to be broadcastable | ||
| rv_value = unbroadcast_value | ||
| if broadcast_dims: | ||
| rv_value = pt.expand_dims(rv_value, tuple(d - n_new_dims for d in broadcast_dims)) | ||
| logp = _logprob_helper(rv, rv_value) | ||
|
|
||
| # The broadcast dims are consumed like support dims and disappear from the logp | ||
| core_ndim = rv_value.ndim - logp.ndim | ||
| squeeze_axes = tuple(d - n_new_dims for d in broadcast_dims if (d - n_new_dims) < logp.ndim) | ||
| if squeeze_axes: | ||
| logp = pt.squeeze(logp, axis=squeeze_axes) | ||
|
|
||
| # Check that dependent values were indeed identical, by comparing with a re-broadcasted value. | ||
| # The check is reduced only over the expanded/broadcast dimensions (and any support | ||
| # dimensions consumed by the base logp), so unrelated batch entries do not | ||
| # contaminate each other. | ||
| # Note: This could fail due to float-precision issues. | ||
| # If that proves to be a problem we should switch to `pt.allclose` | ||
| valid_value = pt.broadcast_to(rv_value, shape) | ||
| core_dims = tuple(range(value.ndim - core_ndim, value.ndim)) | ||
| reduced_dims = tuple(sorted({*expanded_dims, *broadcast_dims, *core_dims})) | ||
| check = pt.all(pt.eq(value, valid_value), axis=reduced_dims) | ||
|
|
||
| return pt.switch(check, logp, -np.inf) | ||
|
|
||
|
|
||
| @node_rewriter([Alloc]) | ||
| def find_measurable_broadcast(fgraph, node): | ||
| r"""Find measurable broadcasts ``broadcast_to(rv, shape)``.""" | ||
| if isinstance(node.op, MeasurableOp): | ||
| return None | ||
|
|
||
| base_rv, *shape = node.inputs | ||
|
|
||
| if not filter_measurable_variables([base_rv]): | ||
| return None | ||
|
|
||
| if check_potential_measurability(shape): | ||
| return None | ||
|
|
||
| # The broadcast dimensions are degenerate copies of the base variable's entries. | ||
| # Without meta information about the support axes, other rewrites would treat the | ||
| # copies as independent entries (e.g., counting the jacobian of a transform once | ||
| # per copy), so the broadcast is only claimed when directly valued, where no other | ||
| # rewrite needs to reason about the returned logp. | ||
| # TODO: When we include the support axis as meta information in each intermediate | ||
| # MeasurableVariable, we can lift this restriction (see https://github.com/pymc-devs/pymc/issues/6360) | ||
| if not any(get_related_valued_nodes(fgraph, node)): | ||
| return None | ||
|
|
||
| return [MeasurableBroadcast()(base_rv, *shape)] | ||
|
|
||
|
|
||
| measurable_ir_rewrites_db.register( | ||
| "find_measurable_broadcast", | ||
| find_measurable_broadcast, | ||
| "basic", | ||
| "shape", | ||
| ) | ||
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,95 @@ | ||
| # Copyright 2024 - present The PyMC Developers | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import numpy as np | ||
| import pytensor | ||
| import pytensor.tensor as pt | ||
| import pytest | ||
| import scipy.stats as st | ||
|
|
||
| from pymc import logp | ||
|
|
||
|
|
||
| def test_measurable_broadcast(): | ||
| b_shape = pt.vector("b_shape", shape=(3,), dtype=int) | ||
|
|
||
| x = pt.random.normal(size=(3, 1)) | ||
| bcast_x = pt.broadcast_to(x, shape=b_shape) | ||
| bcast_x.name = "bcast_x" | ||
|
|
||
| bcast_x_value = bcast_x.clone() | ||
| logp_bcast_x = logp(bcast_x, bcast_x_value) | ||
| logp_fn = pytensor.function([b_shape, bcast_x_value], logp_bcast_x, on_unused_input="ignore") | ||
|
|
||
| # The expanded and broadcast dimensions are consumed like support dimensions: | ||
| # the logp has the base variable's remaining batch shape | ||
| # (assert_allclose also asserts shapes match, if neither is scalar) | ||
| np.testing.assert_allclose( | ||
| logp_fn([1, 3, 1], np.zeros((1, 3, 1))), | ||
| st.norm.logpdf(np.zeros(3)), | ||
| ) | ||
| np.testing.assert_allclose( | ||
| logp_fn([1, 3, 5], np.zeros((1, 3, 5))), | ||
| st.norm.logpdf(np.zeros(3)), | ||
| ) | ||
| np.testing.assert_allclose( | ||
| logp_fn([2, 3, 5], np.broadcast_to(np.arange(3).reshape(1, 3, 1), (2, 3, 5))), | ||
| st.norm.logpdf(np.arange(3)), | ||
| ) | ||
| # Invalid broadcast value | ||
| np.testing.assert_array_equal( | ||
| logp_fn([1, 3, 5], np.arange(3 * 5).reshape(1, 3, 5)), | ||
| np.full(shape=(3,), fill_value=-np.inf), | ||
| ) | ||
| # The invalidity check is elementwise over the base batch dimensions: an | ||
| # inconsistent row only invalidates its own logp | ||
| partially_valid = np.broadcast_to(np.arange(3).reshape(1, 3, 1), (1, 3, 5)).copy() | ||
| partially_valid[0, 1, 3] = 99.0 | ||
| np.testing.assert_allclose( | ||
| logp_fn([1, 3, 5], partially_valid), | ||
| np.where([True, False, True], st.norm.logpdf(np.arange(3)), -np.inf), | ||
| ) | ||
|
|
||
|
|
||
| def test_measurable_broadcast_multivariate(): | ||
| x = pt.random.dirichlet(pt.ones(3), size=(1,)) | ||
| bcast_x = pt.broadcast_to(x, (5, 3)) | ||
|
|
||
| bcast_x_value = bcast_x.clone() | ||
| logp_bcast_x = logp(bcast_x, bcast_x_value) | ||
|
|
||
| rng = np.random.default_rng(170) | ||
| row = rng.dirichlet(np.ones(3)) | ||
| valid_value = np.broadcast_to(row, (5, 3)) | ||
| valid_logp = logp_bcast_x.eval({bcast_x_value: valid_value}) | ||
| assert valid_logp.shape == () | ||
| np.testing.assert_allclose( | ||
| valid_logp, | ||
| st.dirichlet(np.ones(3)).logpdf(row), | ||
| ) | ||
|
|
||
| invalid_value = rng.dirichlet(np.ones(3), size=(5,)) | ||
| np.testing.assert_array_equal( | ||
| logp_bcast_x.eval({bcast_x_value: invalid_value}), | ||
| -np.inf, | ||
| ) | ||
|
|
||
|
|
||
| def test_broadcast_not_measurable_behind_other_ops(): | ||
| # The broadcast dimensions are degenerate copies; other rewrites would treat them | ||
| # as independent entries (e.g., counting the jacobian of the exp once per copy), | ||
| # so the broadcast is only measurable when directly valued | ||
| x = pt.random.normal() | ||
| y = pt.exp(pt.broadcast_to(x, (3,))) | ||
| with pytest.raises(NotImplementedError): | ||
| logp(y, y.clone()) |
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.
Thinking out loud: could this possibly result in inconsistencies elsewhere? For instance, having Mixture components that have been broadcasted which would render them dependent, if that would be an issue
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.
The index mixture only works for basic RVs still so that's fine.
The switch mixture could actually wrongly broadcast the logp. In fact we should also check for invalid switches that mix support dimensions. The current implementation is only correct for
ndim_supp==0!This is another example of why it's so important to have the meta-info for all the MeasurableOps (#6360).
Once we have the meta-info, the Mixture will unambiguously know what kind of measurable variable it is dealing with. In the case of MeasurableBroadcasting, for example, the
ndim_suppwill have to be at least as large as the number of broadcasted dims (which means we should collapse that logp dimension instead of leaving it as we were doing now!).We will also know where those support dims are, so that Mixture can know whether we are sub-selecting across core dims.
Without the meta-info, the only way of knowing
ndim_suppis by checking the dimensionality of the value vs the logp. We use this logic in some places already:pymc/pymc/logprob/transforms.py
Lines 432 to 437 in f67ff8b
pymc/pymc/logprob/tensor.py
Lines 185 to 189 in f67ff8b
Which makes me worry whether the probability of a transformed broadcasted variable may be invalid because the "Jacobian" term is going to be counted multiple times?
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.
You raised a very good point, which makes me wonder to what extent #6797 is correct in general?
For instance, if you scale a
3-vector Dirichletyou shouldn't count the Jacobian 3 times, because one of the entries is redundant.Do we need to propagate information about over-determined elements in multi-dimensional RVs?
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.
The first part of this answer suggests you count it 3 times indeed: https://stats.stackexchange.com/a/487538
I'm surprised :D
Edit: As seen below, that answer is wrong
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.
This I think says something else and correct? https://upcommons.upc.edu/bitstream/handle/2117/366723/p20-CoDaWork2011.pdf?sequence=1&isAllowed=y
I think these should match:
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.
This makes sense! Would you say that it's better to wait for #6360?
I'm not sure if I fully follow 😅 Nonetheless, I'm glad that this question raised some interesting concerns