Skip to content

Add support for negative axis in specify_broadcastable #710

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
merged 16 commits into from
Apr 19, 2024
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
5 changes: 2 additions & 3 deletions pytensor/tensor/shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import cast

import numpy as np
from numpy.core.numeric import normalize_axis_tuple # type: ignore

import pytensor
from pytensor.gradient import DisconnectedType
Expand Down Expand Up @@ -994,9 +995,7 @@ def specify_broadcastable(x, *axes):
if not axes:
return x

if max(axes) >= x.type.ndim:
raise ValueError("Trying to specify broadcastable of non-existent dimension")

axes = normalize_axis_tuple(axes, x.type.ndim)
shape_info = [1 if i in axes else s for i, s in enumerate(x.type.shape)]
return specify_shape(x, shape_info)

Expand Down
10 changes: 8 additions & 2 deletions tests/tensor/test_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,16 +562,22 @@ def test_basic(self):
x = matrix()
assert specify_broadcastable(x, 0).type.shape == (1, None)
assert specify_broadcastable(x, 1).type.shape == (None, 1)
assert specify_broadcastable(x, -1).type.shape == (None, 1)
assert specify_broadcastable(x, 0, 1).type.shape == (1, 1)

x = row()
assert specify_broadcastable(x, 0) is x
assert specify_broadcastable(x, 1) is not x
assert specify_broadcastable(x, -2) is x

def test_validation(self):
x = matrix()
with pytest.raises(ValueError, match="^Trying to specify broadcastable of*"):
specify_broadcastable(x, 2)
axis = 2
with pytest.raises(
ValueError,
match=f"axis {axis} is out of bounds for array of dimension {axis}",
):
specify_broadcastable(x, axis)


class TestRopLop(RopLopChecker):
Expand Down
Loading