|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from uuid import uuid4 |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from pytensor.graph.basic import Apply |
| 8 | +from pytensor.graph.op import Op, Variable |
| 9 | +from pytensor.scalar.basic import ScalarVariable |
| 10 | +from pytensor.xtensor.type import ( |
| 11 | + DIM_LENGTH_SCALAR, |
| 12 | + BaseDim, |
| 13 | + CloneDim, |
| 14 | + DimType, |
| 15 | + DimVariable, |
| 16 | + XTensorVariable, |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +class DimOp(Op): |
| 21 | + def perform(self, node, inputs, outputs): |
| 22 | + raise NotImplementedError( |
| 23 | + f"xtensor operation {self} must be lowered to equivalent tensor operations" |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +# Not a dim op, because it doesn't return a DimVariable |
| 28 | +class Length(Op): |
| 29 | + __props__ = () |
| 30 | + |
| 31 | + def make_node(self, *inputs: Variable) -> Apply: |
| 32 | + (x,) = inputs |
| 33 | + if not isinstance(x, DimVariable): |
| 34 | + raise TypeError(f"x must be a DimVariable, got {type(x.type)}") |
| 35 | + return Apply(self, [x], [DIM_LENGTH_SCALAR()]) |
| 36 | + |
| 37 | + def perform(self, node, inputs, outputs): |
| 38 | + outputs[0][0] = inputs[0] |
| 39 | + |
| 40 | + |
| 41 | +def _dim_size(dim: DimVariable) -> ScalarVariable: |
| 42 | + return Length()(dim) |
| 43 | + |
| 44 | + |
| 45 | +class FromLength(DimOp): |
| 46 | + __props__ = ("dim_type",) |
| 47 | + |
| 48 | + def __init__(self, dim_type: DimType): |
| 49 | + super().__init__() |
| 50 | + self.dim_type = dim_type |
| 51 | + |
| 52 | + def make_node(self, *inputs: Variable) -> Apply: |
| 53 | + (length,) = inputs |
| 54 | + if not isinstance(length, ScalarVariable): |
| 55 | + raise TypeError(f"length must be a ScalarVariable, got {type(length.type)}") |
| 56 | + if length.type != DIM_LENGTH_SCALAR: |
| 57 | + raise TypeError( |
| 58 | + f"length must be of dtype 'DIM_LENGTH_SCALAR', got {length.type.dtype}" |
| 59 | + ) |
| 60 | + return Apply(self, [length], [self.dim_type()]) |
| 61 | + |
| 62 | + def perform(self, node, inputs, outputs): |
| 63 | + """Convert the length to a list of lengths.""" |
| 64 | + outputs[0][0] = inputs[0] |
| 65 | + |
| 66 | + |
| 67 | +def from_length(length: ScalarVariable, name: str | None = None) -> DimVariable: |
| 68 | + # TODO add check for dtype |
| 69 | + if not isinstance(length, ScalarVariable): |
| 70 | + raise TypeError(f"length must be a ScalarVariable, got {type(length.type)}") |
| 71 | + if length.type != DIM_LENGTH_SCALAR: |
| 72 | + raise TypeError( |
| 73 | + f"length must be of dtype 'DIM_LENGTH_SCALAR', got {length.type.dtype}" |
| 74 | + ) |
| 75 | + |
| 76 | + uuid = uuid4() |
| 77 | + dim_type = DimType(dim=BaseDim(uuid=uuid, name=name)) |
| 78 | + op = FromLength(dim_type) |
| 79 | + return op(length, name=name) |
| 80 | + |
| 81 | + |
| 82 | +class FromTensor(Op): |
| 83 | + __props__ = ("dim_type",) |
| 84 | + |
| 85 | + def __init__(self, dim_type: DimType): |
| 86 | + super().__init__() |
| 87 | + self.dim_type = dim_type |
| 88 | + |
| 89 | + def make_node(self, *inputs: Variable) -> Apply: |
| 90 | + (x,) = inputs |
| 91 | + if not isinstance(x, XTensorVariable): |
| 92 | + raise TypeError(f"x must be an XTensorVariable, got {type(x.type)}") |
| 93 | + return Apply(self, [x], [self.dim_type()]) |
| 94 | + |
| 95 | + def perform(self, node, inputs, outputs): |
| 96 | + """Convert the tensor to a dimension variable.""" |
| 97 | + (x,) = inputs |
| 98 | + (x_var,) = node.inputs |
| 99 | + for i, dim in enumerate(x_var.type.dims): |
| 100 | + if dim == self.dim_type.dim: |
| 101 | + outputs[0][0] = x.shape[i] |
| 102 | + return |
| 103 | + raise ValueError( |
| 104 | + f"Dimension {self.dim_type.dim} not found in tensor {x.type.dims}" |
| 105 | + ) |
| 106 | + |
| 107 | + |
| 108 | +def _dim_from_tensor(x: XTensorVariable, idx: int) -> DimVariable: |
| 109 | + op = FromTensor(dim_type=DimType(x.type.dims[idx])) |
| 110 | + return op(x, name=x.type.dims[idx].name) |
| 111 | + |
| 112 | + |
| 113 | +class Clone(Op): |
| 114 | + __props__ = ("dim_type",) |
| 115 | + |
| 116 | + def __init__(self, dim_type): |
| 117 | + super().__init__() |
| 118 | + self.dim_type = dim_type |
| 119 | + |
| 120 | + def make_node(self, *inputs: Variable) -> Apply: |
| 121 | + (x,) = inputs |
| 122 | + if not isinstance(x, DimVariable): |
| 123 | + raise TypeError(f"x must be a DimVariable, got {type(x.type)}") |
| 124 | + return Apply(self, [x], [self.dim_type()]) |
| 125 | + |
| 126 | + def perform(self, node, inputs, outputs): |
| 127 | + outputs[0][0] = inputs[0] |
| 128 | + |
| 129 | + |
| 130 | +def _clone_dim(dim: DimVariable, *, name: str | None = None) -> DimVariable: |
| 131 | + """Rename a dimension variable. |
| 132 | +
|
| 133 | + Args: |
| 134 | + name: The new name for the dimension. |
| 135 | +
|
| 136 | + Returns: |
| 137 | + A new DimVariable with the updated name. |
| 138 | + """ |
| 139 | + dim_type = DimType(dim=CloneDim(uuid=uuid4(), base=dim.type.dim)) |
| 140 | + return Clone(dim_type)(dim, name=name) |
| 141 | + |
| 142 | + |
| 143 | +class Product(Op): |
| 144 | + __props__ = () |
| 145 | + |
| 146 | + def make_node(self, *dims: Variable) -> Apply: |
| 147 | + if not all(isinstance(dim, DimVariable) for dim in dims): |
| 148 | + raise TypeError("All inputs must be DimVariables.") |
| 149 | + out = dim_type() |
| 150 | + return Apply(self, list(dims), [out]) |
| 151 | + |
| 152 | + def perform(self, node, inputs, outputs): |
| 153 | + outputs[0][0] = np.prod(inputs, dtype=DIM_LENGTH_SCALAR.dtype).item() |
| 154 | + |
| 155 | + |
| 156 | +def product_dim(*dims: DimVariable, name: str | None = None) -> DimVariable: |
| 157 | + return Product()(*dims, name=name) |
| 158 | + |
| 159 | + |
| 160 | +def rebase_dim(dim: DimVariable, *tensors: XTensorVariable) -> DimVariable: |
| 161 | + if not isinstance(dim, DimVariable): |
| 162 | + raise TypeError(f"dim must be a DimVariable, got {type(dim)}") |
| 163 | + |
| 164 | + if not tensors: |
| 165 | + raise ValueError("At least one tensor must be provided for rebasing.") |
| 166 | + |
| 167 | + for tensor in tensors: |
| 168 | + for i, tensor_dim in enumerate(tensor.type.dims): |
| 169 | + if dim.type.dim == tensor_dim: |
| 170 | + return _dim_from_tensor(tensor, idx=i) |
| 171 | + raise ValueError( |
| 172 | + f"Dimension {dim.type.dim} not found in any of the provided tensors." |
| 173 | + ) |
0 commit comments