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.

math.py 30 kB

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

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