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

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