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

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