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

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

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