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

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

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