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

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

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