Skip to content
Closed
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
4 changes: 2 additions & 2 deletions pytensor/tensor/rewriting/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ def local_sqrt_sqr(fgraph, node):
node_op = node.op.scalar_op

# Case for sqrt(sqr(x)) -> |x|
if isinstance(prev_op, ps.Sqrt) and isinstance(node_op, ps.Sqr):
if isinstance(prev_op, ps.Sqr) and isinstance(node_op, ps.Sqrt):
new_out = pt_abs(x.owner.inputs[0])
old_out = node.outputs[0]

Expand All @@ -537,7 +537,7 @@ def local_sqrt_sqr(fgraph, node):
return [new_out]

# Case for sqr(sqrt(x)) -> x
if isinstance(prev_op, ps.Sqr) and isinstance(node_op, ps.Sqrt):
if isinstance(prev_op, ps.Sqrt) and isinstance(node_op, ps.Sqr):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(ge(x, 0), x, np.asarray(np.nan, old_out.dtype))
Expand Down
21 changes: 11 additions & 10 deletions tests/tensor/rewriting/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -2082,18 +2082,11 @@ def setup_method(self):
self.rng = np.random.default_rng()

def test_sqr_sqrt(self):
# sqrt(x) ** 2 -> x
# sqr(sqrt(x)) -> x for x >= 0, nan for x < 0
x = pt.tensor("x", shape=(None, None))
out = sqr(sqrt(x))
out = rewrite_graph(out, include=["canonicalize", "specialize", "stabilize"])

assert equal_computations([out], [pt_abs(x)])

def test_sqrt_sqr(self):
x = pt.tensor("x", shape=(None, None))
out = sqrt(sqr(x))
out = rewrite_graph(out, include=["canonicalize", "specialize", "stabilize"])

expected = switch(
ge(x, np.zeros((1, 1), dtype="int8")),
x,
Expand All @@ -2102,9 +2095,17 @@ def test_sqrt_sqr(self):

assert equal_computations([out], [expected])

def test_sqr_sqrt_integer_upcast(self):
def test_sqrt_sqr(self):
# sqrt(sqr(x)) -> |x|
x = pt.tensor("x", shape=(None, None))
out = sqrt(sqr(x))
out = rewrite_graph(out, include=["canonicalize", "specialize", "stabilize"])

assert equal_computations([out], [pt_abs(x)])

def test_sqrt_sqr_integer_upcast(self):
x = ivector("x")
out = sqr(sqrt(x))
out = sqrt(sqr(x))
dtype = out.type.dtype
out = rewrite_graph(out, include=["canonicalize", "specialize", "stabilize"])

Expand Down
Loading