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

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