tensor.py 25.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# 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 functools
import math
from itertools import accumulate
from typing import Iterable, List, Optional, Sequence, Tuple, Union

import numpy as np

from ..core._imperative_rt import CompNode
17
from ..core._wrap import device as as_device
18 19 20 21
from ..core.ops import builtin
from ..core.ops._internal import param_defs as P
from ..core.ops.special import Const
from ..core.tensor.core import TensorBase, TensorWrapperBase, apply
22
from ..core.tensor.tensor_wrapper import _broadcast, _remove_axis
23 24 25 26 27 28 29 30 31 32 33 34 35
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
from .elemwise import ceil

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


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

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

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F

        data_shape = (4, 6)
76
        out = F.eye(data_shape, dtype=np.float32)
77 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.]]

    """
    op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
90
    (result,) = apply(op, Tensor(shape, dtype="int32", device=device))
91 92 93 94
    return result


def full(shape, value, dtype="float32", device=None):
95 96
    """Returns a tensor with given shape and value.
    """
97 98
    if isinstance(shape, int):
        shape = (shape,)
99 100 101 102 103
    if device is None:
        device = get_default_device()
    (x,) = Const(value, dtype=dtype, device=device)(
        Tensor(value, dtype=dtype, device=device)
    )
104
    return broadcast_to(x, shape)
105 106 107


def ones(shape, dtype="float32", device=None):
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    """Returns a ones tensor with given shape.

    :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.]]

    """
130 131 132 133
    return full(shape, 1.0, dtype=dtype, device=device)


def zeros(shape, dtype="float32", device=None):
134 135
    """Returns a zero tensor with given shape.
    """
136 137 138 139
    return full(shape, 0.0, dtype=dtype, device=device)


def zeros_like(inp: Tensor) -> Tensor:
140
    """Returns a zero tensor with the same shape as input tensor.
141

142 143
    :param inp: input tensor.
    :return: output zero tensor.
144 145 146 147 148 149 150 151 152 153 154 155 156

    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 已提交
157
    Outputs:
158

159 160 161 162 163 164 165 166 167 168
    .. testoutput::

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

    """
    return zeros(inp.shape, dtype=inp.dtype, device=inp.device)


def ones_like(inp: Tensor) -> Tensor:
M
Megvii Engine Team 已提交
169
    """Returns a ones tensor with the same shape as input tensor.
170 171 172 173 174
    """
    return ones(inp.shape, dtype=inp.dtype, device=inp.device)


def full_like(inp: Tensor, value: Union[int, float]) -> Tensor:
175
    """Returns a tensor filled with given value with the same shape as input tensor.
176 177 178 179
    """
    return full(inp.shape, value, dtype=inp.dtype, device=inp.device)


180
def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor:
181
    """
182
    Broadcasts a tensor to given shape.
183

184 185 186
    :param inp: input tensor.
    :param shape: target shape.
    :return: output tensor.
187 188 189 190 191 192 193 194 195 196

    Examples:

    .. testcode::

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

        data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
197
        out = F.broadcast_to(data, (4, 2, 3))
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[[0. 1. 2.]
          [3. 4. 5.]]

         [[0. 1. 2.]
          [3. 4. 5.]]

         [[0. 1. 2.]
          [3. 4. 5.]]

         [[0. 1. 2.]
          [3. 4. 5.]]]

    """
217
    return _broadcast(inp, shape)
218 219


220
def concat(inps: Iterable[Tensor], axis: int = 0, device=None) -> Tensor:
221 222 223
    r"""
    Concat some tensors

224
    :param inps: input tensors to concat.
M
Megvii Engine Team 已提交
225 226
    :param axis: over which dimension the tensors are concatenated. Default: 0
    :param device: which device output will be. Default: None
227
    :return: output tensor.
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

    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.]]

    """
252 253 254
    if len(inps) == 1:
        return inps[0]

255
    dtype = dtype_promotion(inps)
256 257 258
    if device is None:
        device = get_device(inps)
    device = as_device(device)
259 260 261 262 263 264 265 266 267

    def convert(x):
        return convert_single_value(x, inps, dtype=dtype)

    inps = tuple(map(convert, inps))
    (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
    return result


268
def stack(inps, axis=0, device=None):
269 270 271
    """Concats a sequence of tensors along a new axis.
    The input tensors must have the same shape.

272 273
    :param inps: input tensors.
    :param axis: which axis will be concatenated.
M
Megvii Engine Team 已提交
274
    :param device: the device output will be. Default: None
275
    :return: output concatenated tensor.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

    Examples:

    .. testcode::

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

        x1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
        x2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
        out = F.stack([x1, x2], axis=0)
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[[ 0.  1.  2.]
          [ 3.  4.  5.]]

         [[ 6.  7.  8.]
          [ 9. 10. 11.]]]

    """
301 302 303 304
    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")
305

306
    inps = [expand_dims(inp, axis=axis) for inp in inps]
307
    return concat(inps, axis=axis, device=device)
308 309 310 311 312 313


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

314
    :param inp: input tensor.
M
Megvii Engine Team 已提交
315
    :param nsplits_or_sections: number of sub tensors or sections information list.
316 317
    :param axis: which axis will be splited.
    :return: output tensor list.
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

    Examples:

    .. testcode::

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

        x = tensor(np.random.random((2,3,4,5)), dtype=np.float32)
        out = F.split(x, 2, axis=3)
        print(out[0].shape, out[1].shape)

    Outputs:

    .. testoutput::

        (2, 3, 4, 3) (2, 3, 4, 2)

    """
    sub_tensors = []
    sections = []

    def swapaxis(inp, src, dst):
        if src == dst:
            return inp
344
        shape = [i for i in range(inp.ndim)]
345 346 347 348 349 350 351
        shape[src] = dst
        shape[dst] = src
        return inp.transpose(shape)

    inp = swapaxis(inp, 0, axis)

    if isinstance(nsplits_or_sections, int):
352 353 354 355 356
        incr_step = ceil(inp.shape[0] / nsplits_or_sections)
        nsplits = nsplits_or_sections
        while nsplits > 0:
            nsplits -= 1
            sections.append(incr_step.astype("int32"))
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
            incr_step += nsplits_or_sections
    else:
        sections = nsplits_or_sections

    st = 0
    for se in sections:
        sub_tensors.append(swapaxis(inp[st:se], axis, 0))
        st = se

    if st < inp.shape[0]:
        sub_tensors.append(swapaxis(inp[st:], axis, 0))

    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 = (
383
                broadcast_to(arange.reshape(*shape), index.shape)
384 385 386 387 388 389 390 391 392 393
                .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:
394
    # TODO: rewrite doc
M
Megvii Engine Team 已提交
395
    r"""Gathers data from input tensor on axis using index.
396 397 398 399 400 401 402

    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 已提交
403
    if input tensor is a n-dimensional tensor with size
404
    :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i,
M
Megvii Engine Team 已提交
405
    then index must be a n-dimensional tensor with size
406
    :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and
407
    output will have the same size as index.
408

409
    :param inp: input tensor.
M
Megvii Engine Team 已提交
410
    :param axis: along which axis to index.
411 412
    :param index: indices of elements to gather.
    :return: output tensor.
413 414 415 416 417 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 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

    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:
466
    # TODO: rewrite doc
467
    r"""Writes all values from the tensor source into input tensor
468
    at the indices specified in the index tensor.
469

470 471 472
    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``.
473

M
Megvii Engine Team 已提交
474
    For a 3-D tensor, input tensor is updated as::
475 476 477 478 479

        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 已提交
480
    ``inp``, ``index`` and ``source`` should have same number of dimensions.
481 482 483 484

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

485
    Moreover, the values of index must be between ``0`` and ``inp.shape(axis) - 1`` inclusive.
486 487 488

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

M
Megvii Engine Team 已提交
492
        Check the following examples, the oup[0][2] is maybe
493 494 495
        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.

496 497 498 499 500
    :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.
501 502 503 504 505 506 507 508 509 510 511 512 513 514 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 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

    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:
572
    r"""Selects elements either from Tensor x or Tensor y, according to mask.
573 574 575 576 577

    .. math::

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

M
Megvii Engine Team 已提交
578
    :param mask: a mask used for choosing ``x`` or ``y``.
579 580 581
    :param x: first choice.
    :param y: second choice.
    :return: output tensor.
582 583 584 585 586 587 588

    Examples:

    .. testcode::

        from megengine import tensor
        import megengine.functional as F
589
        mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool))
590 591 592 593 594 595 596 597 598 599 600 601 602
        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.]]
    """
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

    x, y = convert_inputs(x, y)
    if not isinstance(x, (TensorWrapperBase, TensorBase)):
        raise TypeError("input x must be a tensor")
    if not isinstance(y, (TensorWrapperBase, TensorBase)):
        raise TypeError("input y must be a tensor")
    if not isinstance(mask, (TensorWrapperBase, TensorBase)):
        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)

    if v0.shape == (0,):
        out = v1
    elif v1.shape == (0,):
        out = v0
    else:
        out = concat([v0, v1])

    out[index0] = v0
    out[index1] = v1
    out = out.reshape(x.shape)
    return out
630 631 632 633


def cond_take(mask: Tensor, x: Tensor) -> Tensor:
    r"""
M
Megvii Engine Team 已提交
634
    Takes elements from data if specific condition is satisfied on mask.
635 636 637
    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.
638

639 640
    :param mask: condition param; must be the same shape with data.
    :param x: input tensor from which to take elements.
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

    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 已提交
659
        [1. 4.] [0 3]
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

    """
    if not isinstance(x, (TensorWrapperBase, TensorBase)):
        raise TypeError("input must be a tensor")
    if not isinstance(mask, (TensorWrapperBase, TensorBase)):
        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


676
def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
677
    r"""
678
    Swaps shapes and strides according to given pattern.
679

680
    :param inp: input tensor.
681
    :param pattern: a list of integers including 0, 1, ... , ``ndim``-1,
682
    and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples:
683 684 685 686 687 688 689 690 691

        * (``'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 已提交
692
        * (1,) -> this removes dimensions 0. It must be a broadcastable dimension (1xA to A)
693

694
    :return: output tensor.
695 696 697 698 699 700 701 702 703

    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))
704
        out = F.transpose(x, (1, 0))
705 706 707 708 709 710 711 712 713 714
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[1 0]
         [1 0]]

    """
715
    return inp.transpose(pattern)
716 717 718 719


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

723
    :param inp: input tensor.
M
Megvii Engine Team 已提交
724
    :param target_shape: target shape, it can contain an element of -1 representing ``unspec_axis``.
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750

    Examples:

    .. testcode::

        import numpy as np
        from megengine import tensor
        import megengine.functional as F
        x = tensor(np.arange(12, dtype=np.int32))
        out = F.reshape(x, (3, 2, 2))
        print(out.numpy())

    Outputs:

    .. testoutput::

        [[[ 0  1]
          [ 2  3]]

         [[ 4  5]
          [ 6  7]]

         [[ 8  9]
          [10 11]]]

    """
751
    return inp.reshape(target_shape)
752 753 754 755 756 757


AxisAddRemove = builtin.AxisAddRemove
AxisDesc = AxisAddRemove.AxisDesc


758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
    r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.

    :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)


796
def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
797
    r"""
798
    Adds dimension before given axis.
799

800 801 802
    :param inp: input tensor.
    :param axis: place of new axes.
    :return: output tensor.
803 804 805 806 807 808 809 810

    Examples:

    .. testcode::

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

812
        x = tensor([1, 2])
813
        out = F.expand_dims(x, 0)
814 815 816 817 818 819 820 821 822
        print(out.shape)

    Outputs:

    .. testoutput::

        (1, 2)

    """
823
    Param = builtin.AxisAddRemove.Param
824 825 826 827 828 829 830 831 832 833 834 835

    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)

836 837
    param = Param(*map(builtin.AxisAddRemove.AxisDesc.make_add, axis))
    op = builtin.AxisAddRemove(param=param)
838 839 840 841
    (result,) = apply(op, inp)
    return result


842
def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
843
    r"""
844
    Removes dimension of shape 1.
845

846 847 848
    :param inp: input tensor.
    :param axis: place of axis to be removed.
    :return: output tensor.
849 850 851 852 853 854 855 856

    Examples:

    .. testcode::

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

858
        x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
859
        out = F.squeeze(x, 3)
860 861 862 863 864 865 866 867 868
        print(out.shape)

    Outputs:

    .. testoutput::

        (1, 1, 2)

    """
869
    return _remove_axis(inp, axis)
870 871 872 873 874 875 876 877 878


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

881 882 883 884 885
    :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.
886 887 888 889 890 891 892 893 894 895 896

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F

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

M
Megvii Engine Team 已提交
897
    Outputs:
898

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
    .. testoutput::

        [ 3.    4.75  6.5   8.25 10.  ]

    """
    start = Tensor(start, device=device)
    stop = Tensor(stop, device=device)
    num = Tensor(num, device=device)

    device = device if device is None else device.to_c()
    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(
917
    start: Union[int, float, Tensor] = 0,
918
    stop: Optional[Union[int, float, Tensor]] = None,
919 920 921 922
    step: Union[int, float, Tensor] = 1,
    dtype="float32",
    device: Optional[CompNode] = None,
) -> Tensor:
923
    r"""Returns a tensor with values from start to stop with adjacent interval step.
924

925
    :param start: starting value of the squence, shoule be scalar.
926
    :param stop: ending value of the squence, shoule be scalar.
927 928 929
    :param step: gap between each pair of adjacent values. Default: 1
    :param dtype: result data type.
    :return: generated tensor.
930 931 932 933 934 935 936 937

    Examples:

    .. testcode::

        import numpy as np
        import megengine.functional as F

938
        a = F.arange(5)
939
        print(a.numpy())
940

M
Megvii Engine Team 已提交
941
    Outputs:
942

943 944
    Outputs:

945 946
    .. testoutput::

947
        [0. 1. 2. 3. 4.]
948 949

    """
950 951
    if stop is None:
        start, stop = 0, start
952

953 954
    if isinstance(start, Tensor):
        start = start.astype("float32")
955 956
    if isinstance(stop, Tensor):
        stop = stop.astype("float32")
957 958
    if isinstance(step, Tensor):
        step = step.astype("float32")
959
    num = ceil(Tensor((stop - start) / step, device=device))
960 961 962 963 964
    stop = start + step * (num - 1)
    result = linspace(start, stop, num, device=device)
    if np.dtype(dtype) == np.int32:
        return result.astype(dtype)
    return result