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

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