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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. "maximum",
  50. "minimum",
  51. "mod",
  52. "mul",
  53. "neg",
  54. "not_equal",
  55. "pow",
  56. "right_shift",
  57. "round",
  58. "sin",
  59. "sinh",
  60. "sqrt",
  61. "square",
  62. "sub",
  63. "tan",
  64. "tanh",
  65. ]
  66. def _elemwise_multi_type(*args, mode, **kwargs):
  67. op = builtin.ElemwiseMultiType(mode=mode, **kwargs)
  68. args = convert_inputs(*args)
  69. (result,) = apply(op, *args)
  70. return result
  71. # math operations
  72. def add(x, y):
  73. r"""Element-wise `addition`.
  74. Examples:
  75. .. testcode::
  76. import numpy as np
  77. from megengine import tensor
  78. import megengine.functional as F
  79. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  80. y = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  81. out = F.add(x, y)
  82. print(out.numpy())
  83. Outputs:
  84. .. testoutput::
  85. [[ 0. 2. 4.]
  86. [ 6. 8. 10.]]
  87. """
  88. return _elwise(x, y, mode=Elemwise.Mode.ADD)
  89. def sub(x, y):
  90. r"""Element-wise `subtraction`."""
  91. return _elwise(x, y, mode=Elemwise.Mode.SUB)
  92. def mul(x, y):
  93. r"""Element-wise `multiplication`."""
  94. return _elwise(x, y, mode=Elemwise.Mode.MUL)
  95. def div(x, y):
  96. r"""Element-wise `(x / y)`."""
  97. return _elwise(x, y, mode=Elemwise.Mode.TRUE_DIV)
  98. def floor_div(x, y):
  99. r"""Element-wise `floor(x / y)`."""
  100. return _elwise(x, y, mode=Elemwise.Mode.FLOOR_DIV)
  101. def neg(x):
  102. r"""Element-wise `negation`."""
  103. return _elwise(x, mode=Elemwise.Mode.NEGATE)
  104. def pow(x, y):
  105. r"""Element-wise `power`."""
  106. return _elwise(x, y, mode=Elemwise.Mode.POW)
  107. def mod(x, y):
  108. r"""Element-wise `remainder of division`."""
  109. return _elwise(x, y, mode=Elemwise.Mode.MOD)
  110. def abs(x):
  111. r"""Element-wise `absolute value`."""
  112. return _elwise(x, mode=Elemwise.Mode.ABS)
  113. def exp(x):
  114. r"""Element-wise `exponential`."""
  115. return _elwise(x, mode=Elemwise.Mode.EXP)
  116. def expm1(x):
  117. r"""Element-wise `exp(x)-1`."""
  118. return _elwise(x, mode=Elemwise.Mode.EXPM1)
  119. def log(x):
  120. r"""Element-wise `logarithm (base e)`."""
  121. return _elwise(x, mode=Elemwise.Mode.LOG)
  122. def log1p(x):
  123. r"""Element-wise `log(x+1) (base e)`."""
  124. return _elwise(x, mode=Elemwise.Mode.LOG1P)
  125. def sqrt(x: Tensor) -> Tensor:
  126. r"""Element-wise `sqrt`.
  127. Examples:
  128. .. testcode::
  129. import numpy as np
  130. from megengine import tensor
  131. import megengine.functional as F
  132. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  133. out = F.sqrt(x)
  134. print(out.numpy().round(decimals=4))
  135. Outputs:
  136. .. testoutput::
  137. [[0. 1. 1.4142]
  138. [1.7321 2. 2.2361]]
  139. """
  140. return x ** 0.5
  141. def square(x: Tensor) -> Tensor:
  142. r"""Element-wise `square`.
  143. Examples:
  144. .. testcode::
  145. import numpy as np
  146. import megengine as mge
  147. import megengine.functional as F
  148. data = mge.tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  149. out = F.square(data)
  150. print(out.numpy().round(decimals=4))
  151. Outputs:
  152. .. testoutput::
  153. [[ 0. 1. 4.]
  154. [ 9. 16. 25.]]
  155. """
  156. return x ** 2
  157. def round(x):
  158. r"""Element-wise `rounding to int`."""
  159. return _elwise(x, mode=Elemwise.Mode.ROUND)
  160. def ceil(x):
  161. r"""Element-wise `ceiling`."""
  162. return _elwise(x, mode=Elemwise.Mode.CEIL)
  163. def floor(x):
  164. r"""Element-wise `floor`."""
  165. return _elwise(x, mode=Elemwise.Mode.FLOOR)
  166. def maximum(x, y):
  167. r"""Element-wise `maximum of array elements`."""
  168. return _elwise(x, y, mode=Elemwise.Mode.MAX)
  169. def minimum(x, y):
  170. r"""Element-wise `minimum of array elements`."""
  171. return _elwise(x, y, mode=Elemwise.Mode.MIN)
  172. # trigonometric functions
  173. def cos(x):
  174. r"""Element-wise `cosine`.
  175. Examples:
  176. .. testcode::
  177. import numpy as np
  178. from megengine import tensor
  179. import megengine.functional as F
  180. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  181. out = F.cos(x)
  182. print(out.numpy().round(decimals=4))
  183. Outputs:
  184. .. testoutput::
  185. [[ 1. 0.5403 -0.4161]
  186. [-0.99 -0.6536 0.2837]]
  187. """
  188. return _elwise(x, mode=Elemwise.Mode.COS)
  189. def sin(x):
  190. r"""Element-wise `sine`."""
  191. return _elwise(x, mode=Elemwise.Mode.SIN)
  192. def tan(x):
  193. r"""Element-wise `tangent`."""
  194. return sin(x) / cos(x)
  195. def acos(x):
  196. r"""Element-wise `inverse cosine`."""
  197. return _elwise(x, mode=Elemwise.Mode.ACOS)
  198. def asin(x):
  199. r"""Element-wise `inverse sine`."""
  200. return _elwise(x, mode=Elemwise.Mode.ASIN)
  201. def atan(x):
  202. r"""Element-wise `inverse tangent`."""
  203. return _elwise(x, 1, mode=Elemwise.Mode.ATAN2)
  204. def atan2(y, x):
  205. r"""Element-wise `2-argument arctangent`."""
  206. return _elwise(y, x, mode=Elemwise.Mode.ATAN2)
  207. def cosh(x):
  208. r"""Element-wise `hyperbolic cosine`."""
  209. return 0.5 * (exp(x) + exp(-x))
  210. def sinh(x):
  211. r"""Element-wise `hyperbolic sine`."""
  212. u = expm1(x)
  213. return 0.5 * u / (u + 1) * (u + 2)
  214. def tanh(x):
  215. r"""Element-wise `hyperbolic tangent`."""
  216. return _elwise(x, mode=Elemwise.Mode.TANH)
  217. def asinh(x):
  218. r"""Element-wise `inverse hyperbolic sine`."""
  219. return log(x + (x ** 2 + 1) ** 0.5)
  220. def acosh(x):
  221. r"""Element-wise `inverse hyperbolic cosine`."""
  222. return log(x + (x ** 2 - 1) ** 0.5)
  223. def atanh(x):
  224. r"""Element-wise `inverse hyperbolic tangent`."""
  225. return log1p(2 * x / (1 - x)) / 2
  226. # bit-twiddling functions
  227. def left_shift(x, y):
  228. r"""Element-wise `bitwise binary: x << y`.
  229. Examples:
  230. .. testcode::
  231. import numpy as np
  232. from megengine import tensor
  233. import megengine.functional as F
  234. x = tensor(np.arange(0, 6, dtype=np.int32).reshape(2, 3))
  235. out = F.left_shift(x, 2)
  236. print(out.numpy())
  237. Outputs:
  238. .. testoutput::
  239. [[ 0 4 8]
  240. [12 16 20]]
  241. """
  242. return _elwise(x, y, mode=Elemwise.Mode.SHL)
  243. def right_shift(x, y):
  244. r"""Element-wise `bitwise binary: x >> y`."""
  245. return _elwise(x, y, mode=Elemwise.Mode.SHR)
  246. # logical functions
  247. def logical_and(x, y):
  248. r"""Element-wise `logical and: x && y`."""
  249. return _elwise(x, y, mode=Elemwise.Mode.AND)
  250. def logical_not(x):
  251. r"""Element-wise `logical not: ~x`."""
  252. return _elwise(x, mode=Elemwise.Mode.NOT)
  253. def logical_or(x, y):
  254. r"""Element-wise `logical or: x || y`."""
  255. return _elwise(x, y, mode=Elemwise.Mode.OR)
  256. def logical_xor(x, y):
  257. r"""Element-wise `logical xor: x ^ y`."""
  258. return _elwise(x, y, mode=Elemwise.Mode.XOR)
  259. # comparison functions
  260. def equal(x, y):
  261. r"""Element-wise `(x == y)`.
  262. Examples:
  263. .. testcode::
  264. import numpy as np
  265. from megengine import tensor
  266. import megengine.functional as F
  267. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  268. y = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  269. out = F.equal(x, y)
  270. print(out.numpy())
  271. Outputs:
  272. .. testoutput::
  273. [[1. 1. 1.]
  274. [1. 1. 1.]]
  275. """
  276. return _elwise(x, y, mode=Elemwise.Mode.EQ)
  277. def not_equal(x, y):
  278. r"""Element-wise `(x != y)`."""
  279. return x != y
  280. def less(x, y):
  281. r"""Element-wise `(x < y)`."""
  282. return _elwise(x, y, mode=Elemwise.Mode.LT)
  283. def less_equal(x, y):
  284. r"""Element-wise `(x <= y)`."""
  285. return _elwise(x, y, mode=Elemwise.Mode.LEQ)
  286. def greater(x, y):
  287. r"""Element-wise `(x > y)`."""
  288. return _elwise(y, x, mode=Elemwise.Mode.LT)
  289. def greater_equal(x, y):
  290. r"""Element-wise `(x >= y)`."""
  291. return _elwise(y, x, mode=Elemwise.Mode.LEQ)
  292. # other functions
  293. def clip(x: Tensor, lower=None, upper=None) -> Tensor:
  294. r"""Clamps all elements in input tensor into the range ``[ lower, upper ]`` and returns
  295. a resulting tensor:
  296. .. math::
  297. y_i = \begin{cases}
  298. \text{lower} & \text{if } x_i < \text{lower} \\
  299. x_i & \text{if } \text{lower} \leq x_i \leq \text{upper} \\
  300. \text{upper} & \text{if } x_i > \text{upper}
  301. \end{cases}
  302. Args:
  303. x: input tensor.
  304. lower: lower-bound of the range to be clamped to.
  305. upper: upper-bound of the range to be clamped to.
  306. Returns:
  307. output clamped tensor.
  308. Examples:
  309. .. testcode::
  310. import numpy as np
  311. from megengine import tensor
  312. import megengine.functional as F
  313. a = tensor(np.arange(5).astype(np.int32))
  314. print(F.clip(a, 2, 4).numpy())
  315. print(F.clip(a, lower=3).numpy())
  316. print(F.clip(a, upper=3).numpy())
  317. Outputs:
  318. .. testoutput::
  319. [2 2 2 3 4]
  320. [3 3 3 3 4]
  321. [0 1 2 3 3]
  322. """
  323. assert (
  324. lower is not None or upper is not None
  325. ), "At least one of 'lower' or 'upper' must not be None"
  326. if lower is not None:
  327. if upper is not None:
  328. return minimum(maximum(x, lower), upper)
  329. else:
  330. return maximum(x, lower)
  331. else:
  332. return minimum(x, upper)
  333. sigmoid = deprecated_func("1.3", "megengine.functional.nn", "sigmoid", True)
  334. hsigmoid = deprecated_func("1.3", "megengine.functional.nn", "hsigmoid", True)
  335. relu = deprecated_func("1.3", "megengine.functional.nn", "relu", True)
  336. relu6 = deprecated_func("1.3", "megengine.functional.nn", "relu6", True)
  337. hswish = deprecated_func("1.3", "megengine.functional.nn", "hswish", True)

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