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

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

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