tensor.py 30.8 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
4
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
5 6 7 8 9
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import math
10
from typing import Iterable, Optional, Sequence, Union
11 12 13 14

import numpy as np

from ..core._imperative_rt import CompNode
15
from ..core._imperative_rt.core2 import SymbolVar, apply
16
from ..core._wrap import device as as_device
17
from ..core.ops import builtin
18
from ..core.ops.builtin import Copy, Identity
19
from ..core.ops.special import Const
20
from ..core.tensor.array_method import _broadcast, _remove_axis
21 22 23 24 25 26 27 28 29
from ..core.tensor.utils import (
    astensor1d,
    convert_inputs,
    convert_single_value,
    dtype_promotion,
    get_device,
)
from ..device import get_default_device
from ..tensor import Tensor
30
from .elemwise import ceil, floor_div
31 32 33

__all__ = [
    "arange",
34
    "broadcast_to",
35 36
    "concat",
    "cond_take",
37
    "expand_dims",
38
    "eye",
39
    "flatten",
40 41 42 43 44 45
    "full",
    "full_like",
    "gather",
    "linspace",
    "ones",
    "ones_like",
46
    "repeat",
47
    "reshape",
48
    "split",
M
Megvii Engine Team 已提交
49
    "squeeze",
50 51
    "stack",
    "scatter",
52
    "tile",
53
    "copy",
54
    "transpose",
55 56 57 58 59 60
    "where",
    "zeros",
    "zeros_like",
]


61
def eye(N, M=None, *, dtype="float32", device: Optional[CompNode] = None) -> Tensor:
62 63
    """
    Returns a 2D tensor with ones on the diagonal and zeros elsewhere.
64

M
Megvii Engine Team 已提交
65
    :param shape: expected shape of output tensor.
66 67 68
    :param dtype: data type. Default: None
    :param device: compute node of the matrix. Default: None
    :return: eye matrix.
69 70 71 72 73 74 75 76

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F

77
        out = F.eye(4, 6, dtype=np.float32)
78 79 80 81 82 83 84 85 86 87 88 89
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[1. 0. 0. 0. 0. 0.]
         [0. 1. 0. 0. 0. 0.]
         [0. 0. 1. 0. 0. 0.]
         [0. 0. 0. 1. 0. 0.]]

    """
90 91 92 93 94 95 96 97 98
    if M is not None:
        if isinstance(N, Tensor) or isinstance(M, Tensor):
            shape = astensor1d((N, M))
        else:
            shape = Tensor([N, M], dtype="int32", device=device)
    elif isinstance(N, Tensor):
        shape = N
    else:
        shape = Tensor(N, dtype="int32", device=device)
99
    op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
100
    (result,) = apply(op, shape)
101 102 103
    return result


104
def full(shape, value, dtype="float32", device=None) -> Tensor:
105 106
    """
    Returns a tensor with given shape and value.
107
    """
108 109
    if isinstance(shape, int):
        shape = (shape,)
110 111
    if device is None:
        device = get_default_device()
112
    (x,) = Const(value, dtype=dtype, device=device)()
113
    if shape is ():  # scalar.shape
114
        return x
115
    return broadcast_to(x, shape)
116 117


118
def ones(shape, dtype="float32", device=None) -> Tensor:
119 120
    """
    Returns a ones tensor with given shape.
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    :param inp: input tensor.
    :return: output zero tensor.

    Examples:

    .. testcode::

        import megengine.functional as F

        out = F.ones((2, 1))
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[1.]
         [1.]]

    """
142 143 144
    return full(shape, 1.0, dtype=dtype, device=device)


145
def zeros(shape, dtype="float32", device=None) -> Tensor:
146 147
    """
    Returns a zero tensor with given shape.
148
    """
149 150 151
    return full(shape, 0.0, dtype=dtype, device=device)


152
def zeros_like(inp: Union[Tensor, SymbolVar]) -> Union[Tensor, SymbolVar]:
153 154
    """
    Returns a zero tensor with the same shape as input tensor.
155

156 157
    :param inp: input tensor.
    :return: output zero tensor.
158 159 160 161 162 163 164 165 166 167 168 169 170

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F

        inp = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
        out = F.zeros_like(inp)
        print(out.numpy())

M
Megvii Engine Team 已提交
171
    Outputs:
172

173 174 175 176 177 178
    .. testoutput::

        [[0 0 0]
         [0 0 0]]

    """
179
    return full_like(inp, 0.0)
180 181


182
def ones_like(inp: Union[Tensor, SymbolVar]) -> Union[Tensor, SymbolVar]:
183 184
    """
    Returns a ones tensor with the same shape as input tensor.
185
    """
186
    return full_like(inp, 1.0)
187 188


189 190 191
def full_like(
    inp: Union[Tensor, SymbolVar], value: Union[int, float]
) -> Union[Tensor, SymbolVar]:
192 193
    """
    Returns a tensor filled with given value with the same shape as input tensor.
194
    """
195 196 197 198
    (x,) = Const(value, dtype=inp.dtype, device=inp.device)(inp)
    if inp.shape is ():
        return x
    return broadcast_to(x, inp.shape)
199 200


201
def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor:
202
    """
203
    Broadcasts a tensor to given shape.
204

205 206 207
    :param inp: input tensor.
    :param shape: target shape.
    :return: output tensor.
208 209 210 211 212 213 214 215 216

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F

217 218
        data = tensor(np.arange(0, 3, dtype=np.float32).reshape(3))
        out = F.broadcast_to(data, (2, 3))
219 220 221 222 223 224
        print(out.numpy())

    Outputs:

    .. testoutput::

225 226
        [[0. 1. 2.]
         [0. 1. 2.]]
227 228

    """
229
    return _broadcast(inp, shape)
230 231


232
def concat(inps: Iterable[Tensor], axis: int = 0, device=None) -> Tensor:
233 234 235
    r"""
    Concat some tensors

236
    :param inps: input tensors to concat.
M
Megvii Engine Team 已提交
237 238
    :param axis: over which dimension the tensors are concatenated. Default: 0
    :param device: which device output will be. Default: None
239
    :return: output tensor.
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F

        data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
        data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
        out = F.concat([data1, data2])
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[ 0.  1.  2.]
         [ 3.  4.  5.]
         [ 6.  7.  8.]
         [ 9. 10. 11.]]

    """
264 265 266
    if len(inps) == 1:
        return inps[0]

267
    inps = convert_inputs(*inps, device=device)
268 269 270
    if device is None:
        device = get_device(inps)
    device = as_device(device)
271 272 273 274
    (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
    return result


275
def stack(inps, axis=0, device=None):
276 277
    """
    Concats a sequence of tensors along a new axis.
278 279
    The input tensors must have the same shape.

280 281
    :param inps: input tensors.
    :param axis: which axis will be concatenated.
M
Megvii Engine Team 已提交
282
    :param device: the device output will be. Default: None
283
    :return: output concatenated tensor.
284 285 286 287 288 289 290 291 292

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F

293 294
        x1 = tensor(np.arange(0, 3, dtype=np.float32).reshape((3)))
        x2 = tensor(np.arange(6, 9, dtype=np.float32).reshape((3)))
295 296 297 298 299 300 301
        out = F.stack([x1, x2], axis=0)
        print(out.numpy())

    Outputs:

    .. testoutput::

302 303
        [[0. 1. 2.]
         [6. 7. 8.]]
304 305

    """
306 307 308 309
    if len(inps) > 0 and not isinstance(inps[0].shape, inps[0].__class__):
        shapes = {arr.shape for arr in inps}
        if len(shapes) != 1:
            raise ValueError("All input tensors must have the same shape")
310

311
    inps = [expand_dims(inp, axis=axis) for inp in inps]
312
    return concat(inps, axis=axis, device=device)
313 314 315


def split(inp, nsplits_or_sections, axis=0):
316 317
    """
    Splits the input tensor into several smaller tensors.
318 319
    When nsplits_or_sections is int, the last tensor may be smaller than others.

320
    :param inp: input tensor.
M
Megvii Engine Team 已提交
321
    :param nsplits_or_sections: number of sub tensors or sections information list.
322 323
    :param axis: which axis will be splited.
    :return: output tensor list.
324 325 326 327 328

    Examples:

    .. testcode::

329
        import os
330 331 332 333
        import numpy as np
        from megengine import tensor
        import megengine.functional as F

334 335 336 337
        x = tensor(np.random.random((10, 20)), dtype=np.float32)
        y = F.split(x, 3)
        z = F.split(x, [6, 17], axis=1)
        
338 339
        print([i.numpy().shape for i in y])
        print([i.numpy().shape for i in z])
340 341 342 343 344

    Outputs:

    .. testoutput::

345 346
        [(4, 20), (3, 20), (3, 20)]
        [(10, 6), (10, 11), (10, 3)]
347 348

    """
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    ndim = len(inp.shape)
    if axis >= ndim:
        raise ValueError("Invalid axis {}".format(axis))

    Ntotal = inp.shape[axis]

    try:
        Nsections = len(nsplits_or_sections) + 1
        is_array = True
    except TypeError:
        Nsections = int(nsplits_or_sections)
        is_array = False

    if is_array:
        div_points = [0] + list(nsplits_or_sections) + [Ntotal]
        for i in range(1, len(div_points)):
            if div_points[i - 1] >= div_points[i]:
                raise ValueError(
                    "Invalid nsplits_or_secions: {}".format(nsplits_or_sections)
                )
    else:  # scalar
        if Nsections <= 0:
            raise ValueError("Number sections must be larger than 0")
        if Nsections > Ntotal:
            raise ValueError(
                "The size {} at dim {} cannot be split into {} sections".format(
                    Ntotal, axis, Nsections
                )
            )
378 379 380 381 382 383

        func = (
            floor_div
            if isinstance(Nsections, (SymbolVar, Tensor))
            else lambda x, y: x // y
        )
384
        div_points = [0] + [
385
            func(Ntotal + Nsections - i - 1, Nsections) for i in range(Nsections)
386 387 388
        ]
        for i in range(2, Nsections + 1):
            div_points[i] = div_points[i - 1] + div_points[i]
389

390 391 392 393 394 395 396 397
    sub_tensors = []
    for i in range(Nsections):
        l = div_points[i]
        r = div_points[i + 1]
        slices = tuple(
            [slice(None)] * axis + [slice(l, r)] + [slice(None)] * (ndim - axis - 1)
        )
        sub_tensors.append(inp[slices])
398 399 400 401 402 403 404 405 406 407 408 409 410 411
    return sub_tensors


def _get_idx(index, axis):
    index_dims = len(index.shape)
    idx = []
    for i in range(index_dims):
        if i != axis:
            shape = [1] * index_dims
            shape[i] = index.shape[i]
            arange = linspace(
                0, index.shape[i] - 1, index.shape[i], device=index.device,
            )
            arange = (
412
                broadcast_to(arange.reshape(*shape), index.shape)
413 414 415 416 417 418 419 420 421 422
                .reshape(-1)
                .astype(np.int32)
            )
            idx.append(arange)
        else:
            idx.append(index.reshape(-1))
    return tuple(idx)


def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor:
423
    # TODO: rewrite doc
424 425
    r"""
    Gathers data from input tensor on axis using index.
426 427 428 429 430 431 432

    For a 3-D tensor, the output is specified by::

        out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0
        out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1
        out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2

M
Megvii Engine Team 已提交
433
    if input tensor is a n-dimensional tensor with size
434
    :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i,
M
Megvii Engine Team 已提交
435
    then index must be a n-dimensional tensor with size
436
    :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and
437
    output will have the same size as index.
438

439
    :param inp: input tensor.
M
Megvii Engine Team 已提交
440
    :param axis: along which axis to index.
441 442
    :param index: indices of elements to gather.
    :return: output tensor.
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

    Examples:

    .. testcode::

        import megengine.functional as F
        from megengine import tensor

        inp = tensor([
            [1,2], [3,4], [5,6],
        ])
        index = tensor([[0,2], [1,0]])
        oup = F.gather(inp, 0, index)
        print(oup.numpy())

    Outputs:

    .. testoutput::

        [[1 6]
         [3 2]]

    """
    input_shape = inp.shape
    index_shape = index.shape
    input_dims = len(input_shape)
    index_dims = len(index_shape)
    if input_dims != index_dims:
        raise ValueError(
            "The index tensor must have same dimensions as input tensor, "
            "But the input dims:{}, the index dims:{}".format(input_dims, index_dims)
        )

    if axis < 0 or axis >= input_dims:
        raise ValueError(
            "Index axis {} is output of bounds, should in range [0 {})".format(
                axis, input_dims
            )
        )

    for i in range(input_dims):
        if i != axis and input_shape[i] != index_shape[i]:
            raise ValueError(
                "The input {} and index {} must have the same size apart from axis {}".format(
                    input_shape, index_shape, axis
                )
            )

    idx = _get_idx(index, axis)
    return inp[idx].reshape(index.shape)  # pylint: disable=no-member


def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor:
496
    # TODO: rewrite doc
497 498
    r"""
    Writes all values from the tensor source into input tensor
499
    at the indices specified in the index tensor.
500

501 502 503
    For each value in source, its output index is specified by its index
    in source for ``axis != dimension`` and by the corresponding value in
    index for ``axis = dimension``.
504

M
Megvii Engine Team 已提交
505
    For a 3-D tensor, input tensor is updated as::
506 507 508 509 510

        inp[index[i][j][k]][j][k] = source[i][j][k]  # if axis == 0
        inp[i][index[i][j][k]][k] = source[i][j][k]  # if axis == 1
        inp[i][j][index[i][j][k]] = source[i][j][k]  # if axis == 2

M
Megvii Engine Team 已提交
511
    ``inp``, ``index`` and ``source`` should have same number of dimensions.
512 513 514 515

    It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)``
    for all dimensions ``d``.

516
    Moreover, the values of index must be between ``0`` and ``inp.shape(axis) - 1`` inclusive.
517 518 519

    .. note::
        Please notice that, due to performance issues, the result is uncertain on the GPU device
M
Megvii Engine Team 已提交
520
        if scattering different positions from source to the same destination position
521 522
        regard to index tensor.

M
Megvii Engine Team 已提交
523
        Check the following examples, the oup[0][2] is maybe
524 525 526
        from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339
        if set the index[1][2] from 1 to 0.

527 528 529 530 531
    :param inp: inp tensor which to be scattered.
    :param axis: axis along which to index.
    :param index: indices of elements to scatter.
    :param source: source element(s) to scatter.
    :return: output tensor.
532 533 534 535 536 537 538 539 540 541 542 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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F
        from megengine import tensor

        inp = tensor(np.zeros(shape=(3,5),dtype=np.float32))
        source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]])
        index = tensor([[0,2,0,2,1],[2,0,1,1,2]])
        oup = F.scatter(inp, 0, index,source)
        print(oup.numpy())

    Outputs:

    .. testoutput::

        [[0.9935 0.0718 0.2256 0.     0.    ]
         [0.     0.     0.5939 0.357  0.4396]
         [0.7723 0.9465 0.     0.8926 0.4576]]

    """
    input_shape = inp.shape
    index_shape = index.shape
    source_shape = source.shape
    input_dims = len(input_shape)
    index_dims = len(index_shape)
    source_dims = len(source_shape)

    if input_dims != index_dims or input_dims != source_dims:
        raise ValueError("The input, source and index tensor must have same dimensions")

    if axis < 0 or axis >= input_dims:
        raise ValueError(
            "Index axis {} is output of bounds, should in range [0 {})".format(
                axis, input_dims
            )
        )

    for i in range(source_dims):
        if source_shape[i] > input_shape[i]:
            raise ValueError(
                "The each shape size for source {} must be less than or equal to input {} ".format(
                    source_shape, input_shape
                )
            )

    for i in range(index_dims):
        if index_shape[i] != source_shape[i]:
            raise ValueError(
                "The each shape size for index {} must be equal to source {} ".format(
                    index_shape, source_shape
                )
            )

    for i in range(index_dims):
        if i != axis and index_shape[i] > input_shape[i]:
            raise ValueError(
                "The index {} must be less than or equal to input {} size apart from axis {}".format(
                    index_shape, input_shape, axis
                )
            )

    idx = _get_idx(index, axis)
    inp[idx] = source.flatten()
    return inp


def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor:
603 604
    r"""
    Selects elements either from Tensor x or Tensor y, according to mask.
605 606 607 608 609

    .. math::

        \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i

M
Megvii Engine Team 已提交
610
    :param mask: a mask used for choosing ``x`` or ``y``.
611 612 613
    :param x: first choice.
    :param y: second choice.
    :return: output tensor.
614 615 616 617 618 619 620

    Examples:

    .. testcode::

        from megengine import tensor
        import megengine.functional as F
621
        mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool))
622 623 624 625 626 627 628 629 630 631 632 633 634
        x = tensor(np.array([[1, np.inf], [np.nan, 4]],
            dtype=np.float32))
        y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32))
        out = F.where(mask, x, y)
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[1. 6.]
         [7. 4.]]
    """
635 636

    x, y = convert_inputs(x, y)
637
    if not isinstance(x, Tensor):
638
        raise TypeError("input x must be a tensor")
639
    if not isinstance(y, Tensor):
640
        raise TypeError("input y must be a tensor")
641
    if not isinstance(mask, Tensor):
642 643 644 645 646 647 648 649 650
        raise TypeError("mask must be a tensor")
    if mask.dtype != np.bool_:
        raise ValueError("mask must be bool")
    if x.device != mask.device:
        raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))

    v0, index0 = cond_take(mask, x)
    v1, index1 = cond_take(~mask, y)

651
    out = concat([v0, v1])
652 653 654 655 656

    out[index0] = v0
    out[index1] = v1
    out = out.reshape(x.shape)
    return out
657 658 659 660


def cond_take(mask: Tensor, x: Tensor) -> Tensor:
    r"""
M
Megvii Engine Team 已提交
661
    Takes elements from data if specific condition is satisfied on mask.
662 663 664
    This operator has two outputs: the first is the elements taken,
    and the second is the indices corresponding to those elements;
    they are both 1-dimensional. High-dimension input would first be flattened.
665

666 667
    :param mask: condition param; must be the same shape with data.
    :param x: input tensor from which to take elements.
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F
        mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool_))
        x = tensor(np.array([[1, np.inf], [np.nan, 4]],
            dtype=np.float32))
        v, index = F.cond_take(mask, x)
        print(v.numpy(), index.numpy())

    Outputs:

    .. testoutput::

M
Megvii Engine Team 已提交
686
        [1. 4.] [0 3]
687 688

    """
689
    if not isinstance(x, Tensor):
690
        raise TypeError("input must be a tensor")
691
    if not isinstance(mask, Tensor):
692 693 694 695 696 697 698 699 700 701 702
        raise TypeError("mask must be a tensor")
    if mask.dtype != np.bool_:
        raise ValueError("mask must be bool")
    if x.device != mask.device:
        raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))

    op = builtin.CondTake()
    v, index = apply(op, x, mask)
    return v, index


703
def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
704
    r"""
705
    Swaps shapes and strides according to given pattern.
706

707
    :param inp: input tensor.
708
    :param pattern: a list of integers including 0, 1, ... , ``ndim``-1,
709
        and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples:
710 711 712 713 714 715 716 717 718

        * (``'x'``) -> make a 0d (scalar) into a 1d vector
        * (0, 1) -> identity for 2d vectors
        * (1, 0) -> inverts the first and second dimensions
        * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN)
        * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1)
        * (2, 0, 1) -> AxBxC to CxAxB
        * (0, ``'x'``, 1) -> AxB to Ax1xB
        * (1, ``'x'``, 0) -> AxB to Bx1xA
M
Megvii Engine Team 已提交
719
        * (1,) -> this removes dimensions 0. It must be a broadcastable dimension (1xA to A)
720

721
    :return: output tensor.
722 723 724 725 726 727 728 729 730

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F
        x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32))
731
        out = F.transpose(x, (1, 0))
732 733 734 735 736 737 738 739 740 741
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[1 0]
         [1 0]]

    """
742
    return inp.transpose(list(-1 if _ == "x" else _ for _ in pattern))
743 744 745 746


def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor:
    r"""
747
    Reshapes a tensor to given target shape; total number of logical elements must
748 749
    remain unchanged

750
    :param inp: input tensor.
M
Megvii Engine Team 已提交
751
    :param target_shape: target shape, it can contain an element of -1 representing ``unspec_axis``.
752 753 754 755 756 757 758 759 760

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F
        x = tensor(np.arange(12, dtype=np.int32))
761
        out = F.reshape(x, (3, 4))
762 763 764 765 766 767
        print(out.numpy())

    Outputs:

    .. testoutput::

768 769 770
        [[ 0  1  2  3]
         [ 4  5  6  7]
         [ 8  9 10 11]]
771 772

    """
773
    return inp.reshape(target_shape)
774 775


776
def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
777 778
    r"""
    Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814

    :param inp: input tensor.
    :param start_axis: start dimension that the sub-tensor to be flattened. Default: 0
    :param end_axis: end dimension that the sub-tensor to be flattened. Default: -1
    :return: output tensor.

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F

        inp_shape = (2, 2, 3, 3)
        x = tensor(
            np.arange(36, dtype=np.int32).reshape(inp_shape),
        )
        out = F.flatten(x, 2)
        print(x.numpy().shape)
        print(out.numpy().shape)

    Outputs:

    .. testoutput::

        (2, 2, 3, 3)
        (2, 2, 9)

    """
    target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,)
    if end_axis != -1:
        target_shape += (*inp.shape[end_axis + 1 :],)
    return inp.reshape(*target_shape)


815
def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
816
    r"""
817
    Adds dimension before given axis.
818

819 820 821
    :param inp: input tensor.
    :param axis: place of new axes.
    :return: output tensor.
822 823 824 825 826 827 828 829

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F
830

831
        x = tensor([1, 2])
832
        out = F.expand_dims(x, 0)
833
        print(out.numpy().shape)
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853

    Outputs:

    .. testoutput::

        (1, 2)

    """

    def get_axes():
        try:
            return [int(axis)]
        except (TypeError, ValueError):
            pass
        return list(map(int, axis))

    axis = get_axes()
    ndim = inp.ndim + len(axis)
    axis = sorted(i + ndim if i < 0 else i for i in axis)

854
    op = builtin.AddAxis(axis=axis)
855 856 857 858
    (result,) = apply(op, inp)
    return result


859
def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
860
    r"""
861
    Removes dimension of shape 1.
862

863 864 865
    :param inp: input tensor.
    :param axis: place of axis to be removed.
    :return: output tensor.
866 867 868 869 870 871 872 873

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F
874

875
        x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
876
        out = F.squeeze(x, 3)
877
        print(out.numpy().shape)
878 879 880 881 882 883 884 885

    Outputs:

    .. testoutput::

        (1, 1, 2)

    """
886
    return _remove_axis(inp, axis)
887 888 889 890 891 892 893 894 895


def linspace(
    start: Union[int, float, Tensor],
    stop: Union[int, float, Tensor],
    num: Union[int, Tensor],
    dtype="float32",
    device: Optional[CompNode] = None,
) -> Tensor:
896 897
    r"""
    Returns equally spaced numbers over a specified interval.
898

899 900 901 902 903
    :param start: starting value of the squence, shoule be scalar.
    :param stop: last value of the squence, shoule be scalar.
    :param num: number of values to generate.
    :param dtype: result data type.
    :return: generated tensor.
904 905 906 907 908 909 910 911

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F

912
        a = F.linspace(3, 10, 5)
913 914
        print(a.numpy())

M
Megvii Engine Team 已提交
915
    Outputs:
916

917 918 919 920 921
    .. testoutput::

        [ 3.    4.75  6.5   8.25 10.  ]

    """
922 923 924 925 926 927 928 929
    for item in (start, stop, num):
        cur_device = getattr(item, "device", None)
        if device is None:
            device = cur_device
        else:
            if not (cur_device is None or device == cur_device):
                raise ("ambiguous device for linspace opr")

930 931 932 933 934
    is_symbolvar = list(isinstance(x, SymbolVar) for x in [start, stop, num])
    if any(is_symbolvar) and not all(is_symbolvar):
        raise TypeError("start, stop and num should all be VarNode or none of them")

    if not isinstance(start, (Tensor, SymbolVar)):
935
        start = Tensor(start, device=device)
936
    if not isinstance(stop, (Tensor, SymbolVar)):
937
        stop = Tensor(stop, device=device)
938
    if not isinstance(num, (Tensor, SymbolVar)):
939
        num = Tensor(num, device=device)
940 941 942 943 944 945 946 947 948

    op = builtin.Linspace(comp_node=device)
    (result,) = apply(op, start, stop, num)
    if np.dtype(dtype) == np.int32:
        return result.astype(dtype)
    return result


def arange(
949
    start: Union[int, float, Tensor] = 0,
950
    stop: Optional[Union[int, float, Tensor]] = None,
951 952 953 954
    step: Union[int, float, Tensor] = 1,
    dtype="float32",
    device: Optional[CompNode] = None,
) -> Tensor:
955 956
    r"""
    Returns a tensor with values from start to stop with adjacent interval step.
957

958
    :param start: starting value of the squence, shoule be scalar.
959
    :param stop: ending value of the squence, shoule be scalar.
960 961 962
    :param step: gap between each pair of adjacent values. Default: 1
    :param dtype: result data type.
    :return: generated tensor.
963 964 965 966 967 968 969 970

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F

971
        a = F.arange(5)
972
        print(a.numpy())
973

M
Megvii Engine Team 已提交
974
    Outputs:
975

976 977
    Outputs:

978 979
    .. testoutput::

980
        [0. 1. 2. 3. 4.]
981 982

    """
983 984
    if stop is None:
        start, stop = 0, start
985

986 987
    if isinstance(start, Tensor):
        start = start.astype("float32")
988 989
    if isinstance(stop, Tensor):
        stop = stop.astype("float32")
990 991
    if isinstance(step, Tensor):
        step = step.astype("float32")
992
    num = ceil((stop - start) / step)
993 994 995 996 997
    stop = start + step * (num - 1)
    result = linspace(start, stop, num, device=device)
    if np.dtype(dtype) == np.int32:
        return result.astype(dtype)
    return result
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138


def repeat(inp: Tensor, repeats: int, axis: Optional[int] = None):
    """
    Repeat elements of an array.

    :param inp: input tensor.
    :param repeats: the number of repetitions for each element.
    :param axis: the axis along which to repeat values. By default, use the
                 flattened input array, and return a flat output array.
    :return: output tensor.

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F
        from megengine import tensor

        x = tensor([[1, 2], [3, 4]], np.int32)
        y = F.repeat(x, 2, axis=0)
        print(y.numpy())

    Outputs:

    .. testoutput::

        [[1 2]
         [1 2]
         [3 4]
         [3 4]]

    """
    if axis is None:
        inp = inp.reshape(-1)  # flatten
        axis = 0
    if inp._isscalar():
        inp._unsetscalar()
    shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
    # assume inp.ndim is not changed during trace
    max_axis = len(shape) - 1
    assert axis >= 0 and axis <= max_axis
    assert repeats >= 1

    base_shape, bcast_shape, target_shape = [], [], []
    if axis != 0:
        target_shape.append(shape[:axis])
    base_shape.extend([shape[: axis + 1], [1,]])
    bcast_shape.extend([shape[: axis + 1], [repeats,]])
    target_shape.extend(
        [shape[axis] * repeats,]
    )
    if axis + 1 <= max_axis:
        base_shape.append(shape[axis + 1 :])
        bcast_shape.append(shape[axis + 1 :])
        target_shape.append(shape[axis + 1 :])

    out = broadcast_to(inp.reshape(concat(base_shape)), concat(bcast_shape)).reshape(
        concat(target_shape)
    )
    return out


def _tile_one_dim(inp, rep, axis):
    shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
    # assume inp.ndim is not changed during trace
    max_axis = len(shape) - 1

    base_shape, bcast_shape, target_shape = [], [], []

    if axis != 0:
        base_shape.append(shape[:axis])
        bcast_shape.append(shape[:axis])
        target_shape.append(shape[:axis])
    base_shape.extend([[1,], shape[axis:]])
    bcast_shape.extend([rep, shape[axis:]])
    target_shape.append(shape[axis] * rep)
    if axis + 1 <= max_axis:
        target_shape.append(shape[axis + 1 :])

    out = broadcast_to(inp.reshape(concat(base_shape)), concat(bcast_shape)).reshape(
        concat(target_shape)
    )
    return out


def tile(inp: Tensor, reps: Iterable[int]):
    """
    Construct an array by repeating ``inp`` the number of times given by ``reps``. If reps has length d,
    the result will have dimension of ``max(d, inp.ndim)``. It is required that ``d >= inp.dim``. If ``inp.ndim < d``,
    ``inp`` is promoted to be ``d``-dimensional by prepending new axis.

    :param inp: input tensor.
    :param reps: The number of repetitions of inp along each axis.
    :return: output tensor.

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F
        from megengine import tensor

        x = tensor([[1, 2], [3, 4]], np.int32)
        y = F.tile(x, (2,1))
        print(y.numpy())

    Outputs:

    .. testoutput::

        [[1 2]
        [3 4]
        [1 2]
        [3 4]]

    """
    shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
    reps = astensor1d(reps, inp, dtype="int32", device=inp.device)
    l_shape = len(shape)
    l_reps = len(reps)
    assert (
        l_reps >= l_shape
    ), "Number of dimensions of tiled dims can not be smaller than number of dimensions of tensor"

    for i in range(l_shape):
        rep = reps[i + (l_reps - l_shape)]
        inp = _tile_one_dim(inp, rep, i)

    if l_reps > l_shape:
        shape = inp.shape
        extra = reps[:-l_shape]
        extra_ones = ones_like(extra)
        base_shape = concat([extra_ones, shape])
        bcast_shape = concat([extra, shape])
        target_shape = concat([extra, shape])
        inp = broadcast_to(inp.reshape(base_shape), bcast_shape).reshape(target_shape)

    return inp
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168


def copy(inp, device=None):
    r"""
    Copies tensor to another device.

    :param inp: input tensor.
    :param device: destination device.

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F

        x = tensor([1, 2, 3], np.int32)
        y = F.copy(x, "xpu1")
        print(y.numpy())

    Outputs:

    .. testoutput::

        [1 2 3]
    """
    if device is None:
        return apply(Identity(), inp)[0]
    return apply(Copy(comp_node=as_device(device).to_c()), inp)[0]