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

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