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

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

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