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

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

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