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

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

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