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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 functools
  11. from ..core.ops import builtin
  12. from ..core.tensor import utils
  13. from ..core.tensor.core import apply
  14. from ..tensor import Tensor
  15. __all__ = [
  16. "abs",
  17. "add",
  18. "acos",
  19. "asin",
  20. "atan",
  21. "atan2",
  22. "asinh",
  23. "acosh",
  24. "atanh",
  25. "bitwise_and", # TODO
  26. "bitwise_not", # TODO
  27. "bitwise_or", # TODO
  28. "bitwise_xor", # TODO
  29. "ceil",
  30. "clamp",
  31. "cos",
  32. "cosh",
  33. "div",
  34. "eq",
  35. "exp",
  36. "expm1",
  37. "floor",
  38. "floor_div",
  39. "gt",
  40. "ge",
  41. "hswish",
  42. "hsigmoid",
  43. "left_shift",
  44. "lt",
  45. "le",
  46. "log",
  47. "log1p",
  48. "logical_and",
  49. "logical_not",
  50. "logical_or",
  51. "logical_xor",
  52. "maximum",
  53. "minimum",
  54. "mod",
  55. "mul",
  56. "neg",
  57. "ne",
  58. "pow",
  59. "relu",
  60. "relu6",
  61. "right_shift",
  62. "round",
  63. "sigmoid",
  64. "sin",
  65. "sinh",
  66. "sqrt",
  67. "square",
  68. "sub",
  69. "tan",
  70. "tanh",
  71. "fast_tanh",
  72. ]
  73. def _elwise(*args, mode):
  74. op = builtin.Elemwise(mode=mode)
  75. args = utils.convert_inputs(*args)
  76. (result,) = apply(op, *args)
  77. return result
  78. def _logical(*args, mode):
  79. op = builtin.CondExecPredLogical(mode=mode)
  80. args = utils.convert_inputs(*args)
  81. (result,) = apply(op, *args)
  82. return result
  83. def _elemwise_multi_type(*args, mode, **kwargs):
  84. op = builtin.ElemwiseMultiType(mode=mode, **kwargs)
  85. args = utils.convert_inputs(*args)
  86. (result,) = apply(op, *args)
  87. return result
  88. # math operations
  89. def add(x, y):
  90. """Element-wise addition.
  91. At least one operand should be tensor.
  92. same for sub/mul/div/floor_div/pow/mod/atan2/eq/ne/lt/le/gt/ge/maximum/minmium.
  93. """
  94. return _elwise(x, y, mode="add")
  95. def sub(x, y):
  96. """Element-wise subtract."""
  97. return _elwise(x, y, mode="sub")
  98. def mul(x, y):
  99. """Element-wise multiplication."""
  100. return _elwise(x, y, mode="mul")
  101. def div(x, y):
  102. """Element-wise (x / y)."""
  103. return _elwise(x, y, mode="true_div")
  104. def floor_div(x, y):
  105. """Element-wise floor(x / y)."""
  106. return _elwise(x, y, mode="floor_divide")
  107. def neg(x):
  108. """Element-wise negation."""
  109. return _elwise(x, mode="negate")
  110. def pow(x, y):
  111. """Element-wise power."""
  112. return _elwise(x, y, mode="pow")
  113. def mod(x, y):
  114. """Element-wise remainder of division."""
  115. return _elwise(x, y, mode="mod")
  116. def abs(x):
  117. """Element-wise absolute value."""
  118. return _elwise(x, mode="abs")
  119. def exp(x):
  120. """Element-wise exponential."""
  121. return _elwise(x, mode="exp")
  122. def expm1(x):
  123. """Element-wise exp(x)-1."""
  124. return _elwise(x, mode="expm1")
  125. def log(x):
  126. """Element-wise logarithm (base `e`)."""
  127. return _elwise(x, mode="log")
  128. def log1p(x):
  129. """Element-wise log(x+1) (base `e`)."""
  130. return _elwise(x, mode="log1p")
  131. def sqrt(inp: Tensor) -> Tensor:
  132. """
  133. Return a new tensor with the square-root of the elements of ``inp``.
  134. For negative value, return nan.
  135. :param inp: The input tensor
  136. :return: The computed tensor
  137. Examples:
  138. .. testcode::
  139. import numpy as np
  140. import megengine as mge
  141. import megengine.functional as F
  142. data = mge.tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  143. out = F.sqrt(data)
  144. print(out.numpy())
  145. Outputs:
  146. .. testoutput::
  147. [[0. 1. 1.4142]
  148. [1.7321 2. 2.2361 ]]
  149. """
  150. return inp ** 0.5
  151. def square(inp: Tensor) -> Tensor:
  152. """
  153. Return a new tensor with the square of the elements of ``inp``
  154. :param inp: The input tensor
  155. :return: The computed tensor
  156. Examples:
  157. .. testcode::
  158. import numpy as np
  159. import megengine as mge
  160. import megengine.functional as F
  161. data = mge.tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  162. out = F.square(data)
  163. print(out.numpy())
  164. Outputs:
  165. .. testoutput::
  166. [[0. 1. 4.]
  167. [9. 16. 25.]]
  168. """
  169. return inp ** 2
  170. def round(x):
  171. """Round tensor to int element-wise."""
  172. return _elwise(x, mode="round")
  173. def ceil(x):
  174. """Return the ceil of the input, element-wise."""
  175. return _elwise(x, mode="ceil")
  176. def floor(x):
  177. """Calculate the floor element-wise"""
  178. return _elwise(x, mode="floor")
  179. # trigonometric functions
  180. def cos(x):
  181. """Cosine, element-wise."""
  182. return _elwise(x, mode="cos")
  183. def sin(x):
  184. """Sine, element-wise."""
  185. return _elwise(x, mode="sin")
  186. def tan(x):
  187. return sin(x) / cos(x)
  188. def acos(x):
  189. """Inverse cosine, element-wise."""
  190. return _elwise(x, mode="acos")
  191. def asin(x):
  192. """Inverse sine, element-wise."""
  193. return _elwise(x, mode="asin")
  194. def atan(x):
  195. return _elwise(x, 1, mode="atan2")
  196. def atan2(y, x):
  197. return _elwise(y, x, mode="atan2")
  198. def cosh(x):
  199. r"""Compute element-wise hyperbolic cosine."""
  200. return 0.5 * (exp(x) + exp(-x))
  201. def sinh(x):
  202. r"""Compute element-wise hyperbolic sine."""
  203. u = expm1(x)
  204. return 0.5 * u / (u + 1) * (u + 2)
  205. def tanh(x):
  206. r"""Compute element-wise hyperbolic tangent."""
  207. return _elwise(x, mode="tanh")
  208. def asinh(x):
  209. r"""Compute element-wise inverse hyperbolic sine."""
  210. return log(x + (x ** 2 + 1) ** 0.5)
  211. def acosh(x):
  212. r"""Compute element-wise inverse hyperbolic cosine."""
  213. return log(x + (x ** 2 - 1) ** 0.5)
  214. def atanh(x):
  215. r"""Compute element-wise inverse hyperbolic tangent."""
  216. return log1p(2 * x / (1 - x)) / 2
  217. def fast_tanh(x):
  218. r"""Compute element-wise fast tanh; this is an approximation:
  219. .. math::
  220. \text{fast_tanh}(x) = x * (27. + x * x) / (27. + 9. * x * x)
  221. """
  222. return _elwise(x, mode="fast_tanh")
  223. # bit-twiddling functions
  224. def left_shift(x, y):
  225. return _elwise(x, y, mode="shl")
  226. def right_shift(x, y):
  227. return _elwise(x, y, mode="shl")
  228. def bitwise_and(x, y):
  229. raise NotImplementedError
  230. def bitwise_not(x):
  231. raise NotImplementedError
  232. def bitwise_or(x, y):
  233. raise NotImplementedError
  234. def bitwise_xor(x, y):
  235. raise NotImplementedError
  236. # logical functions
  237. def logical_and(x, y):
  238. return _elwise(x, y, mode="AND")
  239. def logical_not(x):
  240. return _elwise(x, mode="NOT")
  241. def logical_or(x, y):
  242. return _elwise(x, y, mode="OR")
  243. def logical_xor(x, y):
  244. return _elwise(x, y, mode="XOR")
  245. # comparison functions
  246. def eq(x, y):
  247. """Return (x == y) element-wise."""
  248. return _elwise(x, y, mode="eq")
  249. def ne(x, y):
  250. return x != y
  251. def lt(x, y):
  252. """Return (x < y) element-wise."""
  253. return _elwise(x, y, mode="lt")
  254. def le(x, y):
  255. """Return (x =< y) element-wise."""
  256. return _elwise(x, y, mode="leq")
  257. def gt(x, y):
  258. """Return (x > y) element-wise."""
  259. return _elwise(y, x, mode="lt")
  260. def ge(x, y):
  261. """Return (x >= y) element-wise"""
  262. return _elwise(y, x, mode="leq")
  263. def hswish(x):
  264. """Return x * relu6(x + 3) / 6 element-wise"""
  265. return _elwise(x, mode="h_swish")
  266. def hsigmoid(x):
  267. """Return relu6(x + 3) / 6 element-wise"""
  268. return relu6(x + 3) / 6
  269. def relu(x):
  270. """Return `max(x, 0)` element-wise."""
  271. return _elwise(x, mode="relu")
  272. def relu6(x):
  273. """Return min(max(x, 0), 6) element-wise."""
  274. return minimum(maximum(x, 0), 6)
  275. def sigmoid(x):
  276. """Return 1 / ( 1 + exp( -x ) ) element-wise."""
  277. return _elwise(x, mode="sigmoid")
  278. def maximum(x, y):
  279. """Element-wise maximum of array elements."""
  280. return _elwise(x, y, mode="max")
  281. def minimum(x, y):
  282. """Element-wise minimum of array elements."""
  283. return _elwise(x, y, mode="min")
  284. def clamp(inp: Tensor, lower=None, upper=None) -> Tensor:
  285. r"""
  286. Clamp all elements in :attr:`inp` into the range `[` :attr:`lower`, :attr:`upper` `]` and return
  287. a resulting tensor:
  288. .. math::
  289. y_i = \begin{cases}
  290. \text{lower} & \text{if } x_i < \text{lower} \\
  291. x_i & \text{if } \text{lower} \leq x_i \leq \text{upper} \\
  292. \text{upper} & \text{if } x_i > \text{upper}
  293. \end{cases}
  294. :param inp: the input tensor.
  295. :param lower: lower-bound of the range to be clamped to
  296. :param upper: upper-bound of the range to be clamped to
  297. Example:
  298. .. testcode::
  299. import numpy as np
  300. from megengine import tensor
  301. import megengine.functional as F
  302. a = tensor(np.arange(5).astype(np.int32))
  303. print(F.clamp(a, 2, 4).numpy())
  304. print(F.clamp(a, lower=3).numpy())
  305. print(F.clamp(a, upper=3).numpy())
  306. .. testoutput::
  307. [2 2 2 3 4]
  308. [3 3 3 3 4]
  309. [0 1 2 3 3]
  310. """
  311. assert (
  312. lower is not None or upper is not None
  313. ), "At least one of 'lower' or 'upper' must not be None"
  314. if lower is not None:
  315. if upper is not None:
  316. assert lower <= upper, "clamp lower bound is bigger that upper bound"
  317. return minimum(maximum(inp, lower), upper)
  318. else:
  319. return maximum(inp, lower)
  320. else:
  321. return minimum(inp, upper)

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