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 40 kB

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