Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ jobs:
tests/logprob/test_order.py
tests/logprob/test_rewriting.py
tests/logprob/test_scan.py
tests/logprob/test_shape.py
tests/logprob/test_tensor.py
tests/logprob/test_switch.py
tests/logprob/test_transform_value.py
Expand Down
1 change: 1 addition & 0 deletions pymc/logprob/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import pymc.logprob.mixture
import pymc.logprob.order
import pymc.logprob.scan
import pymc.logprob.shape
import pymc.logprob.switch
import pymc.logprob.tensor
import pymc.logprob.transforms
Expand Down
137 changes: 137 additions & 0 deletions pymc/logprob/shape.py
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):

Copy link
Copy Markdown
Member

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

@ricardoV94 ricardoV94 Jul 4, 2023

Copy link
Copy Markdown
Member Author

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:

if input_logprob.ndim < value.ndim:
# For multivariate variables, the Jacobian is diagonal.
# We can get the right result by summing the last dimensions
# of `transform_elemwise.log_jac_det`
ndim_supp = value.ndim - input_logprob.ndim
jacobian = jacobian.sum(axis=tuple(range(-ndim_supp, 0)))

pymc/pymc/logprob/tensor.py

Lines 185 to 189 in f67ff8b

if len({logp.ndim for logp in logps}) != 1:
raise ValueError(
"Joined logps have different number of dimensions, this can happen when "
"joining univariate and multivariate distributions",
)

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?

@ricardoV94 ricardoV94 Jul 4, 2023

Copy link
Copy Markdown
Member Author

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?

@ricardoV94 ricardoV94 Jul 4, 2023

Copy link
Copy Markdown
Member Author

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

Copy link
Copy Markdown
Member Author

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:

import pymc as pm
import numpy as np

x = 0.75
print(
    pm.logp(pm.Beta.dist(5, 9), x).eval(),
    pm.logp(pm.Dirichlet.dist([5, 9]), [x, 1-x]).eval(),
)  # -3.471576058736023 -3.471576058736023

print(
    pm.logp(2 * pm.Beta.dist(5, 9), 2 * x).eval(),
    pm.logp(2 * pm.Dirichlet.dist([5, 9]), 2*np.array([x, 1-x])).eval(),
)  # -4.164723239295968 -4.857870419855914

print(
    pm.logp(2 * pm.Beta.dist(5, 9), 2 * x).eval(),
    (pm.logp(pm.Dirichlet.dist([5, 9]), ([x, 1-x])) - np.log(2)).eval(),
)  # -4.164723239295968 -4.164723239295968

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!).

This makes sense! Would you say that it's better to wait for #6360?

The first part of this answer suggests you count it 3 times indeed: https://stats.stackexchange.com/a/487538

I'm surprised :D

I'm not sure if I fully follow 😅 Nonetheless, I'm glad that this question raised some interesting concerns

"""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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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
)
Comment thread
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",
)
95 changes: 95 additions & 0 deletions tests/logprob/test_shape.py
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())
3 changes: 1 addition & 2 deletions tests/logprob/test_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
from pymc.testing import assert_no_rvs


@pytest.mark.xfail(RuntimeError, reason="logprob for broadcasted RVs not implemented")
def test_bcast_rv_logp():
"""Test that derived logp for broadcasted RV is correct"""

Expand All @@ -61,11 +60,11 @@ def test_bcast_rv_logp():
logp_combined = pt.add(*logp.values())
valid_logp = logp_combined.eval({broadcasted_x_vv: [0, 0]})

# The broadcast dimension is consumed like a support dimension
assert valid_logp.shape == ()
assert np.isclose(valid_logp, st.norm.logpdf(0))

# It's not possible for broadcasted dimensions to have different values
# This should either raise or return -inf
invalid_logp = logp_combined.eval({broadcasted_x_vv: [0, 1]})
assert invalid_logp == -np.inf

Expand Down
Loading