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

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

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