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

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