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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  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 functools import lru_cache
  11. from typing import NamedTuple, Optional, Sequence, Tuple, Union
  12. from ..core import _config
  13. from ..core._imperative_rt.core2 import Const, apply, dtype_promotion
  14. from ..core._imperative_rt.ops import SubgraphBuilder as _SubgraphBuilder
  15. from ..core._imperative_rt.ops import get_global_rng_seed as _get_global_rng_seed
  16. from ..core.ops import builtin
  17. from ..core.ops.builtin import (
  18. BatchNorm,
  19. Dimshuffle,
  20. Dropout,
  21. Elemwise,
  22. GetVarShape,
  23. Identity,
  24. Reduce,
  25. Reshape,
  26. TypeCvt,
  27. )
  28. from ..core.tensor import amp, megbrain_graph
  29. from ..core.tensor.array_method import _elwise_apply
  30. from ..core.tensor.utils import (
  31. astensor1d,
  32. astype,
  33. cast_tensors,
  34. convert_single_value,
  35. make_shape_tuple,
  36. subgraph,
  37. subgraph_fn,
  38. )
  39. from ..device import get_default_device
  40. from ..distributed import WORLD, is_distributed
  41. from ..jit import exclude_from_trace
  42. from ..tensor import Tensor
  43. from ..utils.deprecation import deprecated_func
  44. from ..utils.tuple_function import _pair, _pair_nonzero, _triple, _triple_nonzero
  45. from .debug_param import get_execution_strategy
  46. from .distributed import all_reduce_sum
  47. from .elemwise import _elwise, exp, log, log1p, maximum, minimum
  48. from .math import matmul, max, sum
  49. from .tensor import broadcast_to, concat, expand_dims, ones, squeeze, zeros
  50. __all__ = [
  51. "adaptive_avg_pool2d",
  52. "adaptive_max_pool2d",
  53. "avg_pool2d",
  54. "batch_norm",
  55. "conv1d",
  56. "conv2d",
  57. "conv3d",
  58. "conv_transpose2d",
  59. "conv_transpose3d",
  60. "deformable_conv2d",
  61. "deformable_psroi_pooling",
  62. "dropout",
  63. "embedding",
  64. "gelu",
  65. "hsigmoid",
  66. "hswish",
  67. "indexing_one_hot",
  68. "leaky_relu",
  69. "linear",
  70. "local_conv2d",
  71. "local_response_norm",
  72. "logsigmoid",
  73. "logsumexp",
  74. "logsoftmax",
  75. "max_pool2d",
  76. "one_hot",
  77. "prelu",
  78. "pad",
  79. "relu",
  80. "relu6",
  81. "remap",
  82. "sigmoid",
  83. "sliding_window",
  84. "sliding_window_transpose",
  85. "silu",
  86. "softmax",
  87. "softplus",
  88. "sync_batch_norm",
  89. "warp_affine",
  90. "warp_perspective",
  91. "pixel_shuffle",
  92. ]
  93. def expand_hw(x):
  94. # NOTE: >1d array is accepted, as long as 1 <= size <= 2
  95. try:
  96. x = int(x)
  97. return [x, x]
  98. except (TypeError, ValueError):
  99. pass
  100. h, w = x
  101. return int(h), int(w)
  102. def linear(
  103. inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None, compute_mode="default",
  104. ) -> Tensor:
  105. r"""Applies a linear transformation to the input tensor.
  106. Refer to :class:`~.module.linear.Linear` for more information.
  107. Args:
  108. inp: input tensor with shape `(N, in_features)`.
  109. weight: weight with shape `(out_features, in_features)`.
  110. bias: bias with shape `(out_features,)`. Default: None
  111. """
  112. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  113. ret = matmul(inp, weight, transpose_b=True, compute_mode=compute_mode)
  114. if bias is not None:
  115. if amp._enabled:
  116. bias = bias.astype("float16")
  117. ret += bias
  118. return ret
  119. def conv1d(
  120. inp: Tensor,
  121. weight: Tensor,
  122. bias: Optional[Tensor] = None,
  123. stride: int = 1,
  124. padding: int = 0,
  125. dilation: int = 1,
  126. groups: int = 1,
  127. conv_mode="cross_correlation",
  128. compute_mode="default",
  129. ) -> Tensor:
  130. r"""1D convolution operation.
  131. Refer to :class:`~.Conv1d` for more information.
  132. Args:
  133. inp: The feature map of the convolution operation
  134. weight: The convolution kernel.
  135. bias: The bias added to the result of convolution (if given)
  136. stride: Stride of the 1D convolution operation. Default: 1
  137. padding: Size of the paddings added to the input on both sides of its
  138. spatial dimensions. Only zero-padding is supported. Default: 0
  139. dilation: Dilation of the 1D convolution operation. Default: 1
  140. groups: number of groups to divide input and output channels into,
  141. so as to perform a "grouped convolution". When ``groups`` is not 1,
  142. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  143. and the shape of weight should be ``(groups, out_channel // groups,
  144. in_channels // groups, kernel_size)``. Default: 1
  145. conv_mode: Supports 'cross_correlation'. Default:
  146. 'cross_correlation'.
  147. compute_mode: When set to 'default', no special requirements will be
  148. placed on the precision of intermediate results. When set to 'float32',
  149. float32 would be used for accumulator and intermediate result, but only
  150. effective when input and output are of float16 dtype.
  151. """
  152. assert (
  153. conv_mode.lower() == "cross_correlation"
  154. or conv_mode.name == "CROSS_CORRELATION"
  155. )
  156. assert compute_mode.lower() == "default" or compute_mode.name == "DEFAULT"
  157. assert inp.ndim == 3, "the input dimension of conv1d should be 3"
  158. assert weight.ndim == 3, "the weight dimension of conv1d should be 3"
  159. if amp._enabled:
  160. compute_mode = "float32"
  161. inp, weight, bias = cast_tensors(inp, weight, bias)
  162. else:
  163. dtype = dtype_promotion(inp, weight)
  164. if inp.dtype != dtype:
  165. inp = inp.astype(dtype)
  166. if weight.dtype != dtype:
  167. weight = weight.astype(dtype)
  168. inp = expand_dims(inp, 3)
  169. weight = expand_dims(weight, 3)
  170. if bias is not None:
  171. assert bias.ndim == 3, "the bias dimension of conv1d should be 3"
  172. bias = expand_dims(bias, 3)
  173. stride_h = stride
  174. pad_h = padding
  175. dilate_h = dilation
  176. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  177. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  178. sparse_type = "dense" if groups == 1 else "group"
  179. op = builtin.Convolution(
  180. stride_h=stride_h,
  181. stride_w=1,
  182. pad_h=pad_h,
  183. pad_w=0,
  184. dilate_h=dilate_h,
  185. dilate_w=1,
  186. strategy=get_execution_strategy(),
  187. mode=conv_mode,
  188. compute_mode=compute_mode,
  189. sparse=sparse_type,
  190. format=conv_format,
  191. )
  192. (output,) = apply(op, inp, weight)
  193. if bias is not None:
  194. output += bias
  195. output = squeeze(output, 3)
  196. return output
  197. def conv2d(
  198. inp: Tensor,
  199. weight: Tensor,
  200. bias: Optional[Tensor] = None,
  201. stride: Union[int, Tuple[int, int]] = 1,
  202. padding: Union[int, Tuple[int, int]] = 0,
  203. dilation: Union[int, Tuple[int, int]] = 1,
  204. groups: int = 1,
  205. conv_mode="cross_correlation",
  206. compute_mode="default",
  207. ) -> Tensor:
  208. r"""2D convolution operation.
  209. Refer to :class:`~.module.Conv2d` for more information.
  210. Args:
  211. inp: feature map of the convolution operation.
  212. weight: convolution kernel.
  213. bias: bias added to the result of convolution (if given).
  214. stride: stride of the 2D convolution operation. Default: 1
  215. padding: size of the paddings added to the input on both sides of its
  216. spatial dimensions. Only zero-padding is supported. Default: 0
  217. dilation: dilation of the 2D convolution operation. Default: 1
  218. groups: number of groups into which the input and output channels are divided,
  219. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  220. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  221. and the shape of weight should be ``(groups, out_channel // groups,
  222. in_channels // groups, height, width)``. Default: 1
  223. conv_mode: supports "cross_correlation". Default: "cross_correlation"
  224. compute_mode: when set to "default", no special requirements will be
  225. placed on the precision of intermediate results. When set to "float32",
  226. "float32" would be used for accumulator and intermediate result, but only
  227. effective when input and output are of float16 dtype.
  228. Returns:
  229. output tensor.
  230. """
  231. assert (
  232. conv_mode.lower() == "cross_correlation"
  233. or conv_mode.name == "CROSS_CORRELATION"
  234. )
  235. stride_h, stride_w = expand_hw(stride)
  236. pad_h, pad_w = expand_hw(padding)
  237. dilate_h, dilate_w = expand_hw(dilation)
  238. sparse_type = "dense" if groups == 1 else "group"
  239. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  240. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  241. op = builtin.Convolution(
  242. stride_h=stride_h,
  243. stride_w=stride_w,
  244. pad_h=pad_h,
  245. pad_w=pad_w,
  246. dilate_h=dilate_h,
  247. dilate_w=dilate_w,
  248. strategy=get_execution_strategy(),
  249. mode=conv_mode,
  250. compute_mode=compute_mode,
  251. sparse=sparse_type,
  252. format=conv_format,
  253. )
  254. (output,) = apply(op, inp, weight)
  255. if bias is not None:
  256. output += bias
  257. return output
  258. def conv3d(
  259. inp: Tensor,
  260. weight: Tensor,
  261. bias: Optional[Tensor] = None,
  262. stride: Union[int, Tuple[int, int, int]] = 1,
  263. padding: Union[int, Tuple[int, int, int]] = 0,
  264. dilation: Union[int, Tuple[int, int, int]] = 1,
  265. groups: int = 1,
  266. conv_mode: str = "cross_correlation",
  267. ) -> Tensor:
  268. r"""3D convolution operation.
  269. Refer to :class:`~.Conv3d` for more information.
  270. Args:
  271. inp: feature map of the convolution operation.
  272. weight: convolution kernel.
  273. bias: bias added to the result of convolution (if given).
  274. stride: stride of the 3D convolution operation. Default: 1
  275. padding: size of the paddings added to the input on both sides of its
  276. spatial dimensions. Only zero-padding is supported. Default: 0
  277. dilation: dilation of the 3D convolution operation. Default: 1
  278. groups: number of groups into which the input and output channels are divided,
  279. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  280. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  281. and the shape of weight should be ``(groups, out_channel // groups,
  282. in_channels // groups, depth, height, width)``. Default: 1
  283. conv_mode: supports "cross_correlation". Default: "cross_correlation"
  284. Returns:
  285. output tensor.
  286. """
  287. assert conv_mode.lower() == "cross_correlation"
  288. D, H, W = 0, 1, 2
  289. pad = _triple(padding)
  290. stride = _triple_nonzero(stride)
  291. dilate = _triple_nonzero(dilation)
  292. sparse_type = "dense" if groups == 1 else "group"
  293. op = builtin.Convolution3D(
  294. pad_d=pad[D],
  295. pad_h=pad[H],
  296. pad_w=pad[W],
  297. stride_d=stride[D],
  298. stride_h=stride[H],
  299. stride_w=stride[W],
  300. dilate_d=dilate[D],
  301. dilate_h=dilate[H],
  302. dilate_w=dilate[W],
  303. strategy=get_execution_strategy(),
  304. mode=conv_mode,
  305. sparse=sparse_type,
  306. )
  307. (output,) = apply(op, inp, weight)
  308. if bias is not None:
  309. output += bias
  310. return output
  311. def conv_transpose2d(
  312. inp: Tensor,
  313. weight: Tensor,
  314. bias: Optional[Tensor] = None,
  315. stride: Union[int, Tuple[int, int]] = 1,
  316. padding: Union[int, Tuple[int, int]] = 0,
  317. dilation: Union[int, Tuple[int, int]] = 1,
  318. groups: int = 1,
  319. conv_mode="cross_correlation",
  320. compute_mode="default",
  321. ) -> Tensor:
  322. r"""2D transposed convolution operation.
  323. Refer to :class:`~.module.conv.ConvTranspose2d` for more information.
  324. Args:
  325. inp: feature map of the convolution operation.
  326. weight: convolution kernel.
  327. weight usually has shape ``(in_channels, out_channels, height, width)``.
  328. bias: bias added to the result of convolution (if given).
  329. stride: stride of the 2D convolution operation. Default: 1
  330. padding: size of the paddings added to the input on both sides of its
  331. spatial dimensions. Only zero-padding is supported. Default: 0
  332. dilation: dilation of the 2D convolution operation. Default: 1
  333. groups: number of groups into which the input and output channels are divided,
  334. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  335. ``in_channels`` and ``out_channels`` must be divisible by groups,
  336. and the shape of weight should be ``(groups, in_channels // groups,
  337. out_channels // groups, height, width)``. Default: 1
  338. conv_mode: supports "cross_correlation". Default: "cross_correlation"
  339. compute_mode: when set to "default", no special requirements will be
  340. placed on the precision of intermediate results. When set to "float32",
  341. "float32" would be used for accumulator and intermediate result, but only
  342. effective when input and output are of float16 dtype.
  343. Returns:
  344. output tensor.
  345. """
  346. assert (
  347. conv_mode.lower() == "cross_correlation"
  348. or conv_mode.name == "CROSS_CORRELATION"
  349. )
  350. stride_h, stride_w = expand_hw(stride)
  351. pad_h, pad_w = expand_hw(padding)
  352. dilate_h, dilate_w = expand_hw(dilation)
  353. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  354. sparse_type = "dense" if groups == 1 else "group"
  355. op = builtin.ConvolutionBackwardData(
  356. stride_h=stride_h,
  357. stride_w=stride_w,
  358. pad_h=pad_h,
  359. pad_w=pad_w,
  360. dilate_h=dilate_h,
  361. dilate_w=dilate_w,
  362. strategy=get_execution_strategy(),
  363. compute_mode=compute_mode,
  364. sparse=sparse_type,
  365. )
  366. (output,) = apply(op, weight, inp)
  367. if bias is not None:
  368. if amp._enabled:
  369. bias = cast_tensors(bias)
  370. output += bias
  371. return output
  372. def deformable_conv2d(
  373. inp: Tensor,
  374. weight: Tensor,
  375. offset: Tensor,
  376. mask: Tensor,
  377. bias: Optional[Tensor] = None,
  378. stride: Union[int, Tuple[int, int]] = 1,
  379. padding: Union[int, Tuple[int, int]] = 0,
  380. dilation: Union[int, Tuple[int, int]] = 1,
  381. groups: int = 1,
  382. conv_mode="cross_correlation",
  383. compute_mode="default",
  384. ) -> Tensor:
  385. r"""Deformable Convolution.
  386. Args:
  387. inp: input feature map.
  388. weight: convolution kernel.
  389. weight usually has shape ``(out_channels, in_channels, height, width)``.
  390. offset: input offset to kernel, channel of this tensor should match the deformable settings.
  391. mask: input mask to kernel, channel of this tensor should match the deformable settings.
  392. bias: bias added to the result of convolution (if given).
  393. stride: stride of the 2D convolution operation. Default: 1
  394. padding: size of the paddings added to the input on both sides of its
  395. spatial dimensions. Only zero-padding is supported. Default: 0
  396. dilation: dilation of the 2D convolution operation. Default: 1
  397. groups: number of groups into which the input and output channels are divided,
  398. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  399. ``in_channels`` and ``out_channels`` must be divisible by groups,
  400. and the shape of weight should be ``(groups, out_channel // groups,
  401. in_channels // groups, height, width)``. Default: 1
  402. conv_mode: supports "cross_correlation". Default: "cross_correlation"
  403. compute_mode: when set to "default", no special requirements will be
  404. placed on the precision of intermediate results. When set to "float32",
  405. "float32" would be used for accumulator and intermediate result, but only
  406. effective when input and output are of float16 dtype.
  407. Returns:
  408. output tensor.
  409. """
  410. assert (
  411. conv_mode.lower() == "cross_correlation"
  412. or conv_mode.name == "CROSS_CORRELATION"
  413. )
  414. if amp._enabled:
  415. compute_mode = "float32"
  416. inp, weight, offset, mask, bias = cast_tensors(inp, weight, offset, mask, bias)
  417. else:
  418. offset = offset.astype("float32")
  419. mask = mask.astype("float32")
  420. stride_h, stride_w = expand_hw(stride)
  421. pad_h, pad_w = expand_hw(padding)
  422. dilate_h, dilate_w = expand_hw(dilation)
  423. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  424. sparse_type = "dense" if groups == 1 else "group"
  425. op = builtin.DeformableConv(
  426. stride_h=stride_h,
  427. stride_w=stride_w,
  428. pad_h=pad_h,
  429. pad_w=pad_w,
  430. dilate_h=dilate_h,
  431. dilate_w=dilate_w,
  432. strategy=get_execution_strategy(),
  433. mode=conv_mode,
  434. compute_mode=compute_mode,
  435. sparse=sparse_type,
  436. )
  437. (output,) = apply(op, inp, weight, offset, mask)
  438. if bias is not None:
  439. output += bias
  440. return output
  441. def local_conv2d(
  442. inp: Tensor,
  443. weight: Tensor,
  444. bias: Optional[Tensor] = None,
  445. stride: Union[int, Tuple[int, int]] = 1,
  446. padding: Union[int, Tuple[int, int]] = 0,
  447. dilation: Union[int, Tuple[int, int]] = 1,
  448. conv_mode="cross_correlation",
  449. ):
  450. r"""Applies a spatial convolution with untied kernels over an groupped channeled input 4D tensor.
  451. It is also known as the locally connected layer.
  452. Args:
  453. inp: input feature map.
  454. weight: convolution kernel.
  455. weight usually has shape ``(out_channels, in_channels, height, width)``.
  456. bias: bias added to the result of convolution (if given).
  457. stride: stride of the 2D convolution operation. Default: 1
  458. padding: size of the paddings added to the input on both sides of its
  459. spatial dimensions. Only zero-padding is supported. Default: 0
  460. dilation: dilation of the 2D convolution operation. Default: 1
  461. Returns:
  462. output tensor.
  463. """
  464. assert (
  465. conv_mode.lower() == "cross_correlation"
  466. or conv_mode.name == "CROSS_CORRELATION"
  467. )
  468. stride_h, stride_w = expand_hw(stride)
  469. pad_h, pad_w = expand_hw(padding)
  470. dilate_h, dilate_w = expand_hw(dilation)
  471. dtype = dtype_promotion(inp, weight)
  472. if inp.dtype != dtype:
  473. inp = inp.astype(dtype)
  474. if weight.dtype != dtype:
  475. weight = weight.astype(dtype)
  476. # local conv only support "dense" mode, but weight could contain group dimension.
  477. op = builtin.GroupLocal(
  478. stride_h=stride_h,
  479. stride_w=stride_w,
  480. pad_h=pad_h,
  481. pad_w=pad_w,
  482. dilate_h=dilate_h,
  483. dilate_w=dilate_w,
  484. mode=conv_mode,
  485. sparse="dense",
  486. )
  487. (output,) = apply(op, inp, weight)
  488. if bias is not None:
  489. output += bias
  490. return output
  491. def conv_transpose3d(
  492. inp: Tensor,
  493. weight: Tensor,
  494. bias: Optional[Tensor] = None,
  495. stride: Union[int, Tuple[int, int, int]] = 1,
  496. padding: Union[int, Tuple[int, int, int]] = 0,
  497. dilation: Union[int, Tuple[int, int, int]] = 1,
  498. groups: int = 1,
  499. ) -> Tensor:
  500. r"""3D transposed convolution operation. Only support the case that groups = 1
  501. and conv_mode = "cross_correlation".
  502. Refer to :class:`~.ConvTranspose3d` for more information.
  503. Args:
  504. inp: feature map of the convolution operation.
  505. weight: convolution kernel.
  506. weight usually has shape ``(in_channels, out_channels, depth, height, width)``.
  507. bias: bias added to the result of convolution (if given).
  508. stride: stride of the 3D convolution operation. Default: 1
  509. padding: size of the paddings added to the input on all sides of its
  510. spatial dimensions. Only zero-padding is supported. Default: 0
  511. dilation: dilation of the 3D convolution operation. Default: 1
  512. groups: number of groups into which the input and output channels are divided,
  513. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  514. ``in_channels`` and ``out_channels`` must be divisible by groups,
  515. and the shape of weight should be ``(groups, in_channels // groups,
  516. out_channels // groups, depth, height, width)``. Default: 1
  517. Returns:
  518. output tensor.
  519. """
  520. D, H, W = 0, 1, 2
  521. pad = _triple(padding)
  522. stride = _triple_nonzero(stride)
  523. dilate = _triple_nonzero(dilation)
  524. sparse_type = "dense" if groups == 1 else "group"
  525. op = builtin.Convolution3DBackwardData(
  526. pad_d=pad[D],
  527. pad_h=pad[H],
  528. pad_w=pad[W],
  529. stride_d=stride[D],
  530. stride_h=stride[H],
  531. stride_w=stride[W],
  532. dilate_d=dilate[D],
  533. dilate_h=dilate[H],
  534. dilate_w=dilate[W],
  535. strategy=get_execution_strategy(),
  536. sparse=sparse_type,
  537. )
  538. (output,) = apply(op, weight, inp)
  539. if bias is not None:
  540. output += bias
  541. return output
  542. def max_pool2d(
  543. inp: Tensor,
  544. kernel_size: Union[int, Tuple[int, int]],
  545. stride: Optional[Union[int, Tuple[int, int]]] = None,
  546. padding: Union[int, Tuple[int, int]] = 0,
  547. ) -> Tensor:
  548. r"""Applies a 2D max pooling over an input tensor.
  549. Refer to :class:`~.MaxPool2d` for more information.
  550. Args:
  551. inp: input tensor.
  552. kernel_size: size of the window.
  553. stride: stride of the window. If not provided, its value is set to kernel_size.
  554. Default: None
  555. padding: implicit zero padding added on both sides. Default: 0
  556. Returns:
  557. output tensor.
  558. """
  559. if stride is None:
  560. stride = kernel_size
  561. window_h, window_w = _pair_nonzero(kernel_size)
  562. stride_h, stride_w = _pair_nonzero(stride)
  563. padding_h, padding_w = _pair(padding)
  564. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  565. op = builtin.Pooling(
  566. window_h=window_h,
  567. window_w=window_w,
  568. stride_h=stride_h,
  569. stride_w=stride_w,
  570. pad_h=padding_h,
  571. pad_w=padding_w,
  572. mode="max",
  573. format=conv_format,
  574. )
  575. (output,) = apply(op, inp)
  576. return output
  577. def avg_pool2d(
  578. inp: Tensor,
  579. kernel_size: Union[int, Tuple[int, int]],
  580. stride: Optional[Union[int, Tuple[int, int]]] = None,
  581. padding: Union[int, Tuple[int, int]] = 0,
  582. mode: str = "average_count_exclude_padding",
  583. ) -> Tensor:
  584. r"""Applies 2D average pooling over an input tensor.
  585. Refer to :class:`~.AvgPool2d` for more information.
  586. Args:
  587. inp: input tensor.
  588. kernel_size: size of the window.
  589. stride: stride of the window. If not provided, its value is set to ``kernel_size``.
  590. Default: None
  591. padding: implicit zero padding added on both sides. Default: 0
  592. mode: whether to count padding values, set to "average" will do counting.
  593. Default: "average_count_exclude_padding"
  594. Returns:
  595. output tensor.
  596. """
  597. if stride is None:
  598. stride = kernel_size
  599. window_h, window_w = _pair_nonzero(kernel_size)
  600. stride_h, stride_w = _pair_nonzero(stride)
  601. padding_h, padding_w = _pair(padding)
  602. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  603. op = builtin.Pooling(
  604. window_h=window_h,
  605. window_w=window_w,
  606. stride_h=stride_h,
  607. stride_w=stride_w,
  608. pad_h=padding_h,
  609. pad_w=padding_w,
  610. mode=mode,
  611. format=conv_format,
  612. )
  613. (output,) = apply(op, inp)
  614. return output
  615. def adaptive_max_pool2d(
  616. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  617. ) -> Tensor:
  618. r"""Applies a 2D max adaptive pooling over an input.
  619. Refer to :class:`~.MaxAdaptivePool2d` for more information.
  620. Args:
  621. inp: input tensor.
  622. oshp: OH, OW)` size of the output shape.
  623. Returns:
  624. output tensor.
  625. """
  626. if isinstance(oshp, int):
  627. oshp = (oshp, oshp)
  628. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  629. op = builtin.AdaptivePooling(mode="max", format=conv_format,)
  630. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  631. (output,) = apply(op, inp, oshp)
  632. return output
  633. def adaptive_avg_pool2d(
  634. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  635. ) -> Tensor:
  636. r"""Applies a 2D average adaptive pooling over an input.
  637. Refer to :class:`~.AvgAdaptivePool2d` for more information.
  638. Args:
  639. inp: input tensor.
  640. oshp: OH, OW)` size of the output shape.
  641. Returns:
  642. output tensor.
  643. """
  644. if isinstance(oshp, int):
  645. oshp = (oshp, oshp)
  646. op = builtin.AdaptivePooling(mode="average", format="NCHW",)
  647. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  648. (output,) = apply(op, inp, oshp)
  649. return output
  650. def deformable_psroi_pooling(
  651. inp: Tensor,
  652. rois: Tensor,
  653. trans: Tensor,
  654. no_trans: bool,
  655. part_size: int,
  656. pooled_h: int,
  657. pooled_w: int,
  658. sample_per_part: int,
  659. spatial_scale: float,
  660. trans_std: float = 0.1,
  661. ):
  662. r"""Deformable PSROI(Position Sensitive Region of Interest) Pooling.
  663. Args:
  664. inp: input feature map.
  665. rois: the rois for feature pooling.
  666. trans: input offset to psroi_pooling.
  667. no_trans: check the phase of DeformablePSROIPooling. False to the
  668. 1st phase, True to the 2nd phase.
  669. part_size: part size.
  670. sample_per_part: sample points of each part.
  671. pooled_shape: kernel shape of convolution.
  672. spatial_scale: the spatial_scale w.r.t input image.
  673. trans_std: multiplier used in 2nd phase.
  674. """
  675. op = builtin.DeformablePSROIPooling(
  676. no_trans=no_trans,
  677. part_size=part_size,
  678. pooled_h=pooled_h,
  679. pooled_w=pooled_w,
  680. sample_per_part=sample_per_part,
  681. spatial_scale=spatial_scale,
  682. trans_std=trans_std,
  683. )
  684. output, _ = apply(op, inp, rois, trans)
  685. return output
  686. def hswish(x):
  687. r"""Element-wise `x * relu6(x + 3) / 6`.
  688. Example:
  689. .. testcode::
  690. import numpy as np
  691. from megengine import tensor
  692. import megengine.functional as F
  693. x = tensor(np.arange(5).astype(np.float32))
  694. out = F.hswish(x)
  695. print(out.numpy().round(decimals=4))
  696. .. testoutput::
  697. [0. 0.6667 1.6667 3. 4. ]
  698. """
  699. return _elwise(x, mode=Elemwise.Mode.H_SWISH)
  700. def sigmoid(x):
  701. r"""Element-wise `1 / ( 1 + exp( -x ) )`."""
  702. return _elwise(x, mode=Elemwise.Mode.SIGMOID)
  703. @lru_cache(maxsize=None)
  704. def _get_hsigmoid_op(dtype=None, device=None):
  705. @subgraph_fn(
  706. "Hsigmoid",
  707. dtype=dtype,
  708. device=device,
  709. nr_inputs=1,
  710. jit_fusion=True,
  711. custom_grad=True,
  712. )
  713. def hsigmoid(inputs, f, c):
  714. (inp,) = inputs[0:1]
  715. inp = f("+", inp, c(3))
  716. max_0 = f("max", inp, c(0))
  717. min_6 = f("min", max_0, c(6))
  718. oup = f("/", min_6, c(6))
  719. (oup_grad,) = yield (oup,)
  720. inp_grad = f("/", oup_grad, c(6))
  721. inp_grad = f("cond_leq_mov", max_0, c(6), inp_grad)
  722. inp_grad = f("cond_leq_mov", c(0), inp, inp_grad)
  723. yield (inp_grad,)
  724. return hsigmoid
  725. def hsigmoid(x):
  726. r"""Element-wise `relu6(x + 3) / 6`."""
  727. hsigmoid = _get_hsigmoid_op(x.dtype, x.device)
  728. (x,) = hsigmoid(x)
  729. return x
  730. # return relu6(x + 3) / 6
  731. def relu(x):
  732. r"""Element-wise `max(x, 0)`."""
  733. return _elwise(x, mode=Elemwise.Mode.RELU)
  734. @lru_cache(maxsize=None)
  735. def _get_relu6_op(dtype=None, device=None):
  736. @subgraph_fn(
  737. "ReLU6",
  738. dtype=dtype,
  739. device=device,
  740. nr_inputs=1,
  741. jit_fusion=True,
  742. custom_grad=True,
  743. )
  744. def relu6(inputs, f, c):
  745. (inp,) = inputs[0:1]
  746. max_0 = f("max", inp, c(0))
  747. min_6 = f("min", max_0, c(6))
  748. oup = min_6
  749. (oup_grad,) = yield (oup,)
  750. inp_grad = f("cond_leq_mov", max_0, c(6), oup_grad)
  751. inp_grad = f("cond_leq_mov", c(0), inp, inp_grad)
  752. yield (inp_grad,)
  753. return relu6
  754. def relu6(x):
  755. r"""Element-wise `min(max(x, 0), 6)`."""
  756. relu6 = _get_relu6_op(x.dtype, x.device)
  757. (x,) = relu6(x)
  758. return x
  759. @lru_cache(maxsize=None)
  760. def _get_prelu_op(dtype=None, device=None):
  761. @subgraph_fn(
  762. "PReLU",
  763. dtype=dtype,
  764. device=device,
  765. nr_inputs=2,
  766. jit_fusion=True,
  767. custom_grad=True,
  768. )
  769. def prelu(inputs, f, c):
  770. (inp, weight) = inputs[0:2]
  771. max_0 = f("max", inp, c(0))
  772. min_0 = f("min", inp, c(0))
  773. oup = f("fma3", min_0, weight, max_0)
  774. (oup_grad,) = yield (oup,)
  775. inp_grad_0 = f("cond_leq_mov", c(0), inp, oup_grad)
  776. inp_grad_1 = f("*", oup_grad, weight)
  777. inp_grad_1 = f("cond_leq_mov", inp, c(0), inp_grad_1)
  778. inp_grad = f("+", inp_grad_0, inp_grad_1)
  779. weight_grad = f("*", oup_grad, min_0)
  780. yield (inp_grad, weight_grad)
  781. return prelu
  782. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  783. r"""Elememt-wise PReLU function.
  784. Refer to :class:`~.PReLU` for more information.
  785. """
  786. prelu = _get_prelu_op(dtype=inp.dtype, device=inp.device)
  787. (oup,) = prelu(inp, broadcast_to(weight, inp.shape))
  788. return oup
  789. @lru_cache(maxsize=None)
  790. def _get_leagk_relu_op(negative_slope, *, dtype=None, device=None):
  791. @subgraph_fn(
  792. "LeakyReLU",
  793. dtype=dtype,
  794. device=device,
  795. nr_inputs=1,
  796. jit_fusion=True,
  797. custom_grad=True,
  798. )
  799. def leakyReLU(inputs, f, c):
  800. (inp,) = inputs[0:1]
  801. max_0 = f("max", inp, c(0))
  802. min_0 = f("min", inp, c(0))
  803. oup = f("+", max_0, f("*", min_0, c(negative_slope)))
  804. (oup_grad,) = yield (oup,)
  805. inp_grad_0 = f("cond_leq_mov", c(0), inp, oup_grad)
  806. inp_grad_1 = f("*", oup_grad, c(negative_slope))
  807. inp_grad_1 = f("cond_leq_mov", inp, c(0), inp_grad_1)
  808. inp_grad = f("+", inp_grad_0, inp_grad_1)
  809. yield (inp_grad,)
  810. return leakyReLU
  811. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  812. r"""Element-wose LeakyReLU function
  813. Refer to :class:`~.LeakyReLU` for more information.
  814. """
  815. leakyReLU = _get_leagk_relu_op(negative_slope, dtype=inp.dtype, device=inp.device)
  816. (oup,) = leakyReLU(inp)
  817. return oup
  818. def silu(x):
  819. r"""Applies the element-wise Sigmoid Linear Unit function, i.e. `x * sigmoid(x)`."""
  820. return _elwise(x, mode=Elemwise.Mode.SILU)
  821. def gelu(x):
  822. r"""Applies the element-wise function:
  823. .. math::
  824. \text{gelu}(x) = x\Phi(x)
  825. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  826. """
  827. return _elwise(x, mode=Elemwise.Mode.GELU)
  828. @lru_cache(maxsize=None)
  829. def _get_softplus_op(dtype=None, device=None):
  830. @subgraph_fn(
  831. "Softplus",
  832. dtype=dtype,
  833. device=device,
  834. nr_inputs=1,
  835. jit_fusion=True,
  836. custom_grad=True,
  837. )
  838. def softplus(inputs, f, c):
  839. (inp,) = inputs[0:1]
  840. neg_abs = f("-", f("abs", inp))
  841. exp = f("exp", neg_abs)
  842. oup0 = f("log1p", exp)
  843. oup1 = f("relu", inp)
  844. oup = f("+", oup0, oup1)
  845. (oup_grad,) = yield (oup,)
  846. inp_grad_0 = f("switch_gt0", oup1, oup_grad)
  847. inp_grad_1 = oup_grad
  848. inp_grad_1 = f("/", oup_grad, f("+", exp, c(1)))
  849. inp_grad_1 = f("*", inp_grad_1, exp)
  850. inp_grad_1 = f("-", inp_grad_1)
  851. inp_grad_1 = f("abs_grad", inp, inp_grad_1)
  852. inp_grad = f("+", inp_grad_0, inp_grad_1)
  853. yield (inp_grad,)
  854. return softplus
  855. def softplus(inp: Tensor) -> Tensor:
  856. r"""Applies the element-wise function:
  857. .. math::
  858. \text{softplus}(x) = \log(1 + \exp(x))
  859. softplus is a smooth approximation to the ReLU function and can be used
  860. to constrain the output to be always positive.
  861. For numerical stability the implementation follows this transformation:
  862. .. math::
  863. \text{softplus}(x) = \log(1 + \exp(x))
  864. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  865. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  866. Examples:
  867. .. testcode::
  868. import numpy as np
  869. from megengine import tensor
  870. import megengine.functional as F
  871. x = tensor(np.arange(-3, 3, dtype=np.float32))
  872. y = F.softplus(x)
  873. print(y.numpy().round(decimals=4))
  874. Outputs:
  875. .. testoutput::
  876. [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
  877. """
  878. softplus = _get_softplus_op(inp.dtype, inp.device)
  879. (oup,) = softplus(inp)
  880. return oup
  881. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  882. r"""Applies the :math:`\log(\text{softmax}(x))` function to an n-dimensional
  883. input tensor. The :math:`\text{logsoftmax}(x)` formulation can be simplified as:
  884. .. math::
  885. \text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  886. For numerical stability the implementation follows this transformation:
  887. .. math::
  888. \text{logsoftmax}(x)
  889. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  890. = x - \log (\sum_{i}(\exp (x_{i})))
  891. = x - \text{logsumexp}(x)
  892. Examples:
  893. .. testcode::
  894. import numpy as np
  895. from megengine import tensor
  896. import megengine.functional as F
  897. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  898. y = F.logsoftmax(x, axis=1)
  899. print(y.numpy().round(decimals=4))
  900. Outputs:
  901. .. testoutput::
  902. [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
  903. [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
  904. """
  905. return inp - logsumexp(inp, axis, keepdims=True)
  906. @lru_cache(maxsize=None)
  907. def _get_logsigmoid_op(dtype=None, device=None):
  908. @subgraph_fn(
  909. "LogSigmoid",
  910. dtype=dtype,
  911. device=device,
  912. nr_inputs=1,
  913. jit_fusion=True,
  914. custom_grad=True,
  915. )
  916. def logsigmoid(inputs, f, c):
  917. (inp,) = inputs[0:1]
  918. neg_abs = f("-", f("abs", inp))
  919. exp = f("exp", neg_abs)
  920. oup0 = f("log1p", exp)
  921. oup1 = f("relu", f("-", inp))
  922. oup = f("+", oup0, oup1)
  923. oup = f("-", oup)
  924. (oup_grad,) = yield (oup,)
  925. oup_grad = f("-", oup_grad)
  926. inp_grad_0 = f("switch_gt0", oup1, oup_grad)
  927. inp_grad_0 = f("-", inp_grad_0)
  928. inp_grad_1 = oup_grad
  929. inp_grad_1 = f("/", inp_grad_1, f("+", exp, c(1)))
  930. inp_grad_1 = f("*", inp_grad_1, exp)
  931. inp_grad_1 = f("-", inp_grad_1)
  932. inp_grad_1 = f("abs_grad", inp, inp_grad_1)
  933. inp_grad = f("+", inp_grad_0, inp_grad_1)
  934. yield (inp_grad,)
  935. return logsigmoid
  936. def logsigmoid(inp: Tensor) -> Tensor:
  937. r"""Applies the element-wise function:
  938. .. math::
  939. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  940. = \log(1/(1 + \exp(-x)))
  941. = - \log(1 + \exp(-x))
  942. = - \text{softplus}(-x)
  943. Examples:
  944. .. testcode::
  945. import numpy as np
  946. from megengine import tensor
  947. import megengine.functional as F
  948. x = tensor(np.arange(-5, 5, dtype=np.float32))
  949. y = F.logsigmoid(x)
  950. print(y.numpy().round(decimals=4))
  951. Outputs:
  952. .. testoutput::
  953. [-5.0067 -4.0182 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
  954. -0.0181]
  955. """
  956. logsigmoid = _get_logsigmoid_op(inp.dtype, inp.device)
  957. (oup,) = logsigmoid(inp)
  958. return oup
  959. def logsumexp(
  960. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  961. ) -> Tensor:
  962. r"""Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  963. .. math::
  964. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  965. For numerical stability, the implementation follows this transformation:
  966. .. math::
  967. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  968. = \text{logsumexp}(x)=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  969. where
  970. .. math::
  971. b = \max(x_j)
  972. Examples:
  973. .. testcode::
  974. import numpy as np
  975. from megengine import tensor
  976. import megengine.functional as F
  977. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  978. y = F.logsumexp(x, axis=1, keepdims=False)
  979. print(y.numpy().round(decimals=4))
  980. Outputs:
  981. .. testoutput::
  982. [-0.5481 4.4519]
  983. """
  984. max_value = max(inp.detach(), axis, keepdims=True)
  985. if keepdims:
  986. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  987. else:
  988. return squeeze(max_value, axis=None) + log(
  989. sum(exp(inp - max_value), axis, keepdims)
  990. )
  991. def _get_softmax_axis(ndim: int) -> int:
  992. if ndim in (0, 1, 3):
  993. return 0
  994. return 1
  995. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  996. r"""Applies a :math:`\text{softmax}(x)` function. :math:`\text{softmax}(x)` is defined as:
  997. .. math::
  998. \text{softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  999. It is applied to all elements along axis, and rescales elements so that
  1000. they stay in the range `[0, 1]` and sum to 1.
  1001. See :class:`~.module.Softmax` for more details.
  1002. Examples:
  1003. .. testcode::
  1004. import numpy as np
  1005. from megengine import tensor
  1006. import megengine.functional as F
  1007. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  1008. out = F.softmax(x)
  1009. print(out.numpy().round(decimals=4))
  1010. Outputs:
  1011. .. testoutput::
  1012. [[0.0117 0.0317 0.0861 0.2341 0.6364]
  1013. [0.0117 0.0317 0.0861 0.2341 0.6364]]
  1014. """
  1015. if axis is None:
  1016. axis = _get_softmax_axis(len(inp.shape))
  1017. if isinstance(axis, list):
  1018. offset = inp.max(axis=axis, keepdims=True).detach()
  1019. cached = exp(inp - offset)
  1020. down = sum(cached, axis=axis, keepdims=True)
  1021. return cached / down
  1022. else:
  1023. op = builtin.Softmax(axis=axis,)
  1024. (output,) = apply(op, inp)
  1025. return output
  1026. def layer_norm(
  1027. inp: Tensor,
  1028. normalized_shape: tuple,
  1029. affine: bool,
  1030. weight: Optional[Tensor] = None,
  1031. bias: Optional[Tensor] = None,
  1032. eps: float = 1e-5,
  1033. ):
  1034. r"""Applies layer normalization to the input. Support tensor of any shape as input.
  1035. Reference: https://arxiv.org/pdf/1803.08494.pdf.
  1036. Args:
  1037. inp: input tensor.
  1038. normalized_shape: the shape that you want to be normalizated
  1039. affine: whether to use weight and bias
  1040. weight: must not be None when the affine is true
  1041. bias: must not be None when the affine is true
  1042. eps: a value added to the denominator for numerical stability. Default: 1e-5
  1043. """
  1044. if amp._enabled:
  1045. inp, weight, bias = cast_tensors(inp, weight, bias, promote=True)
  1046. if isinstance(normalized_shape, int):
  1047. normalized_shape = [normalized_shape]
  1048. normalized_dim = len(normalized_shape)
  1049. assert normalized_dim > 0
  1050. normalized_size = 1
  1051. for i in range(normalized_dim):
  1052. normalized_size = normalized_size * normalized_shape[i]
  1053. op = builtin.LayerNorm(
  1054. affine=affine,
  1055. eps=eps,
  1056. normalized_dim=normalized_dim,
  1057. normalized_size=normalized_size,
  1058. )
  1059. if affine:
  1060. assert weight is not None and bias is not None
  1061. return apply(op, inp, weight, bias)[0]
  1062. else:
  1063. # assert weight is None and bias is None
  1064. return apply(op, inp)[0]
  1065. def batch_norm(
  1066. inp: Tensor,
  1067. running_mean: Tensor = None,
  1068. running_var: Tensor = None,
  1069. weight: Optional[Tensor] = None,
  1070. bias: Optional[Tensor] = None,
  1071. *,
  1072. training: bool = False,
  1073. momentum: float = 0.9,
  1074. eps: float = 1e-5,
  1075. inplace: bool = True,
  1076. compute_mode="default",
  1077. param_dim="dim_1c11"
  1078. ):
  1079. r"""Applies batch normalization to the input.
  1080. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  1081. Args:
  1082. inp: input tensor.
  1083. running_mean: tensor to store running mean.
  1084. running_var: tensor to store running variance.
  1085. weight: scaling tensor in the learnable affine parameters.
  1086. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  1087. bias: bias tensor in the learnable affine parameters.
  1088. See :math:`\beta` in :class:`~.BatchNorm2d`.
  1089. training: a boolean value to indicate whether batch norm is performed
  1090. in training mode. Default: False
  1091. momentum: value used for the ``running_mean`` and ``running_var``
  1092. computation. Default: 0.9
  1093. eps: a value added to the denominator for numerical stability. Default: 1e-5
  1094. inplace: whether to update ``running_mean`` and ``running_var``
  1095. inplace or return new tensors. Default: True
  1096. """
  1097. def make_full_if_none(x, value):
  1098. x_ndim = None if x is None else x.ndim
  1099. # in general case, x will be returned here directly
  1100. if x_ndim is not None and x_ndim != 1:
  1101. return x
  1102. if param_dim == "dim_1c11":
  1103. C = inp.shape[1]
  1104. pshape = (1, C, 1, 1)
  1105. elif param_dim == "dim_111c":
  1106. C = inp.shape[3]
  1107. pshape = (1, 1, 1, C)
  1108. else:
  1109. raise ValueError("Invalid param_dim {}".format(param_dim))
  1110. if x is None:
  1111. x = Const(value, inp.dtype, inp.device, None)
  1112. shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
  1113. (result,) = apply(builtin.Broadcast(), x, shape)
  1114. return result
  1115. else:
  1116. assert x_ndim == 1
  1117. shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
  1118. (result,) = apply(builtin.Reshape(), x, shape)
  1119. return result
  1120. has_mean = running_mean is not None
  1121. has_var = running_var is not None
  1122. if not training:
  1123. assert has_mean, "running_mean must be provided in inference mode"
  1124. assert has_var, "running_var must be provided in inference mode"
  1125. weight = make_full_if_none(weight, 1)
  1126. bias = make_full_if_none(bias, 0)
  1127. if not training:
  1128. op = builtin.BatchNorm(
  1129. fwd_mode=BatchNorm.FwdMode.INFERENCE, epsilon=eps, param_dim=param_dim
  1130. )
  1131. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  1132. return ret
  1133. else:
  1134. op = builtin.BatchNorm(
  1135. avg_factor=1 - momentum, epsilon=eps, param_dim=param_dim
  1136. )
  1137. if has_mean or has_var:
  1138. running_mean = make_full_if_none(running_mean, 0)
  1139. running_var = make_full_if_none(running_var, 1)
  1140. new_mean, new_var, *_, inp = apply(
  1141. op, inp, weight, bias, running_mean, running_var
  1142. )
  1143. if not has_mean:
  1144. new_mean = None
  1145. if not has_var:
  1146. new_var = None
  1147. if inplace:
  1148. if has_mean:
  1149. running_mean[...] = new_mean
  1150. if has_var:
  1151. running_var[...] = new_var
  1152. return inp
  1153. else:
  1154. return inp, new_mean, new_var
  1155. else:
  1156. inp = apply(op, inp, weight, bias)[-1]
  1157. return inp
  1158. @lru_cache(maxsize=None)
  1159. def _get_sync_bn_ops(device, dtype, eps_mode, ndim, channels):
  1160. # fmt: off
  1161. @subgraph("SyncBnStage0", dtype, device, 1)
  1162. def syncbn_stage0(inputs, f, c):
  1163. input = inputs[0]
  1164. reduce_shape = c((1, channels) + (1,) * (ndim - 2), dtype="int32", device=device)
  1165. input_shape = f(GetVarShape(), input)
  1166. input_elems = f(Reduce(mode="product", axis=0), input_shape)
  1167. reduce_elems = f(Reduce(mode="product", axis=0), reduce_shape)
  1168. reduce_size = f("//", input_elems, reduce_elems)
  1169. channel_x1s = f(Reduce(mode="sum"), input, reduce_shape)
  1170. channel_x2s = f(Reduce(mode="sum_sqr"), input, reduce_shape)
  1171. reduce_size_f = f(TypeCvt(dtype=dtype), reduce_size)
  1172. return (reduce_shape, reduce_size_f, channel_x1s, channel_x2s), (False, False, True, True)
  1173. @subgraph("SyncBnStage1", dtype, device, 7)
  1174. def syncbn_stage1(inputs, f, c):
  1175. input, reduce_size, channel_x1s, channel_x2s, eps = inputs[0:5]
  1176. weight, bias = inputs[5:7]
  1177. channel_mean = f("/", channel_x1s, reduce_size)
  1178. channel_var =\
  1179. f("+", f("/", f("**", channel_x1s, c(2)),
  1180. f("-", f("*", reduce_size, reduce_size))),
  1181. f("/", channel_x2s, reduce_size))
  1182. invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
  1183. inv_var_wt = f("*", invsqrt_channel_var, weight)
  1184. neg_channel_mean = f("-", channel_mean)
  1185. outvar =\
  1186. f("fma3", input, inv_var_wt,
  1187. f("+", f("*", neg_channel_mean, inv_var_wt),
  1188. bias))
  1189. return (outvar, channel_mean, channel_var, inv_var_wt), (True, False, False, False)
  1190. @subgraph("SyncBnStage1Inference", dtype, device, 6)
  1191. def syncbn_stage1_inference(inputs, f, c):
  1192. input, channel_mean, channel_var, eps = inputs[0:4]
  1193. weight, bias = inputs[4:6]
  1194. invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
  1195. inv_var_wt = f("*", invsqrt_channel_var, weight)
  1196. neg_channel_mean = f("-", channel_mean)
  1197. outvar =\
  1198. f("+", f("*", input, inv_var_wt),
  1199. f("+", f("*", neg_channel_mean, inv_var_wt),
  1200. bias))
  1201. return (outvar,), (True,)
  1202. @subgraph("SyncBnStage2", dtype, device, 7)
  1203. def syncbn_stage2(inputs, f, c):
  1204. running_mean, running_var, momentum = inputs[0:3]
  1205. reduce_size, channel_x1s, channel_x2s, channel_mean = inputs[3:7]
  1206. c1_minus_momentum = f("-", c(1), momentum)
  1207. reduce_size_minus_c1 = f("-", reduce_size, c(1))
  1208. running_mean = f("fma4",
  1209. running_mean, momentum,
  1210. c1_minus_momentum, channel_mean,
  1211. )
  1212. channel_variance_unbiased =\
  1213. f("+", f("/", f("**", channel_x1s, c(2)),
  1214. f("*", f("-", reduce_size),
  1215. reduce_size_minus_c1)),
  1216. f("/", channel_x2s,
  1217. reduce_size_minus_c1))
  1218. running_var = f("fma4",
  1219. running_var, momentum,
  1220. c1_minus_momentum, channel_variance_unbiased
  1221. )
  1222. return (running_mean, running_var), (True, True)
  1223. @subgraph("SyncBnConcatStats", dtype, device, 3)
  1224. def syncbn_concat_stats(inputs, f, c):
  1225. reduce_size, channel_x1s, channel_x2s = inputs[0:3]
  1226. reduce_size = f(builtin.Broadcast(), reduce_size, c([1]*ndim, dtype="int32"))
  1227. stats = f(builtin.Concat(axis=1, comp_node=device), reduce_size, channel_x1s, channel_x2s)
  1228. return (stats,), (True,)
  1229. @subgraph("SyncBnSplitStats", dtype, device, 1)
  1230. def syncbn_split_stats(inputs, f, c):
  1231. stats = inputs[0]
  1232. c_1 = c(1, dtype="int32")
  1233. channel_x1s_end = c(channels+1, dtype="int32")
  1234. def _subtensor(src, axis, begin, end):
  1235. items = (axis, (begin is not None), (end is not None), False, False),
  1236. args = ()
  1237. if begin is not None:
  1238. args += begin,
  1239. if end is not None:
  1240. args += end,
  1241. return f(builtin.Subtensor(items=items), src, *args)
  1242. reduce_size = _subtensor(stats, 1, None, c_1)
  1243. channel_x1s = _subtensor(stats, 1, c_1, channel_x1s_end)
  1244. channel_x2s = _subtensor(stats, 1, channel_x1s_end, None)
  1245. reduce_size = f(builtin.Reshape(), reduce_size, c_1)
  1246. return (reduce_size, channel_x1s, channel_x2s), (False, True, True)
  1247. # fmt: on
  1248. return (
  1249. syncbn_stage0,
  1250. syncbn_stage1,
  1251. syncbn_stage1_inference,
  1252. syncbn_stage2,
  1253. syncbn_concat_stats,
  1254. syncbn_split_stats,
  1255. )
  1256. def sync_batch_norm(
  1257. inp: Tensor,
  1258. running_mean: Tensor,
  1259. running_var: Tensor,
  1260. weight: Optional[Tensor] = None,
  1261. bias: Optional[Tensor] = None,
  1262. training: bool = False,
  1263. momentum: Union[float, Tensor] = 0.9,
  1264. eps: float = 1e-5,
  1265. eps_mode="additive",
  1266. group=WORLD,
  1267. ) -> Tensor:
  1268. r"""Applies synchronized batch normalization to the input.
  1269. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  1270. Args:
  1271. inp: input tensor.
  1272. running_mean: tensor to store running mean.
  1273. running_var: tensor to store running variance.
  1274. weight: scaling tensor in the learnable affine parameters.
  1275. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  1276. bias: bias tensor in the learnable affine parameters.
  1277. See :math:`\beta` in :class:`~.BatchNorm2d`.
  1278. training: a boolean value to indicate whether batch norm is performed
  1279. in traning mode. Default: False
  1280. momentum: value used for the ``running_mean`` and ``running_var``
  1281. computation. Default: 0.9
  1282. eps: a value added to the denominator for numerical stability.
  1283. Default: 1e-5
  1284. eps_mode: mode of calculation for eps, "max" or "additive".
  1285. Default: "additive"
  1286. group: communication group, caculate mean and variance between this group.
  1287. Default: :obj:`~megengine.distributed.WORLD`
  1288. """
  1289. _eps_mode = eps_mode.lower()
  1290. assert _eps_mode in {"max", "additive"}, "unknown eps_mode: {}".format(eps_mode)
  1291. if _eps_mode == "additive" and not (is_distributed() and training):
  1292. return batch_norm(
  1293. inp,
  1294. running_mean,
  1295. running_var,
  1296. weight,
  1297. bias,
  1298. training=training,
  1299. momentum=momentum,
  1300. eps=eps,
  1301. )
  1302. if amp._enabled:
  1303. inp, weight, bias, running_mean, running_var = cast_tensors(
  1304. inp, weight, bias, running_mean, running_var, promote=True
  1305. )
  1306. _channels = make_shape_tuple(inp.shape)[1]
  1307. _ndim = inp.ndim
  1308. _device = inp.device
  1309. _dtype = inp.dtype
  1310. if _ndim != 4:
  1311. raise NotImplementedError("sync_batch_norm for ndim != 4")
  1312. def _make_full_if_none(x, value):
  1313. if x is None:
  1314. x = Const(value, inp.dtype, _device, None)
  1315. (result,) = apply(builtin.Broadcast(), x, reduce_shape)
  1316. return result
  1317. elif x.ndim == 1:
  1318. (result,) = apply(builtin.Reshape(), x, reduce_shape)
  1319. return result
  1320. return x
  1321. (
  1322. syncbn_stage0,
  1323. syncbn_stage1,
  1324. syncbn_stage1_inference,
  1325. syncbn_stage2,
  1326. syncbn_concat_stats,
  1327. syncbn_split_stats,
  1328. ) = _get_sync_bn_ops(_device, _dtype, eps_mode, _ndim, _channels)
  1329. reduce_shape, reduce_size, channel_x1s, channel_x2s = apply(syncbn_stage0(), inp)
  1330. eps = convert_single_value(eps, dtype=inp.dtype, device=inp.device)
  1331. weight = _make_full_if_none(weight, 1)
  1332. bias = _make_full_if_none(bias, 0)
  1333. if training:
  1334. if is_distributed():
  1335. # reduce all nodes' data to calculate mean and variance
  1336. (stat,) = apply(
  1337. syncbn_concat_stats(), reduce_size, channel_x1s, channel_x2s
  1338. )
  1339. stat = all_reduce_sum(stat, group)
  1340. reduce_size, channel_x1s, channel_x2s = apply(syncbn_split_stats(), stat)
  1341. outvar, channel_mean, *_ = apply(
  1342. syncbn_stage1(),
  1343. inp,
  1344. reduce_size,
  1345. channel_x1s,
  1346. channel_x2s,
  1347. eps,
  1348. weight,
  1349. bias,
  1350. )
  1351. else:
  1352. assert running_var is not None and running_mean is not None
  1353. channel_mean = running_mean
  1354. channel_var = running_var
  1355. outvar, *_ = apply(
  1356. syncbn_stage1_inference(), inp, channel_mean, channel_var, eps, weight, bias
  1357. )
  1358. # outvar = output * weight + bias
  1359. # where output = inp * invsqrt_channel_variance + (
  1360. # -channel_mean * invsqrt_channel_variance
  1361. # )
  1362. # Manually expand output for gopt
  1363. if training and running_var is not None and running_mean is not None:
  1364. momentum = convert_single_value(momentum, dtype=inp.dtype, device=inp.device)
  1365. running_mean[...], running_var[...] = apply(
  1366. syncbn_stage2(),
  1367. running_mean,
  1368. running_var,
  1369. momentum,
  1370. reduce_size,
  1371. channel_x1s,
  1372. channel_x2s,
  1373. channel_mean,
  1374. )
  1375. if amp._enabled:
  1376. outvar = outvar.astype("float16")
  1377. return outvar
  1378. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1379. r"""Returns a new tensor where each of the elements are randomly set to zero
  1380. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1381. Args:
  1382. inp: input tensor.
  1383. drop_prob: probability to drop (set to zero) a single element.
  1384. training: the default behavior of ``dropout`` during training is to rescale the output,
  1385. then it can be replaced by an :class:`~.module.identify.Identity` during inference. Default: True
  1386. Returns:
  1387. the ouput tensor
  1388. Examples:
  1389. .. testcode::
  1390. import numpy as np
  1391. from megengine import tensor
  1392. import megengine.functional as F
  1393. # test training mode
  1394. data = tensor(np.ones(10000000, dtype=np.float32))
  1395. out = F.nn.dropout(data, 1.0 / 3.0, training=True)
  1396. assert not out.numpy().all()
  1397. # test eval mode
  1398. out = F.nn.dropout(data, 1.0 / 3.0, training=False)
  1399. assert out.numpy().all()
  1400. Outputs:
  1401. .. testoutput::
  1402. :options: +SKIP
  1403. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1404. """
  1405. assert 0 <= drop_prob < 1
  1406. if not training or drop_prob == 0:
  1407. return inp
  1408. # model in training mode, e.g. model.train()
  1409. op = Dropout(drop_prob=drop_prob, seed=_get_global_rng_seed(), handle=0)
  1410. outputs = apply(op, inp)
  1411. return outputs[0]
  1412. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  1413. r"""Performs one-hot encoding for the input tensor.
  1414. Args:
  1415. inp: input tensor.
  1416. num_classes: number of classes denotes the last dimension of the output tensor.
  1417. Examples:
  1418. .. testcode::
  1419. import numpy as np
  1420. from megengine import tensor
  1421. import megengine.functional as F
  1422. x = tensor(np.arange(1, 4, dtype=np.int32))
  1423. out = F.one_hot(x, num_classes=4)
  1424. print(out.numpy())
  1425. Outputs:
  1426. .. testoutput::
  1427. [[0 1 0 0]
  1428. [0 0 1 0]
  1429. [0 0 0 1]]
  1430. """
  1431. zeros_tensor = zeros(
  1432. list(inp.shape) + [num_classes], dtype=inp.dtype, device=inp.device
  1433. )
  1434. ones_tensor = ones(list(inp.shape) + [1], dtype=inp.dtype, device=inp.device)
  1435. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  1436. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  1437. return result
  1438. def embedding(
  1439. inp: Tensor,
  1440. weight: Tensor,
  1441. padding_idx: Optional[int] = None,
  1442. max_norm: Optional[float] = None,
  1443. norm_type: Optional[float] = None,
  1444. ):
  1445. r"""Applies lookup table for embedding.
  1446. Args:
  1447. inp: tensor with indices.
  1448. weight: learnable weights which embeds from.
  1449. padding_idx: should be set to None, not supported now.
  1450. max_norm: should be set to None, not supported now.
  1451. norm_type: should be set to None, not supported now.
  1452. Refer to :class:`~.module.Embedding` for more information.
  1453. """
  1454. if padding_idx is not None:
  1455. raise ValueError("Not support padding_idx Now!")
  1456. if max_norm is not None or norm_type is not None:
  1457. raise ValueError("Not support weight normlization Now!")
  1458. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1459. return weight[inp.reshape(-1)].reshape(dest_shp)
  1460. def indexing_one_hot(
  1461. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1462. ) -> Tensor:
  1463. r"""One-hot indexing for some axes.
  1464. Args:
  1465. src: input tensor.
  1466. index: index tensor.
  1467. axis: axis on src for which values in index index. Default: 1
  1468. keepdims: whether not to remove the axis in result. Default: False
  1469. Examples:
  1470. .. testcode::
  1471. import megengine.functional as F
  1472. from megengine import tensor
  1473. src = tensor([[1.0, 2.0]])
  1474. index = tensor([0])
  1475. val = F.indexing_one_hot(src, index)
  1476. print(val.numpy())
  1477. Outputs:
  1478. .. testoutput::
  1479. [1.]
  1480. """
  1481. assert isinstance(src, Tensor), "src must be of Tensor type"
  1482. op = builtin.IndexingOneHot(axis=axis)
  1483. index = convert_single_value(index, dtype="int32", device=src.device)
  1484. (result,) = apply(op, src, index)
  1485. if not keepdims:
  1486. result = squeeze(result, axis)
  1487. return result
  1488. def sliding_window(
  1489. inp: Tensor,
  1490. kernel_size: Union[int, Tuple[int, int]],
  1491. padding: Union[int, Tuple[int, int]] = 0,
  1492. stride: Union[int, Tuple[int, int]] = 1,
  1493. dilation: Union[int, Tuple[int, int]] = 1,
  1494. ) -> Tensor:
  1495. r"""Extracts sliding local blocks from a batched input tensor.
  1496. Refer to :class:`~.module.sliding_window.SlidingWindow` for more information.
  1497. Args:
  1498. inp: input tensor.
  1499. kernel_size: size of the window.
  1500. padding: implicit zero padding added on both sides of input. Default: 0
  1501. stride: stride of the window. Default: 1
  1502. dilation: dilation of the window. Default: 1
  1503. """
  1504. padding_h, padding_w = _pair(padding)
  1505. stride_h, stride_w = _pair_nonzero(stride)
  1506. dilation_h, dilation_w = _pair_nonzero(dilation)
  1507. window_h, window_w = _pair_nonzero(kernel_size)
  1508. op = builtin.Images2Neibs(
  1509. pad_h=padding_h,
  1510. pad_w=padding_w,
  1511. stride_h=stride_h,
  1512. stride_w=stride_w,
  1513. dilate_h=dilation_h,
  1514. dilate_w=dilation_w,
  1515. window_h=window_h,
  1516. window_w=window_w,
  1517. )
  1518. (output,) = apply(op, inp)
  1519. return output
  1520. def sliding_window_transpose(
  1521. inp: Tensor,
  1522. output_size: Union[int, Tuple[int, int]],
  1523. kernel_size: Union[int, Tuple[int, int]],
  1524. padding: Union[int, Tuple[int, int]] = 0,
  1525. stride: Union[int, Tuple[int, int]] = 1,
  1526. dilation: Union[int, Tuple[int, int]] = 1,
  1527. ) -> Tensor:
  1528. r"""Sum over the sliding windows on the corresponding input location.
  1529. Refer to :class:`~.module.sliding_window.SlidingWindowTranspose` for more information.
  1530. Args:
  1531. inp: input tensor.
  1532. output_size: shape of output tensor.
  1533. kernel_size: size of the window.
  1534. padding: implicit zero padding added on both sides of input. Default: 0
  1535. stride: stride of the window. Default: 1
  1536. dilation: dilation of the window. Default: 1
  1537. """
  1538. output_h, output_w = _pair_nonzero(output_size)
  1539. padding_h, padding_w = _pair(padding)
  1540. stride_h, stride_w = _pair_nonzero(stride)
  1541. dilation_h, dilation_w = _pair_nonzero(dilation)
  1542. window_h, window_w = _pair_nonzero(kernel_size)
  1543. expected_h = (
  1544. output_h + 2 * padding_h - dilation_h * (window_h - 1) - 1
  1545. ) // stride_h + 1
  1546. expected_w = (
  1547. output_w + 2 * padding_w - dilation_w * (window_w - 1) - 1
  1548. ) // stride_w + 1
  1549. assert inp.ndim == 6, "the input dimension of sliding_window_transpose should be 6"
  1550. assert (
  1551. inp.shape[2] == expected_h and inp.shape[3] == expected_w
  1552. ), "the input shape and output size do not match"
  1553. op = builtin.SlidingWindowTranspose(
  1554. out_h=output_h,
  1555. out_w=output_w,
  1556. pad_h=padding_h,
  1557. pad_w=padding_w,
  1558. stride_h=stride_h,
  1559. stride_w=stride_w,
  1560. dilate_h=dilation_h,
  1561. dilate_w=dilation_w,
  1562. window_h=window_h,
  1563. window_w=window_w,
  1564. )
  1565. (output,) = apply(op, inp)
  1566. return output
  1567. def pad(
  1568. src: Tensor,
  1569. pad_width: Tuple[Tuple[int, int], ...],
  1570. mode: str = "constant",
  1571. constant_value: float = 0.0,
  1572. ) -> Tensor:
  1573. r"""Pads the input tensor.
  1574. Args:
  1575. pad_width: A tuple. Each element in the tuple is the tuple of 2-elements,
  1576. the 2 elements represent the padding size on both sides of the current dimension, ``(front_offset, back_offset)``
  1577. mode: One of the following string values. Default: ``'constant'``
  1578. * ``'constant'``: Pads with a constant value.
  1579. * ``'reflect'``: Pads with the edge values of tensor.
  1580. * ``'replicate'``: Pads with the reflection of the tensor mirrored on the first and last values of the tensor along each axis.
  1581. constant_val: Fill value for ``'constant'`` padding. Default: 0
  1582. Examples:
  1583. >>> import numpy as np
  1584. >>> inp = Tensor([[1., 2., 3.],[4., 5., 6.]])
  1585. >>> inp
  1586. Tensor([[1. 2. 3.]
  1587. [4. 5. 6.]], device=xpux:0)
  1588. >>> F.nn.pad(inp, pad_width=((1, 1),), mode="constant")
  1589. Tensor([[0. 0. 0.]
  1590. [1. 2. 3.]
  1591. [4. 5. 6.]
  1592. [0. 0. 0.]], device=xpux:0)
  1593. >>> F.nn.pad(inp, pad_width=((1, 1),), mode="constant", constant_value=9)
  1594. Tensor([[9. 9. 9.]
  1595. [1. 2. 3.]
  1596. [4. 5. 6.]
  1597. [9. 9. 9.]], device=xpux:0)
  1598. >>> F.nn.pad(inp, pad_width=((1, 1), (1, 2)), mode="reflect")
  1599. Tensor([[5. 4. 5. 6. 5. 4.]
  1600. [2. 1. 2. 3. 2. 1.]
  1601. [5. 4. 5. 6. 5. 4.]
  1602. [2. 1. 2. 3. 2. 1.]], device=xpux:0)
  1603. >>> F.nn.pad(inp, pad_width=((1, 1), (1, 2)), mode="replicate")
  1604. Tensor([[1. 1. 2. 3. 3. 3.]
  1605. [1. 1. 2. 3. 3. 3.]
  1606. [4. 4. 5. 6. 6. 6.]
  1607. [4. 4. 5. 6. 6. 6.]], device=xpux:0)
  1608. """
  1609. p_offsets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  1610. assert mode.lower() in ["constant", "edge", "replicate", "reflect"]
  1611. if mode.lower() == "edge":
  1612. mode = "replicate"
  1613. for i in range(0, len(pad_width)):
  1614. p_offsets[i * 2] = pad_width[i][0]
  1615. p_offsets[i * 2 + 1] = pad_width[i][1]
  1616. op = builtin.Padding(
  1617. front_offset_dim0=p_offsets[0],
  1618. front_offset_dim1=p_offsets[2],
  1619. front_offset_dim2=p_offsets[4],
  1620. front_offset_dim3=p_offsets[6],
  1621. front_offset_dim4=p_offsets[8],
  1622. front_offset_dim5=p_offsets[10],
  1623. front_offset_dim6=p_offsets[12],
  1624. back_offset_dim0=p_offsets[1],
  1625. back_offset_dim1=p_offsets[3],
  1626. back_offset_dim2=p_offsets[5],
  1627. back_offset_dim3=p_offsets[7],
  1628. back_offset_dim4=p_offsets[9],
  1629. back_offset_dim5=p_offsets[11],
  1630. back_offset_dim6=p_offsets[13],
  1631. padding_val=constant_value,
  1632. padding_mode=mode.upper(),
  1633. )
  1634. (output,) = apply(op, src)
  1635. return output
  1636. def local_response_norm(
  1637. inp: Tensor,
  1638. kernel_size: int = 5,
  1639. k: float = 2.0,
  1640. alpha: float = 1e-4,
  1641. beta: float = 0.75,
  1642. ) -> Tensor:
  1643. r"""
  1644. Apply local response normalization to the input tensor.
  1645. Args:
  1646. kernel_size: the size of the kernel to apply LRN on.
  1647. k: hyperparameter k. The default vaule is 2.0.
  1648. alpha: hyperparameter alpha. The default value is 1e-4.
  1649. beta: hyperparameter beta. The default value is 0.75.
  1650. Example:
  1651. .. testcode::
  1652. from megengine import tensor
  1653. import megengine.functional as f
  1654. import numpy as np
  1655. inp = tensor(np.arange(25, dtype=np.float32).reshape(1,1,5,5))
  1656. GT = np.array([[[[ 0., 0.999925, 1.9994003, 2.9979765, 3.9952066],
  1657. [ 4.9906454, 5.983851, 6.974385, 7.961814, 8.945709 ],
  1658. [ 9.925651, 10.90122, 11.872011, 12.837625, 13.7976675],
  1659. [14.751757, 15.699524, 16.640602, 17.574642, 18.501305 ],
  1660. [19.420258, 20.331186, 21.233786, 22.127764, 23.012836 ]]]])
  1661. out = f.local_response_norm(inp, kernel_size=3, k=1.0, alpha=1e-4, beta=0.75)
  1662. np.testing.assert_allclose(GT, out.numpy(), rtol=1e-6, atol=1e-6)
  1663. print('pass')
  1664. Outputs:
  1665. .. testoutput::
  1666. pass
  1667. """
  1668. op = builtin.LRN(n=kernel_size, k=k, alpha=alpha, beta=beta,)
  1669. (output,) = apply(op, inp)
  1670. return output
  1671. @lru_cache(maxsize=None)
  1672. def _get_layerPixelShuffle(device, dtype, dim_order):
  1673. @subgraph("LayerPixelShuffle", dtype, device, 3)
  1674. def layerPixelShuffle(inputs, f, c):
  1675. inp, shape_0, shape_1 = inputs
  1676. inp = f(Reshape(), inp, shape_0)
  1677. inp = f(Dimshuffle(dim_order), inp)
  1678. oup = f(Reshape(), inp, shape_1)
  1679. return (oup,), (True,)
  1680. return layerPixelShuffle
  1681. def pixel_shuffle(inp: Tensor, upscale_factor: int) -> Tensor:
  1682. """
  1683. Rearranges elements in a tensor of shape (*, C x r^2, H, W) to a tensor of
  1684. shape (*, C, H x r, W x r), where r is an upscale factor, where * is zero
  1685. or more batch dimensions.
  1686. :param inp: input tensor.
  1687. :param upscale_factor: upscale factor of pixel_shuffle.
  1688. :return: output tensor.
  1689. """
  1690. assert upscale_factor > 0, "upscale_factor should larger than 0"
  1691. assert inp.ndim >= 3, "the input dimension of pixel_shuffle should be larger than 3"
  1692. assert (
  1693. inp.shape[-3] % (upscale_factor ** 2) == 0
  1694. ), "the -3 dimension should be divided by (upscale_factor ** 2)"
  1695. _device = inp.device
  1696. _dtype = inp.dtype
  1697. shape_ori = inp.shape
  1698. high_dim = shape_ori[:-3]
  1699. square = upscale_factor ** 2
  1700. n = 1
  1701. for item in high_dim:
  1702. n *= item
  1703. shape_0 = (
  1704. n,
  1705. int(shape_ori[-3] / square),
  1706. upscale_factor,
  1707. upscale_factor,
  1708. shape_ori[-2],
  1709. shape_ori[-1],
  1710. )
  1711. shape_1 = (
  1712. *high_dim,
  1713. int(shape_ori[-3] / square),
  1714. shape_ori[-2] * upscale_factor,
  1715. shape_ori[-1] * upscale_factor,
  1716. )
  1717. dim_order = (0, 1, 4, 2, 5, 3)
  1718. layerPixelShuffle = _get_layerPixelShuffle(_device, _dtype, dim_order)
  1719. shape_0 = convert_single_value(shape_0, device=inp.device)
  1720. shape_1 = convert_single_value(shape_1, device=inp.device)
  1721. outvar, *_ = apply(layerPixelShuffle(), inp, shape_0, shape_1)
  1722. return outvar
  1723. from .quantized import conv_bias_activation # isort:skip
  1724. from .loss import * # isort:skip
  1725. from .metric import * # isort:skip
  1726. from .vision import * # isort:skip