You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tensor.py 42 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from functools import lru_cache
  10. from typing import Iterable, Optional, Sequence, Tuple, Union
  11. import numpy as np
  12. from ..core._imperative_rt import CompNode
  13. from ..core._imperative_rt.core2 import SymbolVar, apply, dtype_promotion
  14. from ..core._wrap import as_device
  15. from ..core.ops import builtin
  16. from ..core.ops.builtin import Copy, Identity
  17. from ..core.ops.special import Const
  18. from ..core.tensor.array_method import _broadcast, _remove_axis
  19. from ..core.tensor.utils import (
  20. astensor1d,
  21. convert_inputs,
  22. get_device,
  23. isscalar,
  24. setscalar,
  25. subgraph_fn,
  26. )
  27. from ..device import get_default_device
  28. from ..tensor import Tensor
  29. from .elemwise import ceil
  30. __all__ = [
  31. "arange",
  32. "broadcast_to",
  33. "concat",
  34. "cond_take",
  35. "cumsum",
  36. "diag",
  37. "expand_dims",
  38. "eye",
  39. "flatten",
  40. "full",
  41. "full_like",
  42. "gather",
  43. "linspace",
  44. "ones",
  45. "ones_like",
  46. "repeat",
  47. "reshape",
  48. "roll",
  49. "split",
  50. "squeeze",
  51. "stack",
  52. "scatter",
  53. "tile",
  54. "copy",
  55. "transpose",
  56. "where",
  57. "zeros",
  58. "zeros_like",
  59. ]
  60. def diag(inp, k=0) -> Tensor:
  61. r"""If ``inp`` is a 1D tensor, then returns a 2D tensor with the elements of ``inp`` as the diagonal.
  62. If ``inp`` is a 2D tensor, then returns a 1D tensor with the diagonal elements of ``inp``.
  63. Args:
  64. inp: input tensor.
  65. k: diagonal in consider. Use :math:`k=0` for the main diagonal, :math:`k>0` for diagonals above the
  66. main diagonal, and :math:`k<0` for diagonals below the main diagonal. Default: 0.
  67. Returns:
  68. the extracted diagonal or constructed diagonal array.
  69. Examples:
  70. >>> inp = F.arange(6, dtype='int32').reshape(2,3)
  71. >>> out = F.diag(inp, k=1)
  72. >>> out
  73. Tensor([1 5], dtype=int32, device=xpux:0)
  74. >>> F.diag(out)
  75. Tensor([[1 0]
  76. [0 5]], dtype=int32, device=xpux:0)
  77. """
  78. op = builtin.Diag(k=k)
  79. (result,) = apply(op, inp)
  80. return result
  81. def eye(N, M=None, *, dtype="float32", device: Optional[CompNode] = None) -> Tensor:
  82. r"""Returns a 2D tensor with ones on the diagonal and zeros elsewhere.
  83. Args:
  84. shape: a list, tuple or integer defining the shape of the output tensor.
  85. dtype: the desired data type of the output tensor. Default: ``float32``.
  86. device: the desired device of the output tensor. Default: if ``None``,
  87. use the default device (see :func:`~.megengine.get_default_device`).
  88. Returns:
  89. eye matrix.
  90. Examples:
  91. .. testcode::
  92. import numpy as np
  93. import megengine.functional as F
  94. out = F.eye(4, 6, dtype=np.float32)
  95. print(out.numpy())
  96. Outputs:
  97. .. testoutput::
  98. [[1. 0. 0. 0. 0. 0.]
  99. [0. 1. 0. 0. 0. 0.]
  100. [0. 0. 1. 0. 0. 0.]
  101. [0. 0. 0. 1. 0. 0.]]
  102. """
  103. if M is not None:
  104. if isinstance(N, Tensor) or isinstance(M, Tensor):
  105. shape = astensor1d((N, M))
  106. else:
  107. shape = Tensor([N, M], dtype="int32", device=device)
  108. elif isinstance(N, Tensor):
  109. shape = N
  110. else:
  111. shape = Tensor(N, dtype="int32", device=device)
  112. op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
  113. (result,) = apply(op, shape)
  114. return result
  115. def full(
  116. shape: Union[int, tuple, list],
  117. value: Union[bool, int, float, Tensor],
  118. dtype=None,
  119. device=None,
  120. ) -> Tensor:
  121. r"""Creates a tensor of shape ``shape`` filled with ``value``.
  122. Args:
  123. shape: output tensor shape.
  124. value: fill value.
  125. dtype: output tensor data type. If ``dtype`` is ``None``, the output tensor
  126. data type must be inferred from ``value``. If the value is an ``int``,
  127. the output tensor data type must be the default integer data type. If the
  128. value is a ``float``, the output tensor data type must be the default
  129. floating-point data type. If the value is a ``bool``, the output tensor
  130. must have boolean data type. Default: ``None``.
  131. device: device on which to place the created tensor. Default: ``None``.
  132. Returns:
  133. a tensor where every element is equal to ``value``.
  134. Examples:
  135. .. testcode::
  136. import numpy as np
  137. import megengine.functional as F
  138. out = F.full([2,3], 1.5)
  139. print(out.numpy())
  140. Outputs:
  141. .. testoutput::
  142. [[1.5 1.5 1.5]
  143. [1.5 1.5 1.5]]
  144. """
  145. if isinstance(shape, int):
  146. shape = (shape,)
  147. if device is None:
  148. device = get_default_device()
  149. (x,) = Const(value, dtype=dtype, device=device)()
  150. if type(shape) in (list, tuple) and len(shape) == 0:
  151. return x
  152. return broadcast_to(x, shape)
  153. def ones(
  154. shape: Union[int, Tuple[int, ...]],
  155. *,
  156. dtype="float32",
  157. device: Optional[CompNode] = None
  158. ) -> Tensor:
  159. r"""Returns a new tensor having a specified shape and filled with ones.
  160. Args:
  161. shape (int or sequence of ints): the shape of the output tensor.
  162. Keyword args:
  163. dtype (:attr:`.Tensor.dtype`): output tensor data type. Default: ``float32``.
  164. device (:attr:`.Tensor.device`): device on which to place the created tensor. Default: ``None``.
  165. Returns:
  166. a tensor containing ones.
  167. Examples:
  168. .. testcode::
  169. import megengine.functional as F
  170. out = F.ones(5)
  171. print(out.numpy())
  172. out = F.ones((5, ), dtype='int32')
  173. print(out.numpy())
  174. out = F.ones((2, 2))
  175. print(out.numpy())
  176. out = F.ones([2, 1])
  177. print(out.numpy())
  178. Outputs:
  179. .. testoutput::
  180. [1. 1. 1. 1. 1.]
  181. [1 1 1 1 1]
  182. [[1. 1.]
  183. [1. 1.]]
  184. [[1.]
  185. [1.]]
  186. """
  187. return full(shape, 1.0, dtype=dtype, device=device)
  188. def zeros(
  189. shape: Union[int, Tuple[int, ...]],
  190. *,
  191. dtype="float32",
  192. device: Optional[CompNode] = None
  193. ) -> Tensor:
  194. r"""Returns a new tensor having a specified shape and filled with zeros.
  195. Args:
  196. shape (int or sequence of ints): the shape of the output tensor.
  197. Keyword args:
  198. dtype (:attr:`.Tensor.dtype`): output tensor data type. Default: ``float32``.
  199. device (:attr:`.Tensor.device`): device on which to place the created tensor. Default: ``None``.
  200. Returns:
  201. a tensor containing zeros.
  202. Examples:
  203. >>> F.zeros((2, 1))
  204. Tensor([[0.]
  205. [0.]], device=xpux:0)
  206. """
  207. return full(shape, 0.0, dtype=dtype, device=device)
  208. def zeros_like(inp: Union[Tensor, SymbolVar]) -> Union[Tensor, SymbolVar]:
  209. r"""Returns a tensor filled with zeros with the same shape and data type as input tensor.
  210. Args:
  211. inp (Tensor): input tensor.
  212. Return:
  213. a tensor containing zeros.
  214. Examples:
  215. >>> input = F.arange(9, dtype='int32').reshape(3,3)
  216. >>> F.zeros_like(input)
  217. Tensor([[0 0 0]
  218. [0 0 0]
  219. [0 0 0]], dtype=int32, device=xpux:0)
  220. """
  221. return full_like(inp, 0.0)
  222. def ones_like(inp: Union[Tensor, SymbolVar]) -> Union[Tensor, SymbolVar]:
  223. r"""Returns a tensor filled with ones with the same shape and data type as input tensor.
  224. Args:
  225. inp (Tensor): input tensor.
  226. Return:
  227. a tensor containing ones.
  228. Examples:
  229. >>> input = F.arange(6, dtype='int32').reshape(2,3)
  230. >>> F.ones_like(input)
  231. Tensor([[1 1 1]
  232. [1 1 1]], dtype=int32, device=xpux:0)
  233. """
  234. return full_like(inp, 1.0)
  235. def full_like(
  236. inp: Union[Tensor, SymbolVar], value: Union[int, float]
  237. ) -> Union[Tensor, SymbolVar]:
  238. r"""Returns a tensor filled with given value with the same shape as input tensor.
  239. Args:
  240. inp: input tensor.
  241. value: target value.
  242. Return:
  243. output tensor.
  244. Examples:
  245. .. testcode::
  246. import numpy as np
  247. from megengine import tensor
  248. import megengine.functional as F
  249. inp = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  250. out = F.full_like(inp, 2)
  251. print(out.numpy())
  252. Outputs:
  253. .. testoutput::
  254. [[2 2 2]
  255. [2 2 2]]
  256. """
  257. (x,) = Const(value, dtype=inp.dtype, device=inp.device)(inp)
  258. if inp.ndim == 0:
  259. return x
  260. return broadcast_to(x, inp.shape)
  261. def broadcast_to(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor:
  262. r"""Broadcasts a tensor to given shape.
  263. Args:
  264. inp: input tensor.
  265. shape: target shape.
  266. Returns:
  267. output tensor.
  268. Examples:
  269. .. testcode::
  270. import numpy as np
  271. from megengine import tensor
  272. import megengine.functional as F
  273. data = tensor(np.arange(0, 3, dtype=np.float32).reshape(3))
  274. out = F.broadcast_to(data, (2, 3))
  275. print(out.numpy())
  276. Outputs:
  277. .. testoutput::
  278. [[0. 1. 2.]
  279. [0. 1. 2.]]
  280. """
  281. return _broadcast(inp, shape)
  282. def concat(inps: Iterable[Tensor], axis: int = 0, device=None) -> Tensor:
  283. r"""Concat some tensors
  284. Args:
  285. inps: input tensors to concat.
  286. axis: over which dimension the tensors are concatenated. Default: 0
  287. device: which device output will be. Default: None
  288. Returns:
  289. output tensor.
  290. Examples:
  291. .. testcode::
  292. import numpy as np
  293. from megengine import tensor
  294. import megengine.functional as F
  295. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
  296. data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
  297. out = F.concat([data1, data2])
  298. print(out.numpy())
  299. Outputs:
  300. .. testoutput::
  301. [[ 0. 1. 2.]
  302. [ 3. 4. 5.]
  303. [ 6. 7. 8.]
  304. [ 9. 10. 11.]]
  305. """
  306. if len(inps) == 1:
  307. return inps[0]
  308. # FIXME: remove this convert_inputs
  309. inps = convert_inputs(*inps, device=device)
  310. if device is None:
  311. device = get_device(inps)
  312. device = as_device(device)
  313. (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
  314. return result
  315. def stack(inps, axis=0, device=None):
  316. r"""Concats a sequence of tensors along a new axis.
  317. The input tensors must have the same shape.
  318. Args:
  319. inps: input tensors.
  320. axis: which axis will be concatenated.
  321. device: the device output will be. Default: None
  322. Returns:
  323. output concatenated tensor.
  324. Examples:
  325. .. testcode::
  326. import numpy as np
  327. from megengine import tensor
  328. import megengine.functional as F
  329. x1 = tensor(np.arange(0, 3, dtype=np.float32).reshape((3)))
  330. x2 = tensor(np.arange(6, 9, dtype=np.float32).reshape((3)))
  331. out = F.stack([x1, x2], axis=0)
  332. print(out.numpy())
  333. Outputs:
  334. .. testoutput::
  335. [[0. 1. 2.]
  336. [6. 7. 8.]]
  337. """
  338. if len(inps) > 0 and not isinstance(inps[0].shape, inps[0].__class__):
  339. shapes = {arr.shape for arr in inps}
  340. if len(shapes) != 1:
  341. raise ValueError("All input tensors must have the same shape")
  342. inps = [expand_dims(inp, axis=axis) for inp in inps]
  343. return concat(inps, axis=axis, device=device)
  344. def split(inp, nsplits_or_sections, axis=0):
  345. r"""Splits the input tensor into several smaller tensors.
  346. When nsplits_or_sections is int, the last tensor may be smaller than others.
  347. Args:
  348. inp: input tensor.
  349. nsplits_or_sections: number of sub tensors or sections information list.
  350. axis: which axis will be splited.
  351. Returns:
  352. output tensor list.
  353. Examples:
  354. .. testcode::
  355. import os
  356. import numpy as np
  357. from megengine import tensor
  358. import megengine.functional as F
  359. x = tensor(np.random.random((10, 20)), dtype=np.float32)
  360. y = F.split(x, 3)
  361. z = F.split(x, [6, 17], axis=1)
  362. print([i.numpy().shape for i in y])
  363. print([i.numpy().shape for i in z])
  364. Outputs:
  365. .. testoutput::
  366. [(4, 20), (3, 20), (3, 20)]
  367. [(10, 6), (10, 11), (10, 3)]
  368. """
  369. ndim = len(inp.shape)
  370. if axis >= ndim:
  371. raise ValueError("Invalid axis {}".format(axis))
  372. Ntotal = inp.shape[axis]
  373. if isinstance(nsplits_or_sections, Sequence):
  374. Nsections = len(nsplits_or_sections) + 1
  375. is_array = True
  376. else:
  377. Nsections = int(nsplits_or_sections)
  378. is_array = False
  379. if is_array:
  380. partitions = []
  381. div_points = [0] + list(nsplits_or_sections) + [Ntotal]
  382. for i in range(1, len(div_points)):
  383. if div_points[i - 1] > div_points[i]:
  384. raise ValueError(
  385. "Invalid nsplits_or_secions: {}".format(nsplits_or_sections)
  386. )
  387. partitions.append(div_points[i] - div_points[i - 1])
  388. else: # scalar
  389. if Nsections <= 0:
  390. raise ValueError("Number sections must be larger than 0")
  391. if Nsections > Ntotal:
  392. raise ValueError(
  393. "The size {} at dim {} cannot be split into {} sections".format(
  394. Ntotal, axis, Nsections
  395. )
  396. )
  397. partitions = []
  398. for i in range(Nsections):
  399. section_size = (Ntotal + Nsections - i - 1) // Nsections
  400. partitions.append(section_size)
  401. partitions = [
  402. part
  403. if isinstance(part, (SymbolVar, Tensor))
  404. else Const(part, dtype="int32", device=inp.device)(inp)[0]
  405. for part in partitions
  406. ]
  407. op = builtin.Split(axis=axis)
  408. return apply(op, inp, *partitions)
  409. def _get_idx(index, axis):
  410. index_dims = len(index.shape)
  411. idx = []
  412. for i in range(index_dims):
  413. if i != axis:
  414. shape = [1] * index_dims
  415. shape[i] = index.shape[i]
  416. arange = linspace(
  417. 0, index.shape[i] - 1, index.shape[i], device=index.device,
  418. )
  419. arange = (
  420. broadcast_to(arange.reshape(*shape), index.shape)
  421. .reshape(-1)
  422. .astype(np.int32)
  423. )
  424. idx.append(arange)
  425. else:
  426. idx.append(index.reshape(-1))
  427. return tuple(idx)
  428. def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor:
  429. # TODO: rewrite doc
  430. r"""
  431. Gathers data from input tensor on axis using index.
  432. For a 3-D tensor, the output is specified by:
  433. .. code-block::
  434. out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0
  435. out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1
  436. out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2
  437. if input tensor is a n-dimensional tensor with size
  438. :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i,
  439. then index must be a n-dimensional tensor with size
  440. :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and
  441. output will have the same size as index.
  442. Args:
  443. inp: input tensor.
  444. axis: along which axis to index.
  445. index: indices of elements to gather.
  446. Return:
  447. output tensor.
  448. Examples:
  449. .. testcode::
  450. import megengine.functional as F
  451. from megengine import tensor
  452. inp = tensor([
  453. [1,2], [3,4], [5,6],
  454. ])
  455. index = tensor([[0,2], [1,0]])
  456. oup = F.gather(inp, 0, index)
  457. print(oup.numpy())
  458. Outputs:
  459. .. testoutput::
  460. [[1 6]
  461. [3 2]]
  462. """
  463. input_shape = inp.shape
  464. index_shape = index.shape
  465. input_dims = len(input_shape)
  466. index_dims = len(index_shape)
  467. if input_dims != index_dims:
  468. raise ValueError(
  469. "The index tensor must have same dimensions as input tensor, "
  470. "But the input dims:{}, the index dims:{}".format(input_dims, index_dims)
  471. )
  472. if axis < 0 or axis >= input_dims:
  473. raise ValueError(
  474. "Index axis {} is output of bounds, should in range [0 {})".format(
  475. axis, input_dims
  476. )
  477. )
  478. for i in range(input_dims):
  479. if i != axis and input_shape[i] != index_shape[i]:
  480. raise ValueError(
  481. "The input {} and index {} must have the same size apart from axis {}".format(
  482. input_shape, index_shape, axis
  483. )
  484. )
  485. idx = _get_idx(index, axis)
  486. return inp[idx].reshape(index.shape) # pylint: disable=no-member
  487. def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor:
  488. # TODO: rewrite doc
  489. r"""
  490. Writes all values from the tensor source into input tensor
  491. at the indices specified in the index tensor.
  492. For each value in source, its output index is specified by its index
  493. in source for ``axis != dimension`` and by the corresponding value in
  494. index for ``axis = dimension``.
  495. For a 3-D tensor, input tensor is updated as:
  496. .. code-block::
  497. inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0
  498. inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1
  499. inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2
  500. ``inp``, ``index`` and ``source`` should have same number of dimensions.
  501. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)``
  502. for all dimensions ``d``.
  503. Moreover, the values of index must be between ``0`` and ``inp.shape(axis) - 1`` inclusive.
  504. Note:
  505. Please notice that, due to performance issues, the result is uncertain on the GPU device
  506. if scattering different positions from source to the same destination position
  507. regard to index tensor.
  508. Check the following examples, the oup[0][2] is maybe
  509. from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339
  510. if set the index[1][2] from 1 to 0.
  511. Args:
  512. inp: inp tensor which to be scattered.
  513. axis: axis along which to index.
  514. index: indices of elements to scatter.
  515. source: source element(s) to scatter.
  516. Return:
  517. output tensor.
  518. Examples:
  519. .. testcode::
  520. import numpy as np
  521. import megengine.functional as F
  522. from megengine import tensor
  523. inp = tensor(np.zeros(shape=(3,5),dtype=np.float32))
  524. source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]])
  525. index = tensor([[0,2,0,2,1],[2,0,1,1,2]])
  526. oup = F.scatter(inp, 0, index,source)
  527. print(oup.numpy())
  528. Outputs:
  529. .. testoutput::
  530. [[0.9935 0.0718 0.2256 0. 0. ]
  531. [0. 0. 0.5939 0.357 0.4396]
  532. [0.7723 0.9465 0. 0.8926 0.4576]]
  533. """
  534. input_shape = inp.shape
  535. index_shape = index.shape
  536. source_shape = source.shape
  537. input_dims = len(input_shape)
  538. index_dims = len(index_shape)
  539. source_dims = len(source_shape)
  540. if input_dims != index_dims or input_dims != source_dims:
  541. raise ValueError("The input, source and index tensor must have same dimensions")
  542. if axis < 0 or axis >= input_dims:
  543. raise ValueError(
  544. "Index axis {} is output of bounds, should in range [0 {})".format(
  545. axis, input_dims
  546. )
  547. )
  548. for i in range(source_dims):
  549. if source_shape[i] > input_shape[i]:
  550. raise ValueError(
  551. "The each shape size for source {} must be less than or equal to input {} ".format(
  552. source_shape, input_shape
  553. )
  554. )
  555. for i in range(index_dims):
  556. if index_shape[i] != source_shape[i]:
  557. raise ValueError(
  558. "The each shape size for index {} must be equal to source {} ".format(
  559. index_shape, source_shape
  560. )
  561. )
  562. for i in range(index_dims):
  563. if i != axis and index_shape[i] > input_shape[i]:
  564. raise ValueError(
  565. "The index {} must be less than or equal to input {} size apart from axis {}".format(
  566. index_shape, input_shape, axis
  567. )
  568. )
  569. idx = _get_idx(index, axis)
  570. inp[idx] = source.flatten()
  571. return inp
  572. @lru_cache(maxsize=None)
  573. def _get_where_op(dtype=None, device=None):
  574. @subgraph_fn(
  575. "Where",
  576. dtype=dtype,
  577. device=device,
  578. nr_inputs=3,
  579. jit_fusion=True,
  580. custom_grad=True,
  581. )
  582. def where(inputs, f, c):
  583. (mask, x, y) = inputs[0:3]
  584. oup = f("switch_gt0", mask, x)
  585. ksam = f("-", c(1), mask)
  586. oup = f("+", oup, f("switch_gt0", ksam, y))
  587. (oup_grad,) = yield (oup,)
  588. x_grad = f("switch_gt0", mask, oup_grad)
  589. y_grad = f("switch_gt0", ksam, oup_grad)
  590. yield (None, x_grad, y_grad)
  591. return where
  592. def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor:
  593. r"""Selects elements either from Tensor x or Tensor y, according to mask.
  594. .. math::
  595. \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i
  596. Args:
  597. mask: a mask used for choosing ``x`` or ``y``.
  598. x: first choice.
  599. y: second choice.
  600. Returns:
  601. output tensor.
  602. Examples:
  603. .. testcode::
  604. import numpy as np
  605. from megengine import tensor
  606. import megengine.functional as F
  607. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool))
  608. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  609. dtype=np.float32))
  610. y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32))
  611. out = F.where(mask, x, y)
  612. print(out.numpy())
  613. Outputs:
  614. .. testoutput::
  615. [[1. 6.]
  616. [7. 4.]]
  617. """
  618. if not isinstance(x, Tensor):
  619. raise TypeError("input x must be a tensor")
  620. if not isinstance(y, Tensor):
  621. raise TypeError("input y must be a tensor")
  622. if not isinstance(mask, Tensor):
  623. raise TypeError("mask must be a tensor")
  624. if mask.dtype != np.bool_:
  625. raise ValueError("mask must be bool")
  626. if x.device != mask.device:
  627. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  628. dtype = dtype_promotion(x, y)
  629. device = x.device
  630. if x.dtype != dtype:
  631. x = x.astype(dtype)
  632. if y.dtype != dtype:
  633. y = y.astype(dtype)
  634. mask = mask.astype(dtype)
  635. where = _get_where_op(dtype=dtype, device=device)
  636. (oup,) = where(mask, x, y)
  637. if isscalar(mask):
  638. setscalar(oup)
  639. return oup
  640. def cond_take(mask: Tensor, x: Tensor) -> Tensor:
  641. r"""Takes elements from data if specific condition is satisfied on mask.
  642. This operator has two outputs: the first is the elements taken,
  643. and the second is the indices corresponding to those elements;
  644. they are both 1-dimensional. High-dimension input would first be flattened.
  645. Args:
  646. mask: condition param; must be the same shape with data.
  647. x: input tensor from which to take elements.
  648. Examples:
  649. .. testcode::
  650. import numpy as np
  651. from megengine import tensor
  652. import megengine.functional as F
  653. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool_))
  654. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  655. dtype=np.float32))
  656. v, index = F.cond_take(mask, x)
  657. print(v.numpy(), index.numpy())
  658. Outputs:
  659. .. testoutput::
  660. [1. 4.] [0 3]
  661. """
  662. if not isinstance(x, (Tensor, SymbolVar)):
  663. raise TypeError("input must be a tensor")
  664. if not isinstance(mask, (Tensor, SymbolVar)):
  665. raise TypeError("mask must be a tensor")
  666. if mask.dtype != np.bool_:
  667. raise ValueError("mask must be bool")
  668. if x.device != mask.device:
  669. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  670. op = builtin.CondTake()
  671. v, index = apply(op, x, mask)
  672. return v, index
  673. def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
  674. r"""Swaps shapes and strides according to given pattern.
  675. Args:
  676. inp: input tensor.
  677. pattern: a list of integers including 0, 1, ... , ``ndim``-1,
  678. and any number of ``'x'`` char in dimensions where this tensor should be broadcasted.
  679. For examples:
  680. * (``'x'``) -> make a 0d (scalar) into a 1d vector
  681. * (0, 1) -> identity for 2d vectors
  682. * (1, 0) -> inverts the first and second dimensions
  683. * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN)
  684. * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1)
  685. * (2, 0, 1) -> AxBxC to CxAxB
  686. * (0, ``'x'``, 1) -> AxB to Ax1xB
  687. * (1, ``'x'``, 0) -> AxB to Bx1xA
  688. * (1,) -> this removes dimensions 0. It must be a broadcastable dimension (1xA to A)
  689. Returns:
  690. output tensor.
  691. Examples:
  692. .. testcode::
  693. import numpy as np
  694. from megengine import tensor
  695. import megengine.functional as F
  696. x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32))
  697. out = F.transpose(x, (1, 0))
  698. print(out.numpy())
  699. Outputs:
  700. .. testoutput::
  701. [[1 0]
  702. [1 0]]
  703. """
  704. return inp.transpose(list(-1 if _ == "x" else _ for _ in pattern))
  705. def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor:
  706. r"""Reshapes a tensor without changing its data.
  707. Args:
  708. inp: input tensor to reshape.
  709. target_shape: target shape compatible with the original shape. One shape dimension is allowed
  710. to be `-1` . When a shape dimension is `-1` , the corresponding output tensor shape dimension
  711. must be inferred from the length of the tensor and the remaining dimensions.
  712. Returns:
  713. an output tensor having the same data type, elements, and underlying element order as `inp` .
  714. Examples:
  715. >>> x = F.arange(12)
  716. >>> x
  717. Tensor([ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.], device=xpux:0)
  718. >>> F.reshape(x, (3, 4))
  719. Tensor([[ 0. 1. 2. 3.]
  720. [ 4. 5. 6. 7.]
  721. [ 8. 9. 10. 11.]], device=xpux:0)
  722. >>> F.reshape(x, (2, -1))
  723. Tensor([[ 0. 1. 2. 3. 4. 5.]
  724. [ 6. 7. 8. 9. 10. 11.]], device=xpux:0)
  725. """
  726. return inp.reshape(target_shape)
  727. def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
  728. r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
  729. Args:
  730. inp: input tensor.
  731. start_axis: start dimension that the sub-tensor to be flattened. Default: 0
  732. end_axis: end dimension that the sub-tensor to be flattened. Default: -1
  733. Returns:
  734. output tensor.
  735. Examples:
  736. .. testcode::
  737. import numpy as np
  738. from megengine import tensor
  739. import megengine.functional as F
  740. inp_shape = (2, 2, 3, 3)
  741. x = tensor(
  742. np.arange(36, dtype=np.int32).reshape(inp_shape),
  743. )
  744. out = F.flatten(x, 2)
  745. print(x.numpy().shape)
  746. print(out.numpy().shape)
  747. Outputs:
  748. .. testoutput::
  749. (2, 2, 3, 3)
  750. (2, 2, 9)
  751. """
  752. target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,)
  753. if end_axis != -1:
  754. target_shape += (*inp.shape[end_axis + 1 :],)
  755. return inp.reshape(*target_shape)
  756. def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  757. r"""Adds dimension before given axis.
  758. Args:
  759. inp: input tensor.
  760. axis: place of new axes.
  761. Returns:
  762. output tensor.
  763. Examples:
  764. .. testcode::
  765. import numpy as np
  766. from megengine import tensor
  767. import megengine.functional as F
  768. x = tensor([1, 2])
  769. out = F.expand_dims(x, 0)
  770. print(out.numpy().shape)
  771. Outputs:
  772. .. testoutput::
  773. (1, 2)
  774. """
  775. def get_axes():
  776. try:
  777. return [int(axis)]
  778. except (TypeError, ValueError):
  779. pass
  780. return list(map(int, axis))
  781. axis = get_axes()
  782. try:
  783. ndim = inp.ndim + len(axis)
  784. axis = sorted(i + ndim if i < 0 else i for i in axis)
  785. except ValueError:
  786. if any([ind < 0 for ind in axis]):
  787. raise IndexError(
  788. "Does not support negative index when tensor's ndim is unknown"
  789. )
  790. axis = sorted(axis)
  791. assert axis, "axis could not be empty"
  792. op = builtin.AddAxis(axis=axis)
  793. (result,) = apply(op, inp)
  794. return result
  795. def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
  796. r"""Removes dimension of shape 1.
  797. Args:
  798. inp: input tensor.
  799. axis: place of axis to be removed.
  800. Returns:
  801. output tensor.
  802. Examples:
  803. .. testcode::
  804. import numpy as np
  805. from megengine import tensor
  806. import megengine.functional as F
  807. x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
  808. out = F.squeeze(x, 3)
  809. print(out.numpy().shape)
  810. Outputs:
  811. .. testoutput::
  812. (1, 1, 2)
  813. """
  814. return _remove_axis(inp, axis)
  815. def linspace(
  816. start: Union[int, float, Tensor],
  817. stop: Union[int, float, Tensor],
  818. num: Union[int, Tensor],
  819. dtype="float32",
  820. device: Optional[CompNode] = None,
  821. ) -> Tensor:
  822. r"""Returns equally spaced numbers over a specified interval.
  823. Args:
  824. start: starting value of the squence, shoule be scalar.
  825. stop: last value of the squence, shoule be scalar.
  826. num: number of values to generate.
  827. dtype: result data type.
  828. Returns:
  829. generated tensor.
  830. Examples:
  831. .. testcode::
  832. import numpy as np
  833. import megengine.functional as F
  834. a = F.linspace(3, 10, 5)
  835. print(a.numpy())
  836. Outputs:
  837. .. testoutput::
  838. [ 3. 4.75 6.5 8.25 10. ]
  839. """
  840. for item in (start, stop, num):
  841. cur_device = getattr(item, "device", None)
  842. if device is None:
  843. device = cur_device
  844. else:
  845. if not (cur_device is None or device == cur_device):
  846. raise ("ambiguous device for linspace opr")
  847. is_symbolvar = list(isinstance(x, SymbolVar) for x in [start, stop, num])
  848. if any(is_symbolvar) and not all(is_symbolvar):
  849. raise TypeError("start, stop and num should all be VarNode or none of them")
  850. if not isinstance(start, (Tensor, SymbolVar)):
  851. start = Tensor(start, device=device)
  852. if not isinstance(stop, (Tensor, SymbolVar)):
  853. stop = Tensor(stop, device=device)
  854. if not isinstance(num, (Tensor, SymbolVar)):
  855. num = Tensor(num, device=device)
  856. op = builtin.Linspace(comp_node=device)
  857. (result,) = apply(op, start, stop, num)
  858. if np.dtype(dtype) != np.float32:
  859. return result.astype(dtype)
  860. return result
  861. def arange(
  862. start: Union[int, float, Tensor] = 0,
  863. stop: Optional[Union[int, float, Tensor]] = None,
  864. step: Union[int, float, Tensor] = 1,
  865. dtype="float32",
  866. device: Optional[CompNode] = None,
  867. ) -> Tensor:
  868. r"""Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional tensor.
  869. Note:
  870. This function cannot guarantee that the interval does not include the stop value in those cases
  871. where step is not an integer and floating-point rounding errors affect the length of the output tensor.
  872. Args:
  873. start: if ``stop`` is specified, the start of interval (inclusive); otherwise,
  874. the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.
  875. stop: the end of the interval. Default: ``None``.
  876. step: the distance between two adjacent elements ( ``out[i+1] - out[i]`` ). Must not be 0 ;
  877. may be negative, this results i an empty tensor if stop >= start . Default: 1 .
  878. Keyword args:
  879. dtype( :attr:`.Tensor.dtype` ): output tensor data type. Default: ``float32``.
  880. device( :attr:`.Tensor.device` ): device on which to place the created tensor. Default: ``None``.
  881. Returns:
  882. A one-dimensional tensor containing evenly spaced values.
  883. The length of the output tensor must be ``ceil((stop-start)/step)``
  884. if ``stop - start`` and ``step`` have the same sign, and length 0 otherwise.
  885. Examples:
  886. >>> F.arange(5)
  887. Tensor([0. 1. 2. 3. 4.], device=xpux:0)
  888. >>> F.arange(1, 4)
  889. Tensor([1. 2. 3.], device=xpux:0)
  890. """
  891. if stop is None:
  892. start, stop = 0, start
  893. start = Tensor(start, dtype="float32")
  894. stop = Tensor(stop, dtype="float32")
  895. step = Tensor(step, dtype="float32")
  896. num = ceil((stop - start) / step)
  897. stop = start + step * (num - 1)
  898. result = linspace(start, stop, num, device=device)
  899. if np.dtype(dtype) != np.float32:
  900. return result.astype(dtype)
  901. return result
  902. def repeat(inp: Tensor, repeats: int, axis: Optional[int] = None):
  903. r"""Repeat elements of an array.
  904. Args:
  905. inp: input tensor.
  906. repeats: the number of repetitions for each element.
  907. axis: the axis along which to repeat values. By default, use the
  908. flattened input array, and return a flat output array.
  909. Returns:
  910. output tensor.
  911. Examples:
  912. .. testcode::
  913. import numpy as np
  914. import megengine.functional as F
  915. from megengine import tensor
  916. x = tensor([[1, 2], [3, 4]], np.int32)
  917. y = F.repeat(x, 2, axis=0)
  918. print(y.numpy())
  919. Outputs:
  920. .. testoutput::
  921. [[1 2]
  922. [1 2]
  923. [3 4]
  924. [3 4]]
  925. """
  926. if axis is None:
  927. inp = inp.reshape(-1) # flatten
  928. axis = 0
  929. shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
  930. # assume inp.ndim is not changed during trace
  931. max_axis = len(shape) - 1
  932. assert axis >= 0 and axis <= max_axis
  933. assert repeats >= 1
  934. base_shape, bcast_shape, target_shape = [], [], []
  935. if axis != 0:
  936. target_shape.append(shape[:axis])
  937. base_shape.extend([shape[: axis + 1], [1,]])
  938. bcast_shape.extend([shape[: axis + 1], [repeats,]])
  939. target_shape.extend(
  940. [shape[axis] * repeats,]
  941. )
  942. if axis + 1 <= max_axis:
  943. base_shape.append(shape[axis + 1 :])
  944. bcast_shape.append(shape[axis + 1 :])
  945. target_shape.append(shape[axis + 1 :])
  946. out = broadcast_to(inp.reshape(concat(base_shape)), concat(bcast_shape)).reshape(
  947. concat(target_shape)
  948. )
  949. return out
  950. def _tile_one_dim(inp, rep, axis):
  951. shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
  952. # assume inp.ndim is not changed during trace
  953. max_axis = len(shape) - 1
  954. base_shape, bcast_shape, target_shape = [], [], []
  955. if axis != 0:
  956. base_shape.append(shape[:axis])
  957. bcast_shape.append(shape[:axis])
  958. target_shape.append(shape[:axis])
  959. base_shape.extend([[1,], shape[axis:]])
  960. bcast_shape.extend([rep, shape[axis:]])
  961. target_shape.append(shape[axis] * rep)
  962. if axis + 1 <= max_axis:
  963. target_shape.append(shape[axis + 1 :])
  964. out = broadcast_to(inp.reshape(concat(base_shape)), concat(bcast_shape)).reshape(
  965. concat(target_shape)
  966. )
  967. return out
  968. def tile(inp: Tensor, reps: Iterable[int]):
  969. r"""Construct an array by repeating ``inp`` the number of times given by ``reps``. If reps has length d,
  970. the result will have dimension of ``max(d, inp.ndim)``. It is required that ``d >= inp.dim``. If ``inp.ndim < d``,
  971. ``inp`` is promoted to be ``d``-dimensional by prepending new axis.
  972. Args:
  973. inp: input tensor.
  974. reps: The number of repetitions of inp along each axis.
  975. Returns:
  976. output tensor.
  977. Examples:
  978. .. testcode::
  979. import numpy as np
  980. import megengine.functional as F
  981. from megengine import tensor
  982. x = tensor([[1, 2], [3, 4]], np.int32)
  983. y = F.tile(x, (2,1))
  984. print(y.numpy())
  985. Outputs:
  986. .. testoutput::
  987. [[1 2]
  988. [3 4]
  989. [1 2]
  990. [3 4]]
  991. """
  992. shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
  993. reps = astensor1d(reps, inp, dtype="int32", device=inp.device)
  994. l_shape = len(shape)
  995. l_reps = len(reps)
  996. assert (
  997. l_reps >= l_shape
  998. ), "Number of dimensions of tiled dims can not be smaller than number of dimensions of tensor"
  999. for i in range(l_shape):
  1000. rep = reps[i + (l_reps - l_shape)]
  1001. inp = _tile_one_dim(inp, rep, i)
  1002. if l_reps > l_shape:
  1003. shape = inp.shape
  1004. extra = reps[:-l_shape]
  1005. extra_ones = ones_like(extra)
  1006. base_shape = concat([extra_ones, shape])
  1007. bcast_shape = concat([extra, shape])
  1008. target_shape = concat([extra, shape])
  1009. inp = broadcast_to(inp.reshape(base_shape), bcast_shape).reshape(target_shape)
  1010. return inp
  1011. def copy(inp, device=None):
  1012. r"""Copies tensor to another device.
  1013. Args:
  1014. inp: input tensor.
  1015. device: destination device.
  1016. Examples:
  1017. .. testcode::
  1018. import numpy as np
  1019. import platform
  1020. from megengine import tensor
  1021. from megengine.device import get_device_count
  1022. import megengine.functional as F
  1023. x = tensor([1, 2, 3], np.int32)
  1024. if 1 == get_device_count("gpu"):
  1025. y = F.copy(x, "cpu1")
  1026. print(y.numpy())
  1027. else:
  1028. y = F.copy(x, "xpu1")
  1029. print(y.numpy())
  1030. Outputs:
  1031. .. testoutput::
  1032. [1 2 3]
  1033. """
  1034. if device is None:
  1035. return apply(Identity(), inp)[0]
  1036. return apply(Copy(comp_node=as_device(device).to_c()), inp)[0]
  1037. def roll(
  1038. inp: Tensor,
  1039. shift: Union[int, Iterable[int]],
  1040. axis: Optional[Union[int, Iterable[int]]] = None,
  1041. ):
  1042. r"""Roll the tensor along the given axis(or axes). Elements that are shifted
  1043. beyond the last position are re-introduced at the first position.
  1044. Args:
  1045. inp: input tensor.
  1046. shift: the number of places by which the elements of the tensor are
  1047. shifted. If shift is a tuple, axis must be a tuple of the same size,
  1048. and each axis will be rolled by the corresponding shift value.
  1049. axis: axis along which to roll. If axis is not specified, the tensor
  1050. will be flattened before rolling and then restored to the original shape.
  1051. Duplicate axes is allowed if it is a tuple. Default: None.
  1052. Examples:
  1053. .. testcode::
  1054. import numpy as np
  1055. from megengine import tensor
  1056. import megengine.functional as F
  1057. x = tensor([[1,2],[3,4],[5,6]], np.int32)
  1058. y = F.roll(x, 1, 0)
  1059. print(y.numpy())
  1060. Outputs:
  1061. .. testoutput::
  1062. [[5 6]
  1063. [1 2]
  1064. [3 4]]
  1065. """
  1066. shp_bak = None
  1067. if axis is None:
  1068. shp_bak = inp.shape
  1069. inp = inp.flatten()
  1070. axis = 0
  1071. shp = inp.shape
  1072. dim = len(shp)
  1073. if isinstance(shift, int):
  1074. assert isinstance(axis, int)
  1075. shift, axis = [shift,], [axis,]
  1076. assert len(shift) == len(axis)
  1077. out = inp
  1078. for i in range(len(shift)):
  1079. axis_ = axis[i]
  1080. shift_ = shift[i]
  1081. axis_normalized_ = axis_ + dim if axis_ < 0 else axis_
  1082. assert (
  1083. dim > axis_normalized_ >= 0
  1084. ), "axis out of range (expected to be in range of [{}, {}], but got {})".format(
  1085. -dim, dim - 1, axis_
  1086. )
  1087. if shift_ == 0:
  1088. continue
  1089. size = shp[axis_normalized_]
  1090. shift_normalized_ = 0 if size == 0 else shift_ % size
  1091. if shift_normalized_ > 0:
  1092. a, b = split(out, [size - shift_normalized_,], axis=axis_normalized_)
  1093. else:
  1094. a, b = split(out, [-shift_normalized_,], axis=axis_normalized_)
  1095. out = concat((b, a), axis=axis_normalized_)
  1096. if shp_bak is not None:
  1097. out = out.reshape(shp_bak)
  1098. return out
  1099. def cumsum(inp: Tensor, axis: int):
  1100. r"""Computes the cumulative sum of elements along given axis.
  1101. Args:
  1102. inp: input tensor.
  1103. axis: axis along which cumsum is performed.
  1104. Examples:
  1105. .. testcode::
  1106. from megengine import tensor
  1107. import megengine.functional as F
  1108. x = tensor([[1, 2, 3], [4, 5, 6]], "int32")
  1109. y = F.cumsum(x, 1)
  1110. print(y.numpy())
  1111. Outputs:
  1112. .. testoutput::
  1113. [[ 1 3 6]
  1114. [ 4 9 15]]
  1115. """
  1116. assert isinstance(inp, Tensor), "input of cumsum must be type of Tensor"
  1117. assert axis >= 0 and axis < inp.ndim, "input axis {} out of bound".format(axis)
  1118. op = builtin.Cumsum(axis=axis, exclusive=False, reverse=False)
  1119. return apply(op, inp)[0]