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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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, y):
  108. r"""Element-wise `multiplication`."""
  109. return _elwise(x, y, mode=Elemwise.Mode.MUL)
  110. def div(x, y):
  111. r"""Element-wise `(x / y)`."""
  112. return _elwise(x, y, mode=Elemwise.Mode.TRUE_DIV)
  113. def floor_div(x, y):
  114. r"""Element-wise `floor(x / y)`."""
  115. return _elwise(x, y, mode=Elemwise.Mode.FLOOR_DIV)
  116. def neg(x):
  117. r"""Element-wise `negation`."""
  118. return _elwise(x, mode=Elemwise.Mode.NEGATE)
  119. def pow(x, y):
  120. r"""Element-wise `power`."""
  121. return _elwise(x, y, mode=Elemwise.Mode.POW)
  122. def mod(x, y):
  123. r"""Element-wise `remainder of division`."""
  124. return _elwise(x, y, mode=Elemwise.Mode.MOD)
  125. def abs(x):
  126. r"""Element-wise `absolute value`."""
  127. return _elwise(x, mode=Elemwise.Mode.ABS)
  128. def exp(x):
  129. r"""Element-wise `exponential`."""
  130. return _elwise(x, mode=Elemwise.Mode.EXP)
  131. def expm1(x):
  132. r"""Element-wise `exp(x)-1`."""
  133. return _elwise(x, mode=Elemwise.Mode.EXPM1)
  134. def log(x):
  135. r"""Element-wise `logarithm (base e)`."""
  136. return _elwise(x, mode=Elemwise.Mode.LOG)
  137. def log1p(x):
  138. r"""Element-wise `log(x+1) (base e)`."""
  139. return _elwise(x, mode=Elemwise.Mode.LOG1P)
  140. def sqrt(x: Tensor) -> Tensor:
  141. r"""Element-wise `sqrt`.
  142. Examples:
  143. .. testcode::
  144. import numpy as np
  145. from megengine import tensor
  146. import megengine.functional as F
  147. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  148. out = F.sqrt(x)
  149. print(out.numpy().round(decimals=4))
  150. Outputs:
  151. .. testoutput::
  152. [[0. 1. 1.4142]
  153. [1.7321 2. 2.2361]]
  154. """
  155. return x ** 0.5
  156. def square(x: Tensor) -> Tensor:
  157. r"""Element-wise `square`.
  158. Examples:
  159. .. testcode::
  160. import numpy as np
  161. import megengine as mge
  162. import megengine.functional as F
  163. data = mge.tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  164. out = F.square(data)
  165. print(out.numpy().round(decimals=4))
  166. Outputs:
  167. .. testoutput::
  168. [[ 0. 1. 4.]
  169. [ 9. 16. 25.]]
  170. """
  171. return x ** 2
  172. def round(x):
  173. r"""Element-wise `rounding to int`."""
  174. return _elwise(x, mode=Elemwise.Mode.ROUND)
  175. def ceil(x):
  176. r"""Element-wise `ceiling`."""
  177. return _elwise(x, mode=Elemwise.Mode.CEIL)
  178. def floor(x):
  179. r"""Element-wise `floor`."""
  180. return _elwise(x, mode=Elemwise.Mode.FLOOR)
  181. def maximum(x, y):
  182. r"""Element-wise `maximum of array elements`."""
  183. return _elwise(x, y, mode=Elemwise.Mode.MAX)
  184. def minimum(x, y):
  185. r"""Element-wise `minimum of array elements`."""
  186. return _elwise(x, y, mode=Elemwise.Mode.MIN)
  187. # trigonometric functions
  188. def cos(x):
  189. r"""Element-wise `cosine`.
  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. r"""Element-wise `sine`."""
  206. return _elwise(x, mode=Elemwise.Mode.SIN)
  207. def tan(x):
  208. r"""Element-wise `tangent`."""
  209. return sin(x) / cos(x)
  210. def acos(x):
  211. r"""Element-wise `inverse cosine`."""
  212. return _elwise(x, mode=Elemwise.Mode.ACOS)
  213. def asin(x):
  214. r"""Element-wise `inverse sine`."""
  215. return _elwise(x, mode=Elemwise.Mode.ASIN)
  216. def atan(x):
  217. r"""Element-wise `inverse tangent`."""
  218. return _elwise(x, 1, mode=Elemwise.Mode.ATAN2)
  219. def atan2(y, x):
  220. r"""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. r"""Element-wise `bitwise binary: x << y`.
  244. Examples:
  245. .. testcode::
  246. import numpy as np
  247. from megengine import tensor
  248. import megengine.functional as F
  249. x = tensor(np.arange(0, 6, dtype=np.int32).reshape(2, 3))
  250. out = F.left_shift(x, 2)
  251. print(out.numpy())
  252. Outputs:
  253. .. testoutput::
  254. [[ 0 4 8]
  255. [12 16 20]]
  256. """
  257. return _elwise(x, y, mode=Elemwise.Mode.SHL)
  258. def right_shift(x, y):
  259. r"""Element-wise `bitwise binary: x >> y`."""
  260. return _elwise(x, y, mode=Elemwise.Mode.SHR)
  261. # logical functions
  262. def logical_and(x, y):
  263. r"""Element-wise `logical and: x && y`."""
  264. return _elwise(x, y, mode=Elemwise.Mode.AND)
  265. def logical_not(x):
  266. r"""Element-wise `logical not: ~x`."""
  267. return _elwise(x, mode=Elemwise.Mode.NOT)
  268. def logical_or(x, y):
  269. r"""Element-wise `logical or: x || y`."""
  270. return _elwise(x, y, mode=Elemwise.Mode.OR)
  271. def logical_xor(x, y):
  272. r"""Element-wise `logical xor: x ^ y`."""
  273. return _elwise(x, y, mode=Elemwise.Mode.XOR)
  274. def logaddexp(x: Tensor, y: Tensor) -> Tensor:
  275. r"""Element-wise `numerically stable log(exp(x) + exp(y)`
  276. """
  277. return _elwise(x, y, mode=Elemwise.Mode.LOG_SUM_EXP)
  278. # comparison functions
  279. def equal(x, y):
  280. r"""Element-wise `(x == y)`.
  281. Examples:
  282. .. testcode::
  283. import numpy as np
  284. from megengine import tensor
  285. import megengine.functional as F
  286. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  287. y = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  288. out = F.equal(x, y)
  289. print(out.numpy())
  290. Outputs:
  291. .. testoutput::
  292. [[1. 1. 1.]
  293. [1. 1. 1.]]
  294. """
  295. return _elwise(x, y, mode=Elemwise.Mode.EQ)
  296. def not_equal(x, y):
  297. r"""Element-wise `(x != y)`."""
  298. return x != y
  299. def less(x, y):
  300. r"""Element-wise `(x < y)`."""
  301. return _elwise(x, y, mode=Elemwise.Mode.LT)
  302. def less_equal(x, y):
  303. r"""Element-wise `(x <= y)`."""
  304. return _elwise(x, y, mode=Elemwise.Mode.LEQ)
  305. def greater(x, y):
  306. r"""Element-wise `(x > y)`."""
  307. return _elwise(y, x, mode=Elemwise.Mode.LT)
  308. def greater_equal(x, y):
  309. r"""Element-wise `(x >= y)`."""
  310. return _elwise(y, x, mode=Elemwise.Mode.LEQ)
  311. # other functions
  312. def clip(x: Tensor, lower=None, upper=None) -> Tensor:
  313. r"""Clamps all elements in input tensor into the range ``[ lower, upper ]`` and returns
  314. a resulting tensor:
  315. .. math::
  316. y_i = \begin{cases}
  317. \text{lower} & \text{if } x_i < \text{lower} \\
  318. x_i & \text{if } \text{lower} \leq x_i \leq \text{upper} \\
  319. \text{upper} & \text{if } x_i > \text{upper}
  320. \end{cases}
  321. Args:
  322. x (Tensor): The input tensor.
  323. lower (Numberic,optional): lower-bound of the range to be clamped to.
  324. upper (Numberic,optional): upper-bound of the range to be clamped to.
  325. Note:
  326. * If both `lower` and `upper` are None, raises an AssertionError.
  327. * If `lower` is bigger than `upper`, the result is same as `clip(Tensor(), upper, upper)`.
  328. Returns:
  329. output clamped tensor. The result must have a data type determined by :ref:`dtype-promotion`.
  330. Examples:
  331. >>> x = Tensor([0,1,2,3,4])
  332. >>> F.clip(x, 2, 4)
  333. Tensor([2 2 2 3 4], dtype=int32, device=xpux:0)
  334. >>> x = Tensor([0,1,2,3,4])
  335. >>> F.clip(x, 4, 3)
  336. Tensor([3 3 3 3 3], dtype=int32, device=xpux:0)
  337. >>> x = F.arange(5)
  338. >>> F.clip(x, lower=3)
  339. Tensor([3 3 3 3 4], dtype=int32, device=xpux:0)
  340. >>> x = F.arange(5, dtype=int)
  341. >>> F.clip(x, upper=2.1)
  342. Tensor([0. 1. 2. 2.1 2.1], device=xpux:0)
  343. """
  344. assert (
  345. lower is not None or upper is not None
  346. ), "At least one of 'lower' or 'upper' must not be None"
  347. if lower is not None:
  348. if upper is not None:
  349. return minimum(maximum(x, lower), upper)
  350. else:
  351. return maximum(x, lower)
  352. else:
  353. return minimum(x, upper)
  354. sigmoid = deprecated_func("1.3", "megengine.functional.nn", "sigmoid", True)
  355. hsigmoid = deprecated_func("1.3", "megengine.functional.nn", "hsigmoid", True)
  356. relu = deprecated_func("1.3", "megengine.functional.nn", "relu", True)
  357. relu6 = deprecated_func("1.3", "megengine.functional.nn", "relu6", True)
  358. hswish = deprecated_func("1.3", "megengine.functional.nn", "hswish", True)

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