tensor.py 41.9 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
from functools import lru_cache
3
from typing import Iterable, List, Optional, Sequence, Tuple, Union
4 5 6 7

import numpy as np

from ..core._imperative_rt import CompNode
8
from ..core._imperative_rt.core2 import (
9
    Const,
10
    apply,
11
    broadcast_cpp,
12
    create_complex,
13 14
    dtype_promotion,
    expand_dims_cpp,
15 16
    get_imag,
    get_real,
17
    split_cpp,
18
    squeeze_cpp,
19
)
20
from ..core._wrap import as_device
21
from ..core.ops import builtin
22
from ..core.ops.builtin import Copy, Identity
23
from ..core.tensor.utils import astensor1d, convert_inputs, get_device, subgraph_fn
24 25
from ..device import get_default_device
from ..tensor import Tensor
26
from .elemwise import ceil, cos, sin
27 28 29

__all__ = [
    "arange",
30
    "broadcast_to",
31 32
    "concat",
    "cond_take",
33
    "copy",
M
Megvii Engine Team 已提交
34
    "cumsum",
35
    "diag",
36
    "expand_dims",
37
    "eye",
38
    "flatten",
39 40 41
    "full",
    "full_like",
    "gather",
42
    "imag",
43
    "linspace",
44
    "meshgrid",
45 46
    "ones",
    "ones_like",
47
    "polar",
48
    "repeat",
49
    "reshape",
50
    "roll",
51
    "scatter",
52
    "split",
M
Megvii Engine Team 已提交
53
    "squeeze",
54
    "stack",
55
    "swapaxes",
56
    "tile",
57
    "transpose",
58 59
    "complex",
    "real",
60 61 62 63 64 65
    "where",
    "zeros",
    "zeros_like",
]


66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
# creation functions


def arange(
    start: Union[int, float] = 0,
    stop: Optional[Union[int, float]] = None,
    step: Union[int, float] = 1,
    *,
    dtype="float32",
    device=None,
) -> Tensor:
    r"""Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional tensor.

    Note:
        This function cannot guarantee that the interval does not include the stop value in those cases
        where step is not an integer and floating-point rounding errors affect the length of the output tensor.
82 83

    Args:
84 85 86 87 88 89 90 91 92 93 94
        start(Number): if ``stop`` is specified, the start of interval (inclusive); otherwise,
            the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.
        stop(Number): the end of the interval.
        step(Number): the distance between two adjacent elements ( ``out[i+1] - out[i]`` ). Must not be 0 ;
            may be negative, this results i an empty tensor if stop >= start .

    Keyword args:
        dtype(:attr:`.Tensor.dtype`, optional): output tensor data type.
        device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.

    .. seealso:: :func:`~.functional.linspace`
95 96

    Returns:
97 98 99 100
        A one-dimensional tensor containing evenly spaced values.

        The length of the output tensor must be ``ceil((stop-start)/step)``
        if ``stop - start`` and ``step`` have the same sign, and length 0 otherwise.
101 102

    Examples:
103 104 105 106 107
        >>> F.arange(5)
        Tensor([0. 1. 2. 3. 4.], device=xpux:0)
        >>> F.arange(1, 4)
        Tensor([1. 2. 3.], device=xpux:0)

108
    """
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    if stop is None:
        start, stop = 0, start

    if not isinstance(start, Tensor):
        start = Tensor(start, dtype="float32")
    if not isinstance(stop, Tensor):
        stop = Tensor(stop, dtype="float32")
    if not isinstance(step, Tensor):
        step = Tensor(step, dtype="float32")

    num = ceil((stop - start) / step)
    stop = start + step * (num - 1)
    result = linspace(start, stop, num, device=device)
    if np.dtype(dtype) != np.float32:
        return result.astype(dtype)
    return result


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

    Returns ``num`` evenly spaced samples, calculated over the interval ``[start, stop]``.

    Args:
        start(Number): the start of the interval.
        stop(Number): the end of the interval.
        num(int): number of values to generate.

    Keyword args:
        dtype(:attr:`.Tensor.dtype`, optional): output tensor data type.
            If ``dtype`` is not given, the data type is inferred from ``start`` and ``stop``.
        device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.

    Returns:
        a one-dimensional tensor containing evenly spaced values.

    .. seealso:: :func:`~.functional.arange`

    Examples:
        >>> F.linspace(1, 10, 10)
        Tensor([ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.], device=xpux:0)

        >>> F.linspace(2., 3., 5)
        Tensor([2.   2.25 2.5  2.75 3.  ], device=xpux:0)
    """
    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")

    if not isinstance(start, Tensor):
        start = Tensor(start, device=device)
    if not isinstance(stop, Tensor):
        stop = Tensor(stop, device=device)
    if not isinstance(num, Tensor):
        num = Tensor(num, device=device)

    op = builtin.Linspace(comp_node=device)
    (result,) = apply(op, start, stop, num)
    if np.dtype(dtype) != np.float32:
        return result.astype(dtype)
180 181 182
    return result


183 184
def eye(N: int, M: int = None, *, dtype="float32", device=None) -> Tensor:
    r"""Returns a two-dimensional tensor with ones on the diagonal and zeros elsewhere.
185

186
    Args:
187 188 189 190 191 192 193 194 195 196
        N: number of rows in the output tesnor.
        M: number of columns in the output tesnor.
            If ``None``, the default number of columns in the output tesnor is equal tos ``N``.

    Keyword args:
        dtype(:attr:`.Tensor.dtype`, optional): output tesnor data type.
            If ``None``, the output tesnor data type must be the default floating-point data type.
        device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.

    .. seealso:: If you want to create a diagonal matrix, see :func:`~.functional.diag`.
197

198
    Returns:
199 200
        a tensor where all elements are equal to zero,
        except for the diagonal, whose values are equal to one.
201

202
    Examples:
203 204 205 206 207 208 209 210 211 212 213

        >>> F.eye(3)
        Tensor([[1. 0. 0.]
         [0. 1. 0.]
         [0. 0. 1.]], device=xpux:0)

        >>> F.eye(4, 6)
        Tensor([[1. 0. 0. 0. 0. 0.]
         [0. 1. 0. 0. 0. 0.]
         [0. 0. 1. 0. 0. 0.]
         [0. 0. 0. 1. 0. 0.]], device=xpux:0)
214
    """
215 216 217 218 219 220 221 222 223
    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)
224
    op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
225
    (result,) = apply(op, shape)
226 227 228
    return result


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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
def diag(inp, k: int = 0) -> Tensor:
    r"""Extract a diagonal or construct a diagonal tensor.
    
    If ``inp`` is a 1D tensor, then returns a 2D tensor with the elements of ``inp`` as the diagonal.
    If ``inp`` is a 2D tensor, then returns a 1D tensor with the diagonal elements of ``inp``.

    Args:
        inp: input tensor.
        k: diagonal in consider. Use :math:`k=0` for the main diagonal, :math:`k>0` for diagonals above the
           main diagonal, and :math:`k<0` for diagonals below the main diagonal.

    .. seealso:: If you want to create a identity matrix, see :func:`~.functional.eye`.

    Returns:
        the extracted diagonal or constructed diagonal tensor.

    Examples:

        Input is a 1D tensor:

        >>> F.diag(Tensor([1, 2, 3]))
        Tensor([[1 0 0]
         [0 2 0]
         [0 0 3]], dtype=int32, device=xpux:0)
        >>> F.diag(Tensor([1, 2, 3]), k=1)
        Tensor([[0 1 0 0]
         [0 0 2 0]
         [0 0 0 3]
         [0 0 0 0]], dtype=int32, device=xpux:0)

        Input is a 2D tensor:

        >>> x = F.arange(9).reshape(3, 3)
        >>> x
        Tensor([[0. 1. 2.]
         [3. 4. 5.]
         [6. 7. 8.]], device=xpux:0)
        >>> F.diag(x)
        Tensor([0. 4. 8.], device=xpux:0)

        Get the k-th diagonal of a given matrix:

        >>> F.diag(x, k=1)
        Tensor([1. 5.], device=xpux:0)
        >>> F.diag(x, k=-1)
        Tensor([3. 7.], device=xpux:0)
    """
    op = builtin.Diag(k=k)
    (result,) = apply(op, inp)
    return result


281
def full(
282 283 284
    shape: Union[int, Tuple[int, ...]],
    value: Union[bool, int, float],
    *,
285 286 287
    dtype=None,
    device=None,
) -> Tensor:
288
    r"""Returns a new tensor having a specified shape and filled with given value.
289

290
    Args:
291 292 293 294 295 296 297 298 299 300
        shape(int...): output tensor shape.
        value(Scalar): fill value.

    Keyword args:
        dtype(:attr:`.Tensor.dtype`, optional): output tensor data type. 
            If ``dtype`` is ``None``, the output tensor data type must be inferred from ``value``.
            If the value is an ``int``, the output tensor data type must be the default integer data type.
            If the value is a ``float``, the output tensor data type must be the default floating-point data type.
            If the value is a ``bool``, the output tensor must have boolean data type.
        device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.
301

302
    Returns:
303
        a tensor where every element is equal to ``value``.
304

305
    Examples:
306 307 308
        >>> F.full((2, 3), 6)
        Tensor([[6 6 6]
         [6 6 6]], dtype=int32, device=xpux:0)
309
    """
310

311 312
    if isinstance(shape, int):
        shape = (shape,)
313 314
    if device is None:
        device = get_default_device()
315
    x = Const(value, dtype, device)
316
    if type(shape) in (list, tuple) and len(shape) == 0:
317
        return x
318
    return broadcast_to(x, shape)
319 320


321 322 323 324 325 326 327
def ones(
    shape: Union[int, Tuple[int, ...]],
    *,
    dtype="float32",
    device: Optional[CompNode] = None
) -> Tensor:
    r"""Returns a new tensor having a specified shape and filled with ones.
328

329
    Args:
330
        shape(int...): the shape of the output tensor.
331 332

    Keyword args:
333 334
        dtype(:attr:`.Tensor.dtype`, optional): output tensor data type.
        device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.
335

336
    Returns:
337
        a tensor containing ones.
338

339
    Examples:
340 341 342 343 344 345 346
        >>> F.ones(5)
        Tensor([1. 1. 1. 1. 1.], device=xpux:0)
        >>> F.ones((5, ), dtype='int32')
        Tensor([1 1 1 1 1], dtype=int32, device=xpux:0)
        >>> F.ones((2, 2))
        Tensor([[1. 1.]
         [1. 1.]], device=xpux:0)
347
    """
348 349 350 351 352 353 354 355
    if isinstance(shape, int):
        shape = (shape,)
    if device == None:
        device = get_default_device()
    op = builtin.Fill(1, dtype)
    shape = astensor1d(shape, dtype="int32", device=device)
    (x,) = apply(op, shape)
    return x
356 357


358 359 360 361 362 363 364
def zeros(
    shape: Union[int, Tuple[int, ...]],
    *,
    dtype="float32",
    device: Optional[CompNode] = None
) -> Tensor:
    r"""Returns a new tensor having a specified shape and filled with zeros.
365 366

    Args:
367
        shape(int...): the shape of the output tensor.
368 369

    Keyword args:
370 371
        dtype(:attr:`.Tensor.dtype`, optional): output tensor data type.
        device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.
372 373 374 375 376

    Returns:
        a tensor containing zeros.

    Examples:
377 378 379
        >>> F.zeros((2, 3))
        Tensor([[0. 0. 0.]
         [0. 0. 0.]], device=xpux:0)
380
    """
381 382 383 384 385 386 387 388
    if isinstance(shape, int):
        shape = (shape,)
    if device == None:
        device = get_default_device()
    op = builtin.Fill(0, dtype)
    shape = astensor1d(shape, dtype="int32", device=device)
    (x,) = apply(op, shape)
    return x
389 390


391
def zeros_like(inp: Tensor) -> Tensor:
392
    r"""Returns a tensor filled with zeros with the same shape and data type as input tensor.
393 394

    Args:
395
        inp(Tensor): input tensor from which to derive the output tensor shape.
396

397
    Return:
398
        a tensor having the same shape as input tensor and filled with zeros.
399 400

    Examples:
401 402
        >>> x = F.arange(6, dtype='int32').reshape(2, 3)
        >>> F.zeros_like(x)
403 404
        Tensor([[0 0 0]
         [0 0 0]], dtype=int32, device=xpux:0)
405
    """
406
    return full_like(inp, 0.0)
407 408


409
def ones_like(inp: Tensor) -> Tensor:
410
    r"""Returns a tensor filled with ones with the same shape and data type as input tensor.
411

412
    Args:
413
        inp(Tensor): input tensor from which to derive the output tensor shape.
414

415
    Return:
416
        a tensor having the same shape as input tensor and filled with ones.
417

418
    Examples:
419 420
        >>> x = F.arange(6, dtype='int32').reshape(2, 3)
        >>> F.ones_like(x)
421 422
        Tensor([[1 1 1]
         [1 1 1]], dtype=int32, device=xpux:0)
423
    """
424
    return full_like(inp, 1.0)
425 426


427
def polar(abs: Tensor, angle: Tensor) -> Tensor:
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    r"""Constructs a complex tensor whose elements are Cartesian coordinates
    corresponding to the polar coordinates with absolute value abs and angle angle.

    Args:
        abs(Tensor): the absolute value the complex tensor. Must be float.
        angle(Tensor): the angle of the complex tensor. Must be float.

    Returns:
        the complex tensor

    Examples:
        >>> abs = Tensor([1, 2], dtype=np.float32)
        >>> angle = Tensor([np.pi / 2, 5 * np.pi / 4], dtype=np.float32)
        >>> z = F.polar(abs, angle)
        >>> z
        Tensor([-4.3711e-08+1.j     -1.4142e+00-1.4142j], dtype=complex64, device=xpux:0)
    """
445 446 447 448
    return create_complex(abs * cos(angle), abs * sin(angle))


def complex(real: Tensor, imag: Tensor) -> Tensor:
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    r"""Constructs a complex tensor with its real part equal to real and its imaginary part equal to imag.

    Args:
        real(Tensor): the real part of the complex tensor. Must be float.
        imag(Tensor): the imaginary part of the complex tensor. Must be float.

    Returns:
        the complex tensor

    Examples:
        >>> real = Tensor([1, 2], dtype=np.float32)
        >>> imag = Tensor([3, 4], dtype=np.float32)
        >>> z = F.complex(real, imag)
        >>> z
        Tensor([1.+3.j 2.+4.j], dtype=complex64, device=xpux:0)
        >>> z.dtype
        dtype('complex64')
    """
467 468 469 470 471 472 473 474
    if not isinstance(real, Tensor):
        real = Tensor(real)
    if not isinstance(imag, Tensor):
        imag = Tensor(imag)
    return create_complex(real, imag)


def real(complex: Tensor) -> Tensor:
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    r"""Returns a new tensor containing real values of the complex tensor.

    Args:
        complex(Tensor) the complex tensor

    Returns:
        the real part of the complex tensor

    Examples:
        >>> x=Tensor([0.3100+0.3553j, -0.5445-0.7896j, -1.6492-0.0633j, -0.0638-0.8119j], dtype=np.complex64)
        
        >>> F.real(x)
        Tensor([[ 0.31  ]
         [-0.5445]
         [-1.6492]
         [-0.0638]], device=xpux:0)
    """
492 493 494 495
    return get_real(complex)


def imag(complex: Tensor) -> Tensor:
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
    r"""Returns a new tensor containing imaginary values of the complex tensor.

    Args:
        complex(Tensor) the complex tensor

    Returns:
        the imaginary part of the complex tensor

    Examples:
        >>> x=Tensor([0.3100+0.3553j, -0.5445-0.7896j, -1.6492-0.0633j, -0.0638-0.8119j], dtype=np.complex64)
        
        >>> F.imag(x)
        Tensor([[ 0.3553]
         [-0.7896]
         [-0.0633]
         [-0.8119]], device=xpux:0)
    """
513 514 515
    return get_imag(complex)


516
def full_like(inp: Tensor, value: Union[int, float]) -> Tensor:
517
    r"""Returns a tensor filled with given value with the same shape as input tensor.
518

519
    Args:
520 521
        inp(Tensor): input tensor from which to derive the output tensor shape.
        value(Scalar): fill value.
522 523

    Return:
524
        a tensor having the same shape as input tensor and where every element is equal to fill value.
525 526

    Examples:
527 528
        >>> x = F.arange(6, dtype='int32').reshape(2, 3)
        >>> F.full_like(x, 2)
529 530
        Tensor([[2 2 2]
         [2 2 2]], dtype=int32, device=xpux:0)
531
    """
532 533
    op = builtin.FillLike(value=value)
    (rst,) = apply(op, inp)
534 535
    # rst.format = inp.format
    # see jira:MGE-4505
536
    return rst
537 538


539 540 541
# manipulation functions


542
def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor:
543
    r"""Broadcasts a tensor to given shape.
544

545 546 547
    Args:
        inp: input tensor.
        shape: target shape.
548

549 550
    Returns:
        output tensor.
551

552
    Examples:
553 554 555 556 557 558
        >>> import numpy as np
        >>> data = Tensor(np.arange(0, 3, dtype=np.float32).reshape(3))
        >>> out = F.broadcast_to(data, (2, 3))
        >>> out.numpy()
        array([[0., 1., 2.],
               [0., 1., 2.]], dtype=float32)
559
    """
560
    return broadcast_cpp(inp, shape)
561 562


563
def concat(inps: Iterable[Tensor], axis: int = 0, device=None) -> Tensor:
564
    r"""Concat some tensors
565

566 567 568 569
    Args:
        inps: input tensors to concat.
        axis: over which dimension the tensors are concatenated. Default: 0
        device: which device output will be. Default: None
570

571 572
    Returns:
        output tensor.
573

574
    Examples:
575 576 577 578 579 580 581 582 583
        >>> import numpy as np
        >>> 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])
        >>> out.numpy()
        array([[ 0.,  1.,  2.],
               [ 3.,  4.,  5.],
               [ 6.,  7.,  8.],
               [ 9., 10., 11.]], dtype=float32)
584
    """
585
    if len(inps) == 1:
586 587
        # if we return inps[0] directly, then the grad manager capture nothing
        return copy(inps[0], device)
588

589
    if device is None:
590 591 592
        device = get_device(inps)
    device = as_device(device)
    (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
593 594 595
    return result


596
def stack(inps, axis=0, device=None):
597
    r"""Concats a sequence of tensors along a new axis.
598 599
    The input tensors must have the same shape.

600 601 602 603
    Args:
        inps: input tensors.
        axis: which axis will be concatenated.
        device: the device output will be. Default: None
604

605 606
    Returns:
        output concatenated tensor.
607

608
    Examples:
609 610 611 612 613 614 615
        >>> import numpy as np
        >>> x1 = Tensor(np.arange(0, 3, dtype=np.float32).reshape((3)))
        >>> x2 = Tensor(np.arange(6, 9, dtype=np.float32).reshape((3)))
        >>> out = F.stack([x1, x2], axis=0)
        >>> out.numpy()
        array([[0., 1., 2.],
               [6., 7., 8.]], dtype=float32)
616
    """
617
    if len(inps) == 1:
618 619 620 621 622 623
        ret = expand_dims(inps[0], axis=axis)
        if device is None:
            return ret
        else:
            return copy(ret, device)

624
    if device is None:
625 626 627
        device = get_device(inps)
    device = as_device(device)
    (result,) = apply(builtin.Stack(axis=axis, comp_node=device.to_c()), *inps)
628
    return result
629 630 631


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

635 636 637 638
    Args:
        inp: input tensor.
        nsplits_or_sections: number of sub tensors or sections information list.
        axis: which axis will be splited.
639

640 641
    Returns:
        output tensor list.
642

643
    Examples:
644 645 646 647 648 649 650 651 652
        >>> import os
        >>> import numpy as np
        >>> x = Tensor(np.random.random((10, 20)), dtype=np.float32)
        >>> y = F.split(x, 3)
        >>> z = F.split(x, [6, 17], axis=1)
        >>> print([i.numpy().shape for i in y])
        [(4, 20), (3, 20), (3, 20)]
        >>> print([i.numpy().shape for i in z])
        [(10, 6), (10, 11), (10, 3)]
653
    """
654

655
    return split_cpp(inp, nsplits_or_sections, axis)
656 657 658 659 660


def _get_idx(index, axis):
    index_dims = len(index.shape)
    idx = []
661 662
    if axis < 0:
        axis += index_dims
663 664 665 666 667 668 669 670
    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 = (
671
                broadcast_to(arange.reshape(*shape), index.shape)
672 673 674 675 676 677 678 679 680 681
                .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:
682
    # TODO: rewrite doc
683 684
    r"""
    Gathers data from input tensor on axis using index.
685

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

688 689 690 691 692
    .. code-block::

       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
693

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

700 701 702 703
    Args:
        inp: input tensor.
        axis: along which axis to index.
        index: indices of elements to gather.
704

705 706
    Return:
        output tensor.
707

708
    Examples:
709 710 711 712 713 714 715
        >>> inp = Tensor([
        ...     [1,2], [3,4], [5,6],
        ... ])
        >>> index = Tensor([[0,2], [1,0]])
        >>> F.gather(inp, 0, index)
        Tensor([[1 6]
         [3 2]], dtype=int32, device=xpux:0)
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    """
    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)
        )

    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:
732
    # TODO: rewrite doc
733 734
    r"""
    Writes all values from the tensor source into input tensor
735
    at the indices specified in the index tensor.
736

737 738 739
    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``.
740

741 742 743
    For a 3-D tensor, input tensor is updated as:

    .. code-block::
744

745 746 747
       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
748

M
Megvii Engine Team 已提交
749
    ``inp``, ``index`` and ``source`` should have same number of dimensions.
750 751 752 753

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

754
    Moreover, the values of index must be between ``0`` and ``inp.shape(axis) - 1`` inclusive.
755

756
    Note:
757
        Please notice that, due to performance issues, the result is uncertain on the GPU device
M
Megvii Engine Team 已提交
758
        if scattering different positions from source to the same destination position
759 760
        regard to index tensor.

M
Megvii Engine Team 已提交
761
        Check the following examples, the oup[0][2] is maybe
762 763 764
        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.

765 766 767 768 769
    Args:
        inp: inp tensor which to be scattered.
        axis: axis along which to index.
        index: indices of elements to scatter.
        source: source element(s) to scatter.
770

771 772
    Return:
        output tensor.
773

774
    Examples:
775 776 777 778
        >>> import numpy as np
        >>> 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]])
779
        >>> oup = F.scatter(inp, 0, index, source)
780 781 782 783
        >>> oup.numpy()
        array([[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]], dtype=float32)
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 815 816 817 818 819 820 821 822 823
    """
    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")

    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


824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
@lru_cache(maxsize=None)
def _get_where_op(dtype=None, device=None):
    @subgraph_fn(
        "Where",
        dtype=dtype,
        device=device,
        nr_inputs=3,
        jit_fusion=True,
        custom_grad=True,
    )
    def where(inputs, f, c):
        (mask, x, y) = inputs[0:3]
        oup = f("switch_gt0", mask, x)
        ksam = f("-", c(1), mask)
        oup = f("+", oup, f("switch_gt0", ksam, y))
        (oup_grad,) = yield (oup,)
        x_grad = f("switch_gt0", mask, oup_grad)
        y_grad = f("switch_gt0", ksam, oup_grad)
        yield (None, x_grad, y_grad)

    return where


847
def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor:
848
    r"""Selects elements either from Tensor x or Tensor y, according to mask.
849 850 851 852 853

    .. math::

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

854 855 856 857 858 859 860
    Args:
        mask: a mask used for choosing ``x`` or ``y``.
        x: first choice.
        y: second choice.

    Returns:
        output tensor.
861 862

    Examples:
863 864 865 866 867 868 869 870 871
        >>> import numpy as np
        >>> mask = Tensor(np.array([[True, False], [False, True]], dtype=np.bool))
        >>> 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)
        >>> out.numpy()
        array([[1., 6.],
               [7., 4.]], dtype=float32)
872
    """
873

874
    if not isinstance(x, Tensor):
875
        raise TypeError("input x must be a tensor")
876
    if not isinstance(y, Tensor):
877
        raise TypeError("input y must be a tensor")
878
    if not isinstance(mask, Tensor):
879 880 881 882 883 884
        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))

885
    dtype = dtype_promotion(x, y)
886 887
    device = x.device

888 889 890 891
    if x.dtype != dtype:
        x = x.astype(dtype)
    if y.dtype != dtype:
        y = y.astype(dtype)
892
    mask = mask.astype(dtype)
893

894 895 896
    where = _get_where_op(dtype=dtype, device=device)
    (oup,) = where(mask, x, y)
    return oup
897 898 899


def cond_take(mask: Tensor, x: Tensor) -> Tensor:
900
    r"""Takes elements from data if specific condition is satisfied on mask.
901 902 903
    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.
904

905 906 907
    Args:
        mask: condition param; must be the same shape with data.
        x: input tensor from which to take elements.
908 909

    Examples:
910 911 912 913 914 915 916
        >>> import numpy as np
        >>> 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())
        [1. 4.] [0 3]
917
    """
918
    if not isinstance(x, Tensor):
919
        raise TypeError("input must be a tensor")
920
    if not isinstance(mask, Tensor):
921 922 923 924 925 926 927 928 929 930 931
        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


932
def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    r"""Swaps shapes and strides according to given pattern.

    Args:
        inp: input tensor.
        pattern: a list of integers including 0, 1, ... , ``ndim``-1,
            and any number of ``'x'`` char in dimensions where this tensor should be broadcasted.
            For examples:

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

    Returns:
        output tensor.
953 954

    Examples:
955 956 957 958 959
        >>> import numpy as np
        >>> x = Tensor(np.array([[1, 1], [0, 0]], dtype=np.int32))
        >>> F.transpose(x, (1, 0))
        Tensor([[1 0]
         [1 0]], dtype=int32, device=xpux:0)
960
    """
961
    return inp.transpose(pattern)
962 963


964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
def swapaxes(inp: Tensor, axis1: int, axis2: int) -> Tensor:
    r"""Interchange two axes of a tensor.

    Args:
        inp: input tensor to swapaxes.
        axis1: first axis.
        axis2: second axis.

    Returns:
        a tensor after swapping the two axes of 'inp'.

    Examples:
        >>> x = Tensor(np.array([[[0,1],[2,3]],[[4,5],[6,7]]], dtype=np.int32))
        >>> F.swapaxes(x, 0, 2)
        Tensor([[[0 4]
         [2 6]]
        [[1 5]
         [3 7]]], dtype=int32, device=xpux:0)
    """
    pattern = list(range(inp.ndim))
    tempAxis = pattern[axis1]
    pattern[axis1] = pattern[axis2]
    pattern[axis2] = tempAxis
    return inp.transpose(pattern)


990
def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor:
991
    r"""Reshapes a tensor without changing its data.
992

993
    Args:
994 995 996 997
        inp: input tensor to reshape.
        target_shape: target shape compatible with the original shape. One shape dimension is allowed 
             to be `-1` . When a shape dimension is `-1` , the corresponding output tensor shape dimension 
             must be inferred from the length of the tensor and the remaining dimensions.
998

999 1000
    Returns:
        an output tensor having the same data type, elements, and underlying element order as `inp` .
1001

1002
    Examples:
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        >>> x = F.arange(12)
        >>> x
        Tensor([ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11.], device=xpux:0)
        >>> F.reshape(x, (3, 4))
        Tensor([[ 0.  1.  2.  3.]
         [ 4.  5.  6.  7.]
         [ 8.  9. 10. 11.]], device=xpux:0)
        >>> F.reshape(x, (2, -1))
        Tensor([[ 0.  1.  2.  3.  4.  5.]
         [ 6.  7.  8.  9. 10. 11.]], device=xpux:0)
1013
    """
1014
    return inp.reshape(target_shape)
1015 1016


1017
def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
1018
    r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
1019

1020 1021 1022 1023
    Args:
        inp: input tensor.
        start_axis: start dimension that the sub-tensor to be flattened. Default: 0
        end_axis: end dimension that the sub-tensor to be flattened. Default: -1
1024

1025 1026
    Returns:
        output tensor.
1027

1028
    Examples:
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        >>> import numpy as np
        >>> inp_shape = (2, 2, 3, 3)
        >>> x = Tensor(
        ...     np.arange(36, dtype=np.int32).reshape(inp_shape),
        ... )
        >>> out = F.flatten(x, 2)
        >>> x.numpy().shape
        (2, 2, 3, 3)
        >>> out.numpy().shape
        (2, 2, 9)
1039
    """
1040
    return inp.flatten(start_axis, end_axis)
1041 1042


1043
def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
1044
    r"""Adds dimension before given axis.
1045

1046 1047 1048
    Args:
        inp: input tensor.
        axis: place of new axes.
1049

1050 1051
    Returns:
        output tensor.
1052

1053
    Examples:
1054 1055 1056 1057 1058
        >>> import numpy as np
        >>> x = Tensor([1, 2])
        >>> out = F.expand_dims(x, 0)
        >>> out.numpy().shape
        (1, 2)
1059 1060
    """

1061
    return expand_dims_cpp(inp, axis)
1062 1063


1064
def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
1065
    r"""Removes dimension of shape 1.
1066

1067 1068 1069
    Args:
        inp: input tensor.
        axis: place of axis to be removed.
1070

1071 1072
    Returns:
        output tensor.
1073

1074
    Examples:
1075 1076 1077 1078 1079
        >>> import numpy as np
        >>> x = Tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
        >>> out = F.squeeze(x, 3)
        >>> out.numpy().shape
        (1, 1, 2)
1080
    """
1081
    return squeeze_cpp(inp, axis)
1082 1083


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

1087 1088 1089 1090 1091
    Args:
        inp: input tensor.
        repeats: the number of repetitions for each element.
        axis: the axis along which to repeat values. By default, use the
            flattened input array, and return a flat output array.
1092

1093 1094
    Returns:
        output tensor.
1095

1096
    Examples:
1097 1098 1099 1100 1101 1102 1103
        >>> import numpy as np
        >>> x = Tensor([[1, 2], [3, 4]], np.int32)
        >>> F.repeat(x, 2, axis=0)
        Tensor([[1 2]
         [1 2]
         [3 4]
         [3 4]], dtype=int32, device=xpux:0)
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    """
    if axis is None:
        inp = inp.reshape(-1)  # flatten
        axis = 0
    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 :])

1127 1128 1129 1130
    base_shape = astensor1d(base_shape)
    bcast_shape = astensor1d(bcast_shape)
    target_shape = astensor1d(target_shape)
    out = broadcast_to(inp.reshape(base_shape), bcast_shape).reshape(target_shape)
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    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 :])

1151 1152 1153 1154
    base_shape = astensor1d(base_shape)
    bcast_shape = astensor1d(bcast_shape)
    target_shape = astensor1d(target_shape)
    out = broadcast_to(inp.reshape(base_shape), bcast_shape).reshape(target_shape)
1155 1156 1157 1158
    return out


def tile(inp: Tensor, reps: Iterable[int]):
1159
    r"""Construct an array by repeating ``inp`` the number of times given by ``reps``. If reps has length d,
1160 1161 1162
    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.

1163 1164 1165
    Args:
        inp: input tensor.
        reps: The number of repetitions of inp along each axis.
1166

1167 1168
    Returns:
        output tensor.
1169 1170


1171
    Examples:
1172 1173 1174 1175 1176 1177 1178
        >>> import numpy as np
        >>> x = Tensor([[1, 2], [3, 4]], np.int32)
        >>> F.tile(x, (2,1))
        Tensor([[1 2]
         [3 4]
         [1 2]
         [3 4]], dtype=int32, device=xpux:0)
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    """
    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:
        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
1201 1202 1203


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

1206 1207 1208
    Args:
        inp: input tensor.
        device: destination device.
1209 1210

    Examples:
1211

1212 1213
        >>> import numpy as np
        >>> x = Tensor([1, 2, 3], np.int32)
1214

1215
        >>> F.copy(x, 'cpu1')
1216 1217
        Tensor([1 2 3], dtype=int32, device=cpu1:0)

1218
        >>> F.copy(x, 'xpu0')
1219 1220
        Tensor([1 2 3], dtype=int32, device=xpu0:0)

1221 1222 1223 1224
    """
    if device is None:
        return apply(Identity(), inp)[0]
    return apply(Copy(comp_node=as_device(device).to_c()), inp)[0]
1225 1226 1227 1228 1229 1230 1231


def roll(
    inp: Tensor,
    shift: Union[int, Iterable[int]],
    axis: Optional[Union[int, Iterable[int]]] = None,
):
1232
    r"""Roll the tensor along the given axis(or axes). Elements that are shifted
1233 1234
    beyond the last position are re-introduced at the first position.

1235 1236 1237 1238 1239 1240 1241 1242
    Args:
        inp: input tensor.
        shift: the number of places by which the elements of the tensor are
            shifted. If shift is a tuple, axis must be a tuple of the same size,
            and each axis will be rolled by the corresponding shift value.
        axis: axis along which to roll. If axis is not specified, the tensor
            will be flattened before rolling and then restored to the original shape.
            Duplicate axes is allowed if it is a tuple. Default: None.
1243 1244

    Examples:
1245 1246 1247 1248 1249 1250
        >>> import numpy as np
        >>> x = Tensor([[1,2],[3,4],[5,6]], np.int32)
        >>> F.roll(x, 1, 0)
        Tensor([[5 6]
         [1 2]
         [3 4]], dtype=int32, device=xpux:0)
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    """
    shp_bak = None
    if axis is None:
        shp_bak = inp.shape
        inp = inp.flatten()
        axis = 0
    shp = inp.shape
    dim = len(shp)
    if isinstance(shift, int):
        assert isinstance(axis, int)
        shift, axis = [shift,], [axis,]
    assert len(shift) == len(axis)
    out = inp
    for i in range(len(shift)):
        axis_ = axis[i]
        shift_ = shift[i]
        axis_normalized_ = axis_ + dim if axis_ < 0 else axis_
        assert (
            dim > axis_normalized_ >= 0
        ), "axis out of range (expected to be in range of [{}, {}], but got {})".format(
            -dim, dim - 1, axis_
        )
        if shift_ == 0:
            continue
        size = shp[axis_normalized_]
1276 1277 1278
        shift_normalized_ = 0 if size == 0 else shift_ % size
        if shift_normalized_ > 0:
            a, b = split(out, [size - shift_normalized_,], axis=axis_normalized_)
1279
        else:
1280
            a, b = split(out, [-shift_normalized_,], axis=axis_normalized_)
1281 1282 1283 1284
        out = concat((b, a), axis=axis_normalized_)
    if shp_bak is not None:
        out = out.reshape(shp_bak)
    return out
M
Megvii Engine Team 已提交
1285 1286


1287 1288 1289
# TODO: Should be moved to math - statistical functions


M
Megvii Engine Team 已提交
1290
def cumsum(inp: Tensor, axis: int):
1291
    r"""Calculates the cumulative sum of tensor elements over a given axis.
M
Megvii Engine Team 已提交
1292

1293
    Args:
1294 1295 1296 1297 1298
        inp: input tensor. Should have a numeric data type.
        axis: axis along which cumulative sums must be computed.

    Returns:
        a tensor containing the cumulative sums.
M
Megvii Engine Team 已提交
1299 1300

    Examples:
1301 1302 1303 1304 1305 1306 1307 1308 1309

        If :math:`x_i` is ``NaN``, the cumulative sums is ``NaN`` (i.e., ``NaN`` values propagate).

    Examples:
        >>> x = Tensor([[1, 2, 3], [4, 5, 6]])
        >>> F.cumsum(x, axis = 0)
        Tensor([[1 2 3]
         [5 7 9]], dtype=int32, device=xpux:0)
        >>> F.cumsum(x, axis = 1)
1310 1311
        Tensor([[ 1  3  6]
         [ 4  9 15]], dtype=int32, device=xpux:0)
1312

M
Megvii Engine Team 已提交
1313 1314 1315
    """
    op = builtin.Cumsum(axis=axis, exclusive=False, reverse=False)
    return apply(op, inp)[0]
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361


def meshgrid(*inputs: Tensor, indexing: str = "xy") -> List[Tensor]:
    r"""Returns coordinate matrices from coordinate vectors.

    Args:
        inputs: an arbitrary number of one-dimensional tensors representing grid 
            coordinates. Each input should have the same numeric data type.
        indexing:  Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. 
            If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional 
            cases, respectively), the indexing keyword has no effect and should be ignored.


    Returns:
        out: list of N tensors, where N is the number of provided one-dimensional input tensors. 
            Each returned tensor must have rank N. For N one-dimensional tensors having lengths ``Ni = len(xi)``, 
            
            * if matrix indexing ``ij``, then each returned tensor must have the shape ``(N1, N2, N3, ..., Nn)``.
            * if Cartesian indexing ``xy``, then each returned tensor must have shape ``(N2, N1, N3, ..., Nn)``.
            
            Accordingly, for the two-dimensional case with input one-dimensional tensors of length ``M`` and ``N``, 
            if matrix indexing ``ij``, then each returned tensor must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, 
            then each returned tensor must have shape ``(N, M)``.

            Similarly, for the three-dimensional case with input one-dimensional tensor of length ``M``, ``N``, and ``P``, 
            if matrix indexing  ``ij``, then each returned tensor must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, 
            then each returned tensor must have shape ``(N, M, P)``.

            Each returned tensor should have the same data type as the input tensors.
    
    Examples:
        >>> nx, ny = (3, 2)
        >>> x = F.linspace(0, 1, nx)
        >>> y = F.linspace(0, 1, ny)
        >>> xv, yv = F.meshgrid(x, y)
        >>> xv
        Tensor([[0.  0.5 1. ]
        [0.  0.5 1. ]], device=xpux:0)        
        >>> yv
        Tensor([[0. 0. 0.]
        [1. 1. 1.]], device=xpux:0)


    """
    op = builtin.MeshGrid(indexing)
    return apply(op, *inputs)