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

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