|
| 1 | +from itertools import zip_longest |
| 2 | + |
| 3 | +from pytensor import as_symbolic |
| 4 | +from pytensor.graph import Constant, node_rewriter |
| 5 | +from pytensor.tensor import TensorType, arange, specify_shape |
| 6 | +from pytensor.tensor.subtensor import _non_consecutive_adv_indexing |
| 7 | +from pytensor.tensor.type_other import NoneTypeT, SliceType |
| 8 | +from pytensor.xtensor.basic import tensor_from_xtensor, xtensor_from_tensor |
| 9 | +from pytensor.xtensor.indexing import Index |
| 10 | +from pytensor.xtensor.rewriting.utils import register_xcanonicalize |
| 11 | +from pytensor.xtensor.type import XTensorType |
| 12 | + |
| 13 | + |
| 14 | +def to_basic_idx(idx): |
| 15 | + if isinstance(idx.type, SliceType): |
| 16 | + if isinstance(idx, Constant): |
| 17 | + return idx.data |
| 18 | + elif idx.owner: |
| 19 | + # MakeSlice Op |
| 20 | + # We transform NoneConsts to regular None so that basic Subtensor can be used if possible |
| 21 | + return slice( |
| 22 | + *[ |
| 23 | + None if isinstance(i.type, NoneTypeT) else i |
| 24 | + for i in idx.owner.inputs |
| 25 | + ] |
| 26 | + ) |
| 27 | + else: |
| 28 | + return idx |
| 29 | + if ( |
| 30 | + isinstance(idx.type, XTensorType) |
| 31 | + and idx.type.ndim == 0 |
| 32 | + and idx.type.dtype != bool |
| 33 | + ): |
| 34 | + return idx.values |
| 35 | + raise TypeError("Cannot convert idx to basic idx") |
| 36 | + |
| 37 | + |
| 38 | +@register_xcanonicalize |
| 39 | +@node_rewriter(tracks=[Index]) |
| 40 | +def lower_index(fgraph, node): |
| 41 | + """Lower XTensorVariable indexing to regular TensorVariable indexing. |
| 42 | +
|
| 43 | + xarray-like indexing has two modes: |
| 44 | + 1. Orthogonal indexing: Indices of different output labeled dimensions are combined to produce all combinations of indices. |
| 45 | + 2. Vectorized indexing: Indices of the same output labeled dimension are combined point-wise like in regular numpy advanced indexing. |
| 46 | +
|
| 47 | + An Index Op can combine both modes. |
| 48 | + To achieve orthogonal indexing using numpy semantics we must use multidimensional advanced indexing. |
| 49 | + We expand the dims of each index so they are as large as the number of output dimensions, place the indices that |
| 50 | + belong to the same output dimension in the same axis, and those that belong to different output dimensions in different axes. |
| 51 | +
|
| 52 | + For instance to do an outer 2x2 indexing we can select x[arange(x.shape[0])[:, None], arange(x.shape[1])[None, :]], |
| 53 | + This is a generalization of `np.ix_` that allows combining some dimensions, and not others, as well as have |
| 54 | + indices that have more than one dimension at the start. |
| 55 | +
|
| 56 | + In addition, xarray basic index (slices), can be vectorized with other advanced indices (if they act on the same output dimension). |
| 57 | + However, in numpy, basic indices are always orthogonal to advanced indices. To make them behave like vectorized indices |
| 58 | + we have to convert them slices to equivalent advanced indices. |
| 59 | + We do this by creating an `arange` tensor that matches the shape of the dimension being indexed, |
| 60 | + and then indexing it with the original slice. This index is then handled as a regular advanced index. |
| 61 | +
|
| 62 | + Note: The IndexOp has only 2 types of indices: Slices and XTensorVariables. Regular array indices |
| 63 | + are converted to the appropriate XTensorVariable by `Index.make_node` |
| 64 | + """ |
| 65 | + |
| 66 | + x, *idxs = node.inputs |
| 67 | + [out] = node.outputs |
| 68 | + x_tensor = tensor_from_xtensor(x) |
| 69 | + |
| 70 | + if all( |
| 71 | + ( |
| 72 | + isinstance(idx.type, SliceType) |
| 73 | + or (isinstance(idx.type, XTensorType) and idx.type.ndim == 0) |
| 74 | + ) |
| 75 | + for idx in idxs |
| 76 | + ): |
| 77 | + # Special case having just basic indexing |
| 78 | + x_tensor_indexed = x_tensor[tuple(to_basic_idx(idx) for idx in idxs)] |
| 79 | + |
| 80 | + else: |
| 81 | + # General case, we have to align the indices positionally to achieve vectorized or orthogonal indexing |
| 82 | + # May need to convert basic indexing to advanced indexing if it acts on a dimension that is also indexed by an advanced index |
| 83 | + x_dims = x.type.dims |
| 84 | + x_shape = tuple(x.shape) |
| 85 | + out_ndim = out.type.ndim |
| 86 | + out_dims = out.type.dims |
| 87 | + aligned_idxs = [] |
| 88 | + basic_idx_axis = [] |
| 89 | + # zip_longest adds the implicit slice(None) |
| 90 | + for i, (idx, x_dim) in enumerate( |
| 91 | + zip_longest(idxs, x_dims, fillvalue=as_symbolic(slice(None))) |
| 92 | + ): |
| 93 | + if isinstance(idx.type, SliceType): |
| 94 | + if not any( |
| 95 | + ( |
| 96 | + isinstance(other_idx.type, XTensorType) |
| 97 | + and x_dim in other_idx.dims |
| 98 | + ) |
| 99 | + for j, other_idx in enumerate(idxs) |
| 100 | + if j != i |
| 101 | + ): |
| 102 | + # We can use basic indexing directly if no other index acts on this dimension |
| 103 | + # This is an optimization that avoids creating an unnecessary arange tensor |
| 104 | + # and facilitates the use of the specialized AdvancedSubtensor1 when possible |
| 105 | + aligned_idxs.append(idx) |
| 106 | + basic_idx_axis.append(out_dims.index(x_dim)) |
| 107 | + else: |
| 108 | + # Otherwise we need to convert the basic index into an equivalent advanced indexing |
| 109 | + # And align it so it interacts correctly with the other advanced indices |
| 110 | + adv_idx_equivalent = arange(x_shape[i])[to_basic_idx(idx)] |
| 111 | + ds_order = ["x"] * out_ndim |
| 112 | + ds_order[out_dims.index(x_dim)] = 0 |
| 113 | + aligned_idxs.append(adv_idx_equivalent.dimshuffle(ds_order)) |
| 114 | + else: |
| 115 | + assert isinstance(idx.type, XTensorType) |
| 116 | + if idx.type.ndim == 0: |
| 117 | + # Scalar index, we can use it directly |
| 118 | + aligned_idxs.append(idx.values) |
| 119 | + else: |
| 120 | + # Vector index, we need to align the indexing dimensions with the base_dims |
| 121 | + ds_order = ["x"] * out_ndim |
| 122 | + for j, idx_dim in enumerate(idx.dims): |
| 123 | + ds_order[out_dims.index(idx_dim)] = j |
| 124 | + aligned_idxs.append(idx.values.dimshuffle(ds_order)) |
| 125 | + |
| 126 | + # Squeeze indexing dimensions that were not used because we kept basic indexing slices |
| 127 | + if basic_idx_axis: |
| 128 | + aligned_idxs = [ |
| 129 | + idx.squeeze(axis=basic_idx_axis) |
| 130 | + if (isinstance(idx.type, TensorType) and idx.type.ndim > 0) |
| 131 | + else idx |
| 132 | + for idx in aligned_idxs |
| 133 | + ] |
| 134 | + |
| 135 | + x_tensor_indexed = x_tensor[tuple(aligned_idxs)] |
| 136 | + |
| 137 | + if basic_idx_axis and _non_consecutive_adv_indexing(aligned_idxs): |
| 138 | + # Numpy moves advanced indexing dimensions to the front when they are not consecutive |
| 139 | + # We need to transpose them back to the expected output order |
| 140 | + x_tensor_indexed_basic_dims = [out_dims[idx] for idx in basic_idx_axis] |
| 141 | + x_tensor_indexed_dims = [ |
| 142 | + dim for dim in out_dims if dim not in x_tensor_indexed_basic_dims |
| 143 | + ] + x_tensor_indexed_basic_dims |
| 144 | + transpose_order = [x_tensor_indexed_dims.index(dim) for dim in out_dims] |
| 145 | + x_tensor_indexed = x_tensor_indexed.transpose(transpose_order) |
| 146 | + |
| 147 | + # Add lost shape information |
| 148 | + x_tensor_indexed = specify_shape(x_tensor_indexed, out.type.shape) |
| 149 | + new_out = xtensor_from_tensor(x_tensor_indexed, dims=out.type.dims) |
| 150 | + return [new_out] |
0 commit comments