tensor.py 8.6 KB
Newer Older
1 2
import numpy as np
import torch
3 4
from treevalue import method_treelize
from treevalue.utils import pre_process
5

6
from .base import Torch
HansBug's avatar
HansBug 已提交
7
from .size import Size
8
from ..common import Object, ireduce, clsmeta
9 10
from ..numpy import ndarray
from ..utils import current_names, doc_from
11

12
__all__ = [
HansBug's avatar
HansBug 已提交
13
    'Tensor'
14 15
]

16
_reduce_tensor_wrap = pre_process(lambda it: ((torch.tensor([*it]),), {}))
17
tireduce = pre_process(lambda rfunc: ((_reduce_tensor_wrap(rfunc),), {}))(ireduce)
18 19


20 21 22 23 24 25 26 27 28 29 30
def _to_tensor(*args, **kwargs):
    if (len(args) == 1 and not kwargs) or \
            (not args and set(kwargs.keys()) == {'data'}):
        data = args[0] if len(args) == 1 else kwargs['data']
        if isinstance(data, torch.Tensor):
            return data

    return torch.tensor(*args, **kwargs)


# noinspection PyTypeChecker
31
@current_names()
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
class Tensor(Torch, metaclass=clsmeta(_to_tensor, allow_dict=True)):
    # noinspection PyUnusedLocal
    def __init__(self, data, *args, **kwargs):
        """
        In :class:`treetensor.torch.Tensor`, it's similar but a little bit different with the
        original :class:`torch.Tensor`.

        Examples::

            >>> import torch
            >>> import treetensor.torch as ttorch
            >>> torch.Tensor([1, 2, 3])  # in torch.Tensor, default type is float32
            tensor([1., 2., 3.])

            >>> ttorch.Tensor([1, 2, 3])  # a native Tensor object, its type is auto detected with torch.tensor
            tensor([1, 2, 3])

            >>> ttorch.Tensor([1, 2, 3], dtype=torch.float32)  # with float32 type
            tensor([1., 2., 3.])

            >>> ttorch.Tensor({
            ...     'a': [1, 2, 3],
            ...     'b': {'x': [4.0, 5, 6]},
            ...     'c': [[True, ], [False, ]],
            ... })  # a tree-based Tensor object
            <Tensor 0x7f537bb9a880>
            ├── a --> tensor([1, 2, 3])
            ├── b --> <Tensor 0x7f537bb9a0d0>
            │   └── x --> tensor([4., 5., 6.])
            └── c --> tensor([[ True],
                              [False]])
        """
        super(Torch, self).__init__(data)

66
    @doc_from(torch.Tensor.numpy)
67
    @method_treelize(return_type=ndarray)
68
    def numpy(self: torch.Tensor) -> np.ndarray:
69 70 71 72 73
        """
        Returns ``self`` tree tensor as a NumPy ``ndarray``.
        This tensor and the returned :class:`treetensor.numpy.ndarray` share the same underlying storage.
        Changes to self tensor will be reflected in the ``ndarray`` and vice versa.
        """
74 75
        return self.numpy()

76
    @doc_from(torch.Tensor.tolist)
77
    @method_treelize(return_type=Object)
78
    def tolist(self: torch.Tensor):
79 80 81 82 83 84 85 86 87 88 89 90
        """
        Get the dump result of tree tensor.

        Example::

            >>> import torch
            >>> import treetensor.torch as ttorch
            >>> ttorch.tensor({
            >>>     'a': [[1, 2], [3, 4]],
            >>>     'b': [1, 2, 3],
            >>>     'c': True,
            >>> }).tolist()
91
            Object({
92 93 94 95 96
                'a': [[1, 2], [3, 4]],
                'b': [1, 2, 3],
                'c': True,
            })
        """
97 98
        return self.tolist()

99
    @doc_from(torch.Tensor.cpu)
100 101
    @method_treelize()
    def cpu(self: torch.Tensor, *args, **kwargs):
102 103 104 105 106 107
        """
        Returns a copy of this tree tensor in CPU memory.

        If this tree tensor is already in CPU memory and on the correct device,
        then no copy is performed and the original object is returned.
        """
108 109
        return self.cpu(*args, **kwargs)

110
    @doc_from(torch.Tensor.cuda)
111 112
    @method_treelize()
    def cuda(self: torch.Tensor, *args, **kwargs):
113 114 115 116 117 118
        """
        Returns a copy of this tree tensor in CUDA memory.

        If this tree tensor is already in CUDA memory and on the correct device,
        then no copy is performed and the original object is returned.
        """
119 120
        return self.cuda(*args, **kwargs)

121
    @doc_from(torch.Tensor.to)
122 123
    @method_treelize()
    def to(self: torch.Tensor, *args, **kwargs):
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        """
        Turn the original tree tensor to another format.

        Example::

            >>> import torch
            >>> import treetensor.torch as ttorch
            >>> ttorch.tensor({
            ...     'a': [[1, 11], [2, 22], [3, 33]],
            ...     'b': {'x': [[4, 5], [6, 7]]},
            ... }).to(torch.float64)
            <Tensor 0x7ff363bb6518>
            ├── a --> tensor([[ 1., 11.],
            │                 [ 2., 22.],
            │                 [ 3., 33.]], dtype=torch.float64)
            └── b --> <Tensor 0x7ff363bb6ef0>
                └── x --> tensor([[4., 5.],
                                  [6., 7.]], dtype=torch.float64)
        """
143 144
        return self.to(*args, **kwargs)

145
    @doc_from(torch.Tensor.numel)
146
    @ireduce(sum)
147
    @method_treelize(return_type=Object)
148
    def numel(self: torch.Tensor):
149 150 151
        """
        See :func:`treetensor.torch.numel`
        """
152 153 154
        return self.numel()

    @property
155
    @doc_from(torch.Tensor.shape)
HansBug's avatar
HansBug 已提交
156
    @method_treelize(return_type=Size)
157
    def shape(self: torch.Tensor):
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        """
        Get the size of the tensors in the tree.

        Example::

            >>> import torch
            >>> import treetensor.torch as ttorch
            >>> ttorch.tensor({
            ...     'a': [[1, 11], [2, 22], [3, 33]],
            ...     'b': {'x': [[4, 5], [6, 7]]},
            ... }).shape
            <Size 0x7ff363bbbd68>
            ├── a --> torch.Size([3, 2])
            └── b --> <Size 0x7ff363bbbcf8>
                └── x --> torch.Size([2, 2])
        """
174
        return self.shape
175

176
    # noinspection PyArgumentList
177
    @doc_from(torch.Tensor.all)
178
    @tireduce(torch.all)
179
    @method_treelize(return_type=Object)
180
    def all(self: torch.Tensor, *args, **kwargs) -> bool:
181 182 183
        """
        See :func:`treetensor.torch.all`
        """
184
        return self.all(*args, **kwargs)
185

186
    # noinspection PyArgumentList
187
    @doc_from(torch.Tensor.any)
188
    @tireduce(torch.any)
189
    @method_treelize(return_type=Object)
190
    def any(self: torch.Tensor, *args, **kwargs) -> bool:
191 192 193
        """
        See :func:`treetensor.torch.any`
        """
194 195
        return self.any(*args, **kwargs)

196
    @doc_from(torch.Tensor.max)
197
    @tireduce(torch.max)
198
    @method_treelize(return_type=Object)
199
    def max(self: torch.Tensor, *args, **kwargs):
200 201 202
        """
        See :func:`treetensor.torch.max`
        """
203 204
        return self.max(*args, **kwargs)

205
    @doc_from(torch.Tensor.min)
206
    @tireduce(torch.min)
207
    @method_treelize(return_type=Object)
208
    def min(self: torch.Tensor, *args, **kwargs):
209 210 211
        """
        See :func:`treetensor.torch.min`
        """
212 213
        return self.min(*args, **kwargs)

214
    @doc_from(torch.Tensor.sum)
215
    @tireduce(torch.sum)
216
    @method_treelize(return_type=Object)
217
    def sum(self: torch.Tensor, *args, **kwargs):
218 219 220
        """
        See :func:`treetensor.torch.sum`
        """
221
        return self.sum(*args, **kwargs)
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

    @method_treelize()
    def __eq__(self, other):
        """
        See :func:`treetensor.torch.eq`.
        """
        return self == other

    @method_treelize()
    def __ne__(self, other):
        """
        See :func:`treetensor.torch.ne`.
        """
        return self != other

    @method_treelize()
    def __lt__(self, other):
        """
        See :func:`treetensor.torch.lt`.
        """
        return self < other

    @method_treelize()
    def __gt__(self, other):
        """
        See :func:`treetensor.torch.gt`.
        """
        return self > other

    @method_treelize()
    def __le__(self, other):
        """
        See :func:`treetensor.torch.le`.
        """
        return self <= other

    @method_treelize()
    def __ge__(self, other):
        """
        See :func:`treetensor.torch.ge`.
        """
        return self >= other
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

    @doc_from(torch.Tensor.clone)
    @method_treelize()
    def clone(self, *args, **kwargs):
        """
        See :func:`treetensor.torch.clone`.
        """
        return self.clone(*args, **kwargs)

    @doc_from(torch.Tensor.dot)
    @method_treelize()
    def dot(self, other, *args, **kwargs):
        """
        See :func:`treetensor.torch.dot`.
        """
        return self.dot(other, *args, **kwargs)

    @doc_from(torch.Tensor.mm)
    @method_treelize()
    def mm(self, mat2, *args, **kwargs):
        """
        See :func:`treetensor.torch.mm`.
        """
        return self.mm(mat2, *args, **kwargs)

    @doc_from(torch.Tensor.matmul)
    @method_treelize()
    def matmul(self, tensor2, *args, **kwargs):
        """
        See :func:`treetensor.torch.matmul`.
        """
        return self.matmul(tensor2, *args, **kwargs)