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

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

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