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

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

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