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

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

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