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

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