Skip to content
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

Fix bug when broadcasting branches in local_useless_switch rewrite #681

Merged
merged 1 commit into from
Mar 28, 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
19 changes: 8 additions & 11 deletions pytensor/tensor/rewriting/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1024,18 +1024,15 @@ def local_useless_switch(fgraph, node):

# if left is right -> left
if equivalent_up_to_constant_casting(left, right):
if left.type.broadcastable == out_bcast:
out_dtype = node.outputs[0].type.dtype
if left.type.dtype != out_dtype:
left = cast(left, out_dtype)
copy_stack_trace(node.outputs + left, left)
# When not casting, the other inputs of the switch aren't needed in the traceback
return [left]
if left.type.broadcastable != out_bcast:
left, _ = broadcast_arrays(left, cond)

else:
ret = broadcast_arrays(left, cond)[0]
copy_stack_trace(node.outputs + left, ret)
return [ret]
out_dtype = node.outputs[0].type.dtype
if left.type.dtype != out_dtype:
left = cast(left, out_dtype)

copy_stack_trace(node.outputs + node.inputs, left)
return [left]

# This case happens with scan.
# Elemwise{switch}(le(shape_i{id}(X), 0), 0, shape_i{id}(X)) -> shape_i{id}(X)
Expand Down
19 changes: 19 additions & 0 deletions tests/tensor/rewriting/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,25 @@ def test_broadcasting_3(self):
assert isinstance(f.maker.fgraph.outputs[0].owner.op, Alloc)
assert not any(node.op == pt.switch for node in f.maker.fgraph.toposort())

def test_broadcasting_different_dtype(self):
cond = vector("x", dtype="bool")
float32_branch = as_tensor(np.array([0], dtype="float32"))
float64_branch = as_tensor(np.array([0], dtype="float64"))

out = pt.switch(cond, float32_branch, float64_branch)
expected_out = pt.alloc(float64_branch, cond.shape)

rewritten_out = rewrite_graph(
out, include=("canonicalize", "stabilize", "specialize")
)
assert equal_computations([rewritten_out], [expected_out])

out = pt.switch(cond, float64_branch, float32_branch)
rewritten_out = rewrite_graph(
out, include=("canonicalize", "stabilize", "specialize")
)
assert equal_computations([rewritten_out], [expected_out])


class TestLocalMergeSwitchSameCond:
@pytest.mark.parametrize(
Expand Down
Loading