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

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

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