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

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

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