Skip to content

Commit 0e33cf2

Browse files
committed
Add method __torch_function__ RFC.
1 parent df823a6 commit 0e33cf2

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

RFC 0001.md

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# RFC 0001 — `__torch_function__` for methods of the `torch.Tensor` class.
2+
## Abstract
3+
This RFC describes changes necessary to allow `__torch_function__` to be used by methods of `torch.Tensor` in an attempt to make subclassing more accessible to the users of the class. This entails making an API for subclass views public, and a change in the signature of `__torch_function__`.
4+
5+
## Motivation and Scope
6+
Quoting [[1]], [[2]] and [[3]], the potential goals of this proposal are:
7+
8+
1. Support subclassing `torch.Tensor` in Python
9+
2. Preserve `Tensor` subclasses when calling `torch` functions on them
10+
3. Preserve `Tensor` subclasses when calling `numpy` functions on them
11+
4. Use the NumPy API with PyTorch tensors (i.e. NumPy API calls dispatch to `torch` functions)
12+
5. Use the PyTorch API with `torch.Tensor`-like objects that are _not_ `Tensor` subclasses
13+
6. Reuse NumPy ufunc implementations directly from PyTorch
14+
7. Allow operations on mixed array types, e.g. `tensor + ndarray`
15+
8. Preserve `Tensor` subclasses when calling `Tensor` methods.
16+
9. Propagating subclass instances correctly also with operators, using views/slices/indexing/etc.
17+
10. Preserve subclass attributes when using methods or views/slices/indexing.
18+
11. A way to insert code that operates on both functions and methods uniformly (so we can write a single function that overrides all operators).
19+
20+
We propose to solve this problem with the following changes to PyTorch:
21+
22+
1. Make methods and operators of `torch.Tensor` go through the `__torch_function__` machinery.
23+
2. Add a `types` argument to `__torch_function__`, to make it match NumPy's `__array_function__`.
24+
3. Make `torch.Tensor._make_subclass` public API.
25+
4. Make `torch.Tensor` gain a generic implementation of `__torch_function__`.
26+
27+
## Usage and Impact
28+
Once this proposal is merged, users of subclasses of `torch.Tensor` will have a much more streamlined experience. Namely, the following code example will work as-is, without the need for any further modification:
29+
30+
```python
31+
class SubTensor(torch.Tensor):
32+
a = 1
33+
34+
t = SubTensor([1])
35+
s = t.sum()
36+
isinstance(s, SubTensor) # True
37+
s.a # 1
38+
i = t[0]
39+
isinstance(i, SubTensor) # True
40+
i.a # 1
41+
42+
s2 = t + torch.Tensor(1)
43+
isinstance(s2, SubTensor) # True
44+
s2.a # 1
45+
46+
s3 = torch.Tensor(1) + t
47+
isinstance(s3, SubTensor) # True
48+
s3.a # 1
49+
```
50+
51+
Additionally, it will provide subclass authors hooks to run whenever methods or operators are called, and to modify the result to their specific use-case, perform logging, or otherwise change the result or the action of the method.
52+
53+
## Detailed Description
54+
We propose the following signature change to `__torch_funcion__`, to make it match NumPy: [[4]]
55+
56+
```python
57+
class SubTensor(torch.Tensor):
58+
def __torch_tensor__(self, func, types, args, kwargs):
59+
# Implementation here
60+
```
61+
62+
The reason for this change is necessitated by the need for `super()`. If we set a requirement for `super().__array_function__` to work properly, we would need to provide an easy way for users to signal to `__array_function__` that they are calling to the next-specific implementation. The way we propose to handle this is the same as it is handled in NumPy, albiet not in the context of overriding methods, but rather, in the context of subclasses of `numpy.ndarray` or other classes that implement `__array_function__`.
63+
64+
To access super, one would do the following:
65+
```python
66+
class SubTensor(torch.Tensor):
67+
def __torch_tensor__(self, func, types, args, kwargs):
68+
# Pre-processing here
69+
val = super().__torch_function__(func, tuple(t for t in types if not issubclass(t, SubTensor), args, kwargs)
70+
# Post processing here
71+
```
72+
73+
This way `__torch_function__` knows the list of types to dispatch to, and it will _not_ dispatch to `SubTensor` anymore in this example.
74+
75+
We will also recommend that all `Tensor` subclasses make their own methods go through `__torch_function__` via a decorator `@torch_function_dispatch`. However, this will come with a disclaimer: They _must_ accept that their methods are subject to the same processing as any other `torch.Tensor` methods, namely, that all the processing _will necessarily go through `__torch_function__`, even if through superclasses first_.
76+
77+
### Making `torch.Tensor._make_subclass` public API
78+
`torch.Tensor._make_subclass` will be renamed to `torch.Tensor.make_subclass` and it will become public API.
79+
80+
### Generic implementation of `__torch_function__`
81+
`torch.Tensor` will gain a generic `__torch_function__` of the following form:
82+
83+
```python
84+
class Tensor:
85+
def __torch_tensor__(self, func, types, args, kwargs):
86+
if not all(issubclass(t, type(self)) for t in types):
87+
return NotImplemented
88+
89+
if type(self) is Tensor:
90+
# Defer to internal implementation
91+
ret = func._implementation(*args, **kwargs)
92+
if isinstance(ret, Tensor):
93+
ret = Tensor.make_subclass(ret, type(self))
94+
return ret
95+
```
96+
97+
This method matches `torch` dispatch rules, so for the most part it's possible to pretend it doesn't exist. This also has the side-effect of passing subclasses through methods, and operators (since all operators are methods).
98+
99+
This corresponds exactly to the implmentation `numpy.ndarray` gains in [[4]], except for the fact that subclasses are passed through via another internal mechanism there, as well as the fact that we are checking subclassing against `type(self)` instead of `Tensor`. This has the side-effect of ensuring unrelated class trees are not merged, which is an inconsistency in NumPy's own design.
100+
101+
102+
[1]: https://github.com/pytorch/pytorch/issues/22402 "GitHub Issue 22402 on pytorch/pytorch"
103+
[2]: https://github.com/pytorch/pytorch/issues/28361#issuecomment-544520934 "Comment on GitHub Issue 28361 on pytorch/pytorch"
104+
[3]: https://github.com/pytorch/pytorch/issues/28361#issuecomment-557285807 "Comment on GitHub Issue 28361 on pytorch/pytorch"
105+
[4]: https://numpy.org/neps/nep-0018-array-function-protocol.html "NEP 18 — A dispatch mechanism for NumPy’s high level array functions"

0 commit comments

Comments
 (0)