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

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