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

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