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

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

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