-
-
Notifications
You must be signed in to change notification settings - Fork 2k
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
Derive probability for broadcasting operations #6808
Draft
ricardoV94
wants to merge
2
commits into
pymc-devs:main
Choose a base branch
from
ricardoV94:measurable_broadcast
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.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 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 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 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,121 @@ | ||
# Copyright 2023 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. | ||
from typing import Optional | ||
|
||
import numpy as np | ||
import pytensor.tensor as pt | ||
|
||
from pytensor.graph import node_rewriter | ||
from pytensor.tensor.extra_ops import BroadcastTo | ||
|
||
from pymc.logprob.abstract import MeasurableVariable, _logprob, _logprob_helper | ||
from pymc.logprob.rewriting import PreserveRVMappings, measurable_ir_rewrites_db | ||
|
||
|
||
class MeasurableBroadcast(BroadcastTo): | ||
pass | ||
|
||
|
||
MeasurableVariable.register(MeasurableBroadcast) | ||
|
||
|
||
measurable_broadcast = MeasurableBroadcast() | ||
|
||
|
||
@_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: | ||
|
||
``logp(broadcast_to(normal(size=(3, 1)), (2, 3, 4)), zeros((2, 3, 4))) == logp(normal(size=(3, 1)), zeros((3, 1)))`` | ||
|
||
And zero if the value couldn't have possibly originated via broadcasting: | ||
|
||
``logp(broadcast_to(normal(size=(1,)), (3,)), [1, 2, 3]) == [-np.inf]`` | ||
|
||
""" | ||
[value] = values | ||
|
||
n_new_dims = len(shape) - rv.ndim | ||
assert n_new_dims >= 0 | ||
|
||
# Enumerate broadcasted dims | ||
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.
Show resolved
Hide resolved
|
||
|
||
# "Unbroadcast" value via indexing. | ||
# All entries in the broadcasted dimensions should be the same, so we simply select the first of each. | ||
indices = [] | ||
for i in range(value.ndim): | ||
# Remove expanded dims | ||
if i in expanded_dims: | ||
indices.append(0) | ||
# Keep first entry of broadcasted (but not expanded) dims | ||
elif i in broadcast_dims: | ||
indices.append(slice(0, 1)) | ||
else: | ||
indices.append(slice(None)) | ||
|
||
unbroadcast_value = value[tuple(indices)] | ||
logp = _logprob_helper(rv, unbroadcast_value) | ||
|
||
# Check that dependent values were indeed identical, by comparing with a re-broadcasted value | ||
valid_value = pt.broadcast_to(unbroadcast_value, shape) | ||
# Note: This could fail due to float-precision issues. | ||
# If that proves to be a problem we should switch to `pt.allclose` | ||
check = pt.all(pt.eq(value, valid_value)) | ||
larryshamalama marked this conversation as resolved.
Show resolved
Hide resolved
|
||
logp = pt.switch(check, logp, -np.inf) | ||
|
||
# Reintroduce expanded_dims in the returned logp | ||
if n_new_dims > 0: | ||
logp = pt.shape_padleft(logp, n_new_dims) | ||
|
||
return logp | ||
|
||
|
||
@node_rewriter([BroadcastTo]) | ||
def find_measurable_broadcast(fgraph, node): | ||
r"""Finds `BroadcastTo`\s for which a `logprob` can be computed.""" | ||
|
||
if isinstance(node.op, MeasurableBroadcast): | ||
return None # pragma: no cover | ||
|
||
rv_map_feature: Optional[PreserveRVMappings] = getattr(fgraph, "preserve_rv_mappings", None) | ||
|
||
if rv_map_feature is None: | ||
return None # pragma: no cover | ||
|
||
base_rv, *shape = node.inputs | ||
|
||
if not rv_map_feature.request_measurable([base_rv]): | ||
larryshamalama marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return None | ||
|
||
new_rv = measurable_broadcast.make_node(base_rv, *shape).default_output() | ||
|
||
return [new_rv] | ||
|
||
|
||
measurable_ir_rewrites_db.register( | ||
"find_measurable_broadcast", | ||
find_measurable_broadcast, | ||
"basic", | ||
"shape", | ||
) |
This file contains 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 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,50 @@ | ||
# Copyright 2023 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 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") | ||
|
||
# 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((1, 3, 1))), | ||
) | ||
np.testing.assert_allclose( | ||
logp_fn([1, 3, 5], np.zeros((1, 3, 5))), | ||
st.norm.logpdf(np.zeros((1, 3, 1))), | ||
) | ||
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).reshape(1, 3, 1)), | ||
) | ||
# Invalid broadcast value | ||
np.testing.assert_array_equal( | ||
logp_fn([1, 3, 5], np.arange(3 * 5).reshape(1, 3, 5)), | ||
np.full(shape=(1, 3, 1), fill_value=-np.inf), | ||
) |
This file contains 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
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
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_supp
will 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_supp
is 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?
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 Dirichlet
you 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?
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