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

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

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