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

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

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