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

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台