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

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

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