Named tensors with typed spaces#477
Conversation
PyTensor variables shouldn't show up in the attributes of Variable types. |
|
had a few more thoughts on this, and found that also for unordered spaces we need to know which index a dimension has in the underlying array. With that information one can then index into Now the question is where this information should be kept. Either the Maybe it's enough to keep a |
| class XTensorFromTensor(Op): | ||
| __props__ = ("dims",) | ||
|
|
||
| def __init__(self, dims: Iterable[DimLike]): |
There was a problem hiding this comment.
dims should be Sequence since Iterable can exhaust...
There was a problem hiding this comment.
What do you mean by "exhaust" here?
| class XElemwise(Op): | ||
| __props__ = ("scalar_op",) | ||
|
|
||
| def __init__(self, scalar_op): |
| ... | ||
|
|
||
|
|
||
| class Dim(DimLike): |
There was a problem hiding this comment.
As far as I remember, it is a bad practice to inherit a base class from the protocol
There was a problem hiding this comment.
Dim can be just a dataclass instead
There was a problem hiding this comment.
According to the explanation in the PEP I would disagree: https://peps.python.org/pep-0544/#explicitly-declaring-implementation
By inheriting the protocol, we enable type checkers to warn about incomplete/incorrect implementations.
|
Very happy to close this now that |
I took the branch from #407 and added a
pytensor.xtensor.spacesmodule that defines types to distinguish between "unordered spaces" (BaseSpace) and "ordered spaces" (OrderedSpace).BaseSpaceandOrderedSpaceare similar to sets & tuples, but do not implement some operations that would mess up interpreting them asdims.One idea here is to apply the mathematical operations not only to the variables, but also to their spaces.
For example:
This matches broadcasting in
xarray:However,
xarray.DataArray.dimsare tuples, and the commutative rule does not apply to addition ofxarray.DataArrayvariables'dims:In contrast, with this PR the resulting dims become an unordered space, and the resulting
XTensorTypeare equal:This was basic math, but we could introduce
XOps withXOp.infer_spacemethods that can implement broadcasting rules for any operation:Similarly, this should allow us to implement dot products requiring
OrderedSpaceinputs to produce anOrderedSpaceoutput, or aspecify_dimorderXOpthat orders aBaseSpaceinto anOrderedSpace.Looking at the
(None, None, None)shape from the code block above, I wonder if we should typeXTensorType.shapeas aMapping[DimLike, int | ScalarVariable]🤔