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

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

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