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

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

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