|
| 1 | +from itertools import chain |
| 2 | + |
| 3 | +import pytensor.scalar as ps |
| 4 | +from pytensor.graph import Apply, Op |
| 5 | +from pytensor.tensor import TensorType, tensor |
| 6 | +from pytensor.tensor.utils import _parse_gufunc_signature |
| 7 | +from pytensor.xtensor.type import XTensorType, as_xtensor, xtensor |
| 8 | + |
| 9 | + |
| 10 | +class XOp(Op): |
| 11 | + """A base class for XOps that shouldn't be materialized""" |
| 12 | + |
| 13 | + def perform(self, node, inputs, outputs): |
| 14 | + raise NotImplementedError( |
| 15 | + "xtensor operations must be rewritten as tensor operations" |
| 16 | + ) |
| 17 | + |
| 18 | + |
| 19 | +class TensorFromXTensor(Op): |
| 20 | + view_map = {0: [0]} |
| 21 | + |
| 22 | + def make_node(self, x) -> Apply: |
| 23 | + if not isinstance(x.type, XTensorType): |
| 24 | + raise TypeError(f"x must be have an XTensorType, got {type(x.type)}") |
| 25 | + output = TensorType(x.type.dtype, shape=x.type.shape)() |
| 26 | + return Apply(self, [x], [output]) |
| 27 | + |
| 28 | + def perform(self, node, inputs, output_storage) -> None: |
| 29 | + [x] = inputs |
| 30 | + output_storage[0][0] = x |
| 31 | + |
| 32 | + |
| 33 | +tensor_from_xtensor = TensorFromXTensor() |
| 34 | + |
| 35 | + |
| 36 | +class XTensorFromTensor(Op): |
| 37 | + view_map = {0: [0]} |
| 38 | + __props__ = ("dims",) |
| 39 | + |
| 40 | + def __init__(self, dims): |
| 41 | + super().__init__() |
| 42 | + self.dims = dims |
| 43 | + |
| 44 | + def make_node(self, x) -> Apply: |
| 45 | + if not isinstance(x.type, TensorType): |
| 46 | + raise TypeError(f"x must be an TensorType type, got {type(x.type)}") |
| 47 | + output = xtensor(dtype=x.type.dtype, dims=self.dims, shape=x.type.shape) |
| 48 | + return Apply(self, [x], [output]) |
| 49 | + |
| 50 | + def perform(self, node, inputs, output_storage) -> None: |
| 51 | + [x] = inputs |
| 52 | + output_storage[0][0] = x |
| 53 | + |
| 54 | + |
| 55 | +def xtensor_from_tensor(x, dims): |
| 56 | + return XTensorFromTensor(dims=dims)(x) |
| 57 | + |
| 58 | + |
| 59 | +class XElemwise(XOp): |
| 60 | + __props__ = ("scalar_op",) |
| 61 | + |
| 62 | + def __init__(self, scalar_op): |
| 63 | + super().__init__() |
| 64 | + self.scalar_op = scalar_op |
| 65 | + |
| 66 | + def make_node(self, *inputs): |
| 67 | + inputs = [as_xtensor(inp) for inp in inputs] |
| 68 | + if (self.scalar_op.nin != -1) and (len(inputs) != self.scalar_op.nin): |
| 69 | + raise ValueError( |
| 70 | + f"Wrong number of inputs, expected {self.scalar_op.nin}, got {len(inputs)}" |
| 71 | + ) |
| 72 | + |
| 73 | + dims_and_shape: dict[str, int | None] = {} |
| 74 | + for inp in inputs: |
| 75 | + for dim, dim_length in zip(inp.type.dims, inp.type.shape): |
| 76 | + if dim not in dims_and_shape: |
| 77 | + dims_and_shape[dim] = dim_length |
| 78 | + elif dim_length is not None: |
| 79 | + # Check for conflicting shapes |
| 80 | + if (dims_and_shape[dim] is not None) and ( |
| 81 | + dims_and_shape[dim] != dim_length |
| 82 | + ): |
| 83 | + raise ValueError(f"Dimension {dim} has conflicting shapes") |
| 84 | + # Keep the non-None shape |
| 85 | + dims_and_shape[dim] = dim_length |
| 86 | + |
| 87 | + output_dims, output_shape = zip(*dims_and_shape.items()) |
| 88 | + |
| 89 | + dummy_scalars = [ps.get_scalar_type(inp.type.dtype)() for inp in inputs] |
| 90 | + output_dtypes = [ |
| 91 | + out.type.dtype for out in self.scalar_op.make_node(*dummy_scalars).outputs |
| 92 | + ] |
| 93 | + outputs = [ |
| 94 | + xtensor(dtype=output_dtype, dims=output_dims, shape=output_shape) |
| 95 | + for output_dtype in output_dtypes |
| 96 | + ] |
| 97 | + return Apply(self, inputs, outputs) |
| 98 | + |
| 99 | + |
| 100 | +class XBlockwise(XOp): |
| 101 | + __props__ = ("core_op", "signature", "core_dims") |
| 102 | + |
| 103 | + def __init__( |
| 104 | + self, |
| 105 | + core_op: Op, |
| 106 | + signature: str, |
| 107 | + core_dims: tuple[tuple[tuple[str, ...], ...], tuple[tuple[str, ...], ...]], |
| 108 | + ): |
| 109 | + super().__init__() |
| 110 | + self.core_op = core_op |
| 111 | + self.signature = signature |
| 112 | + self.inputs_sig, self.outputs_sig = _parse_gufunc_signature(signature) |
| 113 | + self.core_dims = core_dims |
| 114 | + |
| 115 | + def make_node(self, *inputs): |
| 116 | + inputs = [as_xtensor(i) for i in inputs] |
| 117 | + if len(inputs) != len(self.inputs_sig): |
| 118 | + raise ValueError( |
| 119 | + f"Wrong number of inputs, expected {len(self.inputs_sig)}, got {len(inputs)}" |
| 120 | + ) |
| 121 | + |
| 122 | + dims_and_shape: dict[str, int | None] = {} |
| 123 | + for inp in inputs: |
| 124 | + for dim, dim_length in zip(inp.type.dims, inp.type.shape): |
| 125 | + if dim not in dims_and_shape: |
| 126 | + dims_and_shape[dim] = dim_length |
| 127 | + elif dim_length is not None: |
| 128 | + # Check for conflicting shapes |
| 129 | + if (dims_and_shape[dim] is not None) and ( |
| 130 | + dims_and_shape[dim] != dim_length |
| 131 | + ): |
| 132 | + raise ValueError(f"Dimension {dim} has conflicting shapes") |
| 133 | + # Keep the non-None shape |
| 134 | + dims_and_shape[dim] = dim_length |
| 135 | + |
| 136 | + core_inputs_dims, core_outputs_dims = self.core_dims |
| 137 | + # TODO: Avoid intermediate dict |
| 138 | + core_dims = set(chain.from_iterable(core_inputs_dims)) |
| 139 | + batched_dims_and_shape = { |
| 140 | + k: v for k, v in dims_and_shape.items() if k not in core_dims |
| 141 | + } |
| 142 | + batch_dims, batch_shape = zip(*batched_dims_and_shape.items()) |
| 143 | + |
| 144 | + dummy_core_inputs = [] |
| 145 | + for inp, core_inp_dims in zip(inputs, core_inputs_dims): |
| 146 | + try: |
| 147 | + core_static_shape = [ |
| 148 | + inp.type.shape[inp.type.dims.index(d)] for d in core_inp_dims |
| 149 | + ] |
| 150 | + except IndexError: |
| 151 | + raise ValueError( |
| 152 | + f"At least one core dim={core_inp_dims} missing from input {inp} with dims={inp.type.dims}" |
| 153 | + ) |
| 154 | + dummy_core_inputs.append( |
| 155 | + tensor(dtype=inp.type.dtype, shape=core_static_shape) |
| 156 | + ) |
| 157 | + core_node = self.core_op.make_node(*dummy_core_inputs) |
| 158 | + |
| 159 | + outputs = [ |
| 160 | + xtensor( |
| 161 | + dtype=core_out.type.dtype, |
| 162 | + shape=batch_shape + core_out.type.shape, |
| 163 | + dims=batch_dims + core_out_dims, |
| 164 | + ) |
| 165 | + for core_out, core_out_dims in zip(core_node.outputs, core_outputs_dims) |
| 166 | + ] |
| 167 | + return Apply(self, inputs, outputs) |
0 commit comments