Skip to content

Fix einsum failing with repeated inputs #1260

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 6 commits into from
Mar 10, 2025
Merged
Changes from 1 commit
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
13 changes: 12 additions & 1 deletion pytensor/tensor/einsum.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,17 @@ def _right_to_left_path(n: int) -> tuple[tuple[int, int], ...]:
return tuple(pairwise(reversed(range(n))))


def _ensure_not_equal(elements):
"""
Ensures that any pair in a list of elements are not the same object. If a pair of elements is found to be equal, then one of them is converted to a copy.
"""
for i in range(len(elements)):
for j in range(i + 1, len(elements)):
if elements[i] == elements[j]:
elements[j] = elements[j].copy()
return elements
Copy link
Member

@ricardoV94 ricardoV94 Mar 3, 2025

Choose a reason for hiding this comment

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

Some small optimization. Don't assume a list is passed and reduce list access. Also is should be better than ==.

Suggested change
for i in range(len(elements)):
for j in range(i + 1, len(elements)):
if elements[i] == elements[j]:
elements[j] = elements[j].copy()
return elements
elements = list(elements)
n_elem = len(elements)
for i, elem1 in enumerate(elements[:-1]):
for j, elem2 in enumerate(elements[i + 1:], start=i+1):
if elem1 is elem2:
elements[j] = elem1.copy()
return elements



def einsum(subscripts: str, *operands: "TensorLike", optimize=None) -> TensorVariable:
"""
Multiplication and summation of tensors using the Einstein summation convention.
Expand Down Expand Up @@ -553,7 +564,7 @@ def einsum(subscripts: str, *operands: "TensorLike", optimize=None) -> TensorVar
"If you need this functionality open an issue in https://github.com/pymc-devs/pytensor/issues to let us know. "
)

tensor_operands = [as_tensor(operand) for operand in operands]
tensor_operands = _ensure_not_equal([as_tensor(operand) for operand in operands])
shapes = [operand.type.shape for operand in tensor_operands]

path: PATH
Expand Down
Loading