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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861
  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. setscalar,
  38. subgraph,
  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. def hsigmoid(x):
  731. r"""Element-wise `relu6(x + 3) / 6`."""
  732. return relu6(x + 3) / 6
  733. def relu(x):
  734. r"""Element-wise `max(x, 0)`."""
  735. return _elwise(x, mode=Elemwise.Mode.RELU)
  736. def relu6(x):
  737. r"""Element-wise `min(max(x, 0), 6)`."""
  738. return minimum(maximum(x, 0), 6)
  739. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  740. r"""Elememt-wise PReLU function.
  741. Refer to :class:`~.PReLU` for more information.
  742. """
  743. return maximum(inp, 0) + weight * minimum(inp, 0)
  744. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  745. r"""Element-wose LeakyReLU function
  746. Refer to :class:`~.LeakyReLU` for more information.
  747. """
  748. return maximum(inp, 0) + negative_slope * minimum(inp, 0)
  749. def silu(x):
  750. r"""Applies the element-wise Sigmoid Linear Unit function, i.e. `x * sigmoid(x)`."""
  751. return _elwise(x, mode=Elemwise.Mode.SILU)
  752. def gelu(x):
  753. r"""Applies the element-wise function:
  754. .. math::
  755. \text{gelu}(x) = x\Phi(x)
  756. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  757. """
  758. return _elwise(x, mode=Elemwise.Mode.GELU)
  759. def softplus(inp: Tensor) -> Tensor:
  760. r"""Applies the element-wise function:
  761. .. math::
  762. \text{softplus}(x) = \log(1 + \exp(x))
  763. softplus is a smooth approximation to the ReLU function and can be used
  764. to constrain the output to be always positive.
  765. For numerical stability the implementation follows this transformation:
  766. .. math::
  767. \text{softplus}(x) = \log(1 + \exp(x))
  768. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  769. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  770. Examples:
  771. .. testcode::
  772. import numpy as np
  773. from megengine import tensor
  774. import megengine.functional as F
  775. x = tensor(np.arange(-3, 3, dtype=np.float32))
  776. y = F.softplus(x)
  777. print(y.numpy().round(decimals=4))
  778. Outputs:
  779. .. testoutput::
  780. [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
  781. """
  782. return log1p(exp(-abs(inp))) + relu(inp)
  783. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  784. r"""Applies the :math:`\log(\text{softmax}(x))` function to an n-dimensional
  785. input tensor. The :math:`\text{logsoftmax}(x)` formulation can be simplified as:
  786. .. math::
  787. \text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  788. For numerical stability the implementation follows this transformation:
  789. .. math::
  790. \text{logsoftmax}(x)
  791. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  792. = x - \log (\sum_{i}(\exp (x_{i})))
  793. = x - \text{logsumexp}(x)
  794. Examples:
  795. .. testcode::
  796. import numpy as np
  797. from megengine import tensor
  798. import megengine.functional as F
  799. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  800. y = F.logsoftmax(x, axis=1)
  801. print(y.numpy().round(decimals=4))
  802. Outputs:
  803. .. testoutput::
  804. [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
  805. [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
  806. """
  807. return inp - logsumexp(inp, axis, keepdims=True)
  808. def logsigmoid(inp: Tensor) -> Tensor:
  809. r"""Applies the element-wise function:
  810. .. math::
  811. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  812. = \log(1/(1 + \exp(-x)))
  813. = - \log(1 + \exp(-x))
  814. = - \text{softplus}(-x)
  815. Examples:
  816. .. testcode::
  817. import numpy as np
  818. from megengine import tensor
  819. import megengine.functional as F
  820. x = tensor(np.arange(-5, 5, dtype=np.float32))
  821. y = F.logsigmoid(x)
  822. print(y.numpy().round(decimals=4))
  823. Outputs:
  824. .. testoutput::
  825. [-5.0067 -4.0182 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
  826. -0.0181]
  827. """
  828. return -softplus(-inp)
  829. def logsumexp(
  830. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  831. ) -> Tensor:
  832. r"""Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  833. .. math::
  834. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  835. For numerical stability, the implementation follows this transformation:
  836. .. math::
  837. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  838. = \text{logsumexp}(x)=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  839. where
  840. .. math::
  841. b = \max(x_j)
  842. Examples:
  843. .. testcode::
  844. import numpy as np
  845. from megengine import tensor
  846. import megengine.functional as F
  847. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  848. y = F.logsumexp(x, axis=1, keepdims=False)
  849. print(y.numpy().round(decimals=4))
  850. Outputs:
  851. .. testoutput::
  852. [-0.5481 4.4519]
  853. """
  854. max_value = max(inp.detach(), axis, keepdims=True)
  855. if keepdims:
  856. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  857. else:
  858. return squeeze(max_value, axis=None) + log(
  859. sum(exp(inp - max_value), axis, keepdims)
  860. )
  861. def _get_softmax_axis(ndim: int) -> int:
  862. if ndim in (0, 1, 3):
  863. return 0
  864. return 1
  865. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  866. r"""Applies a :math:`\text{softmax}(x)` function. :math:`\text{softmax}(x)` is defined as:
  867. .. math::
  868. \text{softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  869. It is applied to all elements along axis, and rescales elements so that
  870. they stay in the range `[0, 1]` and sum to 1.
  871. See :class:`~.module.Softmax` for more details.
  872. Examples:
  873. .. testcode::
  874. import numpy as np
  875. from megengine import tensor
  876. import megengine.functional as F
  877. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  878. out = F.softmax(x)
  879. print(out.numpy().round(decimals=4))
  880. Outputs:
  881. .. testoutput::
  882. [[0.0117 0.0317 0.0861 0.2341 0.6364]
  883. [0.0117 0.0317 0.0861 0.2341 0.6364]]
  884. """
  885. if axis is None:
  886. axis = _get_softmax_axis(len(inp.shape))
  887. offset = inp.max(axis=axis, keepdims=True).detach()
  888. cached = exp(inp - offset)
  889. down = sum(cached, axis=axis, keepdims=True)
  890. return cached / down
  891. def layer_norm(
  892. inp: Tensor,
  893. normalized_shape: tuple,
  894. affine: bool,
  895. weight: Optional[Tensor] = None,
  896. bias: Optional[Tensor] = None,
  897. eps: float = 1e-5,
  898. ):
  899. r"""Applies layer normalization to the input. Support tensor of any shape as input.
  900. Reference: https://arxiv.org/pdf/1803.08494.pdf.
  901. Args:
  902. inp: input tensor.
  903. normalized_shape: the shape that you want to be normalizated
  904. affine: whether to use weight and bias
  905. weight: must not be None when the affine is true
  906. bias: must not be None when the affine is true
  907. eps: a value added to the denominator for numerical stability. Default: 1e-5
  908. """
  909. if amp._enabled:
  910. inp, weight, bias = cast_tensors(inp, weight, bias, promote=True)
  911. if isinstance(normalized_shape, int):
  912. normalized_shape = [normalized_shape]
  913. normalized_dim = len(normalized_shape)
  914. assert normalized_dim > 0
  915. normalized_size = 1
  916. for i in range(normalized_dim):
  917. normalized_size = normalized_size * normalized_shape[i]
  918. op = builtin.LayerNorm(
  919. affine=affine,
  920. eps=eps,
  921. normalized_dim=normalized_dim,
  922. normalized_size=normalized_size,
  923. )
  924. if affine:
  925. assert weight is not None and bias is not None
  926. return apply(op, inp, weight, bias)[0]
  927. else:
  928. # assert weight is None and bias is None
  929. return apply(op, inp)[0]
  930. def batch_norm(
  931. inp: Tensor,
  932. running_mean: Tensor = None,
  933. running_var: Tensor = None,
  934. weight: Optional[Tensor] = None,
  935. bias: Optional[Tensor] = None,
  936. *,
  937. training: bool = False,
  938. momentum: float = 0.9,
  939. eps: float = 1e-5,
  940. inplace: bool = True,
  941. compute_mode="default",
  942. param_dim="dim_1c11"
  943. ):
  944. r"""Applies batch normalization to the input.
  945. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  946. Args:
  947. inp: input tensor.
  948. running_mean: tensor to store running mean.
  949. running_var: tensor to store running variance.
  950. weight: scaling tensor in the learnable affine parameters.
  951. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  952. bias: bias tensor in the learnable affine parameters.
  953. See :math:`\beta` in :class:`~.BatchNorm2d`.
  954. training: a boolean value to indicate whether batch norm is performed
  955. in training mode. Default: False
  956. momentum: value used for the ``running_mean`` and ``running_var``
  957. computation. Default: 0.9
  958. eps: a value added to the denominator for numerical stability. Default: 1e-5
  959. inplace: whether to update ``running_mean`` and ``running_var``
  960. inplace or return new tensors. Default: True
  961. """
  962. if inp.ndim != 4:
  963. raise NotImplementedError("batch_norm for ndim != 4")
  964. if param_dim == "dim_1c11":
  965. C = inp.shape[1]
  966. pshape = (1, C, 1, 1)
  967. elif param_dim == "dim_111c":
  968. C = inp.shape[3]
  969. pshape = (1, 1, 1, C)
  970. else:
  971. raise ValueError("Invalid param_dim {}".format(param_dim))
  972. def make_full_if_none(x, value):
  973. if x is None:
  974. (x,) = Const(value, dtype=inp.dtype, device=inp.device)()
  975. shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
  976. (result,) = apply(builtin.Broadcast(), x, shape)
  977. return result
  978. elif x.ndim == 1:
  979. shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
  980. (result,) = apply(builtin.Reshape(), x, shape)
  981. return result
  982. return x
  983. has_mean = running_mean is not None
  984. has_var = running_var is not None
  985. if not training:
  986. assert has_mean, "running_mean must be provided in inference mode"
  987. assert has_var, "running_var must be provided in inference mode"
  988. if has_mean and running_mean.ndim != 4:
  989. raise ValueError
  990. if has_var and running_var.ndim != 4:
  991. raise ValueError
  992. if amp._enabled:
  993. inp = inp.astype("float16")
  994. weight, bias, running_mean, running_var = cast_tensors(
  995. weight, bias, running_mean, running_var, promote=True
  996. )
  997. weight = make_full_if_none(weight, 1)
  998. bias = make_full_if_none(bias, 0)
  999. if not training:
  1000. op = builtin.BatchNorm(
  1001. fwd_mode=BatchNorm.FwdMode.INFERENCE, epsilon=eps, param_dim=param_dim
  1002. )
  1003. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  1004. return ret
  1005. else:
  1006. op = builtin.BatchNorm(
  1007. avg_factor=1 - momentum, epsilon=eps, param_dim=param_dim
  1008. )
  1009. if has_mean or has_var:
  1010. running_mean = make_full_if_none(running_mean, 0)
  1011. running_var = make_full_if_none(running_var, 1)
  1012. new_mean, new_var, *_, inp = apply(
  1013. op, inp, weight, bias, running_mean, running_var
  1014. )
  1015. if not has_mean:
  1016. new_mean = None
  1017. if not has_var:
  1018. new_var = None
  1019. if inplace:
  1020. if has_mean:
  1021. running_mean[...] = new_mean
  1022. if has_var:
  1023. running_var[...] = new_var
  1024. return inp
  1025. else:
  1026. return inp, new_mean, new_var
  1027. else:
  1028. inp = apply(op, inp, weight, bias)[-1]
  1029. return inp
  1030. @lru_cache(maxsize=None)
  1031. def _get_sync_bn_ops(device, dtype, eps_mode, ndim, channels):
  1032. # fmt: off
  1033. @subgraph("SyncBnStage0", dtype, device, 1)
  1034. def syncbn_stage0(inputs, f, c):
  1035. input = inputs[0]
  1036. reduce_shape = c((1, channels) + (1,) * (ndim - 2), dtype="int32", device=device)
  1037. input_shape = f(GetVarShape(), input)
  1038. input_elems = f(Reduce(mode="product", axis=0), input_shape)
  1039. reduce_elems = f(Reduce(mode="product", axis=0), reduce_shape)
  1040. reduce_size = f("//", input_elems, reduce_elems)
  1041. channel_x1s = f(Reduce(mode="sum"), input, reduce_shape)
  1042. channel_x2s = f(Reduce(mode="sum_sqr"), input, reduce_shape)
  1043. reduce_size_f = f(TypeCvt(dtype=dtype), reduce_size)
  1044. return (reduce_shape, reduce_size_f, channel_x1s, channel_x2s), (False, False, True, True)
  1045. @subgraph("SyncBnStage1", dtype, device, 7)
  1046. def syncbn_stage1(inputs, f, c):
  1047. input, reduce_size, channel_x1s, channel_x2s, eps = inputs[0:5]
  1048. weight, bias = inputs[5:7]
  1049. channel_mean = f("/", channel_x1s, reduce_size)
  1050. channel_var =\
  1051. f("+", f("/", f("**", channel_x1s, c(2)),
  1052. f("-", f("*", reduce_size, reduce_size))),
  1053. f("/", channel_x2s, reduce_size))
  1054. invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
  1055. inv_var_wt = f("*", invsqrt_channel_var, weight)
  1056. neg_channel_mean = f("-", channel_mean)
  1057. outvar =\
  1058. f("fma3", input, inv_var_wt,
  1059. f("+", f("*", neg_channel_mean, inv_var_wt),
  1060. bias))
  1061. return (outvar, channel_mean, channel_var, inv_var_wt), (True, False, False, False)
  1062. @subgraph("SyncBnStage1Inference", dtype, device, 6)
  1063. def syncbn_stage1_inference(inputs, f, c):
  1064. input, channel_mean, channel_var, eps = inputs[0:4]
  1065. weight, bias = inputs[4:6]
  1066. invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
  1067. inv_var_wt = f("*", invsqrt_channel_var, weight)
  1068. neg_channel_mean = f("-", channel_mean)
  1069. outvar =\
  1070. f("+", f("*", input, inv_var_wt),
  1071. f("+", f("*", neg_channel_mean, inv_var_wt),
  1072. bias))
  1073. return (outvar,), (True,)
  1074. @subgraph("SyncBnStage2", dtype, device, 7)
  1075. def syncbn_stage2(inputs, f, c):
  1076. running_mean, running_var, momentum = inputs[0:3]
  1077. reduce_size, channel_x1s, channel_x2s, channel_mean = inputs[3:7]
  1078. c1_minus_momentum = f("-", c(1), momentum)
  1079. reduce_size_minus_c1 = f("-", reduce_size, c(1))
  1080. running_mean = f("fma4",
  1081. running_mean, momentum,
  1082. c1_minus_momentum, channel_mean,
  1083. )
  1084. channel_variance_unbiased =\
  1085. f("+", f("/", f("**", channel_x1s, c(2)),
  1086. f("*", f("-", reduce_size),
  1087. reduce_size_minus_c1)),
  1088. f("/", channel_x2s,
  1089. reduce_size_minus_c1))
  1090. running_var = f("fma4",
  1091. running_var, momentum,
  1092. c1_minus_momentum, channel_variance_unbiased
  1093. )
  1094. return (running_mean, running_var), (True, True)
  1095. @subgraph("SyncBnConcatStats", dtype, device, 3)
  1096. def syncbn_concat_stats(inputs, f, c):
  1097. reduce_size, channel_x1s, channel_x2s = inputs[0:3]
  1098. reduce_size = f(builtin.Broadcast(), reduce_size, c([1]*ndim, dtype="int32"))
  1099. stats = f(builtin.Concat(axis=1, comp_node=device), reduce_size, channel_x1s, channel_x2s)
  1100. return (stats,), (True,)
  1101. @subgraph("SyncBnSplitStats", dtype, device, 1)
  1102. def syncbn_split_stats(inputs, f, c):
  1103. stats = inputs[0]
  1104. c_1 = c(1, dtype="int32")
  1105. channel_x1s_end = c(channels+1, dtype="int32")
  1106. def _subtensor(src, axis, begin, end):
  1107. items = (axis, (begin is not None), (end is not None), False, False),
  1108. args = ()
  1109. if begin is not None:
  1110. args += begin,
  1111. if end is not None:
  1112. args += end,
  1113. return f(builtin.Subtensor(items=items), src, *args)
  1114. reduce_size = _subtensor(stats, 1, None, c_1)
  1115. channel_x1s = _subtensor(stats, 1, c_1, channel_x1s_end)
  1116. channel_x2s = _subtensor(stats, 1, channel_x1s_end, None)
  1117. reduce_size = f(builtin.Reshape(), reduce_size, c_1)
  1118. return (reduce_size, channel_x1s, channel_x2s), (False, True, True)
  1119. # fmt: on
  1120. return (
  1121. syncbn_stage0,
  1122. syncbn_stage1,
  1123. syncbn_stage1_inference,
  1124. syncbn_stage2,
  1125. syncbn_concat_stats,
  1126. syncbn_split_stats,
  1127. )
  1128. def sync_batch_norm(
  1129. inp: Tensor,
  1130. running_mean: Tensor,
  1131. running_var: Tensor,
  1132. weight: Optional[Tensor] = None,
  1133. bias: Optional[Tensor] = None,
  1134. training: bool = False,
  1135. momentum: Union[float, Tensor] = 0.9,
  1136. eps: float = 1e-5,
  1137. eps_mode="additive",
  1138. group=WORLD,
  1139. ) -> Tensor:
  1140. r"""Applies synchronized batch normalization to the input.
  1141. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  1142. Args:
  1143. inp: input tensor.
  1144. running_mean: tensor to store running mean.
  1145. running_var: tensor to store running variance.
  1146. weight: scaling tensor in the learnable affine parameters.
  1147. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  1148. bias: bias tensor in the learnable affine parameters.
  1149. See :math:`\beta` in :class:`~.BatchNorm2d`.
  1150. training: a boolean value to indicate whether batch norm is performed
  1151. in traning mode. Default: False
  1152. momentum: value used for the ``running_mean`` and ``running_var``
  1153. computation. Default: 0.9
  1154. eps: a value added to the denominator for numerical stability.
  1155. Default: 1e-5
  1156. eps_mode: mode of calculation for eps, "max" or "additive".
  1157. Default: "additive"
  1158. group: communication group, caculate mean and variance between this group.
  1159. Default: :obj:`~megengine.distributed.WORLD`
  1160. """
  1161. _eps_mode = eps_mode.lower()
  1162. assert _eps_mode in {"max", "additive"}, "unknown eps_mode: {}".format(eps_mode)
  1163. if _eps_mode == "additive" and not (is_distributed() and training):
  1164. return batch_norm(
  1165. inp,
  1166. running_mean,
  1167. running_var,
  1168. weight,
  1169. bias,
  1170. training=training,
  1171. momentum=momentum,
  1172. eps=eps,
  1173. )
  1174. _channels = make_shape_tuple(inp.shape)[1]
  1175. _ndim = inp.ndim
  1176. _device = inp.device
  1177. _dtype = inp.dtype
  1178. if _ndim != 4:
  1179. raise NotImplementedError("sync_batch_norm for ndim != 4")
  1180. def _make_full_if_none(x, value):
  1181. if x is None:
  1182. (x,) = Const(value, dtype=inp.dtype, device=_device)()
  1183. (result,) = apply(builtin.Broadcast(), x, reduce_shape)
  1184. return result
  1185. elif x.ndim == 1:
  1186. (result,) = apply(builtin.Reshape(), x, reduce_shape)
  1187. return result
  1188. return x
  1189. (
  1190. syncbn_stage0,
  1191. syncbn_stage1,
  1192. syncbn_stage1_inference,
  1193. syncbn_stage2,
  1194. syncbn_concat_stats,
  1195. syncbn_split_stats,
  1196. ) = _get_sync_bn_ops(_device, _dtype, eps_mode, _ndim, _channels)
  1197. reduce_shape, reduce_size, channel_x1s, channel_x2s = apply(syncbn_stage0(), inp)
  1198. eps = convert_single_value(eps, dtype=inp.dtype, device=inp.device)
  1199. weight = _make_full_if_none(weight, 1)
  1200. bias = _make_full_if_none(bias, 0)
  1201. if training:
  1202. if is_distributed():
  1203. # reduce all nodes' data to calculate mean and variance
  1204. (stat,) = apply(
  1205. syncbn_concat_stats(), reduce_size, channel_x1s, channel_x2s
  1206. )
  1207. stat = all_reduce_sum(stat, group)
  1208. reduce_size, channel_x1s, channel_x2s = apply(syncbn_split_stats(), stat)
  1209. outvar, channel_mean, *_ = apply(
  1210. syncbn_stage1(),
  1211. inp,
  1212. reduce_size,
  1213. channel_x1s,
  1214. channel_x2s,
  1215. eps,
  1216. weight,
  1217. bias,
  1218. )
  1219. else:
  1220. assert running_var is not None and running_mean is not None
  1221. channel_mean = running_mean
  1222. channel_var = running_var
  1223. outvar, *_ = apply(
  1224. syncbn_stage1_inference(), inp, channel_mean, channel_var, eps, weight, bias
  1225. )
  1226. # outvar = output * weight + bias
  1227. # where output = inp * invsqrt_channel_variance + (
  1228. # -channel_mean * invsqrt_channel_variance
  1229. # )
  1230. # Manually expand output for gopt
  1231. if training and running_var is not None and running_mean is not None:
  1232. momentum = convert_single_value(momentum, dtype=inp.dtype, device=inp.device)
  1233. running_mean[...], running_var[...] = apply(
  1234. syncbn_stage2(),
  1235. running_mean,
  1236. running_var,
  1237. momentum,
  1238. reduce_size,
  1239. channel_x1s,
  1240. channel_x2s,
  1241. channel_mean,
  1242. )
  1243. return outvar
  1244. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1245. r"""Returns a new tensor where each of the elements are randomly set to zero
  1246. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1247. Args:
  1248. inp: input tensor.
  1249. drop_prob: probability to drop (set to zero) a single element.
  1250. training: the default behavior of ``dropout`` during training is to rescale the output,
  1251. then it can be replaced by an :class:`~.module.identify.Identity` during inference. Default: True
  1252. Returns:
  1253. the ouput tensor
  1254. Examples:
  1255. .. testcode::
  1256. import numpy as np
  1257. from megengine import tensor
  1258. import megengine.functional as F
  1259. # test training mode
  1260. data = tensor(np.ones(10000000, dtype=np.float32))
  1261. out = F.nn.dropout(data, 1.0 / 3.0, training=True)
  1262. assert not out.numpy().all()
  1263. # test eval mode
  1264. out = F.nn.dropout(data, 1.0 / 3.0, training=False)
  1265. assert out.numpy().all()
  1266. Outputs:
  1267. .. testoutput::
  1268. :options: +SKIP
  1269. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1270. """
  1271. assert 0 <= drop_prob < 1
  1272. if not training or drop_prob == 0:
  1273. return inp
  1274. # model in training mode, e.g. model.train()
  1275. op = Dropout(drop_prob=drop_prob, seed=_get_global_rng_seed(), handle=0)
  1276. outputs = apply(op, inp)
  1277. return outputs[0]
  1278. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  1279. r"""Performs one-hot encoding for the input tensor.
  1280. Args:
  1281. inp: input tensor.
  1282. num_classes: number of classes denotes the last dimension of the output tensor.
  1283. Examples:
  1284. .. testcode::
  1285. import numpy as np
  1286. from megengine import tensor
  1287. import megengine.functional as F
  1288. x = tensor(np.arange(1, 4, dtype=np.int32))
  1289. out = F.one_hot(x, num_classes=4)
  1290. print(out.numpy())
  1291. Outputs:
  1292. .. testoutput::
  1293. [[0 1 0 0]
  1294. [0 0 1 0]
  1295. [0 0 0 1]]
  1296. """
  1297. zeros_tensor = zeros(
  1298. list(inp.shape) + [num_classes], dtype=inp.dtype, device=inp.device
  1299. )
  1300. ones_tensor = ones(list(inp.shape) + [1], dtype=inp.dtype, device=inp.device)
  1301. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  1302. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  1303. return result
  1304. def embedding(
  1305. inp: Tensor,
  1306. weight: Tensor,
  1307. padding_idx: Optional[int] = None,
  1308. max_norm: Optional[float] = None,
  1309. norm_type: Optional[float] = None,
  1310. ):
  1311. r"""Applies lookup table for embedding.
  1312. Args:
  1313. inp: tensor with indices.
  1314. weight: learnable weights which embeds from.
  1315. padding_idx: should be set to None, not supported now.
  1316. max_norm: should be set to None, not supported now.
  1317. norm_type: should be set to None, not supported now.
  1318. Refer to :class:`~.module.Embedding` for more information.
  1319. """
  1320. if padding_idx is not None:
  1321. raise ValueError("Not support padding_idx Now!")
  1322. if max_norm is not None or norm_type is not None:
  1323. raise ValueError("Not support weight normlization Now!")
  1324. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1325. return weight[inp.reshape(-1)].reshape(dest_shp)
  1326. def indexing_one_hot(
  1327. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1328. ) -> Tensor:
  1329. r"""One-hot indexing for some axes.
  1330. Args:
  1331. src: input tensor.
  1332. index: index tensor.
  1333. axis: axis on src for which values in index index. Default: 1
  1334. keepdims: whether not to remove the axis in result. Default: False
  1335. Examples:
  1336. .. testcode::
  1337. import megengine.functional as F
  1338. from megengine import tensor
  1339. src = tensor([[1.0, 2.0]])
  1340. index = tensor([0])
  1341. val = F.indexing_one_hot(src, index)
  1342. print(val.numpy())
  1343. Outputs:
  1344. .. testoutput::
  1345. [1.]
  1346. """
  1347. assert isinstance(src, Tensor), "src must be of Tensor type"
  1348. op = builtin.IndexingOneHot(axis=axis)
  1349. index = convert_single_value(index, dtype="int32", device=src.device)
  1350. (result,) = apply(op, src, index)
  1351. if not keepdims:
  1352. result = squeeze(result, axis)
  1353. return result
  1354. def sliding_window(
  1355. inp: Tensor,
  1356. kernel_size: Union[int, Tuple[int, int]],
  1357. padding: Union[int, Tuple[int, int]] = 0,
  1358. stride: Union[int, Tuple[int, int]] = 1,
  1359. dilation: Union[int, Tuple[int, int]] = 1,
  1360. ) -> Tensor:
  1361. r"""Extracts sliding local blocks from a batched input tensor.
  1362. Refer to :class:`~.module.sliding_window.SlidingWindow` for more information.
  1363. Args:
  1364. inp: input tensor.
  1365. kernel_size: size of the window.
  1366. padding: implicit zero padding added on both sides of input. Default: 0
  1367. stride: stride of the window. Default: 1
  1368. dilation: dilation of the window. Default: 1
  1369. """
  1370. padding_h, padding_w = _pair(padding)
  1371. stride_h, stride_w = _pair_nonzero(stride)
  1372. dilation_h, dilation_w = _pair_nonzero(dilation)
  1373. window_h, window_w = _pair_nonzero(kernel_size)
  1374. op = builtin.Images2Neibs(
  1375. pad_h=padding_h,
  1376. pad_w=padding_w,
  1377. stride_h=stride_h,
  1378. stride_w=stride_w,
  1379. dilate_h=dilation_h,
  1380. dilate_w=dilation_w,
  1381. window_h=window_h,
  1382. window_w=window_w,
  1383. )
  1384. (output,) = apply(op, inp)
  1385. return output
  1386. def sliding_window_transpose(
  1387. inp: Tensor,
  1388. output_size: Union[int, Tuple[int, int]],
  1389. kernel_size: Union[int, Tuple[int, int]],
  1390. padding: Union[int, Tuple[int, int]] = 0,
  1391. stride: Union[int, Tuple[int, int]] = 1,
  1392. dilation: Union[int, Tuple[int, int]] = 1,
  1393. ) -> Tensor:
  1394. r"""Sum over the sliding windows on the corresponding input location.
  1395. Refer to :class:`~.module.sliding_window.SlidingWindowTranspose` for more information.
  1396. Args:
  1397. inp: input tensor.
  1398. output_size: shape of output tensor.
  1399. kernel_size: size of the window.
  1400. padding: implicit zero padding added on both sides of input. Default: 0
  1401. stride: stride of the window. Default: 1
  1402. dilation: dilation of the window. Default: 1
  1403. """
  1404. output_h, output_w = _pair_nonzero(output_size)
  1405. padding_h, padding_w = _pair(padding)
  1406. stride_h, stride_w = _pair_nonzero(stride)
  1407. dilation_h, dilation_w = _pair_nonzero(dilation)
  1408. window_h, window_w = _pair_nonzero(kernel_size)
  1409. expected_h = (
  1410. output_h + 2 * padding_h - dilation_h * (window_h - 1) - 1
  1411. ) // stride_h + 1
  1412. expected_w = (
  1413. output_w + 2 * padding_w - dilation_w * (window_w - 1) - 1
  1414. ) // stride_w + 1
  1415. assert inp.ndim == 6, "the input dimension of sliding_window_transpose should be 6"
  1416. assert (
  1417. inp.shape[2] == expected_h and inp.shape[3] == expected_w
  1418. ), "the input shape and output size do not match"
  1419. op = builtin.SlidingWindowTranspose(
  1420. out_h=output_h,
  1421. out_w=output_w,
  1422. pad_h=padding_h,
  1423. pad_w=padding_w,
  1424. stride_h=stride_h,
  1425. stride_w=stride_w,
  1426. dilate_h=dilation_h,
  1427. dilate_w=dilation_w,
  1428. window_h=window_h,
  1429. window_w=window_w,
  1430. )
  1431. (output,) = apply(op, inp)
  1432. return output
  1433. def pad(
  1434. src: Tensor,
  1435. pad_witdth: Tuple[Tuple[int, int], ...],
  1436. mode: str = "constant",
  1437. constant_value: float = 0.0,
  1438. ) -> Tensor:
  1439. """
  1440. Pad is python warpper for padding opr in megbrain, can padding in random one of the max 7 dimensions.
  1441. Supported constant, edge(replicate) and reflect mode, constatnt is the default mode.
  1442. """
  1443. p_offsets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  1444. assert mode.lower() in ["constant", "edge", "replicate", "reflect"]
  1445. if mode.lower() == "edge":
  1446. mode = "replicate"
  1447. for i in range(0, len(pad_witdth)):
  1448. p_offsets[i * 2] = pad_witdth[i][0]
  1449. p_offsets[i * 2 + 1] = pad_witdth[i][1]
  1450. op = builtin.Padding(
  1451. front_offset_dim0=p_offsets[0],
  1452. front_offset_dim1=p_offsets[2],
  1453. front_offset_dim2=p_offsets[4],
  1454. front_offset_dim3=p_offsets[6],
  1455. front_offset_dim4=p_offsets[8],
  1456. front_offset_dim5=p_offsets[10],
  1457. front_offset_dim6=p_offsets[12],
  1458. back_offset_dim0=p_offsets[1],
  1459. back_offset_dim1=p_offsets[3],
  1460. back_offset_dim2=p_offsets[5],
  1461. back_offset_dim3=p_offsets[7],
  1462. back_offset_dim4=p_offsets[9],
  1463. back_offset_dim5=p_offsets[11],
  1464. back_offset_dim6=p_offsets[13],
  1465. padding_val=constant_value,
  1466. padding_mode=mode.upper(),
  1467. )
  1468. (output,) = apply(op, src)
  1469. return output
  1470. def local_response_norm(
  1471. inp: Tensor,
  1472. kernel_size: int = 5,
  1473. k: float = 2.0,
  1474. alpha: float = 1e-4,
  1475. beta: float = 0.75,
  1476. ) -> Tensor:
  1477. r"""
  1478. Apply local response normalization to the input tensor.
  1479. Args:
  1480. kernel_size: the size of the kernel to apply LRN on.
  1481. k: hyperparameter k. The default vaule is 2.0.
  1482. alpha: hyperparameter alpha. The default value is 1e-4.
  1483. beta: hyperparameter beta. The default value is 0.75.
  1484. Example:
  1485. .. testcode::
  1486. from megengine import tensor
  1487. import megengine.functional as f
  1488. import numpy as np
  1489. inp = tensor(np.arange(25, dtype=np.float32).reshape(1,1,5,5))
  1490. GT = np.array([[[[ 0., 0.999925, 1.9994003, 2.9979765, 3.9952066],
  1491. [ 4.9906454, 5.983851, 6.974385, 7.961814, 8.945709 ],
  1492. [ 9.925651, 10.90122, 11.872011, 12.837625, 13.7976675],
  1493. [14.751757, 15.699524, 16.640602, 17.574642, 18.501305 ],
  1494. [19.420258, 20.331186, 21.233786, 22.127764, 23.012836 ]]]])
  1495. out = f.local_response_norm(inp, kernel_size=3, k=1.0, alpha=1e-4, beta=0.75)
  1496. np.testing.assert_allclose(GT, out.numpy(), rtol=1e-6, atol=1e-6)
  1497. print('pass')
  1498. Outputs:
  1499. .. testoutput::
  1500. pass
  1501. """
  1502. op = builtin.LRN(n=kernel_size, k=k, alpha=alpha, beta=beta,)
  1503. (output,) = apply(op, inp)
  1504. return output
  1505. @lru_cache(maxsize=None)
  1506. def _get_layerPixelShuffle(device, dtype, dim_order):
  1507. @subgraph("LayerPixelShuffle", dtype, device, 3)
  1508. def layerPixelShuffle(inputs, f, c):
  1509. inp, shape_0, shape_1 = inputs
  1510. inp = f(Reshape(), inp, shape_0)
  1511. inp = f(Dimshuffle(dim_order), inp)
  1512. oup = f(Reshape(), inp, shape_1)
  1513. return (oup,), (True,)
  1514. return layerPixelShuffle
  1515. def pixel_shuffle(inp: Tensor, upscale_factor: int) -> Tensor:
  1516. """
  1517. Rearranges elements in a tensor of shape (*, C x r^2, H, W) to a tensor of
  1518. shape (*, C, H x r, W x r), where r is an upscale factor, where * is zero
  1519. or more batch dimensions.
  1520. :param inp: input tensor.
  1521. :param upscale_factor: upscale factor of pixel_shuffle.
  1522. :return: output tensor.
  1523. """
  1524. assert upscale_factor > 0, "upscale_factor should larger than 0"
  1525. assert inp.ndim >= 3, "the input dimension of pixel_shuffle should be larger than 3"
  1526. assert (
  1527. inp.shape[-3] % (upscale_factor ** 2) == 0
  1528. ), "the -3 dimension should be divided by (upscale_factor ** 2)"
  1529. _device = inp.device
  1530. _dtype = inp.dtype
  1531. shape_ori = inp.shape
  1532. high_dim = shape_ori[:-3]
  1533. square = upscale_factor ** 2
  1534. n = 1
  1535. for item in high_dim:
  1536. n *= item
  1537. shape_0 = (
  1538. n,
  1539. int(shape_ori[-3] / square),
  1540. upscale_factor,
  1541. upscale_factor,
  1542. shape_ori[-2],
  1543. shape_ori[-1],
  1544. )
  1545. shape_1 = (
  1546. *high_dim,
  1547. shape_ori[-3] / square,
  1548. shape_ori[-2] * upscale_factor,
  1549. shape_ori[-1] * upscale_factor,
  1550. )
  1551. dim_order = (0, 1, 4, 2, 5, 3)
  1552. layerPixelShuffle = _get_layerPixelShuffle(_device, _dtype, dim_order)
  1553. shape_0 = convert_single_value(shape_0, dtype=inp.dtype, device=inp.device)
  1554. shape_1 = convert_single_value(shape_1, dtype=inp.dtype, device=inp.device)
  1555. outvar, *_ = apply(layerPixelShuffle(), inp, shape_0, shape_1)
  1556. return outvar
  1557. from .quantized import conv_bias_activation # isort:skip
  1558. from .loss import * # isort:skip
  1559. from .metric import * # isort:skip
  1560. from .vision import * # isort:skip