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

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

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