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

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

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