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

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

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