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

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台