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

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台