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

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