funcs.py 15.8 KB
Newer Older
1 2 3 4 5
"""
Overview:
    Common functions, based on ``torch`` module.
"""

6 7
import builtins

8
import torch
HansBug's avatar
HansBug 已提交
9
from treevalue import TreeValue
10
from treevalue import func_treelize as original_func_treelize
HansBug's avatar
HansBug 已提交
11
from treevalue.utils import post_process
12

HansBug's avatar
HansBug 已提交
13
from .tensor import Tensor, tireduce
14
from ..common import TreeObject, ireduce
HansBug's avatar
HansBug 已提交
15
from ..utils import replaceable_partial, doc_from, args_mapping
16

17 18 19 20 21 22 23 24
__all__ = [
    'zeros', 'zeros_like',
    'randn', 'randn_like',
    'randint', 'randint_like',
    'ones', 'ones_like',
    'full', 'full_like',
    'empty', 'empty_like',
    'all', 'any',
25
    'min', 'max', 'sum',
26 27
    'eq', 'ne', 'lt', 'le', 'gt', 'ge',
    'equal', 'tensor',
28 29
]

HansBug's avatar
HansBug 已提交
30
func_treelize = post_process(post_process(args_mapping(
31
    lambda i, x: TreeValue(x) if isinstance(x, (dict, TreeValue)) else x)))(
HansBug's avatar
HansBug 已提交
32 33
    replaceable_partial(original_func_treelize, return_type=Tensor)
)
34 35


36
@doc_from(torch.zeros)
37
@func_treelize()
38
def zeros(*args, **kwargs):
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    """
    In ``treetensor``, you can use ``zeros`` to create a tree of tensors with all zeros.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.zeros(2, 3)  # the same as torch.zeros(2, 3)
        torch.tensor([[0.0, 0.0, 0.0],
                      [0.0, 0.0, 0.0]])

        >>> ttorch.zeros({
        >>>     'a': (2, 3),
        >>>     'b': (4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[0.0, 0.0, 0.0],
                               [0.0, 0.0, 0.0]]),
            'b': torch.tensor([0.0, 0.0, 0.0, 0.0]),
        })
    """
60
    return torch.zeros(*args, **kwargs)
61 62


63
# noinspection PyShadowingBuiltins
64
@doc_from(torch.zeros_like)
65
@func_treelize()
66
def zeros_like(input, *args, **kwargs):
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    """
    In ``treetensor``, you can use ``zeros_like`` to create a tree of tensors with all zeros like another tree.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.zeros_like(torch.randn(2, 3))  # the same as torch.zeros_like(torch.randn(2, 3))
        torch.tensor([[0.0, 0.0, 0.0],
                      [0.0, 0.0, 0.0]])

        >>> ttorch.zeros_like({
        >>>     'a': torch.randn(2, 3),
        >>>     'b': torch.randn(4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[0.0, 0.0, 0.0],
                               [0.0, 0.0, 0.0]]),
            'b': torch.tensor([0.0, 0.0, 0.0, 0.0]),
        })
    """
88
    return torch.zeros_like(input, *args, **kwargs)
89 90


91
@doc_from(torch.randn)
92
@func_treelize()
93
def randn(*args, **kwargs):
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    """
    In ``treetensor``, you can use ``randn`` to create a tree of tensors with numbers
    obey standard normal distribution.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.randn(2, 3)  # the same as torch.randn(2, 3)
        torch.tensor([[-0.1524, -0.6836,  0.2071],
                      [-1.0407,  0.2497, -0.2317]])

        >>> ttorch.randn({
        >>>     'a': (2, 3),
        >>>     'b': (4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[-0.2399, -1.3437,  0.0656],
                               [-0.3137, -0.3177, -3.0176]])
            'b': torch.tensor([-1.3047,  0.0188, -0.3311,  0.3112]),
        })
    """
116
    return torch.randn(*args, **kwargs)
117 118


119
# noinspection PyShadowingBuiltins
120
@doc_from(torch.randn_like)
121
@func_treelize()
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
def randn_like(input, *args, **kwargs):
    """
    In ``treetensor``, you can use ``randn_like`` to create a tree of tensors with numbers
    obey standard normal distribution like another tree.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.randn_like(torch.ones(2, 3))  # the same as torch.randn_like(torch.ones(2, 3))
        torch.tensor([[-1.3912,  2.3161,  1.0146],
                      [-0.3242,  0.5288,  2.4341]])

        >>> ttorch.randn_like({
        >>>     'a': torch.ones(2, 3),
        >>>     'b': torch.ones(4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[ 1.0548, -0.4282,  2.2030],
                               [-0.5305, -0.2601, -1.2560]])
            'b': torch.tensor([ 0.4502,  0.3977, -0.5329,  0.3459]),
        })
    """
    return torch.randn_like(input, *args, **kwargs)
146 147


148
@doc_from(torch.randint)
149
@func_treelize()
150 151
def randint(*args, **kwargs):
    return torch.randint(*args, **kwargs)
152 153


154
# noinspection PyShadowingBuiltins
155
@doc_from(torch.randint_like)
156
@func_treelize()
157 158
def randint_like(input, *args, **kwargs):
    return torch.randint_like(input, *args, **kwargs)
159 160


161
@doc_from(torch.ones)
162
@func_treelize()
163
def ones(*args, **kwargs):
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    """
    In ``treetensor``, you can use ``ones`` to create a tree of tensors with all ones.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.ones(2, 3)  # the same as torch.ones(2, 3)
        torch.tensor([[1.0, 1.0, 1.0],
                      [1.0, 1.0, 1.0]])

        >>> ttorch.ones({
        >>>     'a': (2, 3),
        >>>     'b': (4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[1.0, 1.0, 1.0],
                               [1.0, 1.0, 1.0]]),
            'b': torch.tensor([1.0, 1.0, 1.0, 1.0]),
        })
    """
185
    return torch.ones(*args, **kwargs)
186 187


188
# noinspection PyShadowingBuiltins
189
@doc_from(torch.ones_like)
190
@func_treelize()
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
def ones_like(input, *args, **kwargs):
    """
    In ``treetensor``, you can use ``ones_like`` to create a tree of tensors with all ones like another tree.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.ones_like(torch.randn(2, 3))  # the same as torch.ones_like(torch.randn(2, 3))
        torch.tensor([[1.0, 1.0, 1.0],
                      [1.0, 1.0, 1.0]])

        >>> ttorch.ones_like({
        >>>     'a': torch.randn(2, 3),
        >>>     'b': torch.randn(4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[1.0, 1.0, 1.0],
                               [1.0, 1.0, 1.0]]),
            'b': torch.tensor([1.0, 1.0, 1.0, 1.0]),
        })
    """
    return torch.ones_like(input, *args, **kwargs)
214 215


216
@doc_from(torch.full)
217
@func_treelize()
218
def full(*args, **kwargs):
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    """
    In ``treetensor``, you can use ``ones`` to create a tree of tensors with the same value.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.full((2, 3), 2.3)  # the same as torch.full((2, 3), 2.3)
        torch.tensor([[2.3, 2.3, 2.3],
                      [2.3, 2.3, 2.3]])

        >>> ttorch.ones({
        >>>     'a': (2, 3),
        >>>     'b': (4, ),
        >>> }, 2.3)
        ttorch.tensor({
            'a': torch.tensor([[2.3, 2.3, 2.3],
                               [2.3, 2.3, 2.3]]),
            'b': torch.tensor([2.3, 2.3, 2.3, 2.3]),
        })
    """
240
    return torch.full(*args, **kwargs)
241 242


243
# noinspection PyShadowingBuiltins
244
@doc_from(torch.full_like)
245
@func_treelize()
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
def full_like(input, *args, **kwargs):
    """
    In ``treetensor``, you can use ``ones_like`` to create a tree of tensors with
    all the same value of like another tree.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.full_like(torch.randn(2, 3), 2.3)  # the same as torch.full_like(torch.randn(2, 3), 2.3)
        torch.tensor([[2.3, 2.3, 2.3],
                      [2.3, 2.3, 2.3]])

        >>> ttorch.full_like({
        >>>     'a': torch.randn(2, 3),
        >>>     'b': torch.randn(4, ),
        >>> }, 2.3)
        ttorch.tensor({
            'a': torch.tensor([[2.3, 2.3, 2.3],
                               [2.3, 2.3, 2.3]]),
            'b': torch.tensor([2.3, 2.3, 2.3, 2.3]),
        })
    """
    return torch.full_like(input, *args, **kwargs)
270 271


272
@doc_from(torch.empty)
273
@func_treelize()
274
def empty(*args, **kwargs):
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    """
    In ``treetensor``, you can use ``ones`` to create a tree of tensors with
    the uninitialized values.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.empty(2, 3)  # the same as torch.empty(2, 3)
        torch.tensor([[ 6.6531e-39,  8.2002e-35,  1.3593e-43],
                      [ 0.0000e+00, -4.0271e-20,  4.5887e-41]])

        >>> ttorch.empty({
        >>>     'a': (2, 3),
        >>>     'b': (4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[-1.1736e+27,  3.0918e-41, -1.1758e+27],
                               [ 3.0918e-41,  8.9683e-44,  0.0000e+00]]),
            'b': torch.tensor([-4.0271e-20,  4.5887e-41, -1.1213e+27,  3.0918e-41]),
        })
    """
297
    return torch.empty(*args, **kwargs)
298 299


300
# noinspection PyShadowingBuiltins
301
@doc_from(torch.empty_like)
302
@func_treelize()
303 304 305 306 307 308
def empty_like(input, *args, **kwargs):
    """
    In ``treetensor``, you can use ``ones_like`` to create a tree of tensors with
    all the uninitialized values of like another tree.

    Example::
309

310 311 312 313 314
        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.empty_like(torch.randn(2, 3))  # the same as torch.empty_like(torch.randn(2, 3), 2.3)
        torch.tensor([[-4.0271e-20,  4.5887e-41, -4.0271e-20],
                      [ 4.5887e-41,  4.4842e-44,  0.0000e+00]])
315

316 317 318 319 320 321 322 323 324 325 326 327 328 329
        >>> ttorch.empty_like({
        >>>     'a': torch.randn(2, 3),
        >>>     'b': torch.randn(4, ),
        >>> })
        ttorch.tensor({
            'a': torch.tensor([[-1.1978e+27,  3.0918e-41, -1.1976e+27],
                               [ 3.0918e-41,  8.9683e-44,  0.0000e+00]]),
            'b': torch.tensor([-4.0271e-20,  4.5887e-41, -4.0271e-20,  4.5887e-41]),
        })
    """
    return torch.empty_like(input, *args, **kwargs)


# noinspection PyShadowingBuiltins
330
@doc_from(torch.all)
331
@tireduce(torch.all)
332
@func_treelize(return_type=TreeObject)
333
def all(input, *args, **kwargs):
334 335 336 337 338
    """
    In ``treetensor``, you can get the ``all`` result of a whole tree with this function.

    Example::

HansBug's avatar
HansBug 已提交
339 340
        >>> import torch
        >>> import treetensor.torch as ttorch
341
        >>> ttorch.all(torch.tensor([True, True]))  # the same as torch.all
342 343
        torch.tensor(True)

344
        >>> ttorch.all(ttorch.tensor({
HansBug's avatar
HansBug 已提交
345 346
        >>>     'a': [True, True],
        >>>     'b': [True, True],
347 348 349
        >>> }))
        torch.tensor(True)

350
        >>> ttorch.all(ttorch.tensor({
HansBug's avatar
HansBug 已提交
351 352
        >>>     'a': [True, True],
        >>>     'b': [True, False],
353 354 355
        >>> }))
        torch.tensor(False)

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    .. note::

        In this ``all`` function, the return value should be a tensor with single boolean value.

        If what you need is a tree of boolean tensors, you should do like this

            >>> ttorch.tensor({
            >>>     'a': [True, True],
            >>>     'b': [True, False],
            >>> }).map(torch.all)
            ttorch.tensor({
                'a': torch.tensor(True),
                'b': torch.tensor(False),
            })

371
    """
372
    return torch.all(input, *args, **kwargs)
373 374


375
# noinspection PyShadowingBuiltins
376
@doc_from(torch.any)
377 378
@tireduce(torch.any)
@func_treelize(return_type=TreeObject)
379
def any(input, *args, **kwargs):
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    """
    In ``treetensor``, you can get the ``any`` result of a whole tree with this function.

    Example::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.any(torch.tensor([False, False]))  # the same as torch.any
        torch.tensor(False)

        >>> ttorch.any(ttorch.tensor({
        >>>     'a': [True, False],
        >>>     'b': [False, False],
        >>> }))
        torch.tensor(True)

        >>> ttorch.any(ttorch.tensor({
        >>>     'a': [False, False],
        >>>     'b': [False, False],
        >>> }))
        torch.tensor(False)

    .. note::

        In this ``any`` function, the return value should be a tensor with single boolean value.

        If what you need is a tree of boolean tensors, you should do like this

            >>> ttorch.tensor({
            >>>     'a': [True, False],
            >>>     'b': [False, False],
            >>> }).map(torch.any)
            ttorch.tensor({
                'a': torch.tensor(True),
                'b': torch.tensor(False),
            })

    """
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    return torch.any(input, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.min)
@tireduce(torch.min)
@func_treelize(return_type=TreeObject)
def min(input, *args, **kwargs):
    return torch.min(input, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.max)
@tireduce(torch.max)
@func_treelize(return_type=TreeObject)
def max(input, *args, **kwargs):
    return torch.max(input, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.sum)
@tireduce(torch.sum)
@func_treelize(return_type=TreeObject)
def sum(input, *args, **kwargs):
    return torch.sum(input, *args, **kwargs)
443 444


445
# noinspection PyShadowingBuiltins
446
@doc_from(torch.eq)
447
@func_treelize()
448
def eq(input, other, *args, **kwargs):
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    """

    Examples::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.eq(
        >>>     torch.tensor([[1, 2], [3, 4]]),
        >>>     torch.tensor([[1, 1], [4, 4]]),
        >>> )
        torch.tensor([[ True, False],
                      [False,  True]])

        >>> ttorch.eq(
        >>>     ttorch.tensor({
        >>>         'a': [[1, 2], [3, 4]],
        >>>         'b': [1.0, 1.5, 2.0],
        >>>     }),
        >>>     ttorch.tensor({
        >>>         'a': [[1, 1], [4, 4]],
        >>>         'b': [1.3, 1.2, 2.0],
        >>>     }),
        >>> )
    """
473
    return torch.eq(input, other, *args, **kwargs)
474 475


476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
# noinspection PyShadowingBuiltins
@doc_from(torch.ne)
@func_treelize()
def ne(input, other, *args, **kwargs):
    return torch.ne(input, other, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.lt)
@func_treelize()
def lt(input, other, *args, **kwargs):
    return torch.lt(input, other, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.le)
@func_treelize()
def le(input, other, *args, **kwargs):
    return torch.le(input, other, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.gt)
@func_treelize()
def gt(input, other, *args, **kwargs):
    return torch.gt(input, other, *args, **kwargs)


# noinspection PyShadowingBuiltins
@doc_from(torch.ge)
@func_treelize()
def ge(input, other, *args, **kwargs):
    return torch.ge(input, other, *args, **kwargs)


511
# noinspection PyShadowingBuiltins,PyArgumentList
512
@doc_from(torch.equal)
513
@ireduce(builtins.all)
514
@func_treelize()
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
def equal(input, other):
    """
    In ``treetensor``, you can get the equality of the two tree tensors.

    Examples::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.equal(
        >>>     torch.tensor([1, 2, 3]),
        >>>     torch.tensor([1, 2, 3]),
        >>> )  # the same as torch.equal
        True

        >>> ttorch.equal(
        >>>     ttorch.tensor({
        >>>         'a': torch.tensor([1, 2, 3]),
        >>>         'b': torch.tensor([[4, 5], [6, 7]]),
        >>>     }),
        >>>     ttorch.tensor({
        >>>         'a': torch.tensor([1, 2, 3]),
        >>>         'b': torch.tensor([[4, 5], [6, 7]]),
        >>>     }),
        >>> )
        True

    """
    return torch.equal(input, other)
HansBug's avatar
HansBug 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569


@doc_from(torch.tensor)
@func_treelize()
def tensor(*args, **kwargs):
    """
    In ``treetensor``, you can create a tree tensor with simple data structure.

    Examples::

        >>> import torch
        >>> import treetensor.torch as ttorch
        >>> ttorch.tensor(True)  # the same as torch.tensor(True)
        torch.tensor(True)

        >>> ttorch.tensor([1, 2, 3])  # the same as torch.tensor([1, 2, 3])
        torch.tensor([1, 2, 3])

        >>> ttorch.tensor({'a': 1, 'b': [1, 2, 3], 'c': [[True, False], [False, True]]})
        ttorch.Tensor({
            'a': torch.tensor(1),
            'b': torch.tensor([1, 2, 3]),
            'c': torch.tensor([[True, False], [False, True]]),
        })

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