use typing.Annotated
as standardised format for annotating shapes of tensors using type hints.
#98702
Labels
enhancement
Not as big of a feature, but technically not a bug. Should be easy to fix
module: typing
Related to mypy type annotations
triaged
This issue has been looked at a team member, and triaged and prioritized into an appropriate module
Uh oh!
There was an error while loading. Please reload this page.
📚 The doc issue
Currently there is no standard way of annotating shapes of tensors using type hints.
Some of the currently existing solutions:
(the Pro for each of these is that they exist and do what they are suppose to)
Suggest a potential alternative/fix
Add a section to the docs about how to annotate shapes of tensors using type hints according to the ideas outlined below:
Idea
Even with PEP646 classes may only be generic with respect to proper-types (i.e.
Tensor["A"]
would never be a valid type hint as"A"
is not a proper-type). This is wheretyping.Annotated
comes to save the day (native after 3.9 available throughtyping-extension
after 3.7).typing.Annotated
allows a type to be "annotated" using arbitrary Python code. i.e.a: typing.Annotated[T, foo, bar, baz, ...]
where 'T' is the proper-type ofa
andfoo
,bar
,baz
can be any Python expression.Proposal
I propose the following format for tensor shapes:
here there are two primary ways in which dimensions are specified:
'A'
or'B'
.optionally shapes may also be unspecified using
...
akin totyping.Any
.Note that
dtype
would be something liketorch.float32
etc. or may be left out in which casetorch.float
would be assumed.Perhaps we would also allow for multiple unknown dimensions to be represented using
'*D'
. This may be useful when working with batches (that may be spread across unknown number of dimensions).\What this is not.
This isn't some proposal for a static type-checker (which would be possible based on this system) this is simply a call for creating a convention for how to annotate tensor shapes in PyTorch projects (if one wishes to do so).
Personal Motivation
I personally am a big fan of Python type hints. So naturally when I started a new PyTorch project I searched for some convention on how to annotate tensor shapes. [...] Eventually I ended up here.
cc @ezyang @malfet @rgommers @xuzhao9 @gramster
The text was updated successfully, but these errors were encountered: