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

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