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

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

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