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

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

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