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

tensor.py 39 kB

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

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