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

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

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