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

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

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