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

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