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 28 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 _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",
  34. "concat",
  35. "cond_take",
  36. "expand_dims",
  37. "eye",
  38. "flatten",
  39. "full",
  40. "full_like",
  41. "gather",
  42. "identity",
  43. "linspace",
  44. "ones",
  45. "ones_like",
  46. "param_pack_concat",
  47. "param_pack_split",
  48. "reshape",
  49. "split",
  50. "squeeze",
  51. "stack",
  52. "scatter",
  53. "transpose",
  54. "where",
  55. "zeros",
  56. "zeros_like",
  57. ]
  58. def eye(shape, *, dtype="float32", device: Optional[CompNode] = None) -> Tensor:
  59. """Returns a 2D tensor with ones on the diagonal and zeros elsewhere.
  60. :param shape: expected shape of output tensor.
  61. :param dtype: data type. Default: None
  62. :param device: compute node of the matrix. Default: None
  63. :return: eye matrix.
  64. Examples:
  65. .. testcode::
  66. import numpy as np
  67. import megengine.functional as F
  68. data_shape = (4, 6)
  69. out = F.eye(data_shape, dtype=np.float32)
  70. print(out.numpy())
  71. Outputs:
  72. .. testoutput::
  73. [[1. 0. 0. 0. 0. 0.]
  74. [0. 1. 0. 0. 0. 0.]
  75. [0. 0. 1. 0. 0. 0.]
  76. [0. 0. 0. 1. 0. 0.]]
  77. """
  78. op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
  79. (result,) = apply(op, Tensor(shape, dtype="int32", device=device))
  80. return result
  81. def full(shape, value, dtype="float32", device=None):
  82. """Returns a tensor with given shape and value.
  83. """
  84. if isinstance(shape, int):
  85. shape = (shape,)
  86. if device is None:
  87. device = get_default_device()
  88. (x,) = Const(value, dtype=dtype, device=device)(
  89. Tensor(value, dtype=dtype, device=device)
  90. )
  91. return broadcast(x, shape)
  92. def ones(shape, dtype="float32", device=None):
  93. """Returns a ones tensor with given shape.
  94. :param inp: input tensor.
  95. :return: output zero tensor.
  96. Examples:
  97. .. testcode::
  98. import megengine.functional as F
  99. out = F.ones((2, 1))
  100. print(out.numpy())
  101. Outputs:
  102. .. testoutput::
  103. [[1.]
  104. [1.]]
  105. """
  106. return full(shape, 1.0, dtype=dtype, device=device)
  107. def zeros(shape, dtype="float32", device=None):
  108. """Returns a zero tensor with given shape.
  109. """
  110. return full(shape, 0.0, dtype=dtype, device=device)
  111. def zeros_like(inp: Tensor) -> Tensor:
  112. """Returns a zero tensor with the same shape as input tensor.
  113. :param inp: input tensor.
  114. :return: output zero tensor.
  115. Examples:
  116. .. testcode::
  117. import numpy as np
  118. from megengine import tensor
  119. import megengine.functional as F
  120. inp = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  121. out = F.zeros_like(inp)
  122. print(out.numpy())
  123. Outputs:
  124. .. testoutput::
  125. [[0 0 0]
  126. [0 0 0]]
  127. """
  128. return zeros(inp.shape, dtype=inp.dtype, device=inp.device)
  129. def ones_like(inp: Tensor) -> Tensor:
  130. """Returns a ones tensor with the same shape as input tensor.
  131. """
  132. return ones(inp.shape, dtype=inp.dtype, device=inp.device)
  133. def full_like(inp: Tensor, value: Union[int, float]) -> Tensor:
  134. """Returns a tensor filled with given value with the same shape as input tensor.
  135. """
  136. return full(inp.shape, value, dtype=inp.dtype, device=inp.device)
  137. def identity(inp: Tensor) -> Tensor:
  138. """Applies an identity transformation to input tensor.
  139. :param inp: input tensor.
  140. :return: output tensor.
  141. """
  142. op = builtin.Identity()
  143. (data,) = convert_inputs(inp)
  144. (output,) = apply(op, data)
  145. return output
  146. def broadcast(inp: Tensor, shape: Union[int, Iterable[int]]) -> Tensor:
  147. """
  148. Broadcasts a tensor to given shape.
  149. :param inp: input tensor.
  150. :param shape: target shape.
  151. :return: output tensor.
  152. Examples:
  153. .. testcode::
  154. import numpy as np
  155. from megengine import tensor
  156. import megengine.functional as F
  157. data = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  158. out = F.broadcast(data, (4, 2, 3))
  159. print(out.numpy())
  160. Outputs:
  161. .. testoutput::
  162. [[[0. 1. 2.]
  163. [3. 4. 5.]]
  164. [[0. 1. 2.]
  165. [3. 4. 5.]]
  166. [[0. 1. 2.]
  167. [3. 4. 5.]]
  168. [[0. 1. 2.]
  169. [3. 4. 5.]]]
  170. """
  171. return inp.broadcast(shape)
  172. def concat(inps: Iterable[Tensor], axis: int = 0, device=None) -> Tensor:
  173. r"""
  174. Concat some tensors
  175. :param inps: input tensors to concat.
  176. :param axis: over which dimension the tensors are concatenated. Default: 0
  177. :param device: which device output will be. Default: None
  178. :return: output tensor.
  179. Examples:
  180. .. testcode::
  181. import numpy as np
  182. from megengine import tensor
  183. import megengine.functional as F
  184. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
  185. data2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
  186. out = F.concat([data1, data2])
  187. print(out.numpy())
  188. Outputs:
  189. .. testoutput::
  190. [[ 0. 1. 2.]
  191. [ 3. 4. 5.]
  192. [ 6. 7. 8.]
  193. [ 9. 10. 11.]]
  194. """
  195. if len(inps) == 1:
  196. return inps[0]
  197. dtype = dtype_promotion(inps)
  198. if device is None:
  199. device = get_device(inps)
  200. device = as_device(device)
  201. def convert(x):
  202. return convert_single_value(x, inps, dtype=dtype)
  203. inps = tuple(map(convert, inps))
  204. (result,) = apply(builtin.Concat(axis=axis, comp_node=device.to_c()), *inps)
  205. return result
  206. def stack(inps, axis=0, device=None):
  207. """Concats a sequence of tensors along a new axis.
  208. The input tensors must have the same shape.
  209. :param inps: input tensors.
  210. :param axis: which axis will be concatenated.
  211. :param device: the device output will be. Default: None
  212. :return: output concatenated tensor.
  213. Examples:
  214. .. testcode::
  215. import numpy as np
  216. from megengine import tensor
  217. import megengine.functional as F
  218. x1 = tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
  219. x2 = tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
  220. out = F.stack([x1, x2], axis=0)
  221. print(out.numpy())
  222. Outputs:
  223. .. testoutput::
  224. [[[ 0. 1. 2.]
  225. [ 3. 4. 5.]]
  226. [[ 6. 7. 8.]
  227. [ 9. 10. 11.]]]
  228. """
  229. if len(inps) > 0 and not isinstance(inps[0].shape, inps[0].__class__):
  230. shapes = {arr.shape for arr in inps}
  231. if len(shapes) != 1:
  232. raise ValueError("All input tensors must have the same shape")
  233. inps = [expand_dims(inp, axis=axis) for inp in inps]
  234. return concat(inps, axis=axis, device=device)
  235. def split(inp, nsplits_or_sections, axis=0):
  236. """Splits the input tensor into several smaller tensors.
  237. When nsplits_or_sections is int, the last tensor may be smaller than others.
  238. :param inp: input tensor.
  239. :param nsplits_or_sections: number of sub tensors or sections information list.
  240. :param axis: which axis will be splited.
  241. :return: output tensor list.
  242. Examples:
  243. .. testcode::
  244. import numpy as np
  245. from megengine import tensor
  246. import megengine.functional as F
  247. x = tensor(np.random.random((2,3,4,5)), dtype=np.float32)
  248. out = F.split(x, 2, axis=3)
  249. print(out[0].shape, out[1].shape)
  250. Outputs:
  251. .. testoutput::
  252. (2, 3, 4, 3) (2, 3, 4, 2)
  253. """
  254. sub_tensors = []
  255. sections = []
  256. def swapaxis(inp, src, dst):
  257. if src == dst:
  258. return inp
  259. shape = [i for i in range(inp.ndim)]
  260. shape[src] = dst
  261. shape[dst] = src
  262. return inp.transpose(shape)
  263. inp = swapaxis(inp, 0, axis)
  264. if isinstance(nsplits_or_sections, int):
  265. incr_step = ceil(inp.shape[0] / nsplits_or_sections)
  266. nsplits = nsplits_or_sections
  267. while nsplits > 0:
  268. nsplits -= 1
  269. sections.append(incr_step.astype("int32"))
  270. incr_step += nsplits_or_sections
  271. else:
  272. sections = nsplits_or_sections
  273. st = 0
  274. for se in sections:
  275. sub_tensors.append(swapaxis(inp[st:se], axis, 0))
  276. st = se
  277. if st < inp.shape[0]:
  278. sub_tensors.append(swapaxis(inp[st:], axis, 0))
  279. return sub_tensors
  280. def _get_idx(index, axis):
  281. index_dims = len(index.shape)
  282. idx = []
  283. for i in range(index_dims):
  284. if i != axis:
  285. shape = [1] * index_dims
  286. shape[i] = index.shape[i]
  287. arange = linspace(
  288. 0, index.shape[i] - 1, index.shape[i], device=index.device,
  289. )
  290. arange = (
  291. arange.reshape(*shape)
  292. .broadcast(index.shape)
  293. .reshape(-1)
  294. .astype(np.int32)
  295. )
  296. idx.append(arange)
  297. else:
  298. idx.append(index.reshape(-1))
  299. return tuple(idx)
  300. def gather(inp: Tensor, axis: int, index: Tensor) -> Tensor:
  301. r"""Gathers data from input tensor on axis using index.
  302. For a 3-D tensor, the output is specified by::
  303. out[i][j][k] = inp[index[i][j][k]][j][k] # if axis == 0
  304. out[i][j][k] = inp[i][index[i][j][k]][k] # if axis == 1
  305. out[i][j][k] = inp[i][j][index[i][j][k]] # if axis == 2
  306. if input tensor is a n-dimensional tensor with size
  307. :math:`(x_0,x_1,...,x_{i-1},x_i,x_{i+1},...,x_{n-1})` and axis=i,
  308. then index must be a n-dimensional tensor with size
  309. :math:`(x_0,x_1,...,x_{i-1},y,x_{i+1},...,x_{n-1})` where :math:`y\ge 1` and
  310. output will have the same size as index.
  311. :param inp: input tensor.
  312. :param axis: along which axis to index.
  313. :param index: indices of elements to gather.
  314. :return: output tensor.
  315. Examples:
  316. .. testcode::
  317. import megengine.functional as F
  318. from megengine import tensor
  319. inp = tensor([
  320. [1,2], [3,4], [5,6],
  321. ])
  322. index = tensor([[0,2], [1,0]])
  323. oup = F.gather(inp, 0, index)
  324. print(oup.numpy())
  325. Outputs:
  326. .. testoutput::
  327. [[1 6]
  328. [3 2]]
  329. """
  330. input_shape = inp.shape
  331. index_shape = index.shape
  332. input_dims = len(input_shape)
  333. index_dims = len(index_shape)
  334. if input_dims != index_dims:
  335. raise ValueError(
  336. "The index tensor must have same dimensions as input tensor, "
  337. "But the input dims:{}, the index dims:{}".format(input_dims, index_dims)
  338. )
  339. if axis < 0 or axis >= input_dims:
  340. raise ValueError(
  341. "Index axis {} is output of bounds, should in range [0 {})".format(
  342. axis, input_dims
  343. )
  344. )
  345. for i in range(input_dims):
  346. if i != axis and input_shape[i] != index_shape[i]:
  347. raise ValueError(
  348. "The input {} and index {} must have the same size apart from axis {}".format(
  349. input_shape, index_shape, axis
  350. )
  351. )
  352. idx = _get_idx(index, axis)
  353. return inp[idx].reshape(index.shape) # pylint: disable=no-member
  354. def scatter(inp: Tensor, axis: int, index: Tensor, source: Tensor) -> Tensor:
  355. r"""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"""Selects elements either from Tensor x or Tensor y, according to mask.
  436. .. math::
  437. \textrm{out}_i = x_i \textrm{ if } \textrm{mask}_i \textrm{ is True else } y_i
  438. :param mask: a mask used for choosing ``x`` or ``y``.
  439. :param x: first choice.
  440. :param y: second choice.
  441. :return: output tensor.
  442. Examples:
  443. .. testcode::
  444. from megengine import tensor
  445. import megengine.functional as F
  446. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool))
  447. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  448. dtype=np.float32))
  449. y = tensor(np.array([[5, 6], [7, 8]], dtype=np.float32))
  450. out = F.where(mask, x, y)
  451. print(out.numpy())
  452. Outputs:
  453. .. testoutput::
  454. [[1. 6.]
  455. [7. 4.]]
  456. """
  457. x, y = convert_inputs(x, y)
  458. if not isinstance(x, (TensorWrapperBase, TensorBase)):
  459. raise TypeError("input x must be a tensor")
  460. if not isinstance(y, (TensorWrapperBase, TensorBase)):
  461. raise TypeError("input y must be a tensor")
  462. if not isinstance(mask, (TensorWrapperBase, TensorBase)):
  463. raise TypeError("mask must be a tensor")
  464. if mask.dtype != np.bool_:
  465. raise ValueError("mask must be bool")
  466. if x.device != mask.device:
  467. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  468. v0, index0 = cond_take(mask, x)
  469. v1, index1 = cond_take(~mask, y)
  470. if v0.shape == (0,):
  471. out = v1
  472. elif v1.shape == (0,):
  473. out = v0
  474. else:
  475. out = concat([v0, v1])
  476. out[index0] = v0
  477. out[index1] = v1
  478. out = out.reshape(x.shape)
  479. return out
  480. def cond_take(mask: Tensor, x: Tensor) -> Tensor:
  481. r"""
  482. Takes elements from data if specific condition is satisfied on mask.
  483. This operator has two outputs: the first is the elements taken,
  484. and the second is the indices corresponding to those elements;
  485. they are both 1-dimensional. High-dimension input would first be flattened.
  486. :param mask: condition param; must be the same shape with data.
  487. :param x: input tensor from which to take elements.
  488. Examples:
  489. .. testcode::
  490. import numpy as np
  491. from megengine import tensor
  492. import megengine.functional as F
  493. mask = tensor(np.array([[True, False], [False, True]], dtype=np.bool_))
  494. x = tensor(np.array([[1, np.inf], [np.nan, 4]],
  495. dtype=np.float32))
  496. v, index = F.cond_take(mask, x)
  497. print(v.numpy(), index.numpy())
  498. Outputs:
  499. .. testoutput::
  500. [1. 4.] [0 3]
  501. """
  502. if not isinstance(x, (TensorWrapperBase, TensorBase)):
  503. raise TypeError("input must be a tensor")
  504. if not isinstance(mask, (TensorWrapperBase, TensorBase)):
  505. raise TypeError("mask must be a tensor")
  506. if mask.dtype != np.bool_:
  507. raise ValueError("mask must be bool")
  508. if x.device != mask.device:
  509. raise ValueError("ambiguous device: {} vs {}".format(x.device, mask.device))
  510. op = builtin.CondTake()
  511. v, index = apply(op, x, mask)
  512. return v, index
  513. def transpose(inp: Tensor, pattern: Iterable[int]) -> Tensor:
  514. r"""
  515. Swaps shapes and strides according to given pattern.
  516. :param inp: input tensor.
  517. :param pattern: a list of integers including 0, 1, ... , ``ndim``-1,
  518. and any number of ``'x'`` char in dimensions where this tensor should be broadcasted. For examples:
  519. * (``'x'``) -> make a 0d (scalar) into a 1d vector
  520. * (0, 1) -> identity for 2d vectors
  521. * (1, 0) -> inverts the first and second dimensions
  522. * (``'x'``, 0) -> make a row out of a 1d vector (N to 1xN)
  523. * (0, ``'x'``) -> make a column out of a 1d vector (N to Nx1)
  524. * (2, 0, 1) -> AxBxC to CxAxB
  525. * (0, ``'x'``, 1) -> AxB to Ax1xB
  526. * (1, ``'x'``, 0) -> AxB to Bx1xA
  527. * (1,) -> this removes dimensions 0. It must be a broadcastable dimension (1xA to A)
  528. :return: output tensor.
  529. Examples:
  530. .. testcode::
  531. import numpy as np
  532. from megengine import tensor
  533. import megengine.functional as F
  534. x = tensor(np.array([[1, 1], [0, 0]], dtype=np.int32))
  535. out = F.transpose(x, (1, 0))
  536. print(out.numpy())
  537. Outputs:
  538. .. testoutput::
  539. [[1 0]
  540. [1 0]]
  541. """
  542. return inp.transpose(pattern)
  543. def reshape(inp: Tensor, target_shape: Iterable[int]) -> Tensor:
  544. r"""
  545. Reshapes a tensor to given target shape; total number of logical elements must
  546. remain unchanged
  547. :param inp: input tensor.
  548. :param target_shape: target shape, it can contain an element of -1 representing ``unspec_axis``.
  549. Examples:
  550. .. testcode::
  551. import numpy as np
  552. from megengine import tensor
  553. import megengine.functional as F
  554. x = tensor(np.arange(12, dtype=np.int32))
  555. out = F.reshape(x, (3, 2, 2))
  556. print(out.numpy())
  557. Outputs:
  558. .. testoutput::
  559. [[[ 0 1]
  560. [ 2 3]]
  561. [[ 4 5]
  562. [ 6 7]]
  563. [[ 8 9]
  564. [10 11]]]
  565. """
  566. return inp.reshape(target_shape)
  567. AxisAddRemove = builtin.AxisAddRemove
  568. AxisDesc = AxisAddRemove.AxisDesc
  569. def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
  570. r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
  571. :param inp: input tensor.
  572. :param start_axis: start dimension that the sub-tensor to be flattened. Default: 0
  573. :param end_axis: end dimension that the sub-tensor to be flattened. Default: -1
  574. :return: output tensor.
  575. Examples:
  576. .. testcode::
  577. import numpy as np
  578. from megengine import tensor
  579. import megengine.functional as F
  580. inp_shape = (2, 2, 3, 3)
  581. x = tensor(
  582. np.arange(36, dtype=np.int32).reshape(inp_shape),
  583. )
  584. out = F.flatten(x, 2)
  585. print(x.numpy().shape)
  586. print(out.numpy().shape)
  587. Outputs:
  588. .. testoutput::
  589. (2, 2, 3, 3)
  590. (2, 2, 9)
  591. """
  592. target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,)
  593. if end_axis != -1:
  594. target_shape += (*inp.shape[end_axis + 1 :],)
  595. return inp.reshape(*target_shape)
  596. def expand_dims(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  597. r"""
  598. Adds dimension before given axis.
  599. :param inp: input tensor.
  600. :param axis: place of new axes.
  601. :return: output tensor.
  602. Examples:
  603. .. testcode::
  604. import numpy as np
  605. from megengine import tensor
  606. import megengine.functional as F
  607. x = tensor([1, 2])
  608. out = F.expand_dims(x, 0)
  609. print(out.shape)
  610. Outputs:
  611. .. testoutput::
  612. (1, 2)
  613. """
  614. Param = builtin.AxisAddRemove.Param
  615. def get_axes():
  616. try:
  617. return [int(axis)]
  618. except (TypeError, ValueError):
  619. pass
  620. return list(map(int, axis))
  621. axis = get_axes()
  622. ndim = inp.ndim + len(axis)
  623. axis = sorted(i + ndim if i < 0 else i for i in axis)
  624. param = Param(*map(builtin.AxisAddRemove.AxisDesc.make_add, axis))
  625. op = builtin.AxisAddRemove(param=param)
  626. (result,) = apply(op, inp)
  627. return result
  628. def squeeze(inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None) -> Tensor:
  629. r"""
  630. Removes dimension of shape 1.
  631. :param inp: input tensor.
  632. :param axis: place of axis to be removed.
  633. :return: output tensor.
  634. Examples:
  635. .. testcode::
  636. import numpy as np
  637. from megengine import tensor
  638. import megengine.functional as F
  639. x = tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
  640. out = F.squeeze(x, 3)
  641. print(out.shape)
  642. Outputs:
  643. .. testoutput::
  644. (1, 1, 2)
  645. """
  646. return _remove_axis(inp, axis)
  647. def linspace(
  648. start: Union[int, float, Tensor],
  649. stop: Union[int, float, Tensor],
  650. num: Union[int, Tensor],
  651. dtype="float32",
  652. device: Optional[CompNode] = None,
  653. ) -> Tensor:
  654. r"""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. end: 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"""Returns a tensor with values from start to end with adjacent interval step.
  687. :param start: starting value of the squence, shoule be scalar.
  688. :param end: ending value of the squence, shoule be scalar.
  689. :param step: gap between each pair of adjacent values. Default: 1
  690. :param dtype: result data type.
  691. :return: generated tensor.
  692. Examples:
  693. .. testcode::
  694. import numpy as np
  695. import megengine.functional as F
  696. a = F.arange(5)
  697. print(a.numpy())
  698. Outputs:
  699. Outputs:
  700. .. testoutput::
  701. [0. 1. 2. 3. 4.]
  702. """
  703. if end is None:
  704. start, end = 0, start
  705. if isinstance(start, Tensor):
  706. start = start.astype("float32")
  707. if isinstance(end, Tensor):
  708. end = end.astype("float32")
  709. if isinstance(step, Tensor):
  710. step = step.astype("float32")
  711. num = ceil(Tensor((end - start) / step, device=device))
  712. stop = start + step * (num - 1)
  713. result = linspace(start, stop, num, device=device)
  714. if np.dtype(dtype) == np.int32:
  715. return result.astype(dtype)
  716. return result
  717. def param_pack_split(inp: Tensor, offsets: List, shapes: List) -> Tensor:
  718. r"""
  719. Returns split tensor to tensor list as offsets and shapes described,
  720. only used for ``parampack``.
  721. :param inp: input tensor.
  722. :param offsets: offsets of outputs, length of `2 * n`,
  723. while n is tensor nums you want to split,
  724. format `[begin0, end0, begin1, end1]`.
  725. :param shapes: tensor shapes of outputs.
  726. :return: splitted tensors.
  727. Examples:
  728. .. testcode::
  729. import numpy as np
  730. import megengine.functional as F
  731. from megengine import tensor
  732. a = tensor(np.ones((10,), np.int32))
  733. b, c = F.param_pack_split(a, [0, 1, 1, 10], [(1,), (3, 3)])
  734. print(b.numpy())
  735. print(c.numpy())
  736. Outputs:
  737. .. testoutput::
  738. [1]
  739. [[1 1 1]
  740. [1 1 1]
  741. [1 1 1]]
  742. """
  743. op = builtin.ParamPackSplit()
  744. op.offsets = offsets
  745. op.shapes = shapes
  746. return apply(op, inp)
  747. def param_pack_concat(inps: List, offsets: Tensor, offsets_val: List) -> Tensor:
  748. r"""
  749. Returns concated tensor, only used for ``parampack``.
  750. :param inps: input tensors.
  751. :param offsets: device value of offsets.
  752. :param offsets_val: offsets of inputs, length of `2 * n`,
  753. format `[begin0, end0, begin1, end1]`.
  754. :return: concated tensor.
  755. Examples:
  756. .. testcode::
  757. import numpy as np
  758. import megengine.functional as F
  759. from megengine import tensor
  760. a = tensor(np.ones((1,), np.int32))
  761. b = tensor(np.ones((3, 3), np.int32))
  762. offsets_val = [0, 1, 1, 10]
  763. offsets = tensor(offsets_val, np.int32)
  764. c = F.param_pack_concat([a, b], offsets, offsets_val)
  765. print(c.numpy())
  766. Outputs:
  767. .. testoutput::
  768. [1 1 1 1 1 1 1 1 1 1]
  769. """
  770. op = builtin.ParamPackConcat()
  771. op.offsets = offsets_val
  772. return apply(op, *inps, offsets)[0]

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