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.

nn.py 48 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  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=too-many-lines
  10. from typing import Optional, Sequence, Tuple, Union
  11. from ..core._imperative_rt import CompNode
  12. from ..core.ops import builtin
  13. from ..core.ops._internal import param_defs as P
  14. from ..core.ops.special import Const
  15. from ..core.tensor import megbrain_graph, utils
  16. from ..core.tensor.core import TensorBase, TensorWrapperBase, apply
  17. from ..core.tensor.utils import astensor1d
  18. from ..distributed import WORLD, is_distributed
  19. from ..random import uniform
  20. from ..tensor import Tensor
  21. from .debug_param import get_conv_execution_strategy
  22. from .distributed import all_reduce_sum
  23. from .elemwise import exp, floor, log, log1p, maximum, minimum, relu
  24. from .math import argsort, max, sum
  25. from .tensor import add_axis, broadcast, concat, full, ones, remove_axis, reshape, zeros
  26. from .types import _pair, _pair_nonzero
  27. __all__ = [
  28. "adaptive_avg_pool2d",
  29. "adaptive_max_pool2d",
  30. "avg_pool2d",
  31. "batch_norm2d",
  32. "conv2d",
  33. "conv_transpose2d",
  34. "dot",
  35. "dropout",
  36. "indexing_one_hot",
  37. "leaky_relu",
  38. "local_conv2d",
  39. "logsigmoid",
  40. "logsumexp",
  41. "logsoftmax",
  42. "matmul",
  43. "max_pool2d",
  44. "one_hot",
  45. "prelu",
  46. "roi_align",
  47. "roi_pooling",
  48. "softmax",
  49. "softplus",
  50. "svd",
  51. "sync_batch_norm",
  52. "warp_perspective",
  53. ]
  54. def expand_hw(x):
  55. # NOTE: >1d array is accepted, as long as 1 <= size <= 2
  56. try:
  57. x = int(x)
  58. return [x, x]
  59. except (TypeError, ValueError):
  60. pass
  61. h, w = x
  62. return int(h), int(w)
  63. def linear(inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None) -> Tensor:
  64. """Applies a linear transformation to the input tensor.
  65. Refer to :class:`~.module.linear.Linear` for more information.
  66. :param inp: input tensor with shape `(N, in_features)`.
  67. :param weight: weight with shape `(out_features, in_features)`.
  68. :param bias: bias with shape `(out_features,)`.
  69. Default: None
  70. """
  71. ret = matmul(inp, weight, transpose_b=True)
  72. if bias is not None:
  73. ret += bias
  74. return ret
  75. def conv2d(
  76. inp: Tensor,
  77. weight: Tensor,
  78. bias: Optional[Tensor] = None,
  79. stride: Union[int, Tuple[int, int]] = 1,
  80. padding: Union[int, Tuple[int, int]] = 0,
  81. dilation: Union[int, Tuple[int, int]] = 1,
  82. groups: int = 1,
  83. conv_mode="CROSS_CORRELATION",
  84. compute_mode="DEFAULT",
  85. ) -> Tensor:
  86. """2D convolution operation.
  87. Refer to :class:`~.Conv2d` for more information.
  88. :param inp: feature map of the convolution operation.
  89. :param weight: convolution kernel.
  90. :param bias: bias added to the result of convolution (if given).
  91. :param stride: stride of the 2D convolution operation. Default: 1
  92. :param padding: size of the paddings added to the input on both sides of its
  93. spatial dimensions. Only zero-padding is supported. Default: 0
  94. :param dilation: dilation of the 2D convolution operation. Default: 1
  95. :param groups: number of groups into which the input and output channels are divided, so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  96. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  97. and the shape of weight should be `(groups, out_channel // groups,
  98. in_channels // groups, height, width)`.
  99. :type conv_mode: string or :class:`P.Convolution.Mode`
  100. :param conv_mode: supports "CROSS_CORRELATION" or "CONVOLUTION". Default:
  101. "CROSS_CORRELATION"
  102. :type compute_mode: string or
  103. :class:`P.Convolution.ComputeMode`
  104. :param compute_mode: when set to "DEFAULT", no special requirements will be
  105. placed on the precision of intermediate results. When set to "FLOAT32",
  106. "Float32" would be used for accumulator and intermediate result, but only
  107. effective when input and output are of Float16 dtype.
  108. :return: output tensor.
  109. """
  110. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  111. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  112. stride_h, stride_w = expand_hw(stride)
  113. pad_h, pad_w = expand_hw(padding)
  114. dilate_h, dilate_w = expand_hw(dilation)
  115. Sparse = P.Convolution.Sparse
  116. sparse_type = Sparse.DENSE if groups == 1 else Sparse.GROUP
  117. op = builtin.Convolution(
  118. stride_h=stride_h,
  119. stride_w=stride_w,
  120. pad_h=pad_h,
  121. pad_w=pad_w,
  122. dilate_h=dilate_h,
  123. dilate_w=dilate_w,
  124. strategy=get_conv_execution_strategy(),
  125. mode=conv_mode,
  126. compute_mode=compute_mode,
  127. sparse=sparse_type,
  128. )
  129. inp, weight = utils.convert_inputs(inp, weight)
  130. (output,) = apply(op, inp, weight)
  131. if bias is not None:
  132. output += bias
  133. return output
  134. def conv_transpose2d(
  135. inp: Tensor,
  136. weight: Tensor,
  137. bias: Optional[Tensor] = None,
  138. stride: Union[int, Tuple[int, int]] = 1,
  139. padding: Union[int, Tuple[int, int]] = 0,
  140. dilation: Union[int, Tuple[int, int]] = 1,
  141. groups: int = 1,
  142. conv_mode="CROSS_CORRELATION",
  143. compute_mode="DEFAULT",
  144. ) -> Tensor:
  145. """2D transposed convolution operation.
  146. Refer to :class:`~.ConvTranspose2d` for more information.
  147. :param inp: feature map of the convolution operation.
  148. :param weight: convolution kernel.
  149. :param bias: bias added to the result of convolution (if given).
  150. :param stride: stride of the 2D convolution operation. Default: 1
  151. :param padding: size of the paddings added to the input on both sides of its
  152. spatial dimensions. Only zero-padding is supported. Default: 0
  153. :param dilation: dilation of the 2D convolution operation. Default: 1
  154. :param groups: number of groups into which the input and output channels are divided, so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  155. ``in_channels`` and ``out_channels`` must be divisible by groups,
  156. and the shape of weight should be `(groups, out_channel // groups,
  157. in_channels // groups, height, width)`. Default: 1
  158. :type conv_mode: string or :class:`P.Convolution.Mode`
  159. :param conv_mode: supports "CROSS_CORRELATION" or "CONVOLUTION". Default:
  160. "CROSS_CORRELATION"
  161. :type compute_mode: string or
  162. :class:`P.Convolution.ComputeMode`
  163. :param compute_mode: when set to "DEFAULT", no special requirements will be
  164. placed on the precision of intermediate results. When set to "FLOAT32",
  165. "Float32" would be used for accumulator and intermediate result, but only
  166. effective when input and output are of Float16 dtype.
  167. :return: output tensor.
  168. """
  169. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  170. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  171. if groups != 1:
  172. raise NotImplementedError("TODO")
  173. stride_h, stride_w = expand_hw(stride)
  174. pad_h, pad_w = expand_hw(padding)
  175. dilate_h, dilate_w = expand_hw(dilation)
  176. op = builtin.ConvolutionBackwardData(
  177. stride_h=stride_h,
  178. stride_w=stride_w,
  179. pad_h=pad_h,
  180. pad_w=pad_w,
  181. dilate_h=dilate_h,
  182. dilate_w=dilate_w,
  183. strategy=get_conv_execution_strategy(),
  184. )
  185. weight, inp = utils.convert_inputs(weight, inp)
  186. (output,) = apply(op, weight, inp)
  187. if bias is not None:
  188. output += bias
  189. return output
  190. def local_conv2d(
  191. inp: Tensor,
  192. weight: Tensor,
  193. bias: Optional[Tensor] = None,
  194. stride: Union[int, Tuple[int, int]] = 1,
  195. padding: Union[int, Tuple[int, int]] = 0,
  196. dilation: Union[int, Tuple[int, int]] = 1,
  197. conv_mode="CROSS_CORRELATION",
  198. ):
  199. """Applies spatial 2D convolution over an groupped channeled image with untied kernels.
  200. """
  201. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  202. stride_h, stride_w = expand_hw(stride)
  203. pad_h, pad_w = expand_hw(padding)
  204. dilate_h, dilate_w = expand_hw(dilation)
  205. Sparse = P.Convolution.Sparse
  206. op = builtin.GroupLocal(
  207. stride_h=stride_h,
  208. stride_w=stride_w,
  209. pad_h=pad_h,
  210. pad_w=pad_w,
  211. dilate_h=dilate_h,
  212. dilate_w=dilate_w,
  213. mode=conv_mode,
  214. compute_mode="DEFAULT",
  215. sparse=Sparse.DENSE,
  216. )
  217. inp, weight = utils.convert_inputs(inp, weight)
  218. (output,) = apply(op, inp, weight)
  219. if bias is not None:
  220. output += bias
  221. return output
  222. def max_pool2d(
  223. inp: Tensor,
  224. kernel_size: Union[int, Tuple[int, int]],
  225. stride: Optional[Union[int, Tuple[int, int]]] = None,
  226. padding: Union[int, Tuple[int, int]] = 0,
  227. ) -> Tensor:
  228. """Applies a 2D max pooling over an input tensor.
  229. Refer to :class:`~.MaxPool2d` for more information.
  230. :param inp: input tensor.
  231. :param kernel_size: size of the window.
  232. :param stride: stride of the window. If not provided, its value is set to kernel_size.
  233. Default: None
  234. :param padding: implicit zero padding added on both sides. Default: 0
  235. :return: output tensor.
  236. """
  237. if stride is None:
  238. stride = kernel_size
  239. window_h, window_w = _pair_nonzero(kernel_size)
  240. stride_h, stride_w = _pair_nonzero(stride)
  241. padding_h, padding_w = _pair(padding)
  242. op = builtin.Pooling(
  243. window_h=window_h,
  244. window_w=window_w,
  245. stride_h=stride_h,
  246. stride_w=stride_w,
  247. pad_h=padding_h,
  248. pad_w=padding_w,
  249. mode="MAX",
  250. )
  251. (output,) = apply(op, inp)
  252. return output
  253. def avg_pool2d(
  254. inp: Tensor,
  255. kernel_size: Union[int, Tuple[int, int]],
  256. stride: Optional[Union[int, Tuple[int, int]]] = None,
  257. padding: Union[int, Tuple[int, int]] = 0,
  258. mode: str = "AVERAGE_COUNT_EXCLUDE_PADDING",
  259. ) -> Tensor:
  260. """Applies 2D average pooling over an input tensor.
  261. Refer to :class:`~.AvgPool2d` for more information.
  262. :param inp: input tensor.
  263. :param kernel_size: size of the window.
  264. :param stride: stride of the window. If not provided, its value is set to ``kernel_size``.
  265. Default: None
  266. :param padding: implicit zero padding added on both sides. Default: 0
  267. :param mode: whether to count padding values. Default: "AVERAGE_COUNT_EXCLUDE_PADDING"
  268. :return: output tensor.
  269. """
  270. if stride is None:
  271. stride = kernel_size
  272. window_h, window_w = _pair_nonzero(kernel_size)
  273. stride_h, stride_w = _pair_nonzero(stride)
  274. padding_h, padding_w = _pair(padding)
  275. op = builtin.Pooling(
  276. window_h=window_h,
  277. window_w=window_w,
  278. stride_h=stride_h,
  279. stride_w=stride_w,
  280. pad_h=padding_h,
  281. pad_w=padding_w,
  282. mode=mode,
  283. )
  284. (output,) = apply(op, inp)
  285. return output
  286. def adaptive_max_pool2d(
  287. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  288. ) -> Tensor:
  289. """Applies a 2D max adaptive pooling over an input.
  290. Refer to :class:`~.MaxAdaptivePool2d` for more information.
  291. :param inp: The input tensor.
  292. :param oshp: (OH, OW) size of the output shape.
  293. :return: output tensor.
  294. """
  295. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  296. if isinstance(oshp, int):
  297. oshp = (oshp, oshp)
  298. op = builtin.AdaptivePooling(mode="MAX", format="NCHW",)
  299. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  300. (output,) = apply(op, inp, oshp)
  301. return output
  302. def adaptive_avg_pool2d(
  303. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  304. ) -> Tensor:
  305. """Applies a 2D average adaptive pooling over an input.
  306. Refer to :class:`~.AvgAdaptivePool2d` for more information.
  307. :param inp: The input tensor.
  308. :param oshp: (OH, OW) size of the output shape.
  309. :return: output tensor.
  310. """
  311. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  312. if isinstance(oshp, int):
  313. oshp = (oshp, oshp)
  314. op = builtin.AdaptivePooling(mode="AVERAGE", format="NCHW",)
  315. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  316. (output,) = apply(op, inp, oshp)
  317. return output
  318. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  319. r"""
  320. Applies the element-wise PReLU function.
  321. Refer to :class:`~.PReLU` for more information.
  322. """
  323. return maximum(inp, 0) + weight * minimum(inp, 0)
  324. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  325. r"""
  326. Applies the element-wise leaky_relu function
  327. Refer to :class:`~.LeakyReLU` for more information.
  328. """
  329. return maximum(inp, 0) + negative_slope * minimum(inp, 0)
  330. def softplus(inp: Tensor) -> Tensor:
  331. r"""Applies the element-wise function:
  332. .. math::
  333. \text{softplus}(x) = \log(1 + \exp(x))
  334. softplus is a smooth approximation to the ReLU function and can be used
  335. to constrain the output to be always positive.
  336. For numerical stability the implementation follows this transformation:
  337. .. math::
  338. \text{softplus}(x) = \log(1 + \exp(x))
  339. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  340. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  341. :param inp: input tensor.
  342. Examples:
  343. .. testcode::
  344. import numpy as np
  345. from megengine import tensor
  346. import megengine.functional as F
  347. x = tensor(np.arange(-3, 3, dtype=np.float32))
  348. y = F.softplus(x)
  349. print(y.numpy())
  350. Outputs:
  351. .. testoutput::
  352. [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
  353. """
  354. return log1p(exp(-abs(inp))) + relu(inp)
  355. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  356. r"""Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional
  357. input Tensor. The LogSoftmax formulation can be simplified as:
  358. .. math::
  359. \text{LogSoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  360. For numerical stability the implementation follows this transformation:
  361. .. math::
  362. \operatorname{logsoftmax}(x)
  363. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  364. = x - \log (\sum_{i}(\exp (x_{i})))
  365. = x - logsumexp(x)
  366. :param inp: input tensor.
  367. :param axis: axis along which logsoftmax will be applied.
  368. Examples:
  369. .. testcode::
  370. import numpy as np
  371. from megengine import tensor
  372. import megengine.functional as F
  373. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  374. y = F.logsoftmax(x, axis=1)
  375. print(y.numpy())
  376. Outputs:
  377. .. testoutput::
  378. [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
  379. [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
  380. """
  381. return inp - logsumexp(inp, axis, keepdims=True)
  382. def logsigmoid(inp: Tensor) -> Tensor:
  383. r"""Applies the element-wise function:
  384. .. math::
  385. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  386. = \log(1/(1 + exp(-x)))
  387. = - \log(1 + exp(-x))
  388. = - \text{softplus}(-x)
  389. :param inp: input tensor.
  390. Examples:
  391. .. testcode::
  392. import numpy as np
  393. from megengine import tensor
  394. import megengine.functional as F
  395. x = tensor(np.arange(-5, 5, dtype=np.float32))
  396. y = F.logsigmoid(x)
  397. print(y.numpy())
  398. Outputs:
  399. .. testoutput::
  400. [-5.0067 -4.0181 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
  401. -0.0181]
  402. """
  403. return -softplus(-inp)
  404. def logsumexp(
  405. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  406. ) -> Tensor:
  407. r"""
  408. Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  409. .. math::
  410. \operatorname{logsumexp}(\boldsymbol{x})= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  411. For numerical stability, the implementation follows this transformation:
  412. .. math::
  413. \operatorname{logsumexp}(\boldsymbol{x})= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  414. = \operatorname{logsumexp}(\boldsymbol{x})=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  415. where
  416. .. math::
  417. b = \max(x_j)
  418. :param inp: input tensor.
  419. :param axis: axis over which the sum is taken. It could be single axis or list of axes.
  420. :param keepdims: whether to retain :attr:`axis` or not for the output tensor.
  421. Examples:
  422. .. testcode::
  423. import numpy as np
  424. from megengine import tensor
  425. import megengine.functional as F
  426. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  427. y = F.logsumexp(x, axis=1, keepdims=False)
  428. print(y.numpy())
  429. Outputs:
  430. .. testoutput::
  431. [-0.5481 4.4519]
  432. """
  433. max_value = max(inp, axis, keepdims=True)
  434. if keepdims:
  435. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  436. else:
  437. return remove_axis(max_value, axis=None) + log(
  438. sum(exp(inp - max_value), axis, keepdims)
  439. )
  440. def _get_softmax_axis(ndim: int) -> int:
  441. if ndim in (0, 1, 3):
  442. return 0
  443. return 1
  444. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  445. r"""
  446. Applies a softmax function. Softmax is defined as:
  447. .. math::
  448. \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  449. It is applied to all elements along axis, and rescales elements so that
  450. they stay in the range `[0, 1]` and sum to 1.
  451. See :class:`~megengine.module.activation.Softmax` for more details.
  452. :param inp: input tensor.
  453. :param axis: an axis along which softmax will be applied. By default,
  454. softmax will apply along the highest ranked axis.
  455. Examples:
  456. .. testcode::
  457. import numpy as np
  458. from megengine import tensor
  459. import megengine.functional as F
  460. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  461. out = F.softmax(x)
  462. print(out.numpy())
  463. Outputs:
  464. .. testoutput::
  465. [[0.0117 0.0317 0.0861 0.2341 0.6364]
  466. [0.0117 0.0317 0.0861 0.2341 0.6364]]
  467. """
  468. if axis is None:
  469. axis = _get_softmax_axis(len(inp.shape))
  470. offset = inp.max(axis=axis, keepdims=True).detach()
  471. cached = exp(inp - offset)
  472. down = sum(cached, axis=axis, keepdims=True)
  473. return cached / down
  474. def batch_norm2d(
  475. inp: Tensor,
  476. running_mean: Tensor = None,
  477. running_var: Tensor = None,
  478. weight: Optional[Tensor] = None,
  479. bias: Optional[Tensor] = None,
  480. *,
  481. training: bool = False,
  482. momentum: float = 0.9,
  483. eps: float = 1e-5,
  484. inplace: bool = True
  485. ):
  486. r"""Applies batch normalization to the input.
  487. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  488. :param inp: input tensor.
  489. :param running_mean: tensor to store running mean.
  490. :param running_var: tensor to store running variance.
  491. :param weight: scaling tensor in the learnable affine parameters.
  492. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  493. :param bias: bias tensor in the learnable affine parameters.
  494. See :math:`\beta` in :class:`~.BatchNorm2d`.
  495. :param training: a boolean value to indicate whether batch norm is performed
  496. in training mode. Default: False
  497. :param momentum: value used for the ``running_mean`` and ``running_var``
  498. computation.
  499. Default: 0.9
  500. :param eps: a value added to the denominator for numerical stability.
  501. Default: 1e-5
  502. :param inplace: whether to update ``running_mean`` and ``running_var`` inplace or return new tensors
  503. Default: True
  504. :return: output tensor.
  505. """
  506. def full_value(value):
  507. C = inp.shape[1]
  508. (x,) = Const(value, dtype=inp.dtype, device=inp.device)(inp)
  509. return broadcast(x, [1, C, 1, 1])
  510. def expand_or_full(x, value):
  511. if x is None:
  512. return full_value(value)
  513. return add_axis(x, [0, 2, 3])
  514. def make_full_if_none(x, value):
  515. if x is None:
  516. return full(shape=(1, inp.shape[1], 1, 1), value=value)
  517. return x
  518. has_mean = running_mean is not None
  519. has_var = running_var is not None
  520. if not training:
  521. assert has_mean, "running_mean must be provided in inference mode"
  522. assert has_var, "running_var must be provided in inference mode"
  523. if has_mean and running_mean.ndim != 4:
  524. raise ValueError
  525. if has_var and running_var.ndim != 4:
  526. raise ValueError
  527. inp, weight, bias, running_mean, running_var = utils.convert_inputs(
  528. inp, weight, bias, running_mean, running_var
  529. )
  530. weight = expand_or_full(weight, 1)
  531. bias = expand_or_full(bias, 0)
  532. if not training:
  533. op = builtin.BatchNorm(fwd_mode="INFERENCE", epsilon=eps, param_dim="DIM_1C11")
  534. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  535. return ret
  536. else:
  537. op = builtin.BatchNorm(
  538. avg_factor=1 - momentum, epsilon=eps, param_dim="DIM_1C11"
  539. )
  540. if has_mean or has_var:
  541. running_mean = make_full_if_none(running_mean, 0)
  542. running_var = make_full_if_none(running_var, 1)
  543. new_mean, new_var, _, _, inp = apply(
  544. op, inp, weight, bias, running_mean, running_var
  545. )
  546. if not has_mean:
  547. new_mean = None
  548. if not has_var:
  549. new_var = None
  550. if inplace:
  551. if has_mean:
  552. running_mean[...] = new_mean
  553. if has_var:
  554. running_var[...] = new_var
  555. return inp
  556. else:
  557. return inp, new_mean, new_var
  558. else:
  559. _, _, inp, = apply(op, inp, weight, bias)
  560. return inp
  561. def sync_batch_norm(
  562. inp: Tensor,
  563. running_mean: Tensor,
  564. running_var: Tensor,
  565. weight: Optional[Tensor] = None,
  566. bias: Optional[Tensor] = None,
  567. training: bool = False,
  568. momentum: Union[float, Tensor] = 0.9,
  569. eps: float = 1e-5,
  570. eps_mode="ADDITIVE",
  571. group=WORLD,
  572. ) -> Tensor:
  573. r"""Applies synchronized batch normalization to the input.
  574. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  575. :param inp: input tensor.
  576. :param running_mean: tensor to store running mean.
  577. :param running_var: tensor to store running variance.
  578. :param weight: scaling tensor in the learnable affine parameters.
  579. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  580. :param bias: bias tensor in the learnable affine parameters.
  581. See :math:`\beta` in :class:`~.BatchNorm2d`.
  582. :param training: a boolean value to indicate whether batch norm is performed
  583. in traning mode. Default: False
  584. :param momentum: value used for the ``running_mean`` and ``running_var``
  585. computation.
  586. Default: 0.9
  587. :param eps: a value added to the denominator for numerical stability.
  588. Default: 1e-5
  589. :return: output tensor.
  590. """
  591. assert eps_mode in {"MAX", "ADDITIVE"}, "unknown eps_mode: {}".format(eps_mode)
  592. _channels = inp.shape[1]
  593. _ndim = inp.ndim
  594. _device = inp.device
  595. _dtype = inp.dtype
  596. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  597. _reduce_axis = [0] + [i for i in range(2, _ndim)]
  598. if training:
  599. def _sum_on_channel(inp):
  600. return inp.sum(axis=_reduce_axis, keepdims=True)
  601. reduce_size = inp.shape[0]
  602. for i in range(2, _ndim):
  603. reduce_size = reduce_size * inp.shape[i]
  604. channel_x1s = _sum_on_channel(inp)
  605. channel_x2s = _sum_on_channel(inp ** 2)
  606. if is_distributed():
  607. # reduce all nodes' data to calculate mean and variance
  608. reduce_size = broadcast(Tensor(reduce_size, dtype=_dtype), [1] * _ndim)
  609. stat = concat(
  610. [reduce_size.astype(_dtype), channel_x1s, channel_x2s], axis=1
  611. )
  612. stat = all_reduce_sum(stat, group)
  613. reduce_size = stat[:, :1].reshape(1)
  614. channel_x1s = stat[:, 1 : 1 + _channels]
  615. channel_x2s = stat[:, 1 + _channels :]
  616. channel_mean = channel_x1s / reduce_size
  617. channel_variance = (
  618. channel_x1s ** 2 / (-reduce_size * reduce_size) + channel_x2s / reduce_size
  619. )
  620. else:
  621. assert running_var is not None and running_mean is not None
  622. channel_variance = running_var.reshape(*_param_shape)
  623. channel_mean = running_mean.reshape(*_param_shape)
  624. invsqrt_channel_variance = (
  625. maximum(channel_variance, eps) if eps_mode == "MAX" else channel_variance + eps
  626. ) ** -0.5
  627. if weight is not None:
  628. weight = weight.reshape(*_param_shape)
  629. if bias is not None:
  630. bias = bias.reshape(*_param_shape)
  631. # outvar = output * weight + bias
  632. # where output = inp * invsqrt_channel_variance + (
  633. # -channel_mean * invsqrt_channel_variance
  634. # )
  635. # Manually expand output for gopt
  636. if weight is not None:
  637. inv_var_wt = invsqrt_channel_variance * weight
  638. neg_channel_mean = -channel_mean
  639. if bias is not None:
  640. outvar = inp * inv_var_wt + (neg_channel_mean * inv_var_wt + bias)
  641. else:
  642. outvar = inp * inv_var_wt + neg_channel_mean * inv_var_wt
  643. else:
  644. outvar = inp * invsqrt_channel_variance + (
  645. -channel_mean * invsqrt_channel_variance
  646. )
  647. if bias is not None:
  648. outvar = outvar + bias
  649. if training and running_var is not None and running_mean is not None:
  650. running_mean *= momentum
  651. running_mean += (1 - momentum) * channel_mean
  652. channel_variance_unbiased = channel_x1s ** 2 / (
  653. -reduce_size * (reduce_size - 1)
  654. ) + channel_x2s / (reduce_size - 1)
  655. running_var *= momentum
  656. running_var += (1 - momentum) * channel_variance_unbiased
  657. return outvar
  658. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  659. r"""Performs one-hot encoding for the input tensor.
  660. :param inp: input tensor.
  661. :param num_classes: number of classes denotes the last dimension of the output tensor.
  662. :return: output tensor.
  663. Examples:
  664. .. testcode::
  665. import numpy as np
  666. from megengine import tensor
  667. import megengine.functional as F
  668. x = tensor(np.arange(1, 4, dtype=np.int32))
  669. out = F.one_hot(x, num_classes=4)
  670. print(out.numpy())
  671. Outputs:
  672. .. testoutput::
  673. [[0 1 0 0]
  674. [0 0 1 0]
  675. [0 0 0 1]]
  676. """
  677. zeros_tensor = zeros(list(inp.shape) + [num_classes], inp.dtype, inp.device)
  678. ones_tensor = ones(list(inp.shape) + [1], inp.dtype, inp.device)
  679. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  680. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  681. return result
  682. def warp_perspective(
  683. inp: Tensor,
  684. M: Tensor,
  685. dsize: Union[Tuple[int, int], int, Tensor],
  686. border_mode: str = "REPLICATE",
  687. border_val: float = 0.0,
  688. interp_mode: str = "LINEAR",
  689. ):
  690. r"""Applies perspective transformation to batched 2D images.
  691. The input images are transformed to the output images by the transformation matrix:
  692. .. math::
  693. \text{output}(n, c, h, w) = \text{input} \left( n, c,
  694. \frac{M_{00}h + M_{01}w + M_{02}}{M_{20}h + M_{21}w + M_{22}},
  695. \frac{M_{10}h + M_{11}w + M_{12}}{M_{20}h + M_{21}w + M_{22}}
  696. \right)
  697. :param inp: input image.
  698. :param M: `(batch, 3, 3)` transformation matrix.
  699. :param dsize: `(h, w)` size of the output image.
  700. :param border_mode: pixel extrapolation method. Default: "REPLICATE"
  701. :param border_val: value used in case of a constant border. Default: 0
  702. :param interp_mode: interpolation methods. Default: "LINEAR"
  703. :return: output tensor.
  704. Examples:
  705. .. testcode::
  706. import numpy as np
  707. from megengine import tensor
  708. import megengine.functional as F
  709. inp_shape = (1, 1, 4, 4)
  710. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  711. M_shape = (1, 3, 3)
  712. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  713. M = tensor(np.array([[1., 0., 1.],
  714. [0., 1., 1.],
  715. [0., 0., 1.]], dtype=np.float32).reshape(M_shape))
  716. out = F.warp_perspective(x, M, (2, 2))
  717. print(out.numpy())
  718. Outputs:
  719. .. testoutput::
  720. [[[[ 5. 6.]
  721. [ 9. 10.]]]]
  722. """
  723. op = builtin.WarpPerspective(
  724. imode=interp_mode, bmode=border_mode, format="NCHW", border_val=border_val
  725. )
  726. inp, M = utils.convert_inputs(inp, M)
  727. dsize = astensor1d(dsize, inp, dtype="int32", device=inp.device)
  728. (result,) = apply(op, inp, M, dsize)
  729. return result
  730. def matmul(
  731. inp1: Tensor,
  732. inp2: Tensor,
  733. transpose_a=False,
  734. transpose_b=False,
  735. compute_mode="DEFAULT",
  736. format="DEFAULT",
  737. ) -> Tensor:
  738. """
  739. Performs a matrix multiplication of the matrices ``inp1`` and ``inp2``.
  740. With different inputs dim, this function behaves differently:
  741. - Both 1-D tensor, simply forward to ``dot``.
  742. - Both 2-D tensor, normal matrix multiplication.
  743. - If one input tensor is 1-D, matrix vector multiplication.
  744. - If at least one tensor are 3-dimensional or >3-dimensional, the other tensor should have dim >= 2, the batched matrix-matrix is returned, and the tensor with smaller dimension will
  745. be broadcasted. For example:
  746. - inp1: `(n, k, m)`, inp2: `(n, m, p)`, return: `(n, k, p)`
  747. - inp1: `(n, k, m)`, inp2: `(m, p)`, return: `(n, k, p)`
  748. - inp1: `(n, j, k, m)`, inp2: `(n, j, m, p)`, return: `(n, j, k, p)`
  749. :param inp1: first matrix to be multiplied.
  750. :param inp2: second matrix to be multiplied.
  751. :return: output tensor.
  752. Examples:
  753. .. testcode::
  754. import numpy as np
  755. from megengine import tensor
  756. import megengine.functional as F
  757. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  758. data2 = tensor(np.arange(0, 6, dtype=np.float32).reshape(3, 2))
  759. out = F.matmul(data1, data2)
  760. print(out.numpy())
  761. Outputs:
  762. .. testoutput::
  763. [[10. 13.]
  764. [28. 40.]]
  765. """
  766. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  767. dim1, dim2 = inp1.ndim, inp2.ndim
  768. if dim1 == 1 and dim2 == 1:
  769. return dot(inp1, inp2)
  770. shp = None
  771. if dim1 > 3 or dim2 > 3:
  772. shape1, shape2 = list(inp1.shape), list(inp2.shape)
  773. if dim1 != dim2:
  774. if dim1 < dim2:
  775. shape1 = shape2[: dim2 - dim1] + shape1
  776. inp1 = inp1.broadcast(*shape1)
  777. else:
  778. shape2 = shape1[: dim1 - dim2] + shape2
  779. inp2 = inp2.broadcast(*shape2)
  780. reshaped_batch_size = 1
  781. for i in shape1[:-2]:
  782. reshaped_batch_size *= i
  783. inp1 = inp1.reshape(*([reshaped_batch_size] + shape1[-2:]))
  784. inp2 = inp2.reshape(*([reshaped_batch_size] + shape2[-2:]))
  785. op = builtin.BatchedMatrixMul(
  786. transposeA=transpose_a,
  787. transposeB=transpose_b,
  788. compute_mode=compute_mode,
  789. format=format,
  790. )
  791. shp = shape1[:-1] + shape2[-1:]
  792. elif dim1 == 3 or dim2 == 3:
  793. if dim2 < 3:
  794. inp2 = inp2.broadcast(*(inp1.shape[:1] + inp2.shape))
  795. elif dim1 < 3:
  796. inp1 = inp1.broadcast(*(inp2.shape[:1] + inp1.shape))
  797. op = builtin.BatchedMatrixMul(
  798. transposeA=transpose_a,
  799. transposeB=transpose_b,
  800. compute_mode=compute_mode,
  801. format=format,
  802. )
  803. else:
  804. if dim1 == 1:
  805. shp = (inp2.shape[1],)
  806. inp1 = add_axis(inp1, 0)
  807. if dim2 == 1:
  808. shp = (inp1.shape[0],)
  809. inp2 = add_axis(inp2, 1)
  810. op = builtin.MatrixMul(
  811. transposeA=transpose_a,
  812. transposeB=transpose_b,
  813. compute_mode=compute_mode,
  814. format=format,
  815. )
  816. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  817. (result,) = apply(op, inp1, inp2)
  818. if shp is not None:
  819. result = result.reshape(shp)
  820. return result
  821. def dot(inp1: Tensor, inp2: Tensor) -> Tensor:
  822. """
  823. Computes dot-product of two vectors ``inp1`` and ``inp2``.
  824. inputs must be 1-dimensional, scalar input can be automatically broadcasted.
  825. :param inp1: first vector.
  826. :param inp2: second vector.
  827. :return: output value.
  828. Examples:
  829. .. testcode::
  830. import numpy as np
  831. from megengine import tensor
  832. import megengine.functional as F
  833. data1 = tensor(np.arange(0, 6, dtype=np.float32))
  834. data2 = tensor(np.arange(0, 6, dtype=np.float32))
  835. out = F.dot(data1, data2)
  836. print(out.numpy())
  837. Outputs:
  838. .. testoutput::
  839. [55.]
  840. """
  841. op = builtin.Dot()
  842. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  843. (result,) = apply(op, inp1, inp2)
  844. return result
  845. def svd(inp: Tensor, full_matrices=False, compute_uv=True) -> Tensor:
  846. """
  847. Computes the singular value decompositions of input matrix.
  848. :param inp: input matrix, must has shape `[..., M, N]`.
  849. :return: output matrices, `(U, sigma, V)`.
  850. Examples:
  851. .. testcode::
  852. import numpy as np
  853. from megengine import tensor
  854. import megengine.functional as F
  855. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2,3))
  856. _, y, _ = F.svd(x)
  857. print(y.numpy())
  858. Outputs:
  859. .. testoutput::
  860. [7.3485 1. ]
  861. """
  862. op = builtin.SVD(full_matrices=full_matrices, compute_uv=compute_uv)
  863. U, sigma, V = apply(op, inp)
  864. return U, sigma, V
  865. def interpolate(
  866. inp: Tensor,
  867. size: Optional[Union[int, Tuple[int, int]]] = None,
  868. scale_factor: Optional[Union[float, Tuple[float, float]]] = None,
  869. mode: str = "BILINEAR",
  870. align_corners: bool = None,
  871. ) -> Tensor:
  872. r"""Down/up samples the input tensor to either the given size or with the given scale_factor. ``size`` can not coexist with ``scale_factor``.
  873. :param inp: input tensor.
  874. :param size: size of the output tensor. Default: None
  875. :param scale_factor: scaling factor of the output tensor. Default: None
  876. :param mode: interpolation methods, acceptable values are:
  877. "BILINEAR", "LINEAR". Default: "BILINEAR"
  878. :return: output tensor.
  879. Examples:
  880. .. testcode::
  881. import numpy as np
  882. from megengine import tensor
  883. import megengine.functional as F
  884. x = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  885. out = F.nn.interpolate(x, [4, 4], align_corners=False)
  886. print(out.numpy())
  887. out2 = F.nn.interpolate(x, scale_factor=2.)
  888. np.testing.assert_allclose(out.numpy(), out2.numpy())
  889. Outputs:
  890. .. testoutput::
  891. [[[[1. 1.25 1.75 2. ]
  892. [1.5 1.75 2.25 2.5 ]
  893. [2.5 2.75 3.25 3.5 ]
  894. [3. 3.25 3.75 4. ]]]]
  895. """
  896. mode = mode.upper()
  897. if mode not in ["BILINEAR", "LINEAR"]:
  898. raise ValueError("interpolate only support linear or bilinear mode")
  899. if mode not in ["BILINEAR", "LINEAR"]:
  900. if align_corners is not None:
  901. raise ValueError(
  902. "align_corners option can only be set in the bilinear/linear interpolating mode"
  903. )
  904. else:
  905. if align_corners is None:
  906. align_corners = False
  907. if mode == "LINEAR":
  908. inp = add_axis(inp, 3)
  909. if inp.ndim != 4:
  910. raise ValueError("shape of input tensor must correspond to the operartion mode")
  911. if size is None:
  912. if scale_factor is None:
  913. raise ValueError("scale_factor must not be None when size is None")
  914. if isinstance(scale_factor, (float, int)):
  915. scale_factor = float(scale_factor)
  916. if mode == "LINEAR":
  917. scale_factor = (scale_factor, float(1))
  918. else:
  919. scale_factor = (scale_factor, scale_factor)
  920. else:
  921. if mode == "LINEAR":
  922. raise ValueError(
  923. "under LINEAR mode, scale_factor can only be single value"
  924. )
  925. assert len(scale_factor) == 2, "shape of scale_factor must be equal to (2, )"
  926. assert isinstance(scale_factor[0], float) and isinstance(
  927. scale_factor[1], float
  928. ), "scale_factor must be float type"
  929. dsize = tuple(
  930. floor(
  931. Tensor(
  932. inp.shape[i + 2] * scale_factor[i],
  933. dtype="float32",
  934. device=inp.device,
  935. )
  936. )
  937. for i in range(2)
  938. )
  939. dsize = concat([dsize[0], dsize[1]], axis=0)
  940. else:
  941. if scale_factor is not None:
  942. raise ValueError("scale_factor must be None when size is provided")
  943. if isinstance(size, int):
  944. size = (size, 1)
  945. else:
  946. if mode == "LINEAR":
  947. raise ValueError("under LINEAR mode, size can only be single value")
  948. dsize = size
  949. oh, ow = dsize[0], dsize[1]
  950. ih, iw = inp.shape[2], inp.shape[3]
  951. if align_corners:
  952. hscale = (ih - 1.0) / (oh - 1.0)
  953. wscale = 1.0 * iw / ow
  954. if mode != "LINEAR":
  955. wscale = (iw - 1.0) / (ow - 1.0)
  956. row0 = concat(
  957. [wscale, Tensor([0, 0], dtype="float32", device=inp.device)], axis=0
  958. ).reshape(1, 3)
  959. row1 = concat(
  960. [
  961. Tensor(0, dtype="float32", device=inp.device),
  962. hscale,
  963. Tensor(0, dtype="float32", device=inp.device),
  964. ],
  965. axis=0,
  966. ).reshape(1, 3)
  967. weight = concat(
  968. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  969. axis=0,
  970. ).reshape(1, 3, 3)
  971. weight = broadcast(weight, (inp.shape[0], 3, 3))
  972. else:
  973. hscale = 1.0 * ih / oh
  974. wscale = 1.0 * iw / ow
  975. row0 = concat(
  976. [wscale, Tensor(0, dtype="float32", device=inp.device), 0.5 * wscale - 0.5],
  977. axis=0,
  978. ).reshape(1, 3)
  979. row1 = concat(
  980. [Tensor(0, dtype="float32", device=inp.device), hscale, 0.5 * hscale - 0.5],
  981. axis=0,
  982. ).reshape(1, 3)
  983. weight = concat(
  984. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  985. axis=0,
  986. ).reshape(1, 3, 3)
  987. weight = broadcast(weight, (inp.shape[0], 3, 3))
  988. weight = weight.astype("float32")
  989. ret = warp_perspective(inp, weight, dsize, interp_mode="LINEAR")
  990. if mode == "LINEAR":
  991. ret = reshape(ret, ret.shape[0:3])
  992. return ret
  993. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  994. """Returns a new tensor where each of the elements are randomly set to zero
  995. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  996. :param inp: input tensor.
  997. :param drop_prob: probability to drop (set to zero) a single element.
  998. :param training: the default behavior of ``dropout`` during training is to rescale the output,
  999. then it can be replaced by an :class:`~.Identity` during inference. Default: True
  1000. :return: the output tensor
  1001. Examples:
  1002. .. testcode::
  1003. import numpy as np
  1004. from megengine import tensor
  1005. import megengine.functional as F
  1006. x = tensor(np.ones(10, dtype=np.float32))
  1007. out = F.dropout(x, 1./3.)
  1008. print(out.numpy())
  1009. Outputs:
  1010. .. testoutput::
  1011. :options: +SKIP
  1012. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1013. """
  1014. assert 0 <= drop_prob < 1
  1015. rv = uniform(size=inp.shape)
  1016. mask = rv > drop_prob
  1017. inp *= mask.astype(inp.dtype)
  1018. if training:
  1019. inp *= 1 / (1 - drop_prob)
  1020. return inp
  1021. def embedding(
  1022. inp: Tensor,
  1023. weight: Tensor,
  1024. padding_idx: Optional[int] = None,
  1025. max_norm: Optional[float] = None,
  1026. norm_type: Optional[float] = None,
  1027. ):
  1028. """Applies lookup table for embedding.
  1029. :param inp: tensor with indices.
  1030. :param weight: learnable weights which embeds from.
  1031. :param padding_idx: should be set to None, not supported now.
  1032. :param max_norm: should be set to None, not supported now.
  1033. :param norm_type: should be set to None, not supported now.
  1034. :return: output tensor.
  1035. Refer to :class:`~.Embedding` for more information.
  1036. """
  1037. if padding_idx is not None:
  1038. raise ValueError("Not support padding_idx Now!")
  1039. if max_norm is not None or norm_type is not None:
  1040. raise ValueError("Not support weight normlization Now!")
  1041. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1042. return weight[inp.reshape(-1)].reshape(dest_shp)
  1043. def roi_pooling(
  1044. inp: Tensor,
  1045. rois: Tensor,
  1046. output_shape: Union[int, tuple, list],
  1047. mode: str = "max",
  1048. scale: float = 1.0,
  1049. ) -> Tensor:
  1050. """Applies roi pooling on input feature.
  1051. :param inp: tensor that represents the input feature, `(N, C, H, W)` images.
  1052. :param rois: `(K, 5)` boxes. First column is the index into N. The other 4 columns are xyxy.
  1053. :param output_shape: `(height, width)` of output rois feature.
  1054. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "max"
  1055. :param scale: scale the input boxes by this number. Default: 1.0
  1056. :return: `(K, C, output_shape[0], output_shape[1])` feature of rois.
  1057. Examples:
  1058. .. testcode::
  1059. import numpy as np
  1060. from megengine import tensor
  1061. import megengine.functional as F
  1062. np.random.seed(42)
  1063. inp = tensor(np.random.randn(1, 1, 128, 128))
  1064. rois = tensor(np.random.random((4, 5)))
  1065. y = F.roi_pooling(inp, rois, (2, 2))
  1066. print(y.numpy()[0])
  1067. Outputs:
  1068. .. testoutput::
  1069. [[[-0.1383 -0.1383]
  1070. [-0.5035 -0.5035]]]
  1071. """
  1072. assert mode in ["max", "average"], "only max/average mode is supported"
  1073. if isinstance(output_shape, int):
  1074. output_shape = (output_shape, output_shape)
  1075. op = builtin.ROIPooling(mode=mode, scale=scale)
  1076. inp, rois = utils.convert_inputs(inp, rois)
  1077. result, _ = apply(
  1078. op, inp, rois, Tensor(output_shape, dtype="int32", device=inp.device)
  1079. )
  1080. return result
  1081. def roi_align(
  1082. inp: Tensor,
  1083. rois: Tensor,
  1084. output_shape: Union[int, tuple, list],
  1085. mode: str = "average",
  1086. spatial_scale: float = 1.0,
  1087. sample_points: Union[int, tuple, list] = 2,
  1088. aligned: bool = True,
  1089. ) -> Tensor:
  1090. """Applies roi align on input feature.
  1091. :param inp: tensor that represents the input feature, shape is `(N, C, H, W)`.
  1092. :param rois: `(N, 5)` boxes. First column is the box index. The other 4 columns are ``xyxy``.
  1093. :param output_shape: `(height, width)` shape of output rois feature.
  1094. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "average"
  1095. :param spatial_scale: scale the input boxes by this number. Default: 1.0
  1096. :param sample_points: number of inputs samples to take for each output sample.
  1097. 0 to take samples densely. Default: 2
  1098. :param aligned: wheather to align the input feature, with `aligned=True`,
  1099. we first appropriately scale the ROI and then shift it by -0.5. Default: True
  1100. :return: output tensor.
  1101. Examples:
  1102. .. testcode::
  1103. import numpy as np
  1104. from megengine import tensor
  1105. import megengine.functional as F
  1106. np.random.seed(42)
  1107. inp = tensor(np.random.randn(1, 1, 128, 128))
  1108. rois = tensor(np.random.random((4, 5)))
  1109. y = F.roi_align(inp, rois, (2, 2))
  1110. print(y.numpy()[0])
  1111. Outputs:
  1112. .. testoutput::
  1113. [[[0.175 0.175 ]
  1114. [0.1359 0.1359]]]
  1115. """
  1116. assert mode in ["max", "average"], "only max/average mode is supported"
  1117. if isinstance(output_shape, int):
  1118. output_shape = (output_shape, output_shape)
  1119. pooled_height, pooled_width = output_shape
  1120. if isinstance(sample_points, int):
  1121. sample_points = (sample_points, sample_points)
  1122. sample_height, sample_width = sample_points
  1123. offset = 0.5 if aligned else 0.0
  1124. op = builtin.ROIAlign(
  1125. mode=mode,
  1126. format="NCHW",
  1127. spatial_scale=spatial_scale,
  1128. offset=offset,
  1129. pooled_height=pooled_height,
  1130. pooled_width=pooled_width,
  1131. sample_height=sample_height,
  1132. sample_width=sample_width,
  1133. )
  1134. inp, rois = utils.convert_inputs(inp, rois)
  1135. result, *_ = apply(op, inp, rois)
  1136. return result
  1137. def indexing_one_hot(
  1138. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1139. ) -> Tensor:
  1140. r"""One-hot indexing for some axes.
  1141. :param src: input tensor.
  1142. :param index: index tensor.
  1143. :param axis: axis on src for which values in index index. Default: 1
  1144. :param keepdims: whether not to remove the axis in result. Default: False
  1145. :return: output tensor.
  1146. Examples:
  1147. .. testcode::
  1148. import megengine.functional as F
  1149. from megengine import tensor
  1150. src = tensor([[1.0, 2.0]])
  1151. index = tensor([0])
  1152. val = F.indexing_one_hot(src, index)
  1153. print(val.numpy())
  1154. Outputs:
  1155. .. testoutput::
  1156. [1.]
  1157. """
  1158. assert isinstance(
  1159. src, (TensorWrapperBase, TensorBase)
  1160. ), "src must be of Tensor type"
  1161. op = builtin.IndexingOneHot(axis=axis)
  1162. index = utils.convert_single_value(index, (src,), dtype="int32", device=src.device)
  1163. (result,) = apply(op, src, index)
  1164. if not keepdims:
  1165. result = remove_axis(result, axis)
  1166. return result
  1167. def nms(boxes: Tensor, scores: Tensor, iou_thresh: float) -> Tensor:
  1168. r"""
  1169. Performs non-maximum suppression (NMS) on the boxes according to their intersection-over-union(IoU).
  1170. :param boxes: tensor of shape `(N, 4)`; the boxes to perform nms on; each box is expected to be in `(x1, y1, x2, y2)` format.
  1171. :param iou_thresh: IoU threshold for overlapping.
  1172. :param scores: tensor of shape `(N,)`, the score of boxes.
  1173. :return: indices of the elements that have been kept by NMS.
  1174. Examples:
  1175. .. testcode::
  1176. import numpy as np
  1177. from megengine import tensor
  1178. import megengine.functional as F
  1179. x = np.zeros((100,4))
  1180. np.random.seed(42)
  1181. x[:,:2] = np.random.rand(100,2)*20
  1182. x[:,2:] = np.random.rand(100,2)*20 + 100
  1183. scores = tensor(np.random.rand(100))
  1184. inp = tensor(x)
  1185. result = F.nn.nms(inp, scores, iou_thresh=0.7)
  1186. print(result.numpy())
  1187. Outputs:
  1188. .. testoutput::
  1189. [75 69]
  1190. """
  1191. assert (
  1192. boxes.ndim == 2 and boxes.shape[1] == 4
  1193. ), "the expected shape of boxes is (N, 4)"
  1194. assert scores.ndim == 1, "the expected shape of scores is (N,)"
  1195. assert (
  1196. boxes.shape[0] == scores.shape[0]
  1197. ), "number of boxes and scores are not matched"
  1198. boxes = boxes.detach()
  1199. scores = scores.detach()
  1200. sorted_idx = argsort(scores, descending=True)
  1201. boxes = boxes[sorted_idx]
  1202. max_output = boxes.shape[0]
  1203. op = builtin.NMSKeep(iou_thresh, max_output)
  1204. inp = utils.convert_inputs(boxes.reshape(1, -1, 4))
  1205. indices, count = apply(op, *inp)
  1206. indices = indices[0][: count.item()]
  1207. keep_inds = sorted_idx[indices]
  1208. return keep_inds
  1209. from .loss import * # isort:skip
  1210. from .quantized import conv_bias_activation # isort:skip

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