Skip to content

Commit a022812

Browse files
committed
Lift Subtensor over AdvancedSubtensor
1 parent 2d35d6c commit a022812

File tree

2 files changed

+125
-2
lines changed

2 files changed

+125
-2
lines changed

pytensor/tensor/rewriting/subtensor_lift.py

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import numpy as np
55

66
from pytensor import Variable
7+
from pytensor.compile import optdb
78
from pytensor.graph import Constant, FunctionGraph, node_rewriter
89
from pytensor.graph.rewriting.basic import NodeRewriter, copy_stack_trace
910
from pytensor.npy_2_compat import normalize_axis_index, normalize_axis_tuple
@@ -39,16 +40,18 @@
3940
)
4041
from pytensor.tensor.special import Softmax, softmax
4142
from pytensor.tensor.subtensor import (
43+
AdvancedSubtensor,
4244
AdvancedSubtensor1,
4345
Subtensor,
46+
_non_consecutive_adv_indexing,
4447
as_index_literal,
4548
get_canonical_form_slice,
4649
get_constant_idx,
4750
get_idx_list,
4851
indices_from_subtensor,
4952
)
5053
from pytensor.tensor.type import TensorType
51-
from pytensor.tensor.type_other import SliceType
54+
from pytensor.tensor.type_other import NoneTypeT, SliceType
5255
from pytensor.tensor.variable import TensorVariable
5356

5457

@@ -816,3 +819,79 @@ def local_subtensor_shape_constant(fgraph, node):
816819
return [as_tensor([1] * len(shape_parts), dtype=np.int64, ndim=1)]
817820
elif shape_parts:
818821
return [as_tensor(1, dtype=np.int64)]
822+
823+
824+
@node_rewriter([Subtensor])
825+
def local_subtensor_of_adv_subtensor(fgraph, node):
826+
"""Lift a simple Subtensor through an AdvancedSubtensor, when basic index dimensions are to the left of any advanced ones.
827+
828+
x[:, :, vec_idx][i, j] -> x[i, j][vec_idx]
829+
x[:, vec_idx][i, j, k] -> x[i][vec_idx][j, k]
830+
831+
Restricted to a single advanced indexing dimension.
832+
833+
An alternative approach could have fused the basic and advanced indices,
834+
so it is not clear this rewrite should be canonical or a specialization.
835+
Users must include it manually if it fits their use case.
836+
"""
837+
adv_subtensor, *idxs = node.inputs
838+
839+
if not (
840+
adv_subtensor.owner and isinstance(adv_subtensor.owner.op, AdvancedSubtensor)
841+
):
842+
return None
843+
844+
if len(fgraph.clients[adv_subtensor]) > 1:
845+
# AdvancedSubtensor involves a full_copy, so we don't want to do it twice
846+
return None
847+
848+
x, *adv_idxs = adv_subtensor.owner.inputs
849+
850+
# Advanced indexing is a minefield, avoid all cases except for consecutive integer indices
851+
if any(
852+
(
853+
isinstance(adv_idx.type, NoneTypeT)
854+
or (isinstance(adv_idx.type, TensorType) and adv_idx.type.dtype == "bool")
855+
or (isinstance(adv_idx.type, SliceType) and not is_full_slice(adv_idx))
856+
)
857+
for adv_idx in adv_idxs
858+
) or _non_consecutive_adv_indexing(adv_idxs):
859+
return None
860+
861+
for first_adv_idx_dim, adv_idx in enumerate(adv_idxs):
862+
# We already made sure there were only None slices besides integer indexes
863+
if isinstance(adv_idx.type, TensorType):
864+
break
865+
else: # no-break
866+
# Not sure if this should ever happen, but better safe than sorry
867+
return None
868+
869+
basic_idxs = indices_from_subtensor(idxs, node.op.idx_list)
870+
basic_idxs_lifted = basic_idxs[:first_adv_idx_dim]
871+
basic_idxs_kept = ((slice(None),) * len(basic_idxs_lifted)) + basic_idxs[
872+
first_adv_idx_dim:
873+
]
874+
875+
if all(basic_idx == slice(None) for basic_idx in basic_idxs_lifted):
876+
# All basic indices happen to the right of the advanced indices
877+
return None
878+
879+
[basic_subtensor] = node.outputs
880+
dropped_dims = _dims_dropped_by_basic_index(basic_idxs_lifted)
881+
882+
x_indexed = x[basic_idxs_lifted]
883+
copy_stack_trace([basic_subtensor, adv_subtensor], x_indexed)
884+
885+
x_after_index_lift = expand_dims(x_indexed, dropped_dims)
886+
x_after_adv_idx = adv_subtensor.owner.op(x_after_index_lift, *adv_idxs)
887+
copy_stack_trace([basic_subtensor, adv_subtensor], x_after_adv_idx)
888+
889+
new_out = squeeze(x_after_adv_idx[basic_idxs_kept], dropped_dims)
890+
return [new_out]
891+
892+
893+
# Rewrite will only be included if tagged by name
894+
r = local_subtensor_of_adv_subtensor
895+
optdb["canonicalize"].register(r.__name__, r, use_db_name_as_tag=False)
896+
optdb["specialize"].register(r.__name__, r, use_db_name_as_tag=False)
897+
del r

tests/tensor/rewriting/test_subtensor_lift.py

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
)
4848
from pytensor.tensor.shape import SpecifyShape, Unbroadcast, _shape
4949
from pytensor.tensor.special import softmax
50-
from pytensor.tensor.subtensor import Subtensor
50+
from pytensor.tensor.subtensor import AdvancedSubtensor, Subtensor
5151

5252

5353
mode_opt = config.mode
@@ -755,3 +755,47 @@ def __eq__(self, other):
755755
x = shape(Variable(MyType(), None, None))[0]
756756

757757
assert not local_subtensor_shape_constant.transform(None, x.owner)
758+
759+
760+
@pytest.mark.parametrize(
761+
"original_fn, supported",
762+
[
763+
(lambda x: x[:, [0, 1]][0], True),
764+
(lambda x: x[:, [0, 1], [0, 0]][1:], True),
765+
(lambda x: x[:, [[0, 1], [0, 0]]][1:], True),
766+
# Not supported, basic indexing on advanced indexing dim
767+
(lambda x: x[[0, 1]][0], False),
768+
# Not implemented, basic indexing on the right of advanced indexing
769+
(lambda x: x[[0, 1]][:, 0], False),
770+
# Not implemented, complex flavors of advanced indexing
771+
(lambda x: x[:, None, [0, 1]][0], False),
772+
(lambda x: x[:, 5:, [0, 1]][0], False),
773+
(lambda x: x[:, :, np.array([True, False, False])][0], False),
774+
(lambda x: x[[0, 1], :, [0, 1]][:, 0], False),
775+
],
776+
)
777+
def test_local_subtensor_of_adv_subtensor(original_fn, supported):
778+
rng = np.random.default_rng(257)
779+
x = pt.tensor3("x", shape=(7, 5, 3))
780+
x_test = rng.normal(size=x.type.shape)
781+
782+
out = original_fn(x)
783+
opt_out = rewrite_graph(
784+
out, include=("canonicalize", "local_subtensor_of_adv_subtensor")
785+
)
786+
# The graphs generated are too complicated to assert
787+
# We simply check that the happens before the advanced subtensor
788+
toposort = FunctionGraph(outputs=[opt_out], clone=False).toposort()
789+
[idx_subtensor] = [
790+
i for i, node in enumerate(toposort) if isinstance(node.op, Subtensor)
791+
]
792+
[idx_adv_subtensor] = [
793+
i for i, node in enumerate(toposort) if isinstance(node.op, AdvancedSubtensor)
794+
]
795+
swapped = idx_subtensor < idx_adv_subtensor
796+
correct = swapped if supported else not swapped
797+
assert correct, debugprint(opt_out, print_type=True)
798+
np.testing.assert_allclose(
799+
opt_out.eval({x: x_test}, mode=NO_OPTIMIZATION_MODE),
800+
out.eval({x: x_test}, mode=NO_OPTIMIZATION_MODE),
801+
)

0 commit comments

Comments
 (0)