"vscode:/vscode.git/clone" did not exist on "a74f8d9c5d5b57147293c08fc2918b2172fbbfb3"
_datapoint.py 5.87 KB
Newer Older
1
2
from __future__ import annotations

3
from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union
Philip Meier's avatar
Philip Meier committed
4
5

import torch
6
from torch._C import DisableTorchFunctionSubclass
7
from torch.types import _device, _dtype, _size
Philip Meier's avatar
Philip Meier committed
8

9

10
D = TypeVar("D", bound="Datapoint")
11
12


13
class Datapoint(torch.Tensor):
14
15
16
17
18
19
20
    """[Beta] Base class for all datapoints.

    You probably don't want to use this class unless you're defining your own
    custom Datapoints. See
    :ref:`sphx_glr_auto_examples_plot_custom_datapoints.py` for details.
    """

21
22
    @staticmethod
    def _to_tensor(
23
24
        data: Any,
        dtype: Optional[torch.dtype] = None,
25
        device: Optional[Union[torch.device, str, int]] = None,
26
        requires_grad: Optional[bool] = None,
27
    ) -> torch.Tensor:
28
29
        if requires_grad is None:
            requires_grad = data.requires_grad if isinstance(data, torch.Tensor) else False
30
        return torch.as_tensor(data, dtype=dtype, device=device).requires_grad_(requires_grad)
Philip Meier's avatar
Philip Meier committed
31

32
    @classmethod
33
    def wrap_like(cls: Type[D], other: D, tensor: torch.Tensor) -> D:
34
        return tensor.as_subclass(cls)
Philip Meier's avatar
Philip Meier committed
35

36
37
38
    # The ops in this set are those that should *preserve* the Datapoint type,
    # i.e. they are exceptions to the "no wrapping" rule.
    _NO_WRAPPING_EXCEPTIONS = {torch.Tensor.clone, torch.Tensor.to, torch.Tensor.detach, torch.Tensor.requires_grad_}
39

Philip Meier's avatar
Philip Meier committed
40
41
42
43
44
45
46
47
    @classmethod
    def __torch_function__(
        cls,
        func: Callable[..., torch.Tensor],
        types: Tuple[Type[torch.Tensor], ...],
        args: Sequence[Any] = (),
        kwargs: Optional[Mapping[str, Any]] = None,
    ) -> torch.Tensor:
48
49
50
51
52
53
54
        """For general information about how the __torch_function__ protocol works,
        see https://pytorch.org/docs/stable/notes/extending.html#extending-torch

        TL;DR: Every time a PyTorch operator is called, it goes through the inputs and looks for the
        ``__torch_function__`` method. If one is found, it is invoked with the operator as ``func`` as well as the
        ``args`` and ``kwargs`` of the original call.

55
        The default behavior of :class:`~torch.Tensor`'s is to retain a custom tensor type. For the :class:`Datapoint`
56
57
        use case, this has two downsides:

58
        1. Since some :class:`Datapoint`'s require metadata to be constructed, the default wrapping, i.e.
59
60
61
           ``return cls(func(*args, **kwargs))``, will fail for them.
        2. For most operations, there is no way of knowing if the input type is still valid for the output.

62
        For these reasons, the automatic output wrapping is turned off for most operators. The only exceptions are
63
        listed in :attr:`Datapoint._NO_WRAPPING_EXCEPTIONS`
64
        """
65
66
67
68
69
70
        # Since super().__torch_function__ has no hook to prevent the coercing of the output into the input type, we
        # need to reimplement the functionality.

        if not all(issubclass(cls, t) for t in types):
            return NotImplemented

71
        with DisableTorchFunctionSubclass():
72
            output = func(*args, **kwargs or dict())
Philip Meier's avatar
Philip Meier committed
73

74
75
        if func in cls._NO_WRAPPING_EXCEPTIONS and isinstance(args[0], cls):
            # We also require the primary operand, i.e. `args[0]`, to be
76
77
            # an instance of the class that `__torch_function__` was invoked on. The __torch_function__ protocol will
            # invoke this method on *all* types involved in the computation by walking the MRO upwards. For example,
78
79
80
            # `torch.Tensor(...).to(datapoints.Image(...))` will invoke `datapoints.Image.__torch_function__` with
            # `args = (torch.Tensor(), datapoints.Image())` first. Without this guard, the original `torch.Tensor` would
            # be wrapped into a `datapoints.Image`.
81
            return cls.wrap_like(args[0], output)
82

83
84
85
86
        if isinstance(output, cls):
            # DisableTorchFunctionSubclass is ignored by inplace ops like `.add_(...)`,
            # so for those, the output is still a Datapoint. Thus, we need to manually unwrap.
            return output.as_subclass(torch.Tensor)
87

88
        return output
89

90
91
92
93
94
95
    def _make_repr(self, **kwargs: Any) -> str:
        # This is a poor man's implementation of the proposal in https://github.com/pytorch/pytorch/issues/76532.
        # If that ever gets implemented, remove this in favor of the solution on the `torch.Tensor` class.
        extra_repr = ", ".join(f"{key}={value}" for key, value in kwargs.items())
        return f"{super().__repr__()[:-1]}, {extra_repr})"

96
97
98
99
    # Add properties for common attributes like shape, dtype, device, ndim etc
    # this way we return the result without passing into __torch_function__
    @property
    def shape(self) -> _size:  # type: ignore[override]
100
        with DisableTorchFunctionSubclass():
101
102
103
104
            return super().shape

    @property
    def ndim(self) -> int:  # type: ignore[override]
105
        with DisableTorchFunctionSubclass():
106
107
108
109
            return super().ndim

    @property
    def device(self, *args: Any, **kwargs: Any) -> _device:  # type: ignore[override]
110
        with DisableTorchFunctionSubclass():
111
112
113
114
            return super().device

    @property
    def dtype(self) -> _dtype:  # type: ignore[override]
115
        with DisableTorchFunctionSubclass():
116
117
            return super().dtype

118
119
120
121
122
    def __deepcopy__(self: D, memo: Dict[int, Any]) -> D:
        # We need to detach first, since a plain `Tensor.clone` will be part of the computation graph, which does
        # *not* happen for `deepcopy(Tensor)`. A side-effect from detaching is that the `Tensor.requires_grad`
        # attribute is cleared, so we need to refill it before we return.
        # Note: We don't explicitly handle deep-copying of the metadata here. The only metadata we currently have is
Philip Meier's avatar
Philip Meier committed
123
        # `BoundingBoxes.format` and `BoundingBoxes.canvas_size`, which are immutable and thus implicitly deep-copied by
124
        # `BoundingBoxes.clone()`.
125
        return self.detach().clone().requires_grad_(self.requires_grad)  # type: ignore[return-value]