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

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