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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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. import functools
  10. import math
  11. from itertools import accumulate
  12. from typing import Iterable, List, Optional, Sequence, Tuple, Union
  13. import numpy as np
  14. from ..core._imperative_rt import CompNode
  15. from ..core._wrap import device as as_device
  16. from ..core.ops import builtin
  17. from ..core.ops._internal import param_defs as P
  18. from ..core.ops.special import Const
  19. from ..core.tensor.core import TensorBase, TensorWrapperBase, apply
  20. from ..core.tensor.tensor_wrapper import _remove_axis
  21. from ..core.tensor.utils import (
  22. astensor1d,
  23. convert_inputs,
  24. convert_single_value,
  25. dtype_promotion,
  26. get_device,
  27. )
  28. from ..device import get_default_device
  29. from ..tensor import Tensor
  30. from .elemwise import ceil
  31. __all__ = [
  32. "arange",
  33. "broadcast",
  34. "concat",
  35. "cond_take",
  36. "dimshuffle",
  37. "expand_dims",
  38. "eye",
  39. "flatten",
  40. "full",
  41. "full_like",
  42. "gather",
  43. "identity",
  44. "linspace",
  45. "ones",
  46. "ones_like",
  47. "param_pack_concat",
  48. "param_pack_split",
  49. "reshape",
  50. "split",
  51. "squeeze",
  52. "stack",
  53. "scatter",
  54. "transpose",
  55. "where",
  56. "zeros",
  57. "zeros_like",
  58. ]
  59. def eye(shape, *, dtype="float32", device: Optional[CompNode] = None) -> Tensor:
  60. """Returns a 2D tensor with ones on the diagonal and zeros elsewhere.
  61. :param shape: expected shape of output tensor.
  62. :param dtype: data type. Default: None
  63. :param device: compute node of the matrix. Default: None
  64. :return: eye matrix.
  65. Examples:
  66. .. testcode::
  67. import numpy as np
  68. import megengine.functional as F
  69. data_shape = (4, 6)
  70. out = F.eye(data_shape, dtype=np.float32)
  71. print(out.numpy())
  72. Outputs:
  73. .. testoutput::
  74. [[1. 0. 0. 0. 0. 0.]
  75. [0. 1. 0. 0. 0. 0.]
  76. [0. 0. 1. 0. 0. 0.]
  77. [0. 0. 0. 1. 0. 0.]]
  78. """
  79. op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
  80. (result,) = apply(op, Tensor(shape, dtype="int32", device=device))
  81. return result
  82. def full(shape, value, dtype="float32", device=None):
  83. """Returns a tensor with given shape and value.
  84. """
  85. if isinstance(shape, int):
  86. shape = (shape,)
  87. if device is None:
  88. device = get_default_device()
  89. (x,) = Const(value, dtype=dtype, device=device)(
  90. Tensor(value, dtype=dtype, device=device)
  91. )
  92. return broadcast(x, shape)
  93. def ones(shape, dtype="float32", device=None):
  94. """Returns a ones tensor with given shape.
  95. :param inp: input tensor.
  96. :return: output zero tensor.
  97. Examples:
  98. .. testcode::
  99. import megengine.functional as F
  100. out = F.ones((2, 1))
  101. print(out.numpy())
  102. Outputs:
  103. .. testoutput::
  104. [[1.]
  105. [1.]]
  106. """
  107. return full(shape, 1.0, dtype=dtype, device=device)
  108. def zeros(shape, dtype="float32", device=None):
  109. """Returns a zero tensor with given shape.
  110. """
  111. return full(shape, 0.0, dtype=dtype, device=device)
  112. def zeros_like(inp: Tensor) -> Tensor:
  113. """Returns a zero tensor with the same shape as input tensor.
  114. :param inp: input tensor.
  115. :return: output zero tensor.
  116. Examples:
  117. .. testcode::
  118. import numpy as np
  119. from megengine import tensor
  120. import megengine.functional as F
  121. inp = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  122. out = F.zeros_like(inp)
  123. print(out.numpy())
  124. Outputs:
  125. .. testoutput::
  126. [[0 0 0]
  127. [0 0 0]]
  128. """
  129. return zeros(inp.shape, dtype=inp.dtype, device=inp.device)
  130. def ones_like(inp: Tensor) -> Tensor:
  131. """Returns a ones tensor with the same shape as input tensor.
  132. """
  133. return ones(inp.shape, dtype=inp.dtype, device=inp.device)
  134. def full_like(inp: Tensor, value: Union[int, float]) -> Tensor:
  135. """Returns a tensor filled with given value with the same shape as input tensor.
  136. """
  137. return full(inp.shape, value, dtype=inp.dtype, device=inp.device)
  138. def identity(inp: Tensor) -> Tensor:
  139. """Applies an identity transformation to input tensor.
  140. :param inp: input tensor.
  141. :return: output tensor.
  142. """
  143. op = builtin.Identity()
  144. (data,) = convert_inputs(inp)
  145. (output,) = apply(op, data)
  146. return output
  147. def broadcast(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor:
  148. """
  149. Broadcasts a tensor to given shape.
  150. :param inp: input tensor.
  151. :param shape: target shape.
  152. :return: output tensor.
  153. Examples:
  154. .. testcode::
  155. import numpy as np
  156. from megengine import tensor
  157. import megengine.functional as F
  158. data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  159. out = F.broadcast(data, (4, 2, 3))
  160. print(out.numpy())
  161. Outputs:
  162. .. testoutput::
  163. [[[0. 1. 2.]
  164. [3. 4. 5.]]
  165. [[0. 1. 2.]
  166. [3. 4. 5.]]
  167. [[0. 1. 2.]
  168. [3. 4. 5.]]
  169. [[0. 1. 2.]
  170. [3. 4. 5.]]]
  171. """
  172. return inp.broadcast(shape)
  173. def concat(inps: Iterable[Tensor], axis: int = 0, device=None) -> Tensor:
  174. r"""
  175. Concat some tensors
  176. :param inps: input tensors to concat.
  177. :param axis: over which dimension the tensors are concatenated. Default: 0
  178. :param device: which device output will be. Default: None
  179. :return: output tensor.
  180. Examples:
  181. .. testcode::
  182. import numpy as np
  183. from megengine import tensor
  184. import megengine.functional as F
  185. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
  186. data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
  187. out = F.concat([data1, data2])
  188. print(out.numpy())
  189. Outputs:
  190. .. testoutput::
  191. [[ 0. 1. 2.]
  192. [ 3. 4. 5.]
  193. [ 6. 7. 8.]
  194. [ 9. 10. 11.]]
  195. """
  196. if len(inps) == 1:
  197. return inps[0]
  198. dtype = dtype_promotion(inps)
  199. if device is None:
  200. device = get_device(inps)
  201. device = as_device(device)
  202. def convert(x):
  203. return convert_single_value(x, inps, dtype=dtype)
  204. inps = tuple(map(convert, inps))
  205. (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
  206. return result
  207. def stack(inps, axis=0, device=None):
  208. """Concats a sequence of tensors along a new axis.
  209. The input tensors must have the same shape.
  210. :param inps: input tensors.
  211. :param axis: which axis will be concatenated.
  212. :param device: the device output will be. Default: None
  213. :return: output concatenated tensor.
  214. Examples:
  215. .. testcode::
  216. import numpy as np
  217. from megengine import tensor
  218. import megengine.functional as F
  219. x1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
  220. x2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
  221. out = F.stack([x1, x2], axis=0)
  222. print(out.numpy())
  223. Outputs:
  224. .. testoutput::
  225. [[[ 0. 1. 2.]
  226. [ 3. 4. 5.]]
  227. [[ 6. 7. 8.]
  228. [ 9. 10. 11.]]]
  229. """
  230. if len(inps) > 0 and not isinstance(inps[0].shape, inps[0].__class__):
  231. shapes = {arr.shape for arr in inps}
  232. if len(shapes) != 1:
  233. raise ValueError("All input tensors must have the same shape")
  234. inps = [expand_dims(inp, axis=axis) for inp in inps]
  235. return concat(inps, axis=axis, device=device)
  236. def split(inp, nsplits_or_sections, axis=0):
  237. """Splits the input tensor into several smaller tensors.
  238. When nsplits_or_sections is int, the last tensor may be smaller than others.
  239. :param inp: input tensor.
  240. :param nsplits_or_sections: number of sub tensors or sections information list.
  241. :param axis: which axis will be splited.
  242. :return: output tensor list.
  243. Examples:
  244. .. testcode::
  245. import numpy as np
  246. from megengine import tensor
  247. import megengine.functional as F
  248. x = tensor(np.random.random((2,3,4,5)), dtype=np.float32)
  249. out = F.split(x, 2, axis=3)
  250. print(out[0].shape, out[1].shape)
  251. Outputs:
  252. .. testoutput::
  253. (2, 3, 4, 3) (2, 3, 4, 2)
  254. """
  255. sub_tensors = []
  256. sections = []
  257. def swapaxis(inp, src, dst):
  258. if src == dst:
  259. return inp
  260. shape = [i for i in range(inp.ndim)]
  261. shape[src] = dst
  262. shape[dst] = src
  263. return inp.transpose(shape)
  264. inp = swapaxis(inp, 0, axis)
  265. if isinstance(nsplits_or_sections, int):
  266. incr_step = ceil(inp.shape[0] / nsplits_or_sections)
  267. nsplits = nsplits_or_sections
  268. while nsplits > 0:
  269. nsplits -= 1
  270. sections.append(incr_step.astype("int32"))
  271. incr_step += nsplits_or_sections
  272. else:
  273. sections = nsplits_or_sections
  274. st = 0
  275. for se in sections:
  276. sub_tensors.append(swapaxis(inp[st:se], axis, 0))
  277. st = se
  278. if st < inp.shape[0]:
  279. sub_tensors.append(swapaxis(inp[st:], axis, 0))
  280. return sub_tensors
  281. def _get_idx(index, axis):
  282. index_dims = len(index.shape)
  283. idx = []
  284. for i in range(index_dims):
  285. if i != axis:
  286. shape = [1] * index_dims
  287. shape[i] = index.shape[i]
  288. arange = linspace(
  289. 0, index.shape[i] - 1, index.shape[i], device=index.device,
  290. )
  291. arange = (
  292. arange.reshape(*shape)
  293. .broadcast(index.shape)
  294. .reshape(-1)
  295. .astype(np.int32)
  296. )
  297. idx.append(arange)
  298. else:
  299. idx.append(index.reshape(-1))
  300. return tuple(idx)
  301. def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor:
  302. r"""Gathers data from input tensor on axis using index.
  303. For a 3-D tensor, the output is specified by::
  304. out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0
  305. out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1
  306. out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2
  307. if input tensor is a n-dimensional tensor with size
  308. :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i,
  309. then index must be a n-dimensional tensor with size
  310. :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and
  311. output will have the same size as index.
  312. :param inp: input tensor.
  313. :param axis: along which axis to index.
  314. :param index: indices of elements to gather.
  315. :return: output tensor.
  316. Examples:
  317. .. testcode::
  318. import megengine.functional as F
  319. from megengine import tensor
  320. inp = tensor([
  321. [1,2], [3,4], [5,6],
  322. ])
  323. index = tensor([[0,2], [1,0]])
  324. oup = F.gather(inp, 0, index)
  325. print(oup.numpy())
  326. Outputs:
  327. .. testoutput::
  328. [[1 6]
  329. [3 2]]
  330. """
  331. input_shape = inp.shape
  332. index_shape = index.shape
  333. input_dims = len(input_shape)
  334. index_dims = len(index_shape)
  335. if input_dims != index_dims:
  336. raise ValueError(
  337. "The index tensor must have same dimensions as input tensor, "
  338. "But the input dims:{}, the index dims:{}".format(input_dims, index_dims)
  339. )
  340. if axis < 0 or axis >= input_dims:
  341. raise ValueError(
  342. "Index axis {} is output of bounds, should in range [0 {})".format(
  343. axis, input_dims
  344. )
  345. )
  346. for i in range(input_dims):
  347. if i != axis and input_shape[i] != index_shape[i]:
  348. raise ValueError(
  349. "The input {} and index {} must have the same size apart from axis {}".format(
  350. input_shape, index_shape, axis
  351. )
  352. )
  353. idx = _get_idx(index, axis)
  354. return inp[idx].reshape(index.shape) # pylint: disable=no-member
  355. def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor:
  356. r"""Writes all values from the tensor source into input tensor
  357. at the indices specified in the index tensor.
  358. For each value in source, its output index is specified by its index
  359. in source for ``axis != dimension`` and by the corresponding value in
  360. index for ``axis = dimension``.
  361. For a 3-D tensor, input tensor is updated as::
  362. inp[index[i][j][k]][j][k] = source[i][j][k] # if axis == 0
  363. inp[i][index[i][j][k]][k] = source[i][j][k] # if axis == 1
  364. inp[i][j][index[i][j][k]] = source[i][j][k] # if axis == 2
  365. ``inp``, ``index`` and ``source`` should have same number of dimensions.
  366. It is also required that ``source.shape(d) <= inp.shape(d)`` and ``index.shape(d) == source.shape(d)``
  367. for all dimensions ``d``.
  368. Moreover, the values of index must be between ``0`` and ``inp.shape(axis) - 1`` inclusive.
  369. .. note::
  370. Please notice that, due to performance issues, the result is uncertain on the GPU device
  371. if scattering different positions from source to the same destination position
  372. regard to index tensor.
  373. Check the following examples, the oup[0][2] is maybe
  374. from source[0][2] which value is 0.2256 or source[1][2] which value is 0.5339
  375. if set the index[1][2] from 1 to 0.
  376. :param inp: inp tensor which to be scattered.
  377. :param axis: axis along which to index.
  378. :param index: indices of elements to scatter.
  379. :param source: source element(s) to scatter.
  380. :return: output tensor.
  381. Examples:
  382. .. testcode::
  383. import numpy as np
  384. import megengine.functional as F
  385. from megengine import tensor
  386. inp = tensor(np.zeros(shape=(3,5),dtype=np.float32))
  387. source = tensor([[0.9935,0.9465,0.2256,0.8926,0.4396],[0.7723,0.0718,0.5939,0.357,0.4576]])
  388. index = tensor([[0,2,0,2,1],[2,0,1,1,2]])
  389. oup = F.scatter(inp, 0, index,source)
  390. print(oup.numpy())
  391. Outputs:
  392. .. testoutput::
  393. [[0.9935 0.0718 0.2256 0. 0. ]
  394. [0. 0. 0.5939 0.357 0.4396]
  395. [0.7723 0.9465 0. 0.8926 0.4576]]
  396. """
  397. input_shape = inp.shape
  398. index_shape = index.shape
  399. source_shape = source.shape
  400. input_dims = len(input_shape)
  401. index_dims = len(index_shape)
  402. source_dims = len(source_shape)
  403. if input_dims != index_dims or input_dims != source_dims:
  404. raise ValueError("The input, source and index tensor must have same dimensions")
  405. if axis < 0 or axis >= input_dims:
  406. raise ValueError(
  407. "Index axis {} is output of bounds, should in range [0 {})".format(
  408. axis, input_dims
  409. )
  410. )
  411. for i in range(source_dims):
  412. if source_shape[i] > input_shape[i]:
  413. raise ValueError(
  414. "The each shape size for source {} must be less than or equal to input {} ".format(
  415. source_shape, input_shape
  416. )
  417. )
  418. for i in range(index_dims):
  419. if index_shape[i] != source_shape[i]:
  420. raise ValueError(
  421. "The each shape size for index {} must be equal to source {} ".format(
  422. index_shape, source_shape
  423. )
  424. )
  425. for i in range(index_dims):
  426. if i != axis and index_shape[i] > input_shape[i]:
  427. raise ValueError(
  428. "The index {} must be less than or equal to input {} size apart from axis {}".format(
  429. index_shape, input_shape, axis
  430. )
  431. )
  432. idx = _get_idx(index, axis)
  433. inp[idx] = source.flatten()
  434. return inp
  435. def where(mask: Tensor, x: Tensor, y: Tensor) -> Tensor:
  436. r"""Selects elements either from Tensor x or Tensor y, according to mask.
  437. .. math::
  438. \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i
  439. :param mask: a mask used for choosing ``x`` or ``y``.
  440. :param x: first choice.
  441. :param y: second choice.
  442. :return: output tensor.
  443. Examples:
  444. .. testcode::
  445. from megengine import tensor
  446. import megengine.functional as F
  447. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool))
  448. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  449. dtype=np.float32))
  450. y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32))
  451. out = F.where(mask, x, y)
  452. print(out.numpy())
  453. Outputs:
  454. .. testoutput::
  455. [[1. 6.]
  456. [7. 4.]]
  457. """
  458. x, y = convert_inputs(x, y)
  459. if not isinstance(x, (TensorWrapperBase, TensorBase)):
  460. raise TypeError("input x must be a tensor")
  461. if not isinstance(y, (TensorWrapperBase, TensorBase)):
  462. raise TypeError("input y must be a tensor")
  463. if not isinstance(mask, (TensorWrapperBase, TensorBase)):
  464. raise TypeError("mask must be a tensor")
  465. if mask.dtype != np.bool_:
  466. raise ValueError("mask must be bool")
  467. if x.device != mask.device:
  468. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  469. v0, index0 = cond_take(mask, x)
  470. v1, index1 = cond_take(~mask, y)
  471. if v0.shape == (0,):
  472. out = v1
  473. elif v1.shape == (0,):
  474. out = v0
  475. else:
  476. out = concat([v0, v1])
  477. out[index0] = v0
  478. out[index1] = v1
  479. out = out.reshape(x.shape)
  480. return out
  481. def cond_take(mask: Tensor, x: Tensor) -> Tensor:
  482. r"""
  483. Takes elements from data if specific condition is satisfied on mask.
  484. This operator has two outputs: the first is the elements taken,
  485. and the second is the indices corresponding to those elements;
  486. they are both 1-dimensional. High-dimension input would first be flattened.
  487. :param mask: condition param; must be the same shape with data.
  488. :param x: input tensor from which to take elements.
  489. Examples:
  490. .. testcode::
  491. import numpy as np
  492. from megengine import tensor
  493. import megengine.functional as F
  494. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool_))
  495. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  496. dtype=np.float32))
  497. v, index = F.cond_take(mask, x)
  498. print(v.numpy(), index.numpy())
  499. Outputs:
  500. .. testoutput::
  501. [1. 4.] [0 3]
  502. """
  503. if not isinstance(x, (TensorWrapperBase, TensorBase)):
  504. raise TypeError("input must be a tensor")
  505. if not isinstance(mask, (TensorWrapperBase, TensorBase)):
  506. raise TypeError("mask must be a tensor")
  507. if mask.dtype != np.bool_:
  508. raise ValueError("mask must be bool")
  509. if x.device != mask.device:
  510. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  511. op = builtin.CondTake()
  512. v, index = apply(op, x, mask)
  513. return v, index
  514. def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
  515. r"""
  516. Swaps shapes and strides according to given pattern.
  517. :param inp: input tensor.
  518. :param pattern: a list of integers including 0, 1, ... , ``ndim``-1,
  519. and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples:
  520. * (``'x'``) -> make a 0d (scalar) into a 1d vector
  521. * (0, 1) -> identity for 2d vectors
  522. * (1, 0) -> inverts the first and second dimensions
  523. * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN)
  524. * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1)
  525. * (2, 0, 1) -> AxBxC to CxAxB
  526. * (0, ``'x'``, 1) -> AxB to Ax1xB
  527. * (1, ``'x'``, 0) -> AxB to Bx1xA
  528. * (1,) -> this removes dimensions 0. It must be a broadcastable dimension (1xA to A)
  529. :return: output tensor.
  530. Examples:
  531. .. testcode::
  532. import numpy as np
  533. from megengine import tensor
  534. import megengine.functional as F
  535. x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32))
  536. out = F.transpose(x, (1, 0))
  537. print(out.numpy())
  538. Outputs:
  539. .. testoutput::
  540. [[1 0]
  541. [1 0]]
  542. """
  543. return inp.transpose(pattern)
  544. def dimshuffle(inp: Tensor, pattern: Iterable[int]) -> Tensor:
  545. r"""Same as :func:`~.transpose`.
  546. """
  547. return transpose(inp, pattern)
  548. def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor:
  549. r"""
  550. Reshapes a tensor to given target shape; total number of logical elements must
  551. remain unchanged
  552. :param inp: input tensor.
  553. :param target_shape: target shape, it can contain an element of -1 representing ``unspec_axis``.
  554. Examples:
  555. .. testcode::
  556. import numpy as np
  557. from megengine import tensor
  558. import megengine.functional as F
  559. x = tensor(np.arange(12, dtype=np.int32))
  560. out = F.reshape(x, (3, 2, 2))
  561. print(out.numpy())
  562. Outputs:
  563. .. testoutput::
  564. [[[ 0 1]
  565. [ 2 3]]
  566. [[ 4 5]
  567. [ 6 7]]
  568. [[ 8 9]
  569. [10 11]]]
  570. """
  571. return inp.reshape(target_shape)
  572. AxisAddRemove = builtin.AxisAddRemove
  573. AxisDesc = AxisAddRemove.AxisDesc
  574. def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
  575. r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
  576. :param inp: input tensor.
  577. :param start_axis: start dimension that the sub-tensor to be flattened. Default: 0
  578. :param end_axis: end dimension that the sub-tensor to be flattened. Default: -1
  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. inp_shape = (2, 2, 3, 3)
  586. x = tensor(
  587. np.arange(36, dtype=np.int32).reshape(inp_shape),
  588. )
  589. out = F.flatten(x, 2)
  590. print(x.numpy().shape)
  591. print(out.numpy().shape)
  592. Outputs:
  593. .. testoutput::
  594. (2, 2, 3, 3)
  595. (2, 2, 9)
  596. """
  597. target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,)
  598. if end_axis != -1:
  599. target_shape += (*inp.shape[end_axis + 1 :],)
  600. return inp.reshape(*target_shape)
  601. def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  602. r"""
  603. Adds dimension before given axis.
  604. :param inp: input tensor.
  605. :param axis: place of new axes.
  606. :return: output tensor.
  607. Examples:
  608. .. testcode::
  609. import numpy as np
  610. from megengine import tensor
  611. import megengine.functional as F
  612. x = tensor([1, 2])
  613. out = F.expand_dims(x, 0)
  614. print(out.shape)
  615. Outputs:
  616. .. testoutput::
  617. (1, 2)
  618. """
  619. Param = builtin.AxisAddRemove.Param
  620. def get_axes():
  621. try:
  622. return [int(axis)]
  623. except (TypeError, ValueError):
  624. pass
  625. return list(map(int, axis))
  626. axis = get_axes()
  627. ndim = inp.ndim + len(axis)
  628. axis = sorted(i + ndim if i < 0 else i for i in axis)
  629. param = Param(*map(builtin.AxisAddRemove.AxisDesc.make_add, axis))
  630. op = builtin.AxisAddRemove(param=param)
  631. (result,) = apply(op, inp)
  632. return result
  633. def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
  634. r"""
  635. Removes dimension of shape 1.
  636. :param inp: input tensor.
  637. :param axis: place of axis to be removed.
  638. :return: output tensor.
  639. Examples:
  640. .. testcode::
  641. import numpy as np
  642. from megengine import tensor
  643. import megengine.functional as F
  644. x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
  645. out = F.squeeze(x, 3)
  646. print(out.shape)
  647. Outputs:
  648. .. testoutput::
  649. (1, 1, 2)
  650. """
  651. return _remove_axis(inp, axis)
  652. def linspace(
  653. start: Union[int, float, Tensor],
  654. stop: Union[int, float, Tensor],
  655. num: Union[int, Tensor],
  656. dtype="float32",
  657. device: Optional[CompNode] = None,
  658. ) -> Tensor:
  659. r"""Returns equally spaced numbers over a specified interval.
  660. :param start: starting value of the squence, shoule be scalar.
  661. :param stop: last value of the squence, shoule be scalar.
  662. :param num: number of values to generate.
  663. :param dtype: result data type.
  664. :return: generated tensor.
  665. Examples:
  666. .. testcode::
  667. import numpy as np
  668. import megengine.functional as F
  669. a = F.linspace(3,10,5)
  670. print(a.numpy())
  671. Outputs:
  672. .. testoutput::
  673. [ 3. 4.75 6.5 8.25 10. ]
  674. """
  675. start = Tensor(start, device=device)
  676. stop = Tensor(stop, device=device)
  677. num = Tensor(num, device=device)
  678. device = device if device is None else device.to_c()
  679. op = builtin.Linspace(comp_node=device)
  680. (result,) = apply(op, start, stop, num)
  681. if np.dtype(dtype) == np.int32:
  682. return result.astype(dtype)
  683. return result
  684. def arange(
  685. start: Union[int, float, Tensor] = 0,
  686. end: Optional[Union[int, float, Tensor]] = None,
  687. step: Union[int, float, Tensor] = 1,
  688. dtype="float32",
  689. device: Optional[CompNode] = None,
  690. ) -> Tensor:
  691. r"""Returns a tensor with values from start to end with adjacent interval step.
  692. :param start: starting value of the squence, shoule be scalar.
  693. :param end: ending value of the squence, shoule be scalar.
  694. :param step: gap between each pair of adjacent values. Default: 1
  695. :param dtype: result data type.
  696. :return: generated tensor.
  697. Examples:
  698. .. testcode::
  699. import numpy as np
  700. import megengine.functional as F
  701. a = F.arange(5)
  702. print(a.numpy())
  703. Outputs:
  704. Outputs:
  705. .. testoutput::
  706. [0. 1. 2. 3. 4.]
  707. """
  708. if end is None:
  709. start, end = 0, start
  710. if isinstance(start, Tensor):
  711. start = start.astype("float32")
  712. if isinstance(end, Tensor):
  713. end = end.astype("float32")
  714. if isinstance(step, Tensor):
  715. step = step.astype("float32")
  716. num = ceil(Tensor((end - start) / step, device=device))
  717. stop = start + step * (num - 1)
  718. result = linspace(start, stop, num, device=device)
  719. if np.dtype(dtype) == np.int32:
  720. return result.astype(dtype)
  721. return result
  722. def param_pack_split(inp: Tensor, offsets: List, shapes: List) -> Tensor:
  723. r"""
  724. Returns split tensor to tensor list as offsets and shapes described,
  725. only used for ``parampack``.
  726. :param inp: input tensor.
  727. :param offsets: offsets of outputs, length of `2 * n`,
  728. while n is tensor nums you want to split,
  729. format `[begin0, end0, begin1, end1]`.
  730. :param shapes: tensor shapes of outputs.
  731. :return: splitted tensors.
  732. Examples:
  733. .. testcode::
  734. import numpy as np
  735. import megengine.functional as F
  736. from megengine import tensor
  737. a = tensor(np.ones((10,), np.int32))
  738. b, c = F.param_pack_split(a, [0, 1, 1, 10], [(1,), (3, 3)])
  739. print(b.numpy())
  740. print(c.numpy())
  741. Outputs:
  742. .. testoutput::
  743. [1]
  744. [[1 1 1]
  745. [1 1 1]
  746. [1 1 1]]
  747. """
  748. op = builtin.ParamPackSplit()
  749. op.offsets = offsets
  750. op.shapes = shapes
  751. return apply(op, inp)
  752. def param_pack_concat(inps: List, offsets: Tensor, offsets_val: List) -> Tensor:
  753. r"""
  754. Returns concated tensor, only used for ``parampack``.
  755. :param inps: input tensors.
  756. :param offsets: device value of offsets.
  757. :param offsets_val: offsets of inputs, length of `2 * n`,
  758. format `[begin0, end0, begin1, end1]`.
  759. :return: concated tensor.
  760. Examples:
  761. .. testcode::
  762. import numpy as np
  763. import megengine.functional as F
  764. from megengine import tensor
  765. a = tensor(np.ones((1,), np.int32))
  766. b = tensor(np.ones((3, 3), np.int32))
  767. offsets_val = [0, 1, 1, 10]
  768. offsets = tensor(offsets_val, np.int32)
  769. c = F.param_pack_concat([a, b], offsets, offsets_val)
  770. print(c.numpy())
  771. Outputs:
  772. .. testoutput::
  773. [1 1 1 1 1 1 1 1 1 1]
  774. """
  775. op = builtin.ParamPackConcat()
  776. op.offsets = offsets_val
  777. return apply(op, *inps, offsets)[0]

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