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 12 kB

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

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