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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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 collections
  10. import math
  11. from typing import Optional, Sequence, Tuple, Union
  12. from ..core._imperative_rt.core2 import apply
  13. from ..core._trace_option import use_symbolic_shape
  14. from ..core.ops import builtin
  15. from ..core.ops.special import Const
  16. from ..core.tensor import utils
  17. from ..tensor import Tensor
  18. from .debug_param import get_execution_strategy
  19. from .elemwise import clip, exp, log, log1p
  20. from .tensor import broadcast_to, concat, expand_dims, reshape, squeeze
  21. __all__ = [
  22. "argmax",
  23. "argmin",
  24. "argsort",
  25. "dot",
  26. "isinf",
  27. "isnan",
  28. "matinv",
  29. "matmul",
  30. "max",
  31. "mean",
  32. "min",
  33. "norm",
  34. "normalize",
  35. "prod",
  36. "sign",
  37. "sort",
  38. "std",
  39. "sum",
  40. "svd",
  41. "topk",
  42. "var",
  43. ]
  44. def isnan(inp: Tensor) -> Tensor:
  45. r"""
  46. Returns a new tensor representing if each element is ``NaN`` or not.
  47. :param inp: input tensor.
  48. :return: result tensor.
  49. Examples:
  50. .. testcode::
  51. from megengine import tensor
  52. import megengine.functional as F
  53. x = tensor([1, float("nan"), 0])
  54. print(F.isnan(x).numpy())
  55. Outputs:
  56. .. testoutput::
  57. [False True False]
  58. """
  59. return inp != inp
  60. def isinf(inp: Tensor) -> Tensor:
  61. r"""
  62. Returns a new tensor representing if each element is ``Inf`` or not.
  63. :param inp: input tensor.
  64. :return: result tensor.
  65. Examples:
  66. .. testcode::
  67. from megengine import tensor
  68. import megengine.functional as F
  69. x = tensor([1, float("inf"), 0])
  70. print(F.isinf(x).numpy())
  71. Outputs:
  72. .. testoutput::
  73. [False True False]
  74. """
  75. return abs(inp).astype("float32") == float("inf")
  76. def sign(inp: Tensor):
  77. r"""
  78. Returns a new tensor representing the sign of each element in input tensor.
  79. :param: input tensor.
  80. :return: the sign of input tensor.
  81. Examples:
  82. .. testcode::
  83. from megengine import tensor
  84. import megengine.functional as F
  85. x = tensor([1, -1, 0])
  86. print(F.sign(x).numpy())
  87. Outputs:
  88. .. testoutput::
  89. [ 1 -1 0]
  90. """
  91. return (inp > 0).astype(inp.dtype) - (inp < 0).astype(inp.dtype)
  92. def sum(
  93. inp: Tensor,
  94. axis: Optional[Union[int, Sequence[int]]] = None,
  95. keepdims: bool = False,
  96. ) -> Tensor:
  97. r"""
  98. Returns the sum of input tensor along given axis. If axis is a list of dimensions,
  99. reduce over all of them.
  100. :param inp: input tensor.
  101. :param axis: dimension to reduce. If None, all dimensions will be reduced.
  102. Default: None
  103. :param keepdims: whether the output tensor has axis retained or not.
  104. Default: False
  105. :return: output tensor.
  106. Examples:
  107. .. testcode::
  108. import numpy as np
  109. from megengine import tensor
  110. import megengine.functional as F
  111. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  112. out = F.sum(x)
  113. print(out.numpy())
  114. Outputs:
  115. .. testoutput::
  116. 21
  117. """
  118. return inp.sum(axis=axis, keepdims=keepdims)
  119. def prod(
  120. inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None, keepdims=False
  121. ) -> Tensor:
  122. r"""
  123. Returns the product of input tensor along given axis. If axis is a list of dimensions,
  124. reduce over all of them.
  125. :param inp: input tensor.
  126. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  127. :param keepdims: whether the output tensor has axis retained or not. Default: False
  128. :return: output tensor.
  129. Examples:
  130. .. testcode::
  131. import numpy as np
  132. from megengine import tensor
  133. import megengine.functional as F
  134. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  135. out = F.prod(x)
  136. print(out.numpy())
  137. Outputs:
  138. .. testoutput::
  139. 720
  140. """
  141. return inp.prod(axis=axis, keepdims=keepdims)
  142. def mean(
  143. inp: Tensor,
  144. axis: Optional[Union[int, Sequence[int]]] = None,
  145. keepdims: bool = False,
  146. ) -> Tensor:
  147. """
  148. Returns the mean value of input tensor along
  149. given axis. If axis is a list of dimensions,
  150. reduce over all of them.
  151. :param inp: input tensor.
  152. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  153. :param keepdims: whether the output tensor has axis retained or not. Default: False
  154. :return: output tensor.
  155. Examples:
  156. .. testcode::
  157. import numpy as np
  158. from megengine import tensor
  159. import megengine.functional as F
  160. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  161. out = F.mean(x)
  162. print(out.numpy())
  163. Outputs:
  164. .. testoutput::
  165. 3.5
  166. """
  167. return inp.mean(axis=axis, keepdims=keepdims)
  168. def var(
  169. inp: Tensor,
  170. axis: Optional[Union[int, Sequence[int]]] = None,
  171. keepdims: bool = False,
  172. ) -> Tensor:
  173. """
  174. Returns the variance value of input tensor along
  175. given axis. If axis is a list of dimensions,
  176. reduce over all of them.
  177. :param inp: input tensor.
  178. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  179. :param keepdims: whether the output tensor has axis retained or not. Default: False
  180. :return: output tensor.
  181. Examples:
  182. .. testcode::
  183. import numpy as np
  184. from megengine import tensor
  185. import megengine.functional as F
  186. data = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  187. out = F.var(data)
  188. print(out.numpy().round(decimals=4))
  189. Outputs:
  190. .. testoutput::
  191. 2.9167
  192. """
  193. if axis is None:
  194. m = mean(inp, axis=axis, keepdims=False)
  195. else:
  196. m = mean(inp, axis=axis, keepdims=True)
  197. v = inp - m
  198. return mean(v ** 2, axis=axis, keepdims=keepdims)
  199. def std(
  200. inp: Tensor,
  201. axis: Optional[Union[int, Sequence[int]]] = None,
  202. keepdims: bool = False,
  203. ) -> Tensor:
  204. """
  205. Returns the standard deviation of input tensor along
  206. given axis. If axis is a list of dimensions,
  207. reduce over all of them.
  208. :param inp: input tensor.
  209. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  210. :param keepdims: whether the output tensor has axis retained or not. Default: False
  211. :return: output tensor.
  212. Examples:
  213. .. testcode::
  214. import numpy as np
  215. from megengine import tensor
  216. import megengine.functional as F
  217. data = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  218. out = F.std(data, axis=1)
  219. print(out.numpy().round(decimals=4))
  220. Outputs:
  221. .. testoutput::
  222. [0.8165 0.8165]
  223. """
  224. return var(inp, axis=axis, keepdims=keepdims) ** 0.5
  225. def min(
  226. inp: Tensor,
  227. axis: Optional[Union[int, Sequence[int]]] = None,
  228. keepdims: bool = False,
  229. ) -> Tensor:
  230. r"""
  231. Returns the min value of input tensor along
  232. given axis. If axis is a list of dimensions,
  233. reduce over all of them.
  234. :param inp: input tensor.
  235. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  236. :param keepdims: whether the output tensor has axis retained or not. Default: False
  237. :return: output tensor.
  238. Examples:
  239. .. testcode::
  240. import numpy as np
  241. from megengine import tensor
  242. import megengine.functional as F
  243. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  244. out = F.min(x)
  245. print(out.numpy())
  246. Outputs:
  247. .. testoutput::
  248. 1
  249. """
  250. return inp.min(axis=axis, keepdims=keepdims)
  251. def max(
  252. inp: Tensor,
  253. axis: Optional[Union[int, Sequence[int]]] = None,
  254. keepdims: bool = False,
  255. ) -> Tensor:
  256. r"""
  257. Returns the max value of the input tensor along
  258. given axis. If axis is a list of dimensions,
  259. reduce over all of them.
  260. :param inp: input tensor.
  261. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  262. :param keepdims: whether the output tensor has axis retained or not. Default: False
  263. :return: output tensor.
  264. Examples:
  265. .. testcode::
  266. import numpy as np
  267. from megengine import tensor
  268. import megengine.functional as F
  269. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  270. out = F.max(x)
  271. print(out.numpy())
  272. Outputs:
  273. .. testoutput::
  274. 6
  275. """
  276. return inp.max(axis=axis, keepdims=keepdims)
  277. def norm(
  278. inp: Tensor, ord: float = None, axis: int = None, keepdims=False,
  279. ):
  280. """
  281. Calculates ``p``-norm of input tensor along
  282. given axis.
  283. :param inp: input tensor.
  284. :param ord: power of value applied to inp. Default: 2
  285. :param axis: dimension to reduce. If None, input must be a vector. Default: None
  286. :param keepdims: whether the output tensor has axis retained or not. Default: False
  287. :return: output tensor.
  288. Examples:
  289. .. testcode::
  290. import numpy as np
  291. from megengine import tensor
  292. import megengine.functional as F
  293. x = tensor(np.arange(-3, 3, dtype=np.float32))
  294. out = F.norm(x)
  295. print(out.numpy().round(decimals=4))
  296. Outputs:
  297. .. testoutput::
  298. 4.3589
  299. """
  300. if axis is None:
  301. if inp.ndim != 1:
  302. raise TypeError("axis is required unless input is a vector")
  303. if ord is None:
  304. ord = 2
  305. if ord == 0:
  306. return sum(inp != 0, axis=axis, keepdims=keepdims)
  307. if ord == math.inf:
  308. return max(abs(inp))
  309. if ord == -math.inf:
  310. return min(abs(inp))
  311. return sum(abs(inp) ** ord, axis=axis, keepdims=keepdims) ** (1.0 / ord)
  312. def argmin(
  313. inp: Tensor,
  314. axis: Optional[Union[int, Sequence[int]]] = None,
  315. keepdims: bool = False,
  316. ) -> Tensor:
  317. r"""
  318. Returns the indices of the minimum values along
  319. given axis. If axis is a list of dimensions,
  320. reduce over all of them.
  321. :param inp: input tensor.
  322. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  323. :param keepdims: whether the output tensor has axis retained or not. Default: False
  324. :return: output tensor.
  325. Examples:
  326. .. testcode::
  327. import numpy as np
  328. from megengine import tensor
  329. import megengine.functional as F
  330. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  331. out = F.argmin(x)
  332. print(out.numpy())
  333. Outputs:
  334. .. testoutput::
  335. 0
  336. """
  337. if isinstance(axis, collections.abc.Iterable):
  338. axis = list(axis)
  339. axis.sort(reverse=True)
  340. for ai in axis:
  341. op = builtin.Argmin(axis=ai)
  342. (inp,) = apply(op, inp)
  343. if not keepdims:
  344. inp = squeeze(inp, ai)
  345. return inp
  346. if axis is None:
  347. assert not keepdims, "can not set axis=None and keepdims=True"
  348. inp = inp.flatten()
  349. axis = 0
  350. op = builtin.Argmin(axis=axis)
  351. (result,) = apply(op, inp)
  352. if not keepdims:
  353. result = squeeze(result, axis)
  354. return result
  355. def argmax(
  356. inp: Tensor,
  357. axis: Optional[Union[int, Sequence[int]]] = None,
  358. keepdims: bool = False,
  359. ) -> Tensor:
  360. r"""
  361. Returns the indices of the maximum values along
  362. given axis. If axis is a list of dimensions,
  363. reduce over all of them.
  364. :param inp: input tensor.
  365. :param axis: dimension to reduce. If None, all dimensions will be reduced. Default: None
  366. :param keepdims: whether the output tensor has axis retained or not. Default: False
  367. :return: output tensor.
  368. Examples:
  369. .. testcode::
  370. import numpy as np
  371. from megengine import tensor
  372. import megengine.functional as F
  373. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  374. out = F.argmax(x)
  375. print(out.numpy())
  376. Outputs:
  377. .. testoutput::
  378. 5
  379. """
  380. if isinstance(axis, collections.abc.Iterable):
  381. axis = list(axis)
  382. axis.sort(reverse=True)
  383. for ai in axis:
  384. op = builtin.Argmax(axis=ai)
  385. (inp,) = apply(op, inp)
  386. if not keepdims:
  387. inp = squeeze(inp, ai)
  388. return inp
  389. if axis is None:
  390. assert not keepdims, "can not set axis=None and keepdims=True"
  391. inp = inp.flatten()
  392. axis = 0
  393. op = builtin.Argmax(axis=axis)
  394. (result,) = apply(op, inp)
  395. if not keepdims:
  396. result = squeeze(result, axis)
  397. return result
  398. def normalize(
  399. inp: Tensor, ord: float = None, axis: int = None, eps: float = 1e-12,
  400. ) -> Tensor:
  401. r"""
  402. Performs :math:`L_p` normalization of input tensor along
  403. given axis.
  404. For a tensor of shape :math:`(n_0, ..., n_{dim}, ..., n_k)`, each
  405. :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`axis` is transformed as:
  406. .. math::
  407. v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}.
  408. :param inp: input tensor.
  409. :param ord: power of value applied to input tensor. Default: 2
  410. :param axis: dimension to reduce.If None, input must be a vector. Default: None
  411. :param eps: a small value to avoid division by zero. Default: 1e-12
  412. :return: normalized output tensor.
  413. """
  414. if axis is None:
  415. return inp / clip(norm(inp, ord, axis), lower=eps)
  416. else:
  417. return inp / clip(norm(inp, ord, axis, keepdims=True), lower=eps)
  418. def argsort(inp: Tensor, descending: bool = False) -> Tensor:
  419. r"""
  420. Returns the indices that would sort the input tensor.
  421. :param inp: input tensor. If it's 2d, the result would be array of indices show how to sort each row in the input tensor.
  422. :param descending: sort in descending order, where the largest comes first. Default: False
  423. :return: indices of int32 indicates how to sort the input.
  424. Examples:
  425. .. testcode::
  426. import numpy as np
  427. from megengine import tensor
  428. import megengine.functional as F
  429. x = tensor(np.array([1,2], dtype=np.float32))
  430. indices = F.argsort(x)
  431. print(indices.numpy())
  432. Outputs:
  433. .. testoutput::
  434. [0 1]
  435. """
  436. assert len(inp.shape) <= 2, "Input should be 1d or 2d"
  437. if descending:
  438. order = "DESCENDING"
  439. else:
  440. order = "ASCENDING"
  441. op = builtin.Argsort(order=order)
  442. if len(inp.shape) == 1:
  443. inp = inp.reshape(1, -1)
  444. _, result = apply(op, inp)
  445. return result[0]
  446. _, result = apply(op, inp)
  447. return result
  448. def sort(inp: Tensor, descending: bool = False) -> Tuple[Tensor, Tensor]:
  449. r"""
  450. Returns sorted tensor and the indices would sort the input tensor.
  451. :param inp: input tensor. If it's 2d, the result would be sorted by row.
  452. :param descending: sort in descending order, where the largest comes first. Default: False
  453. :return: tuple of two tensors `(sorted_tensor, indices_of_int32)`.
  454. Examples:
  455. .. testcode::
  456. import numpy as np
  457. from megengine import tensor
  458. import megengine.functional as F
  459. x = tensor(np.array([1,2], dtype=np.float32))
  460. out, indices = F.sort(x)
  461. print(out.numpy())
  462. Outputs:
  463. .. testoutput::
  464. [1. 2.]
  465. """
  466. assert len(inp.shape) <= 2, "Input should be 1d or 2d"
  467. if descending:
  468. order = "DESCENDING"
  469. else:
  470. order = "ASCENDING"
  471. op = builtin.Argsort(order=order)
  472. if len(inp.shape) == 1:
  473. inp = inp.reshape(1, -1)
  474. tns, ind = apply(op, inp)
  475. return tns[0], ind[0]
  476. tns, ind = apply(op, inp)
  477. return tns, ind
  478. def topk(
  479. inp: Tensor,
  480. k: int,
  481. descending: bool = False,
  482. kth_only: bool = False,
  483. no_sort: bool = False,
  484. ) -> Tuple[Tensor, Tensor]:
  485. r"""
  486. Selects the ``Top-K`` (by default) smallest elements of 2d matrix by row.
  487. :param inp: input tensor. If input tensor is 2d, each row will be sorted.
  488. :param k: number of elements needed.
  489. :param descending: if True, return the largest elements instead. Default: False
  490. :param kth_only: if True, only the k-th element will be returned. Default: False
  491. :param no_sort: if True, the returned elements can be unordered. Default: False
  492. :return: tuple of two tensors `(topk_tensor, indices_of_int32)`.
  493. Examples:
  494. .. testcode::
  495. import numpy as np
  496. from megengine import tensor
  497. import megengine.functional as F
  498. x = tensor(np.array([2, 4, 6, 8, 7, 5, 3, 1], dtype=np.float32))
  499. top, indices = F.topk(x, 5)
  500. print(top.numpy(), indices.numpy())
  501. Outputs:
  502. .. testoutput::
  503. [1. 2. 3. 4. 5.] [7 0 6 1 5]
  504. """
  505. if descending:
  506. inp = -inp
  507. if kth_only:
  508. mode = "KTH_ONLY"
  509. elif no_sort:
  510. mode = "VALUE_IDX_NOSORT"
  511. else:
  512. mode = "VALUE_IDX_SORTED"
  513. op = builtin.TopK(mode=mode)
  514. if not isinstance(k, Tensor):
  515. (k,) = Const(k, dtype="int32", device=inp.device)()
  516. if len(inp.shape) == 1:
  517. inp = inp.reshape(1, -1)
  518. res = apply(op, inp, k)
  519. if kth_only:
  520. tns = res[0]
  521. else:
  522. tns, ind = res[0][0], res[1][0]
  523. else:
  524. res = apply(op, inp, k)
  525. if kth_only:
  526. tns = res
  527. else:
  528. tns, ind = res[0], res[1]
  529. if descending:
  530. tns = -tns
  531. return tns, ind
  532. def matinv(inp: Tensor) -> Tensor:
  533. """
  534. Computes the inverse of a batch of matrices; input must has shape [..., n, n].
  535. :param inp: input tensor.
  536. :return: output tensor.
  537. Examples:
  538. .. testcode::
  539. import numpy as np
  540. from megengine import tensor
  541. import megengine.functional as F
  542. data = tensor([[1.0, 0.0], [1.0, 1.0]])
  543. out = F.matinv(data)
  544. print(out.numpy())
  545. Outputs:
  546. .. testoutput::
  547. [[ 1. 0.]
  548. [-1. 1.]]
  549. """
  550. (result,) = apply(builtin.MatrixInverse(), inp)
  551. return result
  552. def matmul(
  553. inp1: Tensor,
  554. inp2: Tensor,
  555. transpose_a=False,
  556. transpose_b=False,
  557. compute_mode="DEFAULT",
  558. format="DEFAULT",
  559. ) -> Tensor:
  560. """
  561. Performs a matrix multiplication of the matrices ``inp1`` and ``inp2``.
  562. With different inputs dim, this function behaves differently:
  563. - Both 1-D tensor, simply forward to ``dot``.
  564. - Both 2-D tensor, normal matrix multiplication.
  565. - If one input tensor is 1-D, matrix vector multiplication.
  566. - If at least one tensor are 3-dimensional or >3-dimensional, the other tensor should have dim >= 2, the batched matrix-matrix is returned, and the tensor with smaller dimension will be broadcasted. For example:
  567. - inp1: `(n, k, m)`, inp2: `(n, m, p)`, return: `(n, k, p)`
  568. - inp1: `(n, k, m)`, inp2: `(m, p)`, return: `(n, k, p)`
  569. - inp1: `(n, j, k, m)`, inp2: `(n, j, m, p)`, return: `(n, j, k, p)`
  570. :param inp1: first matrix to be multiplied.
  571. :param inp2: second matrix to be multiplied.
  572. :return: output tensor.
  573. Examples:
  574. .. testcode::
  575. import numpy as np
  576. from megengine import tensor
  577. import megengine.functional as F
  578. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  579. data2 = tensor(np.arange(0, 6, dtype=np.float32).reshape(3, 2))
  580. out = F.matmul(data1, data2)
  581. print(out.numpy())
  582. Outputs:
  583. .. testoutput::
  584. [[10. 13.]
  585. [28. 40.]]
  586. """
  587. remove_row, remove_col = False, False
  588. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  589. dim1, dim2 = inp1.ndim, inp2.ndim
  590. # handle dim=1 cases, dot and matrix-vector multiplication
  591. if dim1 == 1 and dim2 == 1:
  592. return dot(inp1, inp2)
  593. # the underlying matmul op requires input dims to be at least 2
  594. if dim1 == 1:
  595. inp1 = expand_dims(inp1, 0)
  596. dim1 = 2
  597. remove_row = True
  598. if dim2 == 1:
  599. inp2 = expand_dims(inp2, 1)
  600. dim2 = 2
  601. remove_col = True
  602. batch_shape = None
  603. shape1 = inp1.shape
  604. shape2 = inp2.shape
  605. maxdim = dim1 if dim1 > dim2 else dim2
  606. if dim1 >= 3 or dim2 >= 3:
  607. if use_symbolic_shape():
  608. if dim1 > dim2:
  609. shape2 = concat([shape1[:-2], shape2[-2:]])
  610. inp2 = broadcast_to(inp2, shape2)
  611. if dim1 < dim2:
  612. shape1 = concat([shape2[:-2], shape1[-2:]])
  613. inp1 = broadcast_to(inp1, shape1)
  614. if maxdim > 3:
  615. batch_shape = shape1[:-2]
  616. # compress inputs to 3d
  617. (inp1,) = apply(
  618. builtin.Reshape(), inp1, concat([prod(shape1[:-2]), shape1[-2:]])
  619. )
  620. (inp2,) = apply(
  621. builtin.Reshape(), inp2, concat([prod(shape2[:-2]), shape2[-2:]])
  622. )
  623. else:
  624. if dim1 > dim2:
  625. shape2 = shape1[:-2] + shape2[-2:]
  626. inp2 = broadcast_to(inp2, shape2)
  627. if dim1 < dim2:
  628. shape1 = shape2[:-2] + shape1[-2:]
  629. inp1 = broadcast_to(inp1, shape1)
  630. if maxdim > 3:
  631. batch_shape = shape1[:-2]
  632. # compress inputs to 3d
  633. inp1 = inp1.reshape((-1, shape1[-2], shape1[-1]))
  634. inp2 = inp2.reshape((-1, shape2[-2], shape2[-1]))
  635. op = builtin.BatchedMatrixMul(
  636. transposeA=transpose_a,
  637. transposeB=transpose_b,
  638. compute_mode=compute_mode,
  639. format=format,
  640. strategy=get_execution_strategy(),
  641. )
  642. else:
  643. op = builtin.MatrixMul(
  644. transposeA=transpose_a,
  645. transposeB=transpose_b,
  646. compute_mode=compute_mode,
  647. format=format,
  648. strategy=get_execution_strategy(),
  649. )
  650. (result,) = apply(op, inp1, inp2)
  651. if maxdim > 3:
  652. if use_symbolic_shape():
  653. (result,) = apply(
  654. builtin.Reshape(), result, concat([batch_shape, result.shape[-2:]])
  655. )
  656. else:
  657. result = result.reshape(batch_shape + result.shape[-2:])
  658. if remove_row:
  659. result = squeeze(result, axis=-2)
  660. if remove_col:
  661. result = squeeze(result, axis=-1)
  662. return result
  663. def dot(inp1: Tensor, inp2: Tensor) -> Tensor:
  664. """
  665. Computes dot-product of two vectors ``inp1`` and ``inp2``.
  666. inputs must be 1-dimensional or scalar. A scalar input is automatically broadcasted.
  667. Refer to :func:`~.matmul` for more general usage.
  668. :param inp1: first vector.
  669. :param inp2: second vector.
  670. :return: output value.
  671. Examples:
  672. .. testcode::
  673. import numpy as np
  674. from megengine import tensor
  675. import megengine.functional as F
  676. data1 = tensor(np.arange(0, 6, dtype=np.float32))
  677. data2 = tensor(np.arange(0, 6, dtype=np.float32))
  678. out = F.dot(data1, data2)
  679. print(out.numpy())
  680. Outputs:
  681. .. testoutput::
  682. 55.
  683. """
  684. op = builtin.Dot()
  685. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  686. assert (
  687. inp1.ndim <= 1 and inp2.ndim <= 1
  688. ), "Input tensors for dot must be 1-dimensional or scalar"
  689. (result,) = apply(op, inp1, inp2)
  690. utils.setscalar(result)
  691. return result
  692. def svd(inp: Tensor, full_matrices=False, compute_uv=True) -> Tensor:
  693. """
  694. Computes the singular value decompositions of input matrix.
  695. :param inp: input matrix, must has shape `[..., M, N]`.
  696. :return: output matrices, `(U, sigma, V)`.
  697. Examples:
  698. .. testcode::
  699. import numpy as np
  700. from megengine import tensor
  701. import megengine.functional as F
  702. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2,3))
  703. _, y, _ = F.svd(x)
  704. print(y.numpy().round(decimals=3))
  705. Outputs:
  706. .. testoutput::
  707. [7.348 1. ]
  708. """
  709. op = builtin.SVD(full_matrices=full_matrices, compute_uv=compute_uv)
  710. U, sigma, V = apply(op, inp)
  711. return U, sigma, V

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