Skip to content

Commit cbf33e4

Browse files
Add a fusion rewrite for CAReduces with Elemwise inputs
1 parent eadc6e3 commit cbf33e4

File tree

2 files changed

+109
-2
lines changed

2 files changed

+109
-2
lines changed

aesara/tensor/rewriting/elemwise.py

+58-2
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,16 @@
1111
from aesara.graph.basic import Apply, Constant, io_toposort
1212
from aesara.graph.features import ReplaceValidate
1313
from aesara.graph.op import compute_test_value, get_test_value
14-
from aesara.graph.rewriting.basic import GraphRewriter, copy_stack_trace, node_rewriter
14+
from aesara.graph.rewriting.basic import (
15+
GraphRewriter,
16+
copy_stack_trace,
17+
in2out,
18+
node_rewriter,
19+
)
1520
from aesara.graph.rewriting.db import SequenceDB
1621
from aesara.graph.utils import InconsistencyError, MethodNotDefined, TestValueError
1722
from aesara.tensor.basic import MakeVector, alloc, cast, get_scalar_constant_value
18-
from aesara.tensor.elemwise import DimShuffle, Elemwise
23+
from aesara.tensor.elemwise import CAReduce, DimShuffle, Elemwise
1924
from aesara.tensor.exceptions import NotScalarConstantError
2025
from aesara.tensor.rewriting.basic import register_canonicalize, register_specialize
2126
from aesara.tensor.shape import shape_padleft
@@ -944,3 +949,54 @@ def local_useless_composite(fgraph, node):
944949
c = aes.Composite(inputs=comp.inputs, outputs=new_outputs)
945950
e = Elemwise(scalar_op=c)(*node.inputs, return_list=True)
946951
return dict(zip([node.outputs[i] for i in idx], e))
952+
953+
954+
@node_rewriter([CAReduce])
955+
def local_careduce_fusion(fgraph, node):
956+
"""Fuse a `CAReduce` applied to an `Elemwise`."""
957+
958+
(car_input,) = node.inputs
959+
elm_node = car_input.owner
960+
961+
if elm_node is None or not isinstance(elm_node.op, Elemwise):
962+
return False
963+
964+
elm_inputs = elm_node.inputs
965+
966+
if len(elm_inputs) > 1:
967+
# TODO: Implement the multiple inputs case
968+
raise False
969+
970+
# TODO: What about the `dtype`s and other properties in `CAReduceDtype` types?
971+
car_axis = node.op.axis
972+
car_scalar_op = node.op.scalar_op
973+
elm_scalar_op = elm_node.op.scalar_op
974+
975+
scalar_elm_inputs = [
976+
aes.get_scalar_type(inp.type.dtype).make_variable() for inp in elm_inputs
977+
]
978+
elm_output = elm_scalar_op(*scalar_elm_inputs)
979+
# This input represents the previous value in the `CAReduce` binary reduction
980+
carried_car_input = elm_output.type()
981+
scalar_fused_outputs = [car_scalar_op(elm_output, carried_car_input)]
982+
983+
fused_scalar_op = aes.Composite(
984+
inputs=[carried_car_input] + scalar_elm_inputs, outputs=scalar_fused_outputs
985+
)
986+
# The fused `Op` needs to look and behave like a `BinaryScalarOp`
987+
# TODO: Generate a new `type` and make this relationship official?
988+
fused_scalar_op.identity = car_scalar_op.identity
989+
fused_scalar_op.nin = 2
990+
fused_scalar_op.nout = 1
991+
992+
new_car_op = CAReduce(fused_scalar_op, car_axis)
993+
994+
return [new_car_op(*elm_inputs)]
995+
996+
997+
compile.optdb.register( # type: ignore
998+
"local_careduce_fusion",
999+
in2out(local_careduce_fusion),
1000+
# "fusion",
1001+
position=49,
1002+
)

tests/tensor/rewriting/test_elemwise.py

+51
Original file line numberDiff line numberDiff line change
@@ -1105,6 +1105,57 @@ def test_test_values(self, test_value):
11051105
f.maker.fgraph.outputs[0].tag.test_value, np.c_[[2.0]]
11061106
)
11071107

1108+
def test_CAReduce_single_input(self):
1109+
"""Make sure that `CAReduce` and `Elemwise` fusions work with a single input."""
1110+
1111+
mode = Mode(linker="cvm")
1112+
mode._optimizer = mode._optimizer.including(
1113+
"local_careduce_fusion",
1114+
"canonicalize",
1115+
"inplace",
1116+
)
1117+
1118+
x = matrix("x")
1119+
out = exp(x).sum(axis=1)
1120+
1121+
out_fn = function([x], out, mode=mode)
1122+
(out_node,) = out_fn.maker.fgraph.toposort()
1123+
1124+
assert isinstance(getattr(out_node.op, "scalar_op"), aes.basic.Composite)
1125+
1126+
rng = np.random.default_rng(29320)
1127+
x_val = rng.random((4, 3), dtype=config.floatX)
1128+
exp_res = np.exp(x_val).sum(axis=1)
1129+
out_val = out_fn(x_val)
1130+
assert np.array_equal(out_val, exp_res)
1131+
1132+
@pytest.mark.xfail(reason="Not implemented")
1133+
def test_CAReduce_multiple_inputs(self):
1134+
"""Make sure that `CAReduce` and `Elemwise` fusions work with multiple inputs."""
1135+
1136+
mode = Mode(linker="cvm")
1137+
mode._optimizer = mode._optimizer.including(
1138+
"local_careduce_fusion",
1139+
"canonicalize",
1140+
"inplace",
1141+
)
1142+
1143+
x = vector("x")
1144+
y = vector("y")
1145+
out = (x + y).sum()
1146+
1147+
out_fn = function([x, y], out, mode=mode)
1148+
(out_node,) = out_fn.maker.fgraph.toposort()
1149+
1150+
assert isinstance(getattr(out_node.op, "scalar_op"), aes.basic.Composite)
1151+
1152+
rng = np.random.default_rng(29320)
1153+
x_val = rng.random((4, 3), dtype=config.floatX)
1154+
y_val = rng.random((4, 3), dtype=config.floatX)
1155+
exp_res = (x_val + y_val).sum(axis=1)
1156+
out_val = out_fn(x_val, y_val)
1157+
assert np.array_equal(out_val, exp_res)
1158+
11081159

11091160
class TimesN(aes.basic.UnaryScalarOp):
11101161
"""

0 commit comments

Comments
 (0)