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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 functools
  11. import math
  12. import numbers
  13. from typing import Optional, Sequence, Tuple, Union
  14. from ..core.ops import builtin
  15. from ..core.ops._internal import param_defs as P
  16. from ..core.tensor import utils
  17. from ..core.tensor.core import apply
  18. from ..tensor import Tensor
  19. from .elemwise import clamp, exp, log, log1p
  20. from .tensor import remove_axis, reshape
  21. __all__ = [
  22. "all", # TODO
  23. "all_close", # TODO
  24. "any", # TODO
  25. "argmax",
  26. "argmin",
  27. "argsort",
  28. "isinf",
  29. "isnan", # TODO
  30. "max",
  31. "mean",
  32. "median", # TODO
  33. "min",
  34. "norm",
  35. "normalize",
  36. "prod",
  37. "sign", # TODO
  38. "sort",
  39. "std",
  40. "sum",
  41. "topk",
  42. "unique", # TODO
  43. "var",
  44. ]
  45. def all(inp):
  46. raise NotImplementedError
  47. def all_close(inp):
  48. raise NotImplementedError
  49. def any(inp):
  50. raise NotImplementedError
  51. def unique(inp):
  52. raise NotImplementedError
  53. def isnan(inp: Tensor) -> Tensor:
  54. r"""Returns a new tensor representing if each element is NaN or not.
  55. :param: inp
  56. :return: a new tensor representing if each element in :attr:`inp` is NaN or not.
  57. Examples:
  58. .. testcode::
  59. from megengine import tensor
  60. import megengine.functional as F
  61. x = tensor([1, float("nan"), 0])
  62. print(F.isnan(x))
  63. .. testoutput::
  64. Tensor([0 1 0], dtype=uint8)
  65. """
  66. raise NotImplementedError
  67. # return (inp != inp).astype("uint8")
  68. def isinf(inp: Tensor) -> Tensor:
  69. r"""Returns a new tensor representing if each element is Inf or not.
  70. :param: inp
  71. :return: a new tensor representing if each element in :attr:`inp` is Inf or not.
  72. Examples:
  73. .. testcode::
  74. from megengine import tensor
  75. import megengine.functional as F
  76. x = tensor([1, float("inf"), 0])
  77. print(F.isinf(x))
  78. .. testoutput::
  79. Tensor([0 1 0], dtype=uint8)
  80. """
  81. return (abs(inp).astype("float32") == float("inf")).astype("uint8")
  82. def sign(inp: Tensor):
  83. raise NotImplementedError
  84. def sum(
  85. inp: Tensor,
  86. axis: Optional[Union[int, Sequence[int]]] = None,
  87. keepdims: bool = False,
  88. ) -> Tensor:
  89. r"""Returns the sum of each row of the ``inp`` tensor in the given ``axis``.
  90. :param inp: The input tensor.
  91. :param axis: The dimension to reduce. If None, all the dimensions will be reduced.
  92. Default: None
  93. :param keepdims: Whether the output tensor has ``axis`` retained or not.
  94. Default: False
  95. :return: The output tensor
  96. Examples:
  97. .. testcode::
  98. import numpy as np
  99. from megengine import tensor
  100. import megengine.functional as F
  101. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  102. out = F.sum(data)
  103. print(out.numpy())
  104. .. testoutput::
  105. [21]
  106. """
  107. return inp.sum(axis=axis, keepdims=keepdims)
  108. def prod(
  109. inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None, keepdims=False
  110. ) -> Tensor:
  111. r"""
  112. Returns the element product of input tensor along given *axis*.
  113. :param inp: The input tensor
  114. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``
  115. :param keepdims: Whether the output tensor has *axis* retained or not. Default: ``False``
  116. :return: The output tensor
  117. Examples:
  118. .. testcode::
  119. import numpy as np
  120. from megengine import tensor
  121. import megengine.functional as F
  122. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  123. out = F.prod(data)
  124. print(out.numpy())
  125. Outputs:
  126. .. testoutput::
  127. [720]
  128. """
  129. return inp.prod(axis=axis, keepdims=keepdims)
  130. def mean(
  131. inp: Tensor,
  132. axis: Optional[Union[int, Sequence[int]]] = None,
  133. keepdims: bool = False,
  134. ) -> Tensor:
  135. """Returns the mean value of each row of the ``inp`` tensor in
  136. the given ``axis``. If axis is a list of dimensions,
  137. reduce over all of them.
  138. :param inp: The input tensor
  139. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  140. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: False
  141. Examples:
  142. .. testcode::
  143. import numpy as np
  144. from megengine import tensor
  145. import megengine.functional as F
  146. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  147. out = F.mean(data)
  148. print(out.numpy())
  149. .. testoutput::
  150. [3.5]
  151. """
  152. return inp.astype("float32").mean(axis=axis, keepdims=keepdims)
  153. def median(
  154. inp: Tensor,
  155. axis: Optional[Union[int, Sequence[int]]] = None,
  156. keepdims: bool = False,
  157. ) -> Tensor:
  158. raise NotImplementedError
  159. def var(
  160. inp: Tensor,
  161. axis: Optional[Union[int, Sequence[int]]] = None,
  162. keepdims: bool = False,
  163. ) -> Tensor:
  164. """Returns the variance value of input tensor along
  165. given ``axis``. If axis is a list of dimensions,
  166. reduce over all of them.
  167. :param inp: The input tensor.
  168. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``.
  169. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: ``False``.
  170. :return: The output tensor.
  171. Examples:
  172. .. testcode::
  173. import numpy as np
  174. from megengine import tensor
  175. import megengine.functional as F
  176. data = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  177. out = F.var(data)
  178. print(out.numpy())
  179. .. testoutput::
  180. [2.9166667]
  181. """
  182. if axis is None:
  183. m = mean(inp, axis=axis, keepdims=False)
  184. else:
  185. m = mean(inp, axis=axis, keepdims=True)
  186. v = inp - m
  187. return mean(v ** 2, axis=axis, keepdims=keepdims)
  188. def std(
  189. inp: Tensor,
  190. axis: Optional[Union[int, Sequence[int]]] = None,
  191. keepdims: bool = False,
  192. ) -> Tensor:
  193. """Returns the standard deviation of input tensor along
  194. given ``axis``. If axis is a list of dimensions,
  195. reduce over all of them.
  196. :param inp: The input tensor.
  197. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``.
  198. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: ``False``.
  199. :return: The output tensor.
  200. Examples:
  201. .. testcode::
  202. import numpy as np
  203. from megengine import tensor
  204. import megengine.functional as F
  205. data = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  206. out = F.std(data, axis=1)
  207. print(out.numpy())
  208. .. testoutput::
  209. [0.8164966 0.8164966]
  210. """
  211. return var(inp, axis=axis, keepdims=keepdims) ** 0.5
  212. def min(
  213. inp: Tensor,
  214. axis: Optional[Union[int, Sequence[int]]] = None,
  215. keepdims: bool = False,
  216. ) -> Tensor:
  217. r"""
  218. Returns the min value of input tensor along given *axis*.
  219. :param inp: The input tensor
  220. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  221. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  222. :return: The output tensor
  223. Examples:
  224. .. testcode::
  225. import numpy as np
  226. from megengine import tensor
  227. import megengine.functional as F
  228. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  229. y = F.min(x)
  230. print(y.numpy())
  231. Outputs:
  232. .. testoutput::
  233. [1]
  234. """
  235. return inp.min(axis=axis, keepdims=keepdims)
  236. def max(
  237. inp: Tensor,
  238. axis: Optional[Union[int, Sequence[int]]] = None,
  239. keepdims: bool = False,
  240. ) -> Tensor:
  241. r"""Returns the max value of the input tensor along given *axis*.
  242. :param inp: The input tensor
  243. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  244. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  245. :return: The output tensor
  246. Examples:
  247. .. testcode::
  248. import numpy as np
  249. from megengine import tensor
  250. import megengine.functional as F
  251. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  252. y = F.max(x)
  253. print(y.numpy())
  254. .. testoutput::
  255. [6]
  256. """
  257. return inp.max(axis=axis, keepdims=keepdims)
  258. def norm(
  259. inp: Tensor,
  260. p: int = 2,
  261. axis: Optional[Union[int, Sequence[int]]] = None,
  262. keepdims=False,
  263. ):
  264. """Calculate ``p``-norm of input tensor along certain axis.
  265. :param inp: The input tensor
  266. :param p: power of value ``p`` applied to ``inp``. Default: 2
  267. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  268. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: False
  269. :return: The output tensor
  270. Examples:
  271. .. testcode::
  272. import numpy as np
  273. from megengine import tensor
  274. import megengine.functional as F
  275. x = tensor(np.arange(-3, 3, dtype=np.float32).reshape(2,3))
  276. y = F.norm(x)
  277. print(y.numpy())
  278. .. testoutput::
  279. [4.358899]
  280. """
  281. if p == 0:
  282. return sum(inp != 0, axis=axis, keepdims=keepdims)
  283. if p == math.inf:
  284. return max(abs(inp))
  285. if p == -math.inf:
  286. return min(abs(inp))
  287. return sum(abs(inp) ** p, axis=axis, keepdims=keepdims) ** (1.0 / p)
  288. def argmin(
  289. inp: Tensor,
  290. axis: Optional[Union[int, Sequence[int]]] = None,
  291. keepdims: bool = False,
  292. ) -> Tensor:
  293. r"""Returns the indices of the minimum values along an axis
  294. :param inp: The input tensor
  295. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  296. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  297. :return: The output tensor
  298. Examples:
  299. .. testcode::
  300. import numpy as np
  301. from megengine import tensor
  302. import megengine.functional as F
  303. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  304. y = F.argmin(x)
  305. print(y.numpy())
  306. .. testoutput::
  307. [0]
  308. """
  309. if isinstance(axis, collections.abc.Iterable):
  310. axis = list(axis)
  311. axis.sort(reverse=True)
  312. for ai in axis:
  313. op = builtin.Argmin(axis=ai)
  314. (inp,) = apply(op, inp)
  315. if not keepdims:
  316. inp = remove_axis(inp, ai)
  317. return inp
  318. if axis is None:
  319. assert not keepdims, "can not set axis=None and keepdims=True"
  320. inp = inp.flatten()
  321. axis = 0
  322. op = builtin.Argmin(axis=axis)
  323. (result,) = apply(op, inp)
  324. if not keepdims:
  325. result = remove_axis(result, axis)
  326. return result
  327. def argmax(
  328. inp: Tensor,
  329. axis: Optional[Union[int, Sequence[int]]] = None,
  330. keepdims: bool = False,
  331. ) -> Tensor:
  332. r"""Returns the indices of the maximum values along an axis
  333. :param inp: The input tensor
  334. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  335. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  336. :return: The output tensor
  337. Examples:
  338. .. testcode::
  339. import numpy as np
  340. from megengine import tensor
  341. import megengine.functional as F
  342. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  343. y = F.argmax(x)
  344. print(y.numpy())
  345. .. testoutput::
  346. [5]
  347. """
  348. if isinstance(axis, collections.abc.Iterable):
  349. axis = list(axis)
  350. axis.sort(reverse=True)
  351. for ai in axis:
  352. op = builtin.Argmax(axis=ai)
  353. (inp,) = apply(op, inp)
  354. if not keepdims:
  355. inp = remove_axis(inp, ai)
  356. return inp
  357. if axis is None:
  358. assert not keepdims, "can not set axis=None and keepdims=True"
  359. inp = inp.flatten()
  360. axis = 0
  361. op = builtin.Argmax(axis=axis)
  362. (result,) = apply(op, inp)
  363. if not keepdims:
  364. result = remove_axis(result, axis)
  365. return result
  366. def normalize(
  367. inp: Tensor,
  368. p: int = 2,
  369. axis: Optional[Union[int, Sequence[int]]] = None,
  370. eps: float = 1e-12,
  371. ) -> Tensor:
  372. r"""Perform :math:`L_p` normalization of input tensor along certain axis.
  373. For a tensor :attr:`inp` of shape :math:`(n_0, ..., n_{dim}, ..., n_k)`, each
  374. :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`axis` is transformed as:
  375. .. math::
  376. v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}.
  377. :param inp: the input tensor
  378. :param p: power of value ``p`` applied to ``inp``. Default: 2
  379. :param axis: The dimension to reduce. If None, all the dimensions will be reduced
  380. to calculate the norm. Default: None
  381. :param eps: a small value to avoid division by zero. Default: 1e-12
  382. :return: the normalized output tensor
  383. """
  384. if axis is None:
  385. return inp / clamp(norm(inp, p, axis), lower=eps)
  386. else:
  387. return inp / clamp(norm(inp, p, axis, keepdims=True), lower=eps)
  388. def argsort(inp: Tensor, descending: bool = False) -> Tensor:
  389. r"""
  390. Sort the target 2d matrix by row, return both the sorted tensor and indices.
  391. :param inp: The input tensor, if 2d, each row will be sorted
  392. :param descending: Sort in descending order, where the largest comes first. Default: ``False``
  393. :return: Tuple of two tensors (sorted_tensor, indices_of_int32)
  394. Examples:
  395. .. testcode::
  396. import numpy as np
  397. from megengine import tensor
  398. import megengine.functional as F
  399. data = tensor(np.array([1,2], dtype=np.float32))
  400. indices = F.argsort(data)
  401. print(indices.numpy())
  402. Outputs:
  403. .. testoutput::
  404. [0 1]
  405. """
  406. assert len(inp.shape) <= 2, "Input should be 1d or 2d"
  407. if descending:
  408. order = P.Argsort.Order.DESCENDING
  409. else:
  410. order = P.Argsort.Order.ASCENDING
  411. op = builtin.Argsort(order=order)
  412. if len(inp.shape) == 1:
  413. inp = inp.reshape(1, -1)
  414. _, result = apply(op, inp)
  415. return result[0]
  416. _, result = apply(op, inp)
  417. return result
  418. def sort(inp: Tensor, descending: bool = False) -> Tuple[Tensor, Tensor]:
  419. assert len(inp.shape) <= 2, "Input should be 1d or 2d"
  420. if descending:
  421. order = P.Argsort.Order.DESCENDING
  422. else:
  423. order = P.Argsort.Order.ASCENDING
  424. op = builtin.Argsort(order=order)
  425. if len(inp.shape) == 1:
  426. inp = inp.reshape(1, -1)
  427. tns, ind = apply(op, inp)
  428. return tns[0], ind[0]
  429. tns, ind = apply(op, inp)
  430. return tns, ind
  431. def topk(
  432. inp: Tensor,
  433. k: int,
  434. descending: bool = False,
  435. kth_only: bool = False,
  436. no_sort: bool = False,
  437. ) -> Tuple[Tensor, Tensor]:
  438. r"""
  439. Selected the Top-K (by default) smallest elements of 2d matrix by row.
  440. :param inp: The input tensor, if 2d, each row will be sorted
  441. :param k: The number of elements needed
  442. :param descending: If true, return the largest elements instead. Default: ``False``
  443. :param kth_only: If true, only the k-th element will be returned. Default: ``False``
  444. :param no_sort: If true, the returned elements can be unordered. Default: ``False``
  445. :return: Tuple of two tensors (topk_tensor, indices_of_int32)
  446. Examples:
  447. .. testcode::
  448. import numpy as np
  449. from megengine import tensor
  450. import megengine.functional as F
  451. data = tensor(np.array([2, 4, 6, 8, 7, 5, 3, 1], dtype=np.float32))
  452. top, indices = F.topk(data, 5)
  453. print(top.numpy(), indices.numpy())
  454. Outputs:
  455. .. testoutput::
  456. [1. 2. 3. 4. 5.] [7 0 6 1 5]
  457. """
  458. if descending:
  459. inp = -inp
  460. Mode = P.TopK.Mode
  461. if kth_only:
  462. mode = Mode.KTH_ONLY
  463. elif no_sort:
  464. mode = Mode.VALUE_IDX_NOSORT
  465. else:
  466. mode = Mode.VALUE_IDX_SORTED
  467. op = builtin.TopK(mode=mode)
  468. if len(inp.shape) == 1:
  469. inp = inp.reshape(1, -1)
  470. res = apply(op, inp, Tensor(k, dtype="int32"))
  471. if kth_only:
  472. tns = res[0]
  473. else:
  474. tns, ind = res[0][0], res[1][0]
  475. else:
  476. res = apply(op, inp, Tensor(k, dtype="int32"))
  477. if kth_only:
  478. tns = res
  479. else:
  480. tns, ind = res[0], res[1]
  481. if descending:
  482. tns = -tns
  483. return tns, ind

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