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

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

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