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

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

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