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
3 changes: 1 addition & 2 deletions pytensor/scalar/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3929,8 +3929,7 @@ class Real(UnaryScalarOp):
"""

# numpy.real(float32) return a view on the inputs.
# nfunc_spec = ('real', 1, 1)
nfunc_spec = ("real", 1, 1)

def impl(self, x):
return np.real(x)
Expand Down
19 changes: 19 additions & 0 deletions tests/tensor/test_elemwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -1174,3 +1174,22 @@ def test_inplace_dtype_changed():
mode="fast_run",
)
assert fn64.maker.fgraph.outputs[0].owner.op.destroy_map == {}


@pytest.mark.parametrize("linker", ["py", "cvm", "numba"])
def test_nfunc_view_workaround(linker):
# np.real on a buffer returns a view, Elemwise python perform method works around it by making a copy
# Other backends shouldn't worry
a = pt.zvector("a")
b = pt.real(a)
c = Elemwise(ps.mul, inplace_pattern={0: 0})(b, 2.0)
out = c + a
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.

This cannot be computed if c mutates a, through b. PyTensor would be happy to create this graph unless it's told b is a view or mutates a. We enforce this by not letting any elemwise be a view by accident


mode = Mode(linker=linker, optimizer=None)
f = function([a], out, mode=mode, accept_inplace=True)

a_test = np.array([1 + 2j, 3 + 4j, 5 + 6j])
out_expected = np.real(a_test) * 2 + a_test

out_eval = f(a_test)
np.testing.assert_allclose(out_eval, out_expected)
Loading