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

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

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