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 62 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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 Iterable, Optional, Sequence, Tuple, Union
  11. from ..core._imperative_rt import CompNode
  12. from ..core._imperative_rt.core2 import apply
  13. from ..core._trace_option import use_symbolic_shape
  14. from ..core.ops import builtin
  15. from ..core.ops.builtin import BatchNorm
  16. from ..core.ops.special import Const
  17. from ..core.tensor import megbrain_graph, utils
  18. from ..core.tensor.utils import astensor1d, setscalar
  19. from ..distributed import WORLD, is_distributed
  20. from ..jit.tracing import is_tracing
  21. from ..random import uniform
  22. from ..tensor import Tensor
  23. from ..utils.tuple_function import _pair, _pair_nonzero
  24. from .debug_param import get_conv_execution_strategy
  25. from .distributed import all_reduce_sum
  26. from .elemwise import exp, floor, log, log1p, maximum, minimum, relu
  27. from .math import argsort, max, prod, sum
  28. from .tensor import (
  29. broadcast_to,
  30. concat,
  31. expand_dims,
  32. full,
  33. ones,
  34. reshape,
  35. squeeze,
  36. zeros,
  37. )
  38. __all__ = [
  39. "adaptive_avg_pool2d",
  40. "adaptive_max_pool2d",
  41. "avg_pool2d",
  42. "batch_norm",
  43. "conv2d",
  44. "conv_transpose2d",
  45. "deformable_conv2d",
  46. "deformable_psroi_pooling",
  47. "dot",
  48. "dropout",
  49. "indexing_one_hot",
  50. "leaky_relu",
  51. "local_conv2d",
  52. "logsigmoid",
  53. "logsumexp",
  54. "logsoftmax",
  55. "matinv",
  56. "matmul",
  57. "max_pool2d",
  58. "one_hot",
  59. "prelu",
  60. "remap",
  61. "resize",
  62. "softmax",
  63. "softplus",
  64. "svd",
  65. "warp_affine",
  66. "warp_perspective",
  67. "conv1d",
  68. ]
  69. def expand_hw(x):
  70. # NOTE: >1d array is accepted, as long as 1 <= size <= 2
  71. try:
  72. x = int(x)
  73. return [x, x]
  74. except (TypeError, ValueError):
  75. pass
  76. h, w = x
  77. return int(h), int(w)
  78. def linear(inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None) -> Tensor:
  79. """
  80. Applies a linear transformation to the input tensor.
  81. Refer to :class:`~.module.linear.Linear` for more information.
  82. :param inp: input tensor with shape `(N, in_features)`.
  83. :param weight: weight with shape `(out_features, in_features)`.
  84. :param bias: bias with shape `(out_features,)`.
  85. Default: None
  86. """
  87. ret = matmul(inp, weight, transpose_b=True)
  88. if bias is not None:
  89. ret += bias
  90. return ret
  91. def conv2d(
  92. inp: Tensor,
  93. weight: Tensor,
  94. bias: Optional[Tensor] = None,
  95. stride: Union[int, Tuple[int, int]] = 1,
  96. padding: Union[int, Tuple[int, int]] = 0,
  97. dilation: Union[int, Tuple[int, int]] = 1,
  98. groups: int = 1,
  99. conv_mode="CROSS_CORRELATION",
  100. compute_mode="DEFAULT",
  101. ) -> Tensor:
  102. """
  103. 2D convolution operation.
  104. Refer to :class:`~.Conv2d` for more information.
  105. :param inp: feature map of the convolution operation.
  106. :param weight: convolution kernel.
  107. :param bias: bias added to the result of convolution (if given).
  108. :param stride: stride of the 2D convolution operation. Default: 1
  109. :param padding: size of the paddings added to the input on both sides of its
  110. spatial dimensions. Only zero-padding is supported. Default: 0
  111. :param dilation: dilation of the 2D convolution operation. Default: 1
  112. :param groups: number of groups into which the input and output channels are divided,
  113. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  114. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  115. and the shape of weight should be `(groups, out_channel // groups,
  116. in_channels // groups, height, width)`.
  117. :type conv_mode: string or :class:`Convolution.Mode`
  118. :param conv_mode: supports "CROSS_CORRELATION". Default:
  119. "CROSS_CORRELATION"
  120. :type compute_mode: string or
  121. :class:`Convolution.ComputeMode`
  122. :param compute_mode: when set to "DEFAULT", no special requirements will be
  123. placed on the precision of intermediate results. When set to "FLOAT32",
  124. "Float32" would be used for accumulator and intermediate result, but only
  125. effective when input and output are of Float16 dtype.
  126. :return: output tensor.
  127. """
  128. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  129. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  130. stride_h, stride_w = expand_hw(stride)
  131. pad_h, pad_w = expand_hw(padding)
  132. dilate_h, dilate_w = expand_hw(dilation)
  133. sparse_type = "DENSE" if groups == 1 else "GROUP"
  134. op = builtin.Convolution(
  135. stride_h=stride_h,
  136. stride_w=stride_w,
  137. pad_h=pad_h,
  138. pad_w=pad_w,
  139. dilate_h=dilate_h,
  140. dilate_w=dilate_w,
  141. strategy=get_conv_execution_strategy(),
  142. mode=conv_mode,
  143. compute_mode=compute_mode,
  144. sparse=sparse_type,
  145. )
  146. inp, weight = utils.convert_inputs(inp, weight)
  147. (output,) = apply(op, inp, weight)
  148. if bias is not None:
  149. output += bias
  150. return output
  151. def conv_transpose2d(
  152. inp: Tensor,
  153. weight: Tensor,
  154. bias: Optional[Tensor] = None,
  155. stride: Union[int, Tuple[int, int]] = 1,
  156. padding: Union[int, Tuple[int, int]] = 0,
  157. dilation: Union[int, Tuple[int, int]] = 1,
  158. groups: int = 1,
  159. conv_mode="CROSS_CORRELATION",
  160. compute_mode="DEFAULT",
  161. ) -> Tensor:
  162. """
  163. 2D transposed convolution operation.
  164. Refer to :class:`~.ConvTranspose2d` for more information.
  165. :param inp: feature map of the convolution operation.
  166. :param weight: convolution kernel.
  167. :param bias: bias added to the result of convolution (if given).
  168. :param stride: stride of the 2D convolution operation. Default: 1
  169. :param padding: size of the paddings added to the input on both sides of its
  170. spatial dimensions. Only zero-padding is supported. Default: 0
  171. :param dilation: dilation of the 2D convolution operation. Default: 1
  172. :param groups: number of groups into which the input and output channels are divided,
  173. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  174. ``in_channels`` and ``out_channels`` must be divisible by groups,
  175. and the shape of weight should be `(groups, out_channel // groups,
  176. in_channels // groups, height, width)`. Default: 1
  177. :type conv_mode: string or :class:`Convolution.Mode`
  178. :param conv_mode: supports "CROSS_CORRELATION". Default:
  179. "CROSS_CORRELATION"
  180. :type compute_mode: string or
  181. :class:`Convolution.ComputeMode`
  182. :param compute_mode: when set to "DEFAULT", no special requirements will be
  183. placed on the precision of intermediate results. When set to "FLOAT32",
  184. "Float32" would be used for accumulator and intermediate result, but only
  185. effective when input and output are of Float16 dtype.
  186. :return: output tensor.
  187. """
  188. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  189. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  190. if groups != 1:
  191. raise NotImplementedError("TODO")
  192. stride_h, stride_w = expand_hw(stride)
  193. pad_h, pad_w = expand_hw(padding)
  194. dilate_h, dilate_w = expand_hw(dilation)
  195. op = builtin.ConvolutionBackwardData(
  196. stride_h=stride_h,
  197. stride_w=stride_w,
  198. pad_h=pad_h,
  199. pad_w=pad_w,
  200. dilate_h=dilate_h,
  201. dilate_w=dilate_w,
  202. strategy=get_conv_execution_strategy(),
  203. )
  204. weight, inp = utils.convert_inputs(weight, inp)
  205. (output,) = apply(op, weight, inp)
  206. if bias is not None:
  207. output += bias
  208. return output
  209. def deformable_conv2d(
  210. inp: Tensor,
  211. weight: Tensor,
  212. offset: Tensor,
  213. mask: Tensor,
  214. bias: Optional[Tensor] = None,
  215. stride: Union[int, Tuple[int, int]] = 1,
  216. padding: Union[int, Tuple[int, int]] = 0,
  217. dilation: Union[int, Tuple[int, int]] = 1,
  218. groups: int = 1,
  219. conv_mode="CROSS_CORRELATION",
  220. compute_mode="DEFAULT",
  221. ) -> Tensor:
  222. """
  223. Deformable Convolution.
  224. :param inp: input feature map.
  225. :param weight: convolution kernel.
  226. :param offset: input offset to kernel, channel of this tensor should match the deformable settings.
  227. :param mask: input mask to kernel, channel of this tensor should match the deformable settings.
  228. :param bias: bias added to the result of convolution (if given).
  229. :param stride: stride of the 2D convolution operation. Default: 1
  230. :param padding: size of the paddings added to the input on both sides of its
  231. spatial dimensions. Only zero-padding is supported. Default: 0
  232. :param dilation: dilation of the 2D convolution operation. Default: 1
  233. :param groups: number of groups into which the input and output channels are divided,
  234. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  235. ``in_channels`` and ``out_channels`` must be divisible by groups,
  236. and the shape of weight should be `(groups, out_channel // groups,
  237. in_channels // groups, height, width)`. Default: 1
  238. :type conv_mode: string or :class:`Convolution.Mode`
  239. :param conv_mode: supports "CROSS_CORRELATION". Default:
  240. "CROSS_CORRELATION"
  241. :type compute_mode: string or
  242. :class:`Convolution.ComputeMode`
  243. :param compute_mode: when set to "DEFAULT", no special requirements will be
  244. placed on the precision of intermediate results. When set to "FLOAT32",
  245. "Float32" would be used for accumulator and intermediate result, but only
  246. effective when input and output are of Float16 dtype.
  247. :return: output tensor.
  248. """
  249. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  250. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  251. stride_h, stride_w = expand_hw(stride)
  252. pad_h, pad_w = expand_hw(padding)
  253. dilate_h, dilate_w = expand_hw(dilation)
  254. sparse_type = "DENSE" if groups == 1 else "GROUP"
  255. op = builtin.DeformableConv(
  256. stride_h=stride_h,
  257. stride_w=stride_w,
  258. pad_h=pad_h,
  259. pad_w=pad_w,
  260. dilate_h=dilate_h,
  261. dilate_w=dilate_w,
  262. strategy=get_conv_execution_strategy(),
  263. mode=conv_mode,
  264. compute_mode=compute_mode,
  265. sparse=sparse_type,
  266. )
  267. inp, weight, offset, mask = utils.convert_inputs(inp, weight, offset, mask)
  268. (output,) = apply(op, inp, weight, offset, mask)
  269. if bias is not None:
  270. output += bias
  271. return output
  272. def local_conv2d(
  273. inp: Tensor,
  274. weight: Tensor,
  275. bias: Optional[Tensor] = None,
  276. stride: Union[int, Tuple[int, int]] = 1,
  277. padding: Union[int, Tuple[int, int]] = 0,
  278. dilation: Union[int, Tuple[int, int]] = 1,
  279. conv_mode="CROSS_CORRELATION",
  280. ):
  281. """Applies spatial 2D convolution over an groupped channeled image with untied kernels."""
  282. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  283. stride_h, stride_w = expand_hw(stride)
  284. pad_h, pad_w = expand_hw(padding)
  285. dilate_h, dilate_w = expand_hw(dilation)
  286. op = builtin.GroupLocal(
  287. stride_h=stride_h,
  288. stride_w=stride_w,
  289. pad_h=pad_h,
  290. pad_w=pad_w,
  291. dilate_h=dilate_h,
  292. dilate_w=dilate_w,
  293. mode=conv_mode,
  294. compute_mode="DEFAULT",
  295. sparse="DENSE",
  296. )
  297. inp, weight = utils.convert_inputs(inp, weight)
  298. (output,) = apply(op, inp, weight)
  299. if bias is not None:
  300. output += bias
  301. return output
  302. def max_pool2d(
  303. inp: Tensor,
  304. kernel_size: Union[int, Tuple[int, int]],
  305. stride: Optional[Union[int, Tuple[int, int]]] = None,
  306. padding: Union[int, Tuple[int, int]] = 0,
  307. ) -> Tensor:
  308. """
  309. Applies a 2D max pooling over an input tensor.
  310. Refer to :class:`~.MaxPool2d` for more information.
  311. :param inp: input tensor.
  312. :param kernel_size: size of the window.
  313. :param stride: stride of the window. If not provided, its value is set to kernel_size.
  314. Default: None
  315. :param padding: implicit zero padding added on both sides. Default: 0
  316. :return: output tensor.
  317. """
  318. if stride is None:
  319. stride = kernel_size
  320. window_h, window_w = _pair_nonzero(kernel_size)
  321. stride_h, stride_w = _pair_nonzero(stride)
  322. padding_h, padding_w = _pair(padding)
  323. op = builtin.Pooling(
  324. window_h=window_h,
  325. window_w=window_w,
  326. stride_h=stride_h,
  327. stride_w=stride_w,
  328. pad_h=padding_h,
  329. pad_w=padding_w,
  330. mode="MAX",
  331. )
  332. (output,) = apply(op, inp)
  333. return output
  334. def avg_pool2d(
  335. inp: Tensor,
  336. kernel_size: Union[int, Tuple[int, int]],
  337. stride: Optional[Union[int, Tuple[int, int]]] = None,
  338. padding: Union[int, Tuple[int, int]] = 0,
  339. mode: str = "AVERAGE_COUNT_EXCLUDE_PADDING",
  340. ) -> Tensor:
  341. """
  342. Applies 2D average pooling over an input tensor.
  343. Refer to :class:`~.AvgPool2d` for more information.
  344. :param inp: input tensor.
  345. :param kernel_size: size of the window.
  346. :param stride: stride of the window. If not provided, its value is set to ``kernel_size``.
  347. Default: None
  348. :param padding: implicit zero padding added on both sides. Default: 0
  349. :param mode: whether to count padding values. Default: "AVERAGE_COUNT_EXCLUDE_PADDING"
  350. :return: output tensor.
  351. """
  352. if stride is None:
  353. stride = kernel_size
  354. window_h, window_w = _pair_nonzero(kernel_size)
  355. stride_h, stride_w = _pair_nonzero(stride)
  356. padding_h, padding_w = _pair(padding)
  357. op = builtin.Pooling(
  358. window_h=window_h,
  359. window_w=window_w,
  360. stride_h=stride_h,
  361. stride_w=stride_w,
  362. pad_h=padding_h,
  363. pad_w=padding_w,
  364. mode=mode,
  365. )
  366. (output,) = apply(op, inp)
  367. return output
  368. def adaptive_max_pool2d(
  369. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  370. ) -> Tensor:
  371. """
  372. Applies a 2D max adaptive pooling over an input.
  373. Refer to :class:`~.MaxAdaptivePool2d` for more information.
  374. :param inp: input tensor.
  375. :param oshp: `(OH, OW)` size of the output shape.
  376. :return: output tensor.
  377. """
  378. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  379. if isinstance(oshp, int):
  380. oshp = (oshp, oshp)
  381. op = builtin.AdaptivePooling(mode="MAX", format="NCHW",)
  382. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  383. (output,) = apply(op, inp, oshp)
  384. return output
  385. def adaptive_avg_pool2d(
  386. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  387. ) -> Tensor:
  388. """
  389. Applies a 2D average adaptive pooling over an input.
  390. Refer to :class:`~.AvgAdaptivePool2d` for more information.
  391. :param inp: input tensor.
  392. :param oshp: `(OH, OW)` size of the output shape.
  393. :return: output tensor.
  394. """
  395. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  396. if isinstance(oshp, int):
  397. oshp = (oshp, oshp)
  398. op = builtin.AdaptivePooling(mode="AVERAGE", format="NCHW",)
  399. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  400. (output,) = apply(op, inp, oshp)
  401. return output
  402. def deformable_psroi_pooling(
  403. inp: Tensor,
  404. rois: Tensor,
  405. trans: Tensor,
  406. no_trans: bool,
  407. part_size: int,
  408. pooled_h: int,
  409. pooled_w: int,
  410. sample_per_part: int,
  411. spatial_scale: float,
  412. trans_std: float = 0.1,
  413. ):
  414. """
  415. Deformable PSROI(Position Sensitive Region of Interest) Pooling.
  416. :param inp: input feature map.
  417. :param rois: the rois for feature pooling.
  418. :param trans: input offset to psroi_pooling.
  419. :param no_trans: check the phase of DeformablePSROIPooling. False to the
  420. 1st phase, True to the 2nd phase.
  421. :param part_size: part size.
  422. :param sample_per_part: sample points of each part.
  423. :param pooled_shape: kernel shape of convolution.
  424. :param spatial_scale: the spatial_scale w.r.t input image.
  425. :param trans_std: multiplier used in 2nd phase.
  426. """
  427. op = builtin.DeformablePSROIPooling(
  428. no_trans=no_trans,
  429. part_size=part_size,
  430. pooled_h=pooled_h,
  431. pooled_w=pooled_w,
  432. sample_per_part=sample_per_part,
  433. spatial_scale=spatial_scale,
  434. trans_std=trans_std,
  435. )
  436. output, _ = apply(op, inp, rois, trans)
  437. return output
  438. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  439. r"""
  440. Applies the element-wise PReLU function.
  441. Refer to :class:`~.PReLU` for more information.
  442. """
  443. return maximum(inp, 0) + weight * minimum(inp, 0)
  444. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  445. r"""
  446. Applies the element-wise leaky_relu function
  447. Refer to :class:`~.LeakyReLU` for more information.
  448. """
  449. return maximum(inp, 0) + negative_slope * minimum(inp, 0)
  450. def softplus(inp: Tensor) -> Tensor:
  451. r"""
  452. Applies the element-wise function:
  453. .. math::
  454. \text{softplus}(x) = \log(1 + \exp(x))
  455. softplus is a smooth approximation to the ReLU function and can be used
  456. to constrain the output to be always positive.
  457. For numerical stability the implementation follows this transformation:
  458. .. math::
  459. \text{softplus}(x) = \log(1 + \exp(x))
  460. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  461. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  462. :param inp: input tensor.
  463. Examples:
  464. .. testcode::
  465. import numpy as np
  466. from megengine import tensor
  467. import megengine.functional as F
  468. x = tensor(np.arange(-3, 3, dtype=np.float32))
  469. y = F.softplus(x)
  470. print(y.numpy().round(decimals=4))
  471. Outputs:
  472. .. testoutput::
  473. [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
  474. """
  475. return log1p(exp(-abs(inp))) + relu(inp)
  476. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  477. r"""
  478. Applies the :math:`\log(\text{softmax}(x))` function to an n-dimensional
  479. input tensor. The :math:`\text{logsoftmax}(x)` formulation can be simplified as:
  480. .. math::
  481. \text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  482. For numerical stability the implementation follows this transformation:
  483. .. math::
  484. \text{logsoftmax}(x)
  485. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  486. = x - \log (\sum_{i}(\exp (x_{i})))
  487. = x - \text{logsumexp}(x)
  488. :param inp: input tensor.
  489. :param axis: axis along which :math:`\text{logsoftmax}(x)` will be applied.
  490. Examples:
  491. .. testcode::
  492. import numpy as np
  493. from megengine import tensor
  494. import megengine.functional as F
  495. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  496. y = F.logsoftmax(x, axis=1)
  497. print(y.numpy().round(decimals=4))
  498. Outputs:
  499. .. testoutput::
  500. [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
  501. [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
  502. """
  503. return inp - logsumexp(inp, axis, keepdims=True)
  504. def logsigmoid(inp: Tensor) -> Tensor:
  505. r"""
  506. Applies the element-wise function:
  507. .. math::
  508. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  509. = \log(1/(1 + \exp(-x)))
  510. = - \log(1 + \exp(-x))
  511. = - \text{softplus}(-x)
  512. :param inp: input tensor.
  513. Examples:
  514. .. testcode::
  515. import numpy as np
  516. from megengine import tensor
  517. import megengine.functional as F
  518. x = tensor(np.arange(-5, 5, dtype=np.float32))
  519. y = F.logsigmoid(x)
  520. print(y.numpy().round(decimals=4))
  521. Outputs:
  522. .. testoutput::
  523. [-5.0067 -4.0182 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
  524. -0.0181]
  525. """
  526. return -softplus(-inp)
  527. def logsumexp(
  528. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  529. ) -> Tensor:
  530. r"""
  531. Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  532. .. math::
  533. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  534. For numerical stability, the implementation follows this transformation:
  535. .. math::
  536. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  537. = \text{logsumexp}(x)=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  538. where
  539. .. math::
  540. b = \max(x_j)
  541. :param inp: input tensor.
  542. :param axis: axis over which the sum is taken. It could be single axis or list of axes.
  543. :param keepdims: whether to retain :attr:`axis` or not for the output tensor.
  544. Examples:
  545. .. testcode::
  546. import numpy as np
  547. from megengine import tensor
  548. import megengine.functional as F
  549. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  550. y = F.logsumexp(x, axis=1, keepdims=False)
  551. print(y.numpy().round(decimals=4))
  552. Outputs:
  553. .. testoutput::
  554. [-0.5481 4.4519]
  555. """
  556. max_value = max(inp.detach(), axis, keepdims=True)
  557. if keepdims:
  558. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  559. else:
  560. return squeeze(max_value, axis=None) + log(
  561. sum(exp(inp - max_value), axis, keepdims)
  562. )
  563. def _get_softmax_axis(ndim: int) -> int:
  564. if ndim in (0, 1, 3):
  565. return 0
  566. return 1
  567. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  568. r"""
  569. Applies a :math:`\text{softmax}(x)` function. :math:`\text{softmax}(x)` is defined as:
  570. .. math::
  571. \text{softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  572. It is applied to all elements along axis, and rescales elements so that
  573. they stay in the range `[0, 1]` and sum to 1.
  574. See :class:`~megengine.module.activation.Softmax` for more details.
  575. :param inp: input tensor.
  576. :param axis: an axis along which :math:`\text{softmax}(x)` will be applied. By default,
  577. :math:`\text{softmax}(x)` will apply along the highest ranked axis.
  578. Examples:
  579. .. testcode::
  580. import numpy as np
  581. from megengine import tensor
  582. import megengine.functional as F
  583. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  584. out = F.softmax(x)
  585. print(out.numpy().round(decimals=4))
  586. Outputs:
  587. .. testoutput::
  588. [[0.0117 0.0317 0.0861 0.2341 0.6364]
  589. [0.0117 0.0317 0.0861 0.2341 0.6364]]
  590. """
  591. if axis is None:
  592. axis = _get_softmax_axis(len(inp.shape))
  593. offset = inp.max(axis=axis, keepdims=True).detach()
  594. cached = exp(inp - offset)
  595. down = sum(cached, axis=axis, keepdims=True)
  596. return cached / down
  597. def batch_norm(
  598. inp: Tensor,
  599. running_mean: Tensor = None,
  600. running_var: Tensor = None,
  601. weight: Optional[Tensor] = None,
  602. bias: Optional[Tensor] = None,
  603. *,
  604. training: bool = False,
  605. momentum: float = 0.9,
  606. eps: float = 1e-5,
  607. inplace: bool = True
  608. ):
  609. r"""
  610. Applies batch normalization to the input.
  611. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  612. :param inp: input tensor.
  613. :param running_mean: tensor to store running mean.
  614. :param running_var: tensor to store running variance.
  615. :param weight: scaling tensor in the learnable affine parameters.
  616. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  617. :param bias: bias tensor in the learnable affine parameters.
  618. See :math:`\beta` in :class:`~.BatchNorm2d`.
  619. :param training: a boolean value to indicate whether batch norm is performed
  620. in training mode. Default: False
  621. :param momentum: value used for the ``running_mean`` and ``running_var``
  622. computation.
  623. Default: 0.9
  624. :param eps: a value added to the denominator for numerical stability.
  625. Default: 1e-5
  626. :param inplace: whether to update ``running_mean`` and ``running_var`` inplace or return new tensors
  627. Default: True
  628. :return: output tensor.
  629. """
  630. if inp.ndim != 4:
  631. raise NotImplementedError("batch_norm for ndim != 4")
  632. C = inp.shape[1]
  633. def make_full_if_none(x, value):
  634. if x is None:
  635. (x,) = Const(value, dtype=inp.dtype, device=inp.device)()
  636. shape = utils.astensor1d(
  637. (1, C, 1, 1), inp, dtype="int32", device=inp.device
  638. )
  639. (result,) = apply(builtin.Broadcast(), x, shape)
  640. return result
  641. elif x.ndim == 1:
  642. shape = utils.astensor1d(
  643. (1, C, 1, 1), inp, dtype="int32", device=inp.device
  644. )
  645. (result,) = apply(builtin.Reshape(), x, shape)
  646. return result
  647. return x
  648. has_mean = running_mean is not None
  649. has_var = running_var is not None
  650. if not training:
  651. assert has_mean, "running_mean must be provided in inference mode"
  652. assert has_var, "running_var must be provided in inference mode"
  653. if has_mean and running_mean.ndim != 4:
  654. raise ValueError
  655. if has_var and running_var.ndim != 4:
  656. raise ValueError
  657. inp, weight, bias, running_mean, running_var = utils.convert_inputs(
  658. inp, weight, bias, running_mean, running_var
  659. )
  660. weight = make_full_if_none(weight, 1)
  661. bias = make_full_if_none(bias, 0)
  662. if not training:
  663. op = builtin.BatchNorm(
  664. fwd_mode=BatchNorm.FwdMode.INFERENCE, epsilon=eps, param_dim="DIM_1C11"
  665. )
  666. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  667. return ret
  668. else:
  669. op = builtin.BatchNorm(
  670. avg_factor=1 - momentum, epsilon=eps, param_dim="DIM_1C11"
  671. )
  672. if has_mean or has_var:
  673. running_mean = make_full_if_none(running_mean, 0)
  674. running_var = make_full_if_none(running_var, 1)
  675. new_mean, new_var, _, _, inp = apply(
  676. op, inp, weight, bias, running_mean, running_var
  677. )
  678. if not has_mean:
  679. new_mean = None
  680. if not has_var:
  681. new_var = None
  682. if inplace:
  683. if has_mean:
  684. running_mean[...] = new_mean
  685. if has_var:
  686. running_var[...] = new_var
  687. return inp
  688. else:
  689. return inp, new_mean, new_var
  690. else:
  691. (_, _, inp,) = apply(op, inp, weight, bias)
  692. return inp
  693. def sync_batch_norm(
  694. inp: Tensor,
  695. running_mean: Tensor,
  696. running_var: Tensor,
  697. weight: Optional[Tensor] = None,
  698. bias: Optional[Tensor] = None,
  699. training: bool = False,
  700. momentum: Union[float, Tensor] = 0.9,
  701. eps: float = 1e-5,
  702. eps_mode="ADDITIVE",
  703. group=WORLD,
  704. ) -> Tensor:
  705. r"""
  706. Applies synchronized batch normalization to the input.
  707. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  708. :param inp: input tensor.
  709. :param running_mean: tensor to store running mean.
  710. :param running_var: tensor to store running variance.
  711. :param weight: scaling tensor in the learnable affine parameters.
  712. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  713. :param bias: bias tensor in the learnable affine parameters.
  714. See :math:`\beta` in :class:`~.BatchNorm2d`.
  715. :param training: a boolean value to indicate whether batch norm is performed
  716. in traning mode. Default: False
  717. :param momentum: value used for the ``running_mean`` and ``running_var``
  718. computation.
  719. Default: 0.9
  720. :param eps: a value added to the denominator for numerical stability.
  721. Default: 1e-5
  722. :return: output tensor.
  723. """
  724. assert eps_mode in {"MAX", "ADDITIVE"}, "unknown eps_mode: {}".format(eps_mode)
  725. _channels = inp.shape[1]
  726. _ndim = inp.ndim
  727. _device = inp.device
  728. _dtype = inp.dtype
  729. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  730. _reduce_axis = [0] + [i for i in range(2, _ndim)]
  731. if training:
  732. def _sum_on_channel(inp):
  733. return inp.sum(axis=_reduce_axis, keepdims=True)
  734. reduce_size = inp.shape[0]
  735. for i in range(2, _ndim):
  736. reduce_size = reduce_size * inp.shape[i]
  737. channel_x1s = _sum_on_channel(inp)
  738. channel_x2s = _sum_on_channel(inp ** 2)
  739. if is_distributed():
  740. # reduce all nodes' data to calculate mean and variance
  741. reduce_size = broadcast_to(
  742. Tensor(reduce_size).astype(dtype=_dtype), [1] * _ndim
  743. )
  744. stat = concat([reduce_size, channel_x1s, channel_x2s], axis=1)
  745. stat = all_reduce_sum(stat, group)
  746. reduce_size = stat[:, :1].reshape(1)
  747. channel_x1s = stat[:, 1 : 1 + _channels]
  748. channel_x2s = stat[:, 1 + _channels :]
  749. channel_mean = channel_x1s / reduce_size
  750. channel_variance = (
  751. channel_x1s ** 2 / (-reduce_size * reduce_size) + channel_x2s / reduce_size
  752. )
  753. else:
  754. assert running_var is not None and running_mean is not None
  755. channel_variance = running_var.reshape(*_param_shape)
  756. channel_mean = running_mean.reshape(*_param_shape)
  757. invsqrt_channel_variance = (
  758. maximum(channel_variance, eps) if eps_mode == "MAX" else channel_variance + eps
  759. ) ** -0.5
  760. if weight is not None:
  761. weight = weight.reshape(*_param_shape)
  762. if bias is not None:
  763. bias = bias.reshape(*_param_shape)
  764. # outvar = output * weight + bias
  765. # where output = inp * invsqrt_channel_variance + (
  766. # -channel_mean * invsqrt_channel_variance
  767. # )
  768. # Manually expand output for gopt
  769. if weight is not None:
  770. inv_var_wt = invsqrt_channel_variance * weight
  771. neg_channel_mean = -channel_mean
  772. if bias is not None:
  773. outvar = inp * inv_var_wt + (neg_channel_mean * inv_var_wt + bias)
  774. else:
  775. outvar = inp * inv_var_wt + neg_channel_mean * inv_var_wt
  776. else:
  777. outvar = inp * invsqrt_channel_variance + (
  778. -channel_mean * invsqrt_channel_variance
  779. )
  780. if bias is not None:
  781. outvar = outvar + bias
  782. if training and running_var is not None and running_mean is not None:
  783. running_mean *= momentum
  784. running_mean += (1 - momentum) * channel_mean
  785. channel_variance_unbiased = channel_x1s ** 2 / (
  786. -reduce_size * (reduce_size - 1)
  787. ) + channel_x2s / (reduce_size - 1)
  788. running_var *= momentum
  789. running_var += (1 - momentum) * channel_variance_unbiased
  790. return outvar
  791. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  792. r"""
  793. Performs one-hot encoding for the input tensor.
  794. :param inp: input tensor.
  795. :param num_classes: number of classes denotes the last dimension of the output tensor.
  796. :return: output tensor.
  797. Examples:
  798. .. testcode::
  799. import numpy as np
  800. from megengine import tensor
  801. import megengine.functional as F
  802. x = tensor(np.arange(1, 4, dtype=np.int32))
  803. out = F.one_hot(x, num_classes=4)
  804. print(out.numpy())
  805. Outputs:
  806. .. testoutput::
  807. [[0 1 0 0]
  808. [0 0 1 0]
  809. [0 0 0 1]]
  810. """
  811. zeros_tensor = zeros(list(inp.shape) + [num_classes], inp.dtype, inp.device)
  812. ones_tensor = ones(list(inp.shape) + [1], inp.dtype, inp.device)
  813. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  814. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  815. return result
  816. def resize(
  817. inp: Tensor, target_shape: Iterable[int], interp_mode: str = "LINEAR"
  818. ) -> Tensor:
  819. r"""
  820. Applies resize transformation to batched 2D images.
  821. :param inp: `(N, C, H, W)` input tensor. Currently only support "NCHW" format.
  822. :param target_shape: `(H, W)` target images shape.
  823. :param interp_mode: interpolation methods. Defaule mode is "LINEAR", Currently only support "LINEAR".
  824. Examples:
  825. .. testcode::
  826. import numpy as np
  827. from megengine import tensor
  828. import megengine.functional as F
  829. x = tensor(np.random.randn(10, 3, 32, 32))
  830. out = F.resize(x, (16, 16))
  831. print(out.numpy().shape)
  832. Outputs:
  833. .. testoutput::
  834. (10, 3, 16, 16)
  835. """
  836. op = builtin.Resize(imode=interp_mode, format="NCHW")
  837. shape = astensor1d(target_shape, inp, dtype="int32", device=inp.device)
  838. (result,) = apply(op, inp, shape)
  839. return result
  840. def warp_affine(
  841. inp: Tensor,
  842. weight: Tensor,
  843. out_shape,
  844. border_mode="REPLICATE",
  845. border_val=0,
  846. format="NHWC",
  847. imode="LINEAR",
  848. ):
  849. """
  850. Batched affine transform on 2D images.
  851. :param inp: input image.
  852. :param weight: weight tensor.
  853. :param out_shape: output tensor shape.
  854. :param border_mode: pixel extrapolation method.
  855. Default: "WRAP". Currently "CONSTANT", "REFLECT",
  856. "REFLECT_101", "ISOLATED", "WRAP", "REPLICATE", "TRANSPARENT" are supported.
  857. :param border_val: value used in case of a constant border. Default: 0
  858. :param format: "NHWC" as default based on historical concerns,
  859. "NCHW" is also supported. Default: "NCHW".
  860. :param imode: interpolation methods. Could be "LINEAR", "NEAREST", "CUBIC", "AREA".
  861. Default: "LINEAR".
  862. :return: output tensor.
  863. .. note::
  864. Here all available options for params are listed,
  865. however it does not mean that you can use all the combinations.
  866. On different platforms, different combinations are supported.
  867. """
  868. op = builtin.WarpAffine(
  869. border_mode=border_mode, border_val=border_val, format=format, imode=imode
  870. )
  871. out_shape = utils.astensor1d(out_shape, inp, dtype="int32", device=inp.device)
  872. (result,) = apply(op, inp, weight, out_shape)
  873. return result
  874. def warp_perspective(
  875. inp: Tensor,
  876. M: Tensor,
  877. dsize: Union[Tuple[int, int], int, Tensor],
  878. border_mode: str = "REPLICATE",
  879. border_val: float = 0.0,
  880. interp_mode: str = "LINEAR",
  881. ) -> Tensor:
  882. r"""
  883. Applies perspective transformation to batched 2D images.
  884. The input images are transformed to the output images by the transformation matrix:
  885. .. math::
  886. \text{output}(n, c, h, w) = \text{input} \left( n, c,
  887. \frac{M_{00}h + M_{01}w + M_{02}}{M_{20}h + M_{21}w + M_{22}},
  888. \frac{M_{10}h + M_{11}w + M_{12}}{M_{20}h + M_{21}w + M_{22}}
  889. \right)
  890. :param inp: input image.
  891. :param M: `(batch, 3, 3)` transformation matrix.
  892. :param dsize: `(h, w)` size of the output image.
  893. :param border_mode: pixel extrapolation method.
  894. Default: "REPLICATE". Currently also support "CONSTANT", "REFLECT",
  895. "REFLECT_101", "WRAP".
  896. :param border_val: value used in case of a constant border. Default: 0
  897. :param interp_mode: interpolation methods.
  898. Default: "LINEAR". Currently only support "LINEAR" mode.
  899. :return: output tensor.
  900. Note:
  901. The transformation matrix is the inverse of that used by `cv2.warpPerspective`.
  902. Examples:
  903. .. testcode::
  904. import numpy as np
  905. from megengine import tensor
  906. import megengine.functional as F
  907. inp_shape = (1, 1, 4, 4)
  908. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  909. M_shape = (1, 3, 3)
  910. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  911. M = tensor(np.array([[1., 0., 1.],
  912. [0., 1., 1.],
  913. [0., 0., 1.]], dtype=np.float32).reshape(M_shape))
  914. out = F.warp_perspective(x, M, (2, 2))
  915. print(out.numpy())
  916. Outputs:
  917. .. testoutput::
  918. [[[[ 5. 6.]
  919. [ 9. 10.]]]]
  920. """
  921. op = builtin.WarpPerspective(
  922. imode=interp_mode, bmode=border_mode, format="NCHW", border_val=border_val
  923. )
  924. inp, M = utils.convert_inputs(inp, M)
  925. dsize = astensor1d(dsize, inp, dtype="int32", device=inp.device)
  926. (result,) = apply(op, inp, M, dsize)
  927. return result
  928. def remap(
  929. inp: Tensor,
  930. map_xy: Tensor,
  931. border_mode: str = "REPLICATE",
  932. scalar: float = 0.0,
  933. interp_mode: str = "LINEAR",
  934. ) -> Tensor:
  935. r"""
  936. Applies remap transformation to batched 2D images.
  937. The input images are transformed to the output images by the tensor map_xy.
  938. The output's H and W are same as map_xy's H and W.
  939. :param inp: input image
  940. :param map_xy: (batch, oh, ow, 2) transformation matrix
  941. :param border_mode: pixel extrapolation method.
  942. Default: "REPLICATE". Currently also support "CONSTANT", "REFLECT",
  943. "REFLECT_101", "WRAP".
  944. :param scalar: value used in case of a constant border. Default: 0
  945. :param interp_mode: interpolation methods.
  946. Default: "LINEAR". Currently only support "LINEAR" mode.
  947. :return: output tensor.
  948. Examples:
  949. .. testcode::
  950. import numpy as np
  951. from megengine import tensor
  952. import megengine.functional as F
  953. inp_shape = (1, 1, 4, 4)
  954. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  955. map_xy_shape = (1, 2, 2, 2)
  956. map_xy = tensor(np.array([[[1., 0.],[0., 1.]],
  957. [[0., 1.],[0., 1.]]],
  958. dtype=np.float32).reshape(map_xy_shape))
  959. out = F.remap(inp, map_xy)
  960. print(out.numpy())
  961. Outputs:
  962. .. testoutput::
  963. [[[[1. 4.]
  964. [4. 4.]]]]
  965. """
  966. op = builtin.Remap(
  967. imode=interp_mode, border_type=border_mode, format="NCHW", scalar=scalar
  968. )
  969. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  970. (result,) = apply(op, inp, map_xy)
  971. return result
  972. def matinv(inp: Tensor) -> Tensor:
  973. """
  974. Computes the inverse of a batch of matrices; input must has shape [..., n, n].
  975. :param inp: input tensor.
  976. :return: output tensor.
  977. Examples:
  978. .. testcode::
  979. import numpy as np
  980. from megengine import tensor
  981. import megengine.functional as F
  982. data = tensor([[1.0, 0.0], [1.0, 1.0]])
  983. out = F.matinv(data)
  984. print(out.numpy())
  985. Outputs:
  986. .. testoutput::
  987. [[ 1. 0.]
  988. [-1. 1.]]
  989. """
  990. (result,) = apply(builtin.MatrixInverse(), inp)
  991. return result
  992. def matmul(
  993. inp1: Tensor,
  994. inp2: Tensor,
  995. transpose_a=False,
  996. transpose_b=False,
  997. compute_mode="DEFAULT",
  998. format="DEFAULT",
  999. ) -> Tensor:
  1000. """
  1001. Performs a matrix multiplication of the matrices ``inp1`` and ``inp2``.
  1002. With different inputs dim, this function behaves differently:
  1003. - Both 1-D tensor, simply forward to ``dot``.
  1004. - Both 2-D tensor, normal matrix multiplication.
  1005. - If one input tensor is 1-D, matrix vector multiplication.
  1006. - 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
  1007. be broadcasted. For example:
  1008. - inp1: `(n, k, m)`, inp2: `(n, m, p)`, return: `(n, k, p)`
  1009. - inp1: `(n, k, m)`, inp2: `(m, p)`, return: `(n, k, p)`
  1010. - inp1: `(n, j, k, m)`, inp2: `(n, j, m, p)`, return: `(n, j, k, p)`
  1011. :param inp1: first matrix to be multiplied.
  1012. :param inp2: second matrix to be multiplied.
  1013. :return: output tensor.
  1014. Examples:
  1015. .. testcode::
  1016. import numpy as np
  1017. from megengine import tensor
  1018. import megengine.functional as F
  1019. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  1020. data2 = tensor(np.arange(0, 6, dtype=np.float32).reshape(3, 2))
  1021. out = F.matmul(data1, data2)
  1022. print(out.numpy())
  1023. Outputs:
  1024. .. testoutput::
  1025. [[10. 13.]
  1026. [28. 40.]]
  1027. """
  1028. remove_row, remove_col = False, False
  1029. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  1030. dim1, dim2 = inp1.ndim, inp2.ndim
  1031. # handle dim=1 cases, dot and matrix-vector multiplication
  1032. if dim1 == 1 and dim2 == 1:
  1033. return dot(inp1, inp2)
  1034. # the underlying matmul op requires input dims to be at least 2
  1035. if dim1 == 1:
  1036. inp1 = expand_dims(inp1, 0)
  1037. dim1 = 2
  1038. remove_row = True
  1039. if dim2 == 1:
  1040. inp2 = expand_dims(inp2, 1)
  1041. dim2 = 2
  1042. remove_col = True
  1043. batch_shape = None
  1044. shape1 = inp1.shape
  1045. shape2 = inp2.shape
  1046. maxdim = dim1 if dim1 > dim2 else dim2
  1047. if dim1 >= 3 or dim2 >= 3:
  1048. if use_symbolic_shape():
  1049. if dim1 > dim2:
  1050. shape2 = concat([shape1[:-2], shape2[-2:]])
  1051. inp2 = broadcast_to(inp2, shape2)
  1052. if dim1 < dim2:
  1053. shape1 = concat([shape2[:-2], shape1[-2:]])
  1054. inp1 = broadcast_to(inp1, shape1)
  1055. if maxdim > 3:
  1056. batch_shape = shape1[:-2]
  1057. # compress inputs to 3d
  1058. (inp1,) = apply(
  1059. builtin.Reshape(), inp1, concat([prod(shape1[:-2]), shape1[-2:]])
  1060. )
  1061. (inp2,) = apply(
  1062. builtin.Reshape(), inp2, concat([prod(shape2[:-2]), shape2[-2:]])
  1063. )
  1064. else:
  1065. if dim1 > dim2:
  1066. shape2 = shape1[:-2] + shape2[-2:]
  1067. inp2 = broadcast_to(inp2, shape2)
  1068. if dim1 < dim2:
  1069. shape1 = shape2[:-2] + shape1[-2:]
  1070. inp1 = broadcast_to(inp1, shape1)
  1071. if maxdim > 3:
  1072. batch_shape = shape1[:-2]
  1073. # compress inputs to 3d
  1074. inp1 = inp1.reshape((-1, shape1[-2], shape1[-1]))
  1075. inp2 = inp2.reshape((-1, shape2[-2], shape2[-1]))
  1076. op = builtin.BatchedMatrixMul(
  1077. transposeA=transpose_a,
  1078. transposeB=transpose_b,
  1079. compute_mode=compute_mode,
  1080. format=format,
  1081. strategy=get_conv_execution_strategy(),
  1082. )
  1083. else:
  1084. op = builtin.MatrixMul(
  1085. transposeA=transpose_a,
  1086. transposeB=transpose_b,
  1087. compute_mode=compute_mode,
  1088. format=format,
  1089. strategy=get_conv_execution_strategy(),
  1090. )
  1091. (result,) = apply(op, inp1, inp2)
  1092. if maxdim > 3:
  1093. if use_symbolic_shape():
  1094. (result,) = apply(
  1095. builtin.Reshape(), result, concat([batch_shape, result.shape[-2:]])
  1096. )
  1097. else:
  1098. result = result.reshape(batch_shape + result.shape[-2:])
  1099. if remove_row:
  1100. result = squeeze(result, axis=-2)
  1101. if remove_col:
  1102. result = squeeze(result, axis=-1)
  1103. return result
  1104. def dot(inp1: Tensor, inp2: Tensor) -> Tensor:
  1105. """
  1106. Computes dot-product of two vectors ``inp1`` and ``inp2``.
  1107. inputs must be 1-dimensional or scalar. A scalar input is automatically broadcasted.
  1108. Refer to :func:`~.matmul` for more general usage.
  1109. :param inp1: first vector.
  1110. :param inp2: second vector.
  1111. :return: output value.
  1112. Examples:
  1113. .. testcode::
  1114. import numpy as np
  1115. from megengine import tensor
  1116. import megengine.functional as F
  1117. data1 = tensor(np.arange(0, 6, dtype=np.float32))
  1118. data2 = tensor(np.arange(0, 6, dtype=np.float32))
  1119. out = F.dot(data1, data2)
  1120. print(out.numpy())
  1121. Outputs:
  1122. .. testoutput::
  1123. 55.
  1124. """
  1125. op = builtin.Dot()
  1126. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  1127. assert (
  1128. inp1.ndim <= 1 and inp2.ndim <= 1
  1129. ), "Input tensors for dot must be 1-dimensional or scalar"
  1130. (result,) = apply(op, inp1, inp2)
  1131. setscalar(result)
  1132. return result
  1133. def svd(inp: Tensor, full_matrices=False, compute_uv=True) -> Tensor:
  1134. """
  1135. Computes the singular value decompositions of input matrix.
  1136. :param inp: input matrix, must has shape `[..., M, N]`.
  1137. :return: output matrices, `(U, sigma, V)`.
  1138. Examples:
  1139. .. testcode::
  1140. import numpy as np
  1141. from megengine import tensor
  1142. import megengine.functional as F
  1143. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2,3))
  1144. _, y, _ = F.svd(x)
  1145. print(y.numpy().round(decimals=3))
  1146. Outputs:
  1147. .. testoutput::
  1148. [7.348 1. ]
  1149. """
  1150. op = builtin.SVD(full_matrices=full_matrices, compute_uv=compute_uv)
  1151. U, sigma, V = apply(op, inp)
  1152. return U, sigma, V
  1153. def interpolate(
  1154. inp: Tensor,
  1155. size: Optional[Union[int, Tuple[int, int]]] = None,
  1156. scale_factor: Optional[Union[float, Tuple[float, float]]] = None,
  1157. mode: str = "BILINEAR",
  1158. align_corners: bool = None,
  1159. ) -> Tensor:
  1160. r"""
  1161. Down/up samples the input tensor to either the given size or with the given scale_factor. ``size`` can not coexist with ``scale_factor``.
  1162. :param inp: input tensor.
  1163. :param size: size of the output tensor. Default: None
  1164. :param scale_factor: scaling factor of the output tensor. Default: None
  1165. :param mode: interpolation methods, acceptable values are:
  1166. "BILINEAR", "LINEAR". Default: "BILINEAR"
  1167. :return: output tensor.
  1168. Examples:
  1169. .. testcode::
  1170. import numpy as np
  1171. from megengine import tensor
  1172. import megengine.functional as F
  1173. x = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  1174. out = F.nn.interpolate(x, [4, 4], align_corners=False)
  1175. print(out.numpy())
  1176. out2 = F.nn.interpolate(x, scale_factor=2.)
  1177. np.testing.assert_allclose(out.numpy(), out2.numpy())
  1178. Outputs:
  1179. .. testoutput::
  1180. [[[[1. 1.25 1.75 2. ]
  1181. [1.5 1.75 2.25 2.5 ]
  1182. [2.5 2.75 3.25 3.5 ]
  1183. [3. 3.25 3.75 4. ]]]]
  1184. """
  1185. mode = mode.upper()
  1186. if mode not in ["BILINEAR", "LINEAR"]:
  1187. raise ValueError("interpolate only support linear or bilinear mode")
  1188. if mode not in ["BILINEAR", "LINEAR"]:
  1189. if align_corners is not None:
  1190. raise ValueError(
  1191. "align_corners option can only be set in the bilinear/linear interpolating mode"
  1192. )
  1193. else:
  1194. if align_corners is None:
  1195. align_corners = False
  1196. if mode == "LINEAR":
  1197. inp = expand_dims(inp, 3)
  1198. if inp.ndim != 4:
  1199. raise ValueError("shape of input tensor must correspond to the operartion mode")
  1200. if size is None:
  1201. if scale_factor is None:
  1202. raise ValueError("scale_factor must not be None when size is None")
  1203. if isinstance(scale_factor, (float, int)):
  1204. scale_factor = float(scale_factor)
  1205. if mode == "LINEAR":
  1206. scale_factor = (scale_factor, float(1))
  1207. else:
  1208. scale_factor = (scale_factor, scale_factor)
  1209. else:
  1210. if mode == "LINEAR":
  1211. raise ValueError(
  1212. "under LINEAR mode, scale_factor can only be single value"
  1213. )
  1214. assert len(scale_factor) == 2, "shape of scale_factor must be equal to (2, )"
  1215. assert isinstance(scale_factor[0], float) and isinstance(
  1216. scale_factor[1], float
  1217. ), "scale_factor must be float type"
  1218. dsize = tuple(
  1219. floor(
  1220. Tensor(
  1221. inp.shape[i + 2] * scale_factor[i],
  1222. dtype="float32",
  1223. device=inp.device,
  1224. )
  1225. )
  1226. for i in range(2)
  1227. )
  1228. dsize = concat([dsize[0], dsize[1]], axis=0)
  1229. else:
  1230. if scale_factor is not None:
  1231. raise ValueError("scale_factor must be None when size is provided")
  1232. if isinstance(size, int):
  1233. size = (size, 1)
  1234. else:
  1235. if mode == "LINEAR":
  1236. raise ValueError("under LINEAR mode, size can only be single value")
  1237. dsize = size
  1238. oh, ow = dsize[0], dsize[1]
  1239. ih, iw = inp.shape[2], inp.shape[3]
  1240. if align_corners:
  1241. hscale = (ih - 1.0) / (oh - 1.0)
  1242. wscale = 1.0 * iw / ow
  1243. if mode != "LINEAR":
  1244. wscale = (iw - 1.0) / (ow - 1.0)
  1245. row0 = concat(
  1246. [wscale, Tensor([0, 0], dtype="float32", device=inp.device)], axis=0
  1247. ).reshape(1, 3)
  1248. row1 = concat(
  1249. [
  1250. Tensor(0, dtype="float32", device=inp.device),
  1251. hscale,
  1252. Tensor(0, dtype="float32", device=inp.device),
  1253. ],
  1254. axis=0,
  1255. ).reshape(1, 3)
  1256. weight = concat(
  1257. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  1258. axis=0,
  1259. ).reshape(1, 3, 3)
  1260. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  1261. else:
  1262. hscale = 1.0 * ih / oh
  1263. wscale = 1.0 * iw / ow
  1264. row0 = concat(
  1265. [wscale, Tensor(0, dtype="float32", device=inp.device), 0.5 * wscale - 0.5],
  1266. axis=0,
  1267. ).reshape(1, 3)
  1268. row1 = concat(
  1269. [Tensor(0, dtype="float32", device=inp.device), hscale, 0.5 * hscale - 0.5],
  1270. axis=0,
  1271. ).reshape(1, 3)
  1272. weight = concat(
  1273. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  1274. axis=0,
  1275. ).reshape(1, 3, 3)
  1276. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  1277. weight = weight.astype("float32")
  1278. ret = warp_perspective(inp, weight, dsize, interp_mode="LINEAR")
  1279. if mode == "LINEAR":
  1280. ret = reshape(ret, ret.shape[0:3])
  1281. return ret
  1282. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1283. """
  1284. Returns a new tensor where each of the elements are randomly set to zero
  1285. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1286. :param inp: input tensor.
  1287. :param drop_prob: probability to drop (set to zero) a single element.
  1288. :param training: the default behavior of ``dropout`` during training is to rescale the output,
  1289. then it can be replaced by an :class:`~.Identity` during inference. Default: True
  1290. :return: the output tensor
  1291. Examples:
  1292. .. testcode::
  1293. import numpy as np
  1294. from megengine import tensor
  1295. import megengine.functional as F
  1296. x = tensor(np.ones(10, dtype=np.float32))
  1297. out = F.dropout(x, 1./3.)
  1298. print(out.numpy())
  1299. Outputs:
  1300. .. testoutput::
  1301. :options: +SKIP
  1302. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1303. """
  1304. assert 0 <= drop_prob < 1
  1305. rv = uniform(size=inp.shape)
  1306. mask = rv > drop_prob
  1307. inp *= mask.astype(inp.dtype)
  1308. if training:
  1309. inp *= 1 / (1 - drop_prob)
  1310. return inp
  1311. def embedding(
  1312. inp: Tensor,
  1313. weight: Tensor,
  1314. padding_idx: Optional[int] = None,
  1315. max_norm: Optional[float] = None,
  1316. norm_type: Optional[float] = None,
  1317. ):
  1318. """
  1319. Applies lookup table for embedding.
  1320. :param inp: tensor with indices.
  1321. :param weight: learnable weights which embeds from.
  1322. :param padding_idx: should be set to None, not supported now.
  1323. :param max_norm: should be set to None, not supported now.
  1324. :param norm_type: should be set to None, not supported now.
  1325. :return: output tensor.
  1326. Refer to :class:`~.Embedding` for more information.
  1327. """
  1328. if padding_idx is not None:
  1329. raise ValueError("Not support padding_idx Now!")
  1330. if max_norm is not None or norm_type is not None:
  1331. raise ValueError("Not support weight normlization Now!")
  1332. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1333. return weight[inp.reshape(-1)].reshape(dest_shp)
  1334. def roi_pooling(
  1335. inp: Tensor,
  1336. rois: Tensor,
  1337. output_shape: Union[int, tuple, list],
  1338. mode: str = "max",
  1339. scale: float = 1.0,
  1340. ) -> Tensor:
  1341. """
  1342. Applies roi pooling on input feature.
  1343. :param inp: tensor that represents the input feature, `(N, C, H, W)` images.
  1344. :param rois: `(K, 5)` boxes. First column is the index into N. The other 4 columns are xyxy.
  1345. :param output_shape: `(height, width)` of output rois feature.
  1346. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "max"
  1347. :param scale: scale the input boxes by this number. Default: 1.0
  1348. :return: `(K, C, output_shape[0], output_shape[1])` feature of rois.
  1349. Examples:
  1350. .. testcode::
  1351. import numpy as np
  1352. from megengine import tensor
  1353. import megengine.functional as F
  1354. np.random.seed(42)
  1355. inp = tensor(np.random.randn(1, 1, 128, 128))
  1356. rois = tensor(np.random.random((4, 5)))
  1357. y = F.nn.roi_pooling(inp, rois, (2, 2))
  1358. print(y.numpy()[0].round(decimals=4))
  1359. Outputs:
  1360. .. testoutput::
  1361. [[[-0.1383 -0.1383]
  1362. [-0.5035 -0.5035]]]
  1363. """
  1364. assert mode in ["max", "average"], "only max/average mode is supported"
  1365. if isinstance(output_shape, int):
  1366. output_shape = (output_shape, output_shape)
  1367. op = builtin.ROIPooling(mode=mode, scale=scale)
  1368. inp, rois = utils.convert_inputs(inp, rois)
  1369. result, _ = apply(
  1370. op, inp, rois, Tensor(output_shape, dtype="int32", device=inp.device)
  1371. )
  1372. return result
  1373. def roi_align(
  1374. inp: Tensor,
  1375. rois: Tensor,
  1376. output_shape: Union[int, tuple, list],
  1377. mode: str = "average",
  1378. spatial_scale: float = 1.0,
  1379. sample_points: Union[int, tuple, list] = 2,
  1380. aligned: bool = True,
  1381. ) -> Tensor:
  1382. """
  1383. Applies roi align on input feature.
  1384. :param inp: tensor that represents the input feature, shape is `(N, C, H, W)`.
  1385. :param rois: `(N, 5)` boxes. First column is the box index. The other 4 columns are ``xyxy``.
  1386. :param output_shape: `(height, width)` shape of output rois feature.
  1387. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "average"
  1388. :param spatial_scale: scale the input boxes by this number. Default: 1.0
  1389. :param sample_points: number of inputs samples to take for each output sample.
  1390. 0 to take samples densely. Default: 2
  1391. :param aligned: wheather to align the input feature, with `aligned=True`,
  1392. we first appropriately scale the ROI and then shift it by -0.5. Default: True
  1393. :return: output tensor.
  1394. Examples:
  1395. .. testcode::
  1396. import numpy as np
  1397. from megengine import tensor
  1398. import megengine.functional as F
  1399. np.random.seed(42)
  1400. inp = tensor(np.random.randn(1, 1, 128, 128))
  1401. rois = tensor(np.random.random((4, 5)))
  1402. y = F.nn.roi_align(inp, rois, (2, 2))
  1403. print(y.numpy()[0].round(decimals=4))
  1404. Outputs:
  1405. .. testoutput::
  1406. [[[0.175 0.175 ]
  1407. [0.1359 0.1359]]]
  1408. """
  1409. assert mode in ["max", "average"], "only max/average mode is supported"
  1410. if isinstance(output_shape, int):
  1411. output_shape = (output_shape, output_shape)
  1412. pooled_height, pooled_width = output_shape
  1413. if isinstance(sample_points, int):
  1414. sample_points = (sample_points, sample_points)
  1415. sample_height, sample_width = sample_points
  1416. offset = 0.5 if aligned else 0.0
  1417. op = builtin.ROIAlign(
  1418. mode=mode,
  1419. format="NCHW",
  1420. spatial_scale=spatial_scale,
  1421. offset=offset,
  1422. pooled_height=pooled_height,
  1423. pooled_width=pooled_width,
  1424. sample_height=sample_height,
  1425. sample_width=sample_width,
  1426. )
  1427. inp, rois = utils.convert_inputs(inp, rois)
  1428. result, *_ = apply(op, inp, rois)
  1429. return result
  1430. def indexing_one_hot(
  1431. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1432. ) -> Tensor:
  1433. r"""
  1434. One-hot indexing for some axes.
  1435. :param src: input tensor.
  1436. :param index: index tensor.
  1437. :param axis: axis on src for which values in index index. Default: 1
  1438. :param keepdims: whether not to remove the axis in result. Default: False
  1439. :return: output tensor.
  1440. Examples:
  1441. .. testcode::
  1442. import megengine.functional as F
  1443. from megengine import tensor
  1444. src = tensor([[1.0, 2.0]])
  1445. index = tensor([0])
  1446. val = F.indexing_one_hot(src, index)
  1447. print(val.numpy())
  1448. Outputs:
  1449. .. testoutput::
  1450. [1.]
  1451. """
  1452. assert isinstance(src, Tensor), "src must be of Tensor type"
  1453. op = builtin.IndexingOneHot(axis=axis)
  1454. index = utils.convert_single_value(index, dtype="int32", device=src.device)
  1455. (result,) = apply(op, src, index)
  1456. if not keepdims:
  1457. result = squeeze(result, axis)
  1458. return result
  1459. def conv1d(
  1460. inp: Tensor,
  1461. weight: Tensor,
  1462. bias: Optional[Tensor] = None,
  1463. stride: int = 1,
  1464. padding: int = 0,
  1465. dilation: int = 1,
  1466. groups: int = 1,
  1467. conv_mode="CROSS_CORRELATION",
  1468. compute_mode="DEFAULT",
  1469. ) -> Tensor:
  1470. """1D convolution operation.
  1471. Refer to :class:`~.Conv1d` for more information.
  1472. :param inp: The feature map of the convolution operation
  1473. :param weight: The convolution kernel
  1474. :param bias: The bias added to the result of convolution (if given)
  1475. :param stride: Stride of the 1D convolution operation. Default: 1
  1476. :param padding: Size of the paddings added to the input on both sides of its
  1477. spatial dimensions. Only zero-padding is supported. Default: 0
  1478. :param dilation: Dilation of the 1D convolution operation. Default: 1
  1479. :param groups: number of groups to divide input and output channels into,
  1480. so as to perform a "grouped convolution". When ``groups`` is not 1,
  1481. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  1482. and the shape of weight should be ``(groups, out_channel // groups,
  1483. in_channels // groups, height, width)``.
  1484. :type conv_mode: string or :class:`mgb.opr_param_defs.Convolution.Mode`
  1485. :param conv_mode: Supports 'CROSS_CORRELATION'. Default:
  1486. 'CROSS_CORRELATION'.
  1487. :type compute_mode: string or
  1488. :class:`mgb.opr_param_defs.Convolution.ComputeMode`
  1489. :param compute_mode: When set to 'DEFAULT', no special requirements will be
  1490. placed on the precision of intermediate results. When set to 'FLOAT32',
  1491. Float32 would be used for accumulator and intermediate result, but only
  1492. effective when input and output are of Float16 dtype.
  1493. """
  1494. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  1495. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  1496. assert inp.ndim == 3, "the input dimension of conv1d should be 3"
  1497. assert weight.ndim == 3, "the weight dimension of conv1d should be 3"
  1498. inp = expand_dims(inp, 3)
  1499. weight = expand_dims(weight, 3)
  1500. if bias is not None:
  1501. assert bias.ndim == 3, "the bias dimension of conv1d should be 3"
  1502. bias = expand_dims(bias, 3)
  1503. stride_h = stride
  1504. pad_h = padding
  1505. dilate_h = dilation
  1506. sparse_type = "DENSE" if groups == 1 else "GROUP"
  1507. op = builtin.Convolution(
  1508. stride_h=stride_h,
  1509. stride_w=1,
  1510. pad_h=pad_h,
  1511. pad_w=0,
  1512. dilate_h=dilate_h,
  1513. dilate_w=1,
  1514. strategy=get_conv_execution_strategy(),
  1515. mode=conv_mode,
  1516. compute_mode=compute_mode,
  1517. sparse=sparse_type,
  1518. )
  1519. inp, weight = utils.convert_inputs(inp, weight)
  1520. (output,) = apply(op, inp, weight)
  1521. if bias is not None:
  1522. output += bias
  1523. output = squeeze(output, 3)
  1524. return output
  1525. def nms(
  1526. boxes: Tensor, scores: Tensor, iou_thresh: float, max_output: Optional[int] = None
  1527. ) -> Tensor:
  1528. r"""
  1529. Performs non-maximum suppression (NMS) on the boxes according to their intersection-over-union(IoU).
  1530. :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.
  1531. :param iou_thresh: IoU threshold for overlapping.
  1532. :param scores: tensor of shape `(N,)`, the score of boxes.
  1533. :param max_output: the maximum number of boxes to keep; it is optional if this operator is not traced
  1534. otherwise it required to be specified; if it is not specified, all boxes are kept.
  1535. :return: indices of the elements that have been kept by NMS.
  1536. Examples:
  1537. .. testcode::
  1538. import numpy as np
  1539. from megengine import tensor
  1540. import megengine.functional as F
  1541. x = np.zeros((100,4))
  1542. np.random.seed(42)
  1543. x[:,:2] = np.random.rand(100,2)*20
  1544. x[:,2:] = np.random.rand(100,2)*20 + 100
  1545. scores = tensor(np.random.rand(100))
  1546. inp = tensor(x)
  1547. result = F.nn.nms(inp, scores, iou_thresh=0.7)
  1548. print(result.numpy())
  1549. Outputs:
  1550. .. testoutput::
  1551. [75 69]
  1552. """
  1553. assert (
  1554. boxes.ndim == 2 and boxes.shape[1] == 4
  1555. ), "the expected shape of boxes is (N, 4)"
  1556. assert scores.ndim == 1, "the expected shape of scores is (N,)"
  1557. assert (
  1558. boxes.shape[0] == scores.shape[0]
  1559. ), "number of boxes and scores are not matched"
  1560. boxes = boxes.detach()
  1561. scores = scores.detach()
  1562. sorted_idx = argsort(scores, descending=True)
  1563. boxes = boxes[sorted_idx]
  1564. if is_tracing():
  1565. assert (
  1566. max_output is not None and max_output > 0
  1567. ), "max_output should be specified under tracing"
  1568. if max_output is None:
  1569. max_output = boxes.shape[0]
  1570. op = builtin.NMSKeep(iou_thresh, max_output)
  1571. inp = utils.convert_inputs(boxes.reshape(1, -1, 4))
  1572. indices, count = apply(op, *inp)
  1573. indices = indices[0][: count[0]]
  1574. keep_inds = sorted_idx[indices]
  1575. return keep_inds
  1576. def nvof(src: Tensor, precision: int = 1) -> Tensor:
  1577. r"""
  1578. Implements NVIDIA Optical Flow SDK.
  1579. :src shape: input tensor with shape (n, t, h, w, c4).
  1580. :src dtype: uint8.
  1581. :param precision: 0:NV_OF_PERF_LEVEL_SLOW 1:NV_OF_PERF_LEVEL_MEDIUM 2:NV_OF_PERF_LEVEL_FAST.
  1582. :output shape: (n, t-1, h//4, w//4, c2).
  1583. :output dtype: int16.
  1584. .. code-block:: python
  1585. import numpy as np
  1586. from megengine import tensor
  1587. import megengine.functional as F
  1588. x = np.random.random_integers(0, 255, (1,2,224,244,4)).astype("uint8")
  1589. src = tensor(x)
  1590. result = F.nn.nvof(src, precision=1)
  1591. print(result.numpy())
  1592. """
  1593. assert isinstance(src, (Tensor, megbrain_graph.VarNode)), "src must be Tensor type"
  1594. assert src.ndim == 5 and src.shape[4] == 4
  1595. src = src.detach()
  1596. op = builtin.NvOf(precision=precision)
  1597. return apply(op, src)[0]
  1598. from .loss import * # isort:skip
  1599. from .quantized import conv_bias_activation # isort:skip

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