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

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

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