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

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