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. if device is None:
  309. device = get_device(inps)
  310. device = as_device(device)
  311. (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
  312. return result
  313. def stack(inps, axis=0, device=None):
  314. r"""Concats a sequence of tensors along a new axis.
  315. The input tensors must have the same shape.
  316. Args:
  317. inps: input tensors.
  318. axis: which axis will be concatenated.
  319. device: the device output will be. Default: None
  320. Returns:
  321. output concatenated tensor.
  322. Examples:
  323. .. testcode::
  324. import numpy as np
  325. from megengine import tensor
  326. import megengine.functional as F
  327. x1 = tensor(np.arange(0, 3, dtype=np.float32).reshape((3)))
  328. x2 = tensor(np.arange(6, 9, dtype=np.float32).reshape((3)))
  329. out = F.stack([x1, x2], axis=0)
  330. print(out.numpy())
  331. Outputs:
  332. .. testoutput::
  333. [[0. 1. 2.]
  334. [6. 7. 8.]]
  335. """
  336. if len(inps) > 0 and not isinstance(inps[0].shape, inps[0].__class__):
  337. shapes = {arr.shape for arr in inps}
  338. if len(shapes) != 1:
  339. raise ValueError("All input tensors must have the same shape")
  340. inps = [expand_dims(inp, axis=axis) for inp in inps]
  341. return concat(inps, axis=axis, device=device)
  342. def split(inp, nsplits_or_sections, axis=0):
  343. r"""Splits the input tensor into several smaller tensors.
  344. When nsplits_or_sections is int, the last tensor may be smaller than others.
  345. Args:
  346. inp: input tensor.
  347. nsplits_or_sections: number of sub tensors or sections information list.
  348. axis: which axis will be splited.
  349. Returns:
  350. output tensor list.
  351. Examples:
  352. .. testcode::
  353. import os
  354. import numpy as np
  355. from megengine import tensor
  356. import megengine.functional as F
  357. x = tensor(np.random.random((10, 20)), dtype=np.float32)
  358. y = F.split(x, 3)
  359. z = F.split(x, [6, 17], axis=1)
  360. print([i.numpy().shape for i in y])
  361. print([i.numpy().shape for i in z])
  362. Outputs:
  363. .. testoutput::
  364. [(4, 20), (3, 20), (3, 20)]
  365. [(10, 6), (10, 11), (10, 3)]
  366. """
  367. return split_cpp(inp, nsplits_or_sections, axis)
  368. def _get_idx(index, axis):
  369. index_dims = len(index.shape)
  370. idx = []
  371. for i in range(index_dims):
  372. if i != axis:
  373. shape = [1] * index_dims
  374. shape[i] = index.shape[i]
  375. arange = linspace(
  376. 0, index.shape[i] - 1, index.shape[i], device=index.device,
  377. )
  378. arange = (
  379. broadcast_to(arange.reshape(*shape), index.shape)
  380. .reshape(-1)
  381. .astype(np.int32)
  382. )
  383. idx.append(arange)
  384. else:
  385. idx.append(index.reshape(-1))
  386. return tuple(idx)
  387. def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor:
  388. # TODO: rewrite doc
  389. r"""
  390. Gathers data from input tensor on axis using index.
  391. For a 3-D tensor, the output is specified by:
  392. .. code-block::
  393. out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0
  394. out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1
  395. out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2
  396. if input tensor is a n-dimensional tensor with size
  397. :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i,
  398. then index must be a n-dimensional tensor with size
  399. :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and
  400. output will have the same size as index.
  401. Args:
  402. inp: input tensor.
  403. axis: along which axis to index.
  404. index: indices of elements to gather.
  405. Return:
  406. output tensor.
  407. Examples:
  408. .. testcode::
  409. import megengine.functional as F
  410. from megengine import tensor
  411. inp = tensor([
  412. [1,2], [3,4], [5,6],
  413. ])
  414. index = tensor([[0,2], [1,0]])
  415. oup = F.gather(inp, 0, index)
  416. print(oup.numpy())
  417. Outputs:
  418. .. testoutput::
  419. [[1 6]
  420. [3 2]]
  421. """
  422. input_shape = inp.shape
  423. index_shape = index.shape
  424. input_dims = len(input_shape)
  425. index_dims = len(index_shape)
  426. if input_dims != index_dims:
  427. raise ValueError(
  428. "The index tensor must have same dimensions as input tensor, "
  429. "But the input dims:{}, the index dims:{}".format(input_dims, index_dims)
  430. )
  431. if axis < 0 or axis >= input_dims:
  432. raise ValueError(
  433. "Index axis {} is output of bounds, should in range [0 {})".format(
  434. axis, input_dims
  435. )
  436. )
  437. for i in range(input_dims):
  438. if i != axis and input_shape[i] != index_shape[i]:
  439. raise ValueError(
  440. "The input {} and index {} must have the same size apart from axis {}".format(
  441. input_shape, index_shape, axis
  442. )
  443. )
  444. idx = _get_idx(index, axis)
  445. return inp[idx].reshape(index.shape) # pylint: disable=no-member
  446. def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor:
  447. # TODO: rewrite doc
  448. r"""
  449. Writes all values from the tensor source into input tensor
  450. at the indices specified in the index tensor.
  451. For each value in source, its output index is specified by its index
  452. in source for ``axis != dimension`` and by the corresponding value in
  453. index for ``axis = dimension``.
  454. For a 3-D tensor, input tensor is updated as:
  455. .. code-block::
  456. inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0
  457. inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1
  458. inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2
  459. ``inp``, ``index`` and ``source`` should have same number of dimensions.
  460. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)``
  461. for all dimensions ``d``.
  462. Moreover, the values of index must be between ``0`` and ``inp.shape(axis) - 1`` inclusive.
  463. Note:
  464. Please notice that, due to performance issues, the result is uncertain on the GPU device
  465. if scattering different positions from source to the same destination position
  466. regard to index tensor.
  467. Check the following examples, the oup[0][2] is maybe
  468. from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339
  469. if set the index[1][2] from 1 to 0.
  470. Args:
  471. inp: inp tensor which to be scattered.
  472. axis: axis along which to index.
  473. index: indices of elements to scatter.
  474. source: source element(s) to scatter.
  475. Return:
  476. output tensor.
  477. Examples:
  478. .. testcode::
  479. import numpy as np
  480. import megengine.functional as F
  481. from megengine import tensor
  482. inp = tensor(np.zeros(shape=(3,5),dtype=np.float32))
  483. source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]])
  484. index = tensor([[0,2,0,2,1],[2,0,1,1,2]])
  485. oup = F.scatter(inp, 0, index,source)
  486. print(oup.numpy())
  487. Outputs:
  488. .. testoutput::
  489. [[0.9935 0.0718 0.2256 0. 0. ]
  490. [0. 0. 0.5939 0.357 0.4396]
  491. [0.7723 0.9465 0. 0.8926 0.4576]]
  492. """
  493. input_shape = inp.shape
  494. index_shape = index.shape
  495. source_shape = source.shape
  496. input_dims = len(input_shape)
  497. index_dims = len(index_shape)
  498. source_dims = len(source_shape)
  499. if input_dims != index_dims or input_dims != source_dims:
  500. raise ValueError("The input, source and index tensor must have same dimensions")
  501. if axis < 0 or axis >= input_dims:
  502. raise ValueError(
  503. "Index axis {} is output of bounds, should in range [0 {})".format(
  504. axis, input_dims
  505. )
  506. )
  507. for i in range(source_dims):
  508. if source_shape[i] > input_shape[i]:
  509. raise ValueError(
  510. "The each shape size for source {} must be less than or equal to input {} ".format(
  511. source_shape, input_shape
  512. )
  513. )
  514. for i in range(index_dims):
  515. if index_shape[i] != source_shape[i]:
  516. raise ValueError(
  517. "The each shape size for index {} must be equal to source {} ".format(
  518. index_shape, source_shape
  519. )
  520. )
  521. for i in range(index_dims):
  522. if i != axis and index_shape[i] > input_shape[i]:
  523. raise ValueError(
  524. "The index {} must be less than or equal to input {} size apart from axis {}".format(
  525. index_shape, input_shape, axis
  526. )
  527. )
  528. idx = _get_idx(index, axis)
  529. inp[idx] = source.flatten()
  530. return inp
  531. @lru_cache(maxsize=None)
  532. def _get_where_op(dtype=None, device=None):
  533. @subgraph_fn(
  534. "Where",
  535. dtype=dtype,
  536. device=device,
  537. nr_inputs=3,
  538. jit_fusion=True,
  539. custom_grad=True,
  540. )
  541. def where(inputs, f, c):
  542. (mask, x, y) = inputs[0:3]
  543. oup = f("switch_gt0", mask, x)
  544. ksam = f("-", c(1), mask)
  545. oup = f("+", oup, f("switch_gt0", ksam, y))
  546. (oup_grad,) = yield (oup,)
  547. x_grad = f("switch_gt0", mask, oup_grad)
  548. y_grad = f("switch_gt0", ksam, oup_grad)
  549. yield (None, x_grad, y_grad)
  550. return where
  551. def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor:
  552. r"""Selects elements either from Tensor x or Tensor y, according to mask.
  553. .. math::
  554. \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i
  555. Args:
  556. mask: a mask used for choosing ``x`` or ``y``.
  557. x: first choice.
  558. y: second choice.
  559. Returns:
  560. output tensor.
  561. Examples:
  562. .. testcode::
  563. import numpy as np
  564. from megengine import tensor
  565. import megengine.functional as F
  566. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool))
  567. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  568. dtype=np.float32))
  569. y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32))
  570. out = F.where(mask, x, y)
  571. print(out.numpy())
  572. Outputs:
  573. .. testoutput::
  574. [[1. 6.]
  575. [7. 4.]]
  576. """
  577. if not isinstance(x, Tensor):
  578. raise TypeError("input x must be a tensor")
  579. if not isinstance(y, Tensor):
  580. raise TypeError("input y must be a tensor")
  581. if not isinstance(mask, Tensor):
  582. raise TypeError("mask must be a tensor")
  583. if mask.dtype != np.bool_:
  584. raise ValueError("mask must be bool")
  585. if x.device != mask.device:
  586. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  587. dtype = dtype_promotion(x, y)
  588. device = x.device
  589. if x.dtype != dtype:
  590. x = x.astype(dtype)
  591. if y.dtype != dtype:
  592. y = y.astype(dtype)
  593. mask = mask.astype(dtype)
  594. where = _get_where_op(dtype=dtype, device=device)
  595. (oup,) = where(mask, x, y)
  596. return oup
  597. def cond_take(mask: Tensor, x: Tensor) -> Tensor:
  598. r"""Takes elements from data if specific condition is satisfied on mask.
  599. This operator has two outputs: the first is the elements taken,
  600. and the second is the indices corresponding to those elements;
  601. they are both 1-dimensional. High-dimension input would first be flattened.
  602. Args:
  603. mask: condition param; must be the same shape with data.
  604. x: input tensor from which to take elements.
  605. Examples:
  606. .. testcode::
  607. import numpy as np
  608. from megengine import tensor
  609. import megengine.functional as F
  610. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool_))
  611. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  612. dtype=np.float32))
  613. v, index = F.cond_take(mask, x)
  614. print(v.numpy(), index.numpy())
  615. Outputs:
  616. .. testoutput::
  617. [1. 4.] [0 3]
  618. """
  619. if not isinstance(x, (Tensor, SymbolVar)):
  620. raise TypeError("input must be a tensor")
  621. if not isinstance(mask, (Tensor, SymbolVar)):
  622. raise TypeError("mask must be a tensor")
  623. if mask.dtype != np.bool_:
  624. raise ValueError("mask must be bool")
  625. if x.device != mask.device:
  626. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  627. op = builtin.CondTake()
  628. v, index = apply(op, x, mask)
  629. return v, index
  630. def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
  631. r"""Swaps shapes and strides according to given pattern.
  632. Args:
  633. inp: input tensor.
  634. pattern: a list of integers including 0, 1, ... , ``ndim``-1,
  635. and any number of ``'x'`` char in dimensions where this tensor should be broadcasted.
  636. For examples:
  637. * (``'x'``) -> make a 0d (scalar) into a 1d vector
  638. * (0, 1) -> identity for 2d vectors
  639. * (1, 0) -> inverts the first and second dimensions
  640. * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN)
  641. * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1)
  642. * (2, 0, 1) -> AxBxC to CxAxB
  643. * (0, ``'x'``, 1) -> AxB to Ax1xB
  644. * (1, ``'x'``, 0) -> AxB to Bx1xA
  645. * (1,) -> this removes dimensions 0. It must be a broadcastable dimension (1xA to A)
  646. Returns:
  647. output tensor.
  648. Examples:
  649. .. testcode::
  650. import numpy as np
  651. from megengine import tensor
  652. import megengine.functional as F
  653. x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32))
  654. out = F.transpose(x, (1, 0))
  655. print(out.numpy())
  656. Outputs:
  657. .. testoutput::
  658. [[1 0]
  659. [1 0]]
  660. """
  661. return inp.transpose(pattern)
  662. def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor:
  663. r"""Reshapes a tensor without changing its data.
  664. Args:
  665. inp: input tensor to reshape.
  666. target_shape: target shape compatible with the original shape. One shape dimension is allowed
  667. to be `-1` . When a shape dimension is `-1` , the corresponding output tensor shape dimension
  668. must be inferred from the length of the tensor and the remaining dimensions.
  669. Returns:
  670. an output tensor having the same data type, elements, and underlying element order as `inp` .
  671. Examples:
  672. >>> x = F.arange(12)
  673. >>> x
  674. Tensor([ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.], device=xpux:0)
  675. >>> F.reshape(x, (3, 4))
  676. Tensor([[ 0. 1. 2. 3.]
  677. [ 4. 5. 6. 7.]
  678. [ 8. 9. 10. 11.]], device=xpux:0)
  679. >>> F.reshape(x, (2, -1))
  680. Tensor([[ 0. 1. 2. 3. 4. 5.]
  681. [ 6. 7. 8. 9. 10. 11.]], device=xpux:0)
  682. """
  683. return inp.reshape(target_shape)
  684. def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
  685. r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
  686. Args:
  687. inp: input tensor.
  688. start_axis: start dimension that the sub-tensor to be flattened. Default: 0
  689. end_axis: end dimension that the sub-tensor to be flattened. Default: -1
  690. Returns:
  691. output tensor.
  692. Examples:
  693. .. testcode::
  694. import numpy as np
  695. from megengine import tensor
  696. import megengine.functional as F
  697. inp_shape = (2, 2, 3, 3)
  698. x = tensor(
  699. np.arange(36, dtype=np.int32).reshape(inp_shape),
  700. )
  701. out = F.flatten(x, 2)
  702. print(x.numpy().shape)
  703. print(out.numpy().shape)
  704. Outputs:
  705. .. testoutput::
  706. (2, 2, 3, 3)
  707. (2, 2, 9)
  708. """
  709. target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,)
  710. if end_axis != -1:
  711. target_shape += (*inp.shape[end_axis + 1 :],)
  712. return inp.reshape(*target_shape)
  713. def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  714. r"""Adds dimension before given axis.
  715. Args:
  716. inp: input tensor.
  717. axis: place of new axes.
  718. Returns:
  719. output tensor.
  720. Examples:
  721. .. testcode::
  722. import numpy as np
  723. from megengine import tensor
  724. import megengine.functional as F
  725. x = tensor([1, 2])
  726. out = F.expand_dims(x, 0)
  727. print(out.numpy().shape)
  728. Outputs:
  729. .. testoutput::
  730. (1, 2)
  731. """
  732. return expand_dims_cpp(inp, axis)
  733. def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
  734. r"""Removes dimension of shape 1.
  735. Args:
  736. inp: input tensor.
  737. axis: place of axis to be removed.
  738. Returns:
  739. output tensor.
  740. Examples:
  741. .. testcode::
  742. import numpy as np
  743. from megengine import tensor
  744. import megengine.functional as F
  745. x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
  746. out = F.squeeze(x, 3)
  747. print(out.numpy().shape)
  748. Outputs:
  749. .. testoutput::
  750. (1, 1, 2)
  751. """
  752. return squeeze_cpp(inp, axis)
  753. def linspace(
  754. start: Union[int, float, Tensor],
  755. stop: Union[int, float, Tensor],
  756. num: Union[int, Tensor],
  757. dtype="float32",
  758. device: Optional[CompNode] = None,
  759. ) -> Tensor:
  760. r"""Returns equally spaced numbers over a specified interval.
  761. Args:
  762. start: starting value of the squence, shoule be scalar.
  763. stop: last value of the squence, shoule be scalar.
  764. num: number of values to generate.
  765. dtype: result data type.
  766. Returns:
  767. generated tensor.
  768. Examples:
  769. .. testcode::
  770. import numpy as np
  771. import megengine.functional as F
  772. a = F.linspace(3, 10, 5)
  773. print(a.numpy())
  774. Outputs:
  775. .. testoutput::
  776. [ 3. 4.75 6.5 8.25 10. ]
  777. """
  778. for item in (start, stop, num):
  779. cur_device = getattr(item, "device", None)
  780. if device is None:
  781. device = cur_device
  782. else:
  783. if not (cur_device is None or device == cur_device):
  784. raise ("ambiguous device for linspace opr")
  785. is_symbolvar = list(isinstance(x, SymbolVar) for x in [start, stop, num])
  786. if any(is_symbolvar) and not all(is_symbolvar):
  787. raise TypeError("start, stop and num should all be VarNode or none of them")
  788. if not isinstance(start, (Tensor, SymbolVar)):
  789. start = Tensor(start, device=device)
  790. if not isinstance(stop, (Tensor, SymbolVar)):
  791. stop = Tensor(stop, device=device)
  792. if not isinstance(num, (Tensor, SymbolVar)):
  793. num = Tensor(num, device=device)
  794. op = builtin.Linspace(comp_node=device)
  795. (result,) = apply(op, start, stop, num)
  796. if np.dtype(dtype) != np.float32:
  797. return result.astype(dtype)
  798. return result
  799. def arange(
  800. start: Union[int, float, Tensor] = 0,
  801. stop: Optional[Union[int, float, Tensor]] = None,
  802. step: Union[int, float, Tensor] = 1,
  803. dtype="float32",
  804. device: Optional[CompNode] = None,
  805. ) -> Tensor:
  806. r"""Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional tensor.
  807. Note:
  808. This function cannot guarantee that the interval does not include the stop value in those cases
  809. where step is not an integer and floating-point rounding errors affect the length of the output tensor.
  810. Args:
  811. start: if ``stop`` is specified, the start of interval (inclusive); otherwise,
  812. the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.
  813. stop: the end of the interval. Default: ``None``.
  814. step: the distance between two adjacent elements ( ``out[i+1] - out[i]`` ). Must not be 0 ;
  815. may be negative, this results i an empty tensor if stop >= start . Default: 1 .
  816. Keyword args:
  817. dtype( :attr:`.Tensor.dtype` ): output tensor data type. Default: ``float32``.
  818. device( :attr:`.Tensor.device` ): device on which to place the created tensor. Default: ``None``.
  819. Returns:
  820. A one-dimensional tensor containing evenly spaced values.
  821. The length of the output tensor must be ``ceil((stop-start)/step)``
  822. if ``stop - start`` and ``step`` have the same sign, and length 0 otherwise.
  823. Examples:
  824. >>> F.arange(5)
  825. Tensor([0. 1. 2. 3. 4.], device=xpux:0)
  826. >>> F.arange(1, 4)
  827. Tensor([1. 2. 3.], device=xpux:0)
  828. """
  829. if stop is None:
  830. start, stop = 0, start
  831. start = Tensor(start, dtype="float32")
  832. stop = Tensor(stop, dtype="float32")
  833. step = Tensor(step, dtype="float32")
  834. num = ceil((stop - start) / step)
  835. stop = start + step * (num - 1)
  836. result = linspace(start, stop, num, device=device)
  837. if np.dtype(dtype) != np.float32:
  838. return result.astype(dtype)
  839. return result
  840. def repeat(inp: Tensor, repeats: int, axis: Optional[int] = None):
  841. r"""Repeat elements of an array.
  842. Args:
  843. inp: input tensor.
  844. repeats: the number of repetitions for each element.
  845. axis: the axis along which to repeat values. By default, use the
  846. flattened input array, and return a flat output array.
  847. Returns:
  848. output tensor.
  849. Examples:
  850. .. testcode::
  851. import numpy as np
  852. import megengine.functional as F
  853. from megengine import tensor
  854. x = tensor([[1, 2], [3, 4]], np.int32)
  855. y = F.repeat(x, 2, axis=0)
  856. print(y.numpy())
  857. Outputs:
  858. .. testoutput::
  859. [[1 2]
  860. [1 2]
  861. [3 4]
  862. [3 4]]
  863. """
  864. if axis is None:
  865. inp = inp.reshape(-1) # flatten
  866. axis = 0
  867. shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
  868. # assume inp.ndim is not changed during trace
  869. max_axis = len(shape) - 1
  870. assert axis >= 0 and axis <= max_axis
  871. assert repeats >= 1
  872. base_shape, bcast_shape, target_shape = [], [], []
  873. if axis != 0:
  874. target_shape.append(shape[:axis])
  875. base_shape.extend([shape[: axis + 1], [1,]])
  876. bcast_shape.extend([shape[: axis + 1], [repeats,]])
  877. target_shape.extend(
  878. [shape[axis] * repeats,]
  879. )
  880. if axis + 1 <= max_axis:
  881. base_shape.append(shape[axis + 1 :])
  882. bcast_shape.append(shape[axis + 1 :])
  883. target_shape.append(shape[axis + 1 :])
  884. base_shape = astensor1d(base_shape)
  885. bcast_shape = astensor1d(bcast_shape)
  886. target_shape = astensor1d(target_shape)
  887. out = broadcast_to(inp.reshape(base_shape), bcast_shape).reshape(target_shape)
  888. return out
  889. def _tile_one_dim(inp, rep, axis):
  890. shape = astensor1d(inp.shape, inp, dtype="int32", device=inp.device)
  891. # assume inp.ndim is not changed during trace
  892. max_axis = len(shape) - 1
  893. base_shape, bcast_shape, target_shape = [], [], []
  894. if axis != 0:
  895. base_shape.append(shape[:axis])
  896. bcast_shape.append(shape[:axis])
  897. target_shape.append(shape[:axis])
  898. base_shape.extend([[1,], shape[axis:]])
  899. bcast_shape.extend([rep, shape[axis:]])
  900. target_shape.append(shape[axis] * rep)
  901. if axis + 1 <= max_axis:
  902. target_shape.append(shape[axis + 1 :])
  903. base_shape = astensor1d(base_shape)
  904. bcast_shape = astensor1d(bcast_shape)
  905. target_shape = astensor1d(target_shape)
  906. out = broadcast_to(inp.reshape(base_shape), bcast_shape).reshape(target_shape)
  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]