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

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

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