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

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