You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tensor.py 40 kB

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

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