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.6 kB

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

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