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.

elemwise.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. # pylint: disable=unused-argument,invalid-name,redefined-builtin,arguments-out-of-order
  10. import numpy as np
  11. from ..core._imperative_rt.core2 import SymbolVar, apply
  12. from ..core.ops import builtin
  13. from ..core.ops.builtin import Elemwise
  14. from ..core.tensor.array_method import _elwise
  15. from ..core.tensor.utils import convert_inputs
  16. from ..tensor import Tensor
  17. from ..utils.deprecation import deprecated_func
  18. __all__ = [
  19. "abs",
  20. "add",
  21. "acos",
  22. "asin",
  23. "atan",
  24. "atan2",
  25. "asinh",
  26. "acosh",
  27. "atanh",
  28. "ceil",
  29. "clip",
  30. "cos",
  31. "cosh",
  32. "div",
  33. "equal",
  34. "exp",
  35. "expm1",
  36. "floor",
  37. "floor_div",
  38. "greater",
  39. "greater_equal",
  40. "left_shift",
  41. "less",
  42. "less_equal",
  43. "log",
  44. "log1p",
  45. "logical_and",
  46. "logical_not",
  47. "logical_or",
  48. "logical_xor",
  49. "logaddexp",
  50. "maximum",
  51. "minimum",
  52. "mod",
  53. "mul",
  54. "neg",
  55. "not_equal",
  56. "pow",
  57. "right_shift",
  58. "round",
  59. "sin",
  60. "sinh",
  61. "sqrt",
  62. "square",
  63. "sub",
  64. "tan",
  65. "tanh",
  66. ]
  67. def _elemwise_multi_type(*args, mode, **kwargs):
  68. op = builtin.ElemwiseMultiType(mode=mode, **kwargs)
  69. args = convert_inputs(*args)
  70. (result,) = apply(op, *args)
  71. return result
  72. # math operations
  73. def add(x, y):
  74. r"""Element-wise `addition`.
  75. Examples:
  76. .. testcode::
  77. import numpy as np
  78. from megengine import tensor
  79. import megengine.functional as F
  80. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  81. y = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  82. out = F.add(x, y)
  83. print(out.numpy())
  84. Outputs:
  85. .. testoutput::
  86. [[ 0. 2. 4.]
  87. [ 6. 8. 10.]]
  88. """
  89. return _elwise(x, y, mode=Elemwise.Mode.ADD)
  90. def sub(x, y):
  91. r"""Element-wise `sub`.
  92. Examples:
  93. .. testcode::
  94. import numpy as np
  95. from megengine import tensor
  96. import megengine.functional as F
  97. x = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  98. y = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  99. out = F.sub(x, y)
  100. print(out.numpy())
  101. Outputs:
  102. .. testoutput::
  103. [[1. 1. 1.]
  104. [1. 1. 1.]]
  105. """
  106. return _elwise(x, y, mode=Elemwise.Mode.SUB)
  107. def mul(x: Tensor, y: Tensor) -> Tensor:
  108. r"""Calculates the product for each element :math:`x_i` of the input tensor `x` with the respective element :math:`y_i` of the input tensor `y`.
  109. Note:
  110. * If either :math:`x_i` or :math:`y_i` is `NaN`, the result is `NaN`.
  111. * If :math:`x_i` is either `+infinity` or `-infinity` and :math:`y_i` is either `+0` or `-0`, the result is `NaN`.
  112. * If :math:`x_i` is either `+0` or `-0` and :math:`y_i` is either `+infinity` or `-infinity`, the result is `NaN`.
  113. * If :math:`x_i` and :math:`y_i` have different mathematical signs, the result has a negative mathematical sign, unless the result is `NaN`.
  114. * If :math:`x_i` is either `+infinity` or `-infinity` and :math:`y_i` is either `+infinity` or `-infinity`,
  115. the result is a signed infinity with the mathematical sign determined by the rule already stated above.
  116. * If :math:`x_i` is either `+infinity` or `-infinity` and :math:`y_i` is a nonzero finite number,
  117. the result is a signed infinity with the mathematical sign determined by the rule already stated above.
  118. * If :math:`x_i` is a nonzero finite number and :math:`y_i` is either `+infinity` or `-infinity`,
  119. the result is a signed infinity with the mathematical sign determined by the rule already stated above.
  120. * In the remaining cases, where neither `infinity` nor `NaN` is involved,
  121. the product must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported rounding mode.
  122. If the magnitude is too large to represent, the result is an `infinity` of appropriate mathematical sign.
  123. If the magnitude is too small to represent, the result is a zero of appropriate mathematical sign.
  124. * Floating-point multiplication is not always associative due to finite precision.
  125. Args:
  126. x: first input tensor. Should have a numeric data type.
  127. y: second input tensor. Must be compatible with `x` (see :ref:`broadcasting-rule` ). Should have a numeric data type.
  128. Returns:
  129. A tensor containing the element-wise products. The returned array must have a data type determined by :ref:`dtype-promotion`.
  130. Examples:
  131. >>> F.mul(2, 3)
  132. Tensor(6, dtype=int32, device=xpux:0)
  133. >>> F.mul(2.0, 3.0)
  134. Tensor(6.0, device=xpux:0)
  135. >>> x = F.arange(6.0).reshape(2, 3)
  136. >>> y = F.arange(3.0)
  137. >>> F.mul(x, y)
  138. Tensor([[ 0. 1. 4.]
  139. [ 0. 4. 10.]], device=xpux:0)
  140. The `*` operator can be used as a shorthand for :func:`~.functional.mul` on tensors.
  141. >>> x = F.arange(6.0).reshape(2, 3)
  142. >>> y = F.arange(3.0)
  143. >>> x * y
  144. Tensor([[ 0. 1. 4.]
  145. [ 0. 4. 10.]], device=xpux:0)
  146. """
  147. return _elwise(x, y, mode=Elemwise.Mode.MUL)
  148. def div(x, y):
  149. r"""Element-wise `(x / y)`."""
  150. return _elwise(x, y, mode=Elemwise.Mode.TRUE_DIV)
  151. def floor_div(x, y):
  152. r"""Element-wise `floor(x / y)`."""
  153. return _elwise(x, y, mode=Elemwise.Mode.FLOOR_DIV)
  154. def neg(x):
  155. r"""Element-wise `negation`."""
  156. return _elwise(x, mode=Elemwise.Mode.NEGATE)
  157. def pow(x, y):
  158. r"""Element-wise `power`."""
  159. return _elwise(x, y, mode=Elemwise.Mode.POW)
  160. def mod(x, y):
  161. r"""Element-wise `remainder of division`."""
  162. return _elwise(x, y, mode=Elemwise.Mode.MOD)
  163. def abs(x):
  164. r"""Element-wise `absolute value`."""
  165. return _elwise(x, mode=Elemwise.Mode.ABS)
  166. def exp(x):
  167. r"""Element-wise `exponential`."""
  168. return _elwise(x, mode=Elemwise.Mode.EXP)
  169. def expm1(x):
  170. r"""Element-wise `exp(x)-1`."""
  171. return _elwise(x, mode=Elemwise.Mode.EXPM1)
  172. def log(x):
  173. r"""Element-wise `logarithm (base e)`."""
  174. return _elwise(x, mode=Elemwise.Mode.LOG)
  175. def log1p(x):
  176. r"""Element-wise `log(x+1) (base e)`."""
  177. return _elwise(x, mode=Elemwise.Mode.LOG1P)
  178. def sqrt(x: Tensor) -> Tensor:
  179. r"""Element-wise `sqrt`.
  180. Examples:
  181. .. testcode::
  182. import numpy as np
  183. from megengine import tensor
  184. import megengine.functional as F
  185. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  186. out = F.sqrt(x)
  187. print(out.numpy().round(decimals=4))
  188. Outputs:
  189. .. testoutput::
  190. [[0. 1. 1.4142]
  191. [1.7321 2. 2.2361]]
  192. """
  193. return x ** 0.5
  194. def square(x: Tensor) -> Tensor:
  195. r"""Element-wise `square`.
  196. Examples:
  197. .. testcode::
  198. import numpy as np
  199. import megengine as mge
  200. import megengine.functional as F
  201. data = mge.tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  202. out = F.square(data)
  203. print(out.numpy().round(decimals=4))
  204. Outputs:
  205. .. testoutput::
  206. [[ 0. 1. 4.]
  207. [ 9. 16. 25.]]
  208. """
  209. return x ** 2
  210. def round(x):
  211. r"""Element-wise `rounding to int`."""
  212. return _elwise(x, mode=Elemwise.Mode.ROUND)
  213. def ceil(x):
  214. r"""Element-wise `ceiling`."""
  215. return _elwise(x, mode=Elemwise.Mode.CEIL)
  216. def floor(x):
  217. r"""Element-wise `floor`."""
  218. return _elwise(x, mode=Elemwise.Mode.FLOOR)
  219. def maximum(x, y):
  220. r"""Element-wise `maximum of array elements`."""
  221. return _elwise(x, y, mode=Elemwise.Mode.MAX)
  222. def minimum(x, y):
  223. r"""Element-wise `minimum of array elements`."""
  224. return _elwise(x, y, mode=Elemwise.Mode.MIN)
  225. # trigonometric functions
  226. def cos(x):
  227. r"""Element-wise `cosine`.
  228. Examples:
  229. .. testcode::
  230. import numpy as np
  231. from megengine import tensor
  232. import megengine.functional as F
  233. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  234. out = F.cos(x)
  235. print(out.numpy().round(decimals=4))
  236. Outputs:
  237. .. testoutput::
  238. [[ 1. 0.5403 -0.4161]
  239. [-0.99 -0.6536 0.2837]]
  240. """
  241. return _elwise(x, mode=Elemwise.Mode.COS)
  242. def sin(x):
  243. r"""Element-wise `sine`."""
  244. return _elwise(x, mode=Elemwise.Mode.SIN)
  245. def tan(x):
  246. r"""Element-wise `tangent`."""
  247. return sin(x) / cos(x)
  248. def acos(x):
  249. r"""Element-wise `inverse cosine`."""
  250. return _elwise(x, mode=Elemwise.Mode.ACOS)
  251. def asin(x):
  252. r"""Element-wise `inverse sine`."""
  253. return _elwise(x, mode=Elemwise.Mode.ASIN)
  254. def atan(x):
  255. r"""Element-wise `inverse tangent`."""
  256. return _elwise(x, 1, mode=Elemwise.Mode.ATAN2)
  257. def atan2(y, x):
  258. r"""Element-wise `2-argument arctangent`."""
  259. return _elwise(y, x, mode=Elemwise.Mode.ATAN2)
  260. def cosh(x):
  261. r"""Element-wise `hyperbolic cosine`."""
  262. return 0.5 * (exp(x) + exp(-x))
  263. def sinh(x):
  264. r"""Element-wise `hyperbolic sine`."""
  265. u = expm1(x)
  266. return 0.5 * u / (u + 1) * (u + 2)
  267. def tanh(x):
  268. r"""Element-wise `hyperbolic tangent`."""
  269. return _elwise(x, mode=Elemwise.Mode.TANH)
  270. def asinh(x):
  271. r"""Element-wise `inverse hyperbolic sine`."""
  272. return log(x + (x ** 2 + 1) ** 0.5)
  273. def acosh(x):
  274. r"""Element-wise `inverse hyperbolic cosine`."""
  275. return log(x + (x ** 2 - 1) ** 0.5)
  276. def atanh(x):
  277. r"""Element-wise `inverse hyperbolic tangent`."""
  278. return log1p(2 * x / (1 - x)) / 2
  279. # bit-twiddling functions
  280. def left_shift(x, y):
  281. r"""Element-wise `bitwise binary: x << y`.
  282. Examples:
  283. .. testcode::
  284. import numpy as np
  285. from megengine import tensor
  286. import megengine.functional as F
  287. x = tensor(np.arange(0, 6, dtype=np.int32).reshape(2, 3))
  288. out = F.left_shift(x, 2)
  289. print(out.numpy())
  290. Outputs:
  291. .. testoutput::
  292. [[ 0 4 8]
  293. [12 16 20]]
  294. """
  295. return _elwise(x, y, mode=Elemwise.Mode.SHL)
  296. def right_shift(x, y):
  297. r"""Element-wise `bitwise binary: x >> y`."""
  298. return _elwise(x, y, mode=Elemwise.Mode.SHR)
  299. # logical functions
  300. def logical_and(x, y):
  301. r"""Element-wise `logical and: x && y`."""
  302. return _elwise(x, y, mode=Elemwise.Mode.AND)
  303. def logical_not(x):
  304. r"""Element-wise `logical not: ~x`."""
  305. return _elwise(x, mode=Elemwise.Mode.NOT)
  306. def logical_or(x, y):
  307. r"""Element-wise `logical or: x || y`."""
  308. return _elwise(x, y, mode=Elemwise.Mode.OR)
  309. def logical_xor(x, y):
  310. r"""Element-wise `logical xor: x ^ y`."""
  311. return _elwise(x, y, mode=Elemwise.Mode.XOR)
  312. def logaddexp(x: Tensor, y: Tensor) -> Tensor:
  313. r"""Element-wise `numerically stable log(exp(x) + exp(y)`
  314. """
  315. return _elwise(x, y, mode=Elemwise.Mode.LOG_SUM_EXP)
  316. # comparison functions
  317. def equal(x, y):
  318. r"""Element-wise `(x == y)`.
  319. Examples:
  320. .. testcode::
  321. import numpy as np
  322. from megengine import tensor
  323. import megengine.functional as F
  324. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  325. y = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  326. out = F.equal(x, y)
  327. print(out.numpy())
  328. Outputs:
  329. .. testoutput::
  330. [[1. 1. 1.]
  331. [1. 1. 1.]]
  332. """
  333. return _elwise(x, y, mode=Elemwise.Mode.EQ)
  334. def not_equal(x, y):
  335. r"""Element-wise `(x != y)`."""
  336. return x != y
  337. def less(x, y):
  338. r"""Element-wise `(x < y)`."""
  339. return _elwise(x, y, mode=Elemwise.Mode.LT)
  340. def less_equal(x, y):
  341. r"""Element-wise `(x <= y)`."""
  342. return _elwise(x, y, mode=Elemwise.Mode.LEQ)
  343. def greater(x, y):
  344. r"""Element-wise `(x > y)`."""
  345. return _elwise(y, x, mode=Elemwise.Mode.LT)
  346. def greater_equal(x, y):
  347. r"""Element-wise `(x >= y)`."""
  348. return _elwise(y, x, mode=Elemwise.Mode.LEQ)
  349. # other functions
  350. def clip(x: Tensor, lower=None, upper=None) -> Tensor:
  351. r"""Clamps all elements in input tensor into the range ``[ lower, upper ]`` and returns
  352. a resulting tensor:
  353. .. math::
  354. y_i = \begin{cases}
  355. \text{lower} & \text{if } x_i < \text{lower} \\
  356. x_i & \text{if } \text{lower} \leq x_i \leq \text{upper} \\
  357. \text{upper} & \text{if } x_i > \text{upper}
  358. \end{cases}
  359. Args:
  360. x: input tensor.
  361. lower: lower-bound of the range to be clamped to.
  362. upper: upper-bound of the range to be clamped to.
  363. Returns:
  364. output clamped tensor.
  365. Examples:
  366. .. testcode::
  367. import numpy as np
  368. from megengine import tensor
  369. import megengine.functional as F
  370. a = tensor(np.arange(5).astype(np.int32))
  371. print(F.clip(a, 2, 4).numpy())
  372. print(F.clip(a, lower=3).numpy())
  373. print(F.clip(a, upper=3).numpy())
  374. Outputs:
  375. .. testoutput::
  376. [2 2 2 3 4]
  377. [3 3 3 3 4]
  378. [0 1 2 3 3]
  379. """
  380. assert (
  381. lower is not None or upper is not None
  382. ), "At least one of 'lower' or 'upper' must not be None"
  383. if lower is not None:
  384. if upper is not None:
  385. return minimum(maximum(x, lower), upper)
  386. else:
  387. return maximum(x, lower)
  388. else:
  389. return minimum(x, upper)
  390. sigmoid = deprecated_func("1.3", "megengine.functional.nn", "sigmoid", True)
  391. hsigmoid = deprecated_func("1.3", "megengine.functional.nn", "hsigmoid", True)
  392. relu = deprecated_func("1.3", "megengine.functional.nn", "relu", True)
  393. relu6 = deprecated_func("1.3", "megengine.functional.nn", "relu6", True)
  394. hswish = deprecated_func("1.3", "megengine.functional.nn", "hswish", True)