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

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

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