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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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 typing import Optional, Sequence, Tuple, Union
  11. from ..core._imperative_rt.core2 import apply, dtype_promotion
  12. from ..core.ops import builtin
  13. from ..core.ops.builtin import BatchNorm, Elemwise
  14. from ..core.ops.special import Const
  15. from ..core.tensor import amp, megbrain_graph
  16. from ..core.tensor.array_method import _elwise_apply
  17. from ..core.tensor.utils import (
  18. astensor1d,
  19. astype,
  20. cast_tensors,
  21. convert_single_value,
  22. setscalar,
  23. )
  24. from ..device import get_default_device
  25. from ..distributed import WORLD, is_distributed
  26. from ..random import uniform
  27. from ..tensor import Tensor
  28. from ..utils.deprecation import deprecated_func
  29. from ..utils.tuple_function import _pair, _pair_nonzero, _triple, _triple_nonzero
  30. from .debug_param import get_execution_strategy
  31. from .distributed import all_reduce_sum
  32. from .elemwise import _elwise, exp, log, log1p, maximum, minimum
  33. from .math import matmul, max, sum
  34. from .tensor import broadcast_to, concat, expand_dims, ones, squeeze, zeros
  35. __all__ = [
  36. "adaptive_avg_pool2d",
  37. "adaptive_max_pool2d",
  38. "avg_pool2d",
  39. "batch_norm",
  40. "conv1d",
  41. "conv2d",
  42. "conv3d",
  43. "conv_transpose2d",
  44. "conv_transpose3d",
  45. "deformable_conv2d",
  46. "deformable_psroi_pooling",
  47. "dropout",
  48. "embedding",
  49. "gelu",
  50. "hsigmoid",
  51. "hswish",
  52. "indexing_one_hot",
  53. "leaky_relu",
  54. "linear",
  55. "local_conv2d",
  56. "logsigmoid",
  57. "logsumexp",
  58. "logsoftmax",
  59. "max_pool2d",
  60. "one_hot",
  61. "prelu",
  62. "relu",
  63. "relu6",
  64. "remap",
  65. "resize",
  66. "sigmoid",
  67. "sliding_window",
  68. "sliding_window_transpose",
  69. "silu",
  70. "softmax",
  71. "softplus",
  72. "sync_batch_norm",
  73. "warp_affine",
  74. "warp_perspective",
  75. ]
  76. def expand_hw(x):
  77. # NOTE: >1d array is accepted, as long as 1 <= size <= 2
  78. try:
  79. x = int(x)
  80. return [x, x]
  81. except (TypeError, ValueError):
  82. pass
  83. h, w = x
  84. return int(h), int(w)
  85. def linear(
  86. inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None, compute_mode="default",
  87. ) -> Tensor:
  88. """
  89. Applies a linear transformation to the input tensor.
  90. Refer to :class:`~.module.linear.Linear` for more information.
  91. :param inp: input tensor with shape `(N, in_features)`.
  92. :param weight: weight with shape `(out_features, in_features)`.
  93. :param bias: bias with shape `(out_features,)`.
  94. Default: None
  95. """
  96. ret = matmul(inp, weight, transpose_b=True, compute_mode=compute_mode)
  97. if bias is not None:
  98. if amp._enabled:
  99. bias = bias.astype("float16")
  100. ret += bias
  101. return ret
  102. def conv1d(
  103. inp: Tensor,
  104. weight: Tensor,
  105. bias: Optional[Tensor] = None,
  106. stride: int = 1,
  107. padding: int = 0,
  108. dilation: int = 1,
  109. groups: int = 1,
  110. conv_mode="cross_correlation",
  111. compute_mode="default",
  112. ) -> Tensor:
  113. """1D convolution operation.
  114. Refer to :class:`~.Conv1d` for more information.
  115. :param inp: The feature map of the convolution operation
  116. :param weight: The convolution kernel.
  117. :param bias: The bias added to the result of convolution (if given)
  118. :param stride: Stride of the 1D convolution operation. Default: 1
  119. :param padding: Size of the paddings added to the input on both sides of its
  120. spatial dimensions. Only zero-padding is supported. Default: 0
  121. :param dilation: Dilation of the 1D convolution operation. Default: 1
  122. :param groups: number of groups to divide input and output channels into,
  123. so as to perform a "grouped convolution". When ``groups`` is not 1,
  124. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  125. and the shape of weight should be ``(groups, out_channel // groups,
  126. in_channels // groups, kernel_size)``. Default: 1
  127. :type conv_mode: string or :class:`mgb.opr_param_defs.Convolution.Mode`
  128. :param conv_mode: Supports 'cross_correlation'. Default:
  129. 'cross_correlation'.
  130. :type compute_mode: string or
  131. :class:`mgb.opr_param_defs.Convolution.ComputeMode`
  132. :param compute_mode: When set to 'default', no special requirements will be
  133. placed on the precision of intermediate results. When set to 'float32',
  134. float32 would be used for accumulator and intermediate result, but only
  135. effective when input and output are of float16 dtype.
  136. """
  137. assert (
  138. conv_mode.lower() == "cross_correlation"
  139. or conv_mode.name == "CROSS_CORRELATION"
  140. )
  141. assert compute_mode.lower() == "default" or compute_mode.name == "DEFAULT"
  142. assert inp.ndim == 3, "the input dimension of conv1d should be 3"
  143. assert weight.ndim == 3, "the weight dimension of conv1d should be 3"
  144. if amp._enabled:
  145. compute_mode = "float32"
  146. inp, weight, bias = cast_tensors(inp, weight, bias)
  147. else:
  148. dtype = dtype_promotion(inp, weight)
  149. if inp.dtype != dtype:
  150. inp = inp.astype(dtype)
  151. if weight.dtype != dtype:
  152. weight = weight.astype(dtype)
  153. inp = expand_dims(inp, 3)
  154. weight = expand_dims(weight, 3)
  155. if bias is not None:
  156. assert bias.ndim == 3, "the bias dimension of conv1d should be 3"
  157. bias = expand_dims(bias, 3)
  158. stride_h = stride
  159. pad_h = padding
  160. dilate_h = dilation
  161. sparse_type = "dense" if groups == 1 else "group"
  162. op = builtin.Convolution(
  163. stride_h=stride_h,
  164. stride_w=1,
  165. pad_h=pad_h,
  166. pad_w=0,
  167. dilate_h=dilate_h,
  168. dilate_w=1,
  169. strategy=get_execution_strategy(),
  170. mode=conv_mode,
  171. compute_mode=compute_mode,
  172. sparse=sparse_type,
  173. )
  174. (output,) = apply(op, inp, weight)
  175. if bias is not None:
  176. output += bias
  177. output = squeeze(output, 3)
  178. return output
  179. def conv2d(
  180. inp: Tensor,
  181. weight: Tensor,
  182. bias: Optional[Tensor] = None,
  183. stride: Union[int, Tuple[int, int]] = 1,
  184. padding: Union[int, Tuple[int, int]] = 0,
  185. dilation: Union[int, Tuple[int, int]] = 1,
  186. groups: int = 1,
  187. conv_mode="cross_correlation",
  188. compute_mode="default",
  189. ) -> Tensor:
  190. """
  191. 2D convolution operation.
  192. Refer to :class:`~.module.Conv2d` for more information.
  193. :param inp: feature map of the convolution operation.
  194. :param weight: convolution kernel.
  195. :param bias: bias added to the result of convolution (if given).
  196. :param stride: stride of the 2D convolution operation. Default: 1
  197. :param padding: size of the paddings added to the input on both sides of its
  198. spatial dimensions. Only zero-padding is supported. Default: 0
  199. :param dilation: dilation of the 2D convolution operation. Default: 1
  200. :param groups: number of groups into which the input and output channels are divided,
  201. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  202. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  203. and the shape of weight should be ``(groups, out_channel // groups,
  204. in_channels // groups, height, width)``. Default: 1
  205. :type conv_mode: string or :class:`Convolution.Mode`
  206. :param conv_mode: supports "cross_correlation". Default:
  207. "cross_correlation"
  208. :type compute_mode: string or
  209. :class:`Convolution.ComputeMode`
  210. :param compute_mode: when set to "default", no special requirements will be
  211. placed on the precision of intermediate results. When set to "float32",
  212. "float32" would be used for accumulator and intermediate result, but only
  213. effective when input and output are of float16 dtype.
  214. :return: output tensor.
  215. """
  216. assert (
  217. conv_mode.lower() == "cross_correlation"
  218. or conv_mode.name == "CROSS_CORRELATION"
  219. )
  220. if amp._enabled:
  221. compute_mode = "float32"
  222. inp, weight, bias = cast_tensors(inp, weight, bias)
  223. else:
  224. dtype = dtype_promotion(inp, weight)
  225. if inp.dtype != dtype:
  226. inp = inp.astype(dtype)
  227. if weight.dtype != dtype:
  228. weight = weight.astype(dtype)
  229. stride_h, stride_w = expand_hw(stride)
  230. pad_h, pad_w = expand_hw(padding)
  231. dilate_h, dilate_w = expand_hw(dilation)
  232. sparse_type = "dense" if groups == 1 else "group"
  233. op = builtin.Convolution(
  234. stride_h=stride_h,
  235. stride_w=stride_w,
  236. pad_h=pad_h,
  237. pad_w=pad_w,
  238. dilate_h=dilate_h,
  239. dilate_w=dilate_w,
  240. strategy=get_execution_strategy(),
  241. mode=conv_mode,
  242. compute_mode=compute_mode,
  243. sparse=sparse_type,
  244. )
  245. (output,) = apply(op, inp, weight)
  246. if bias is not None:
  247. output += bias
  248. return output
  249. def conv3d(
  250. inp: Tensor,
  251. weight: Tensor,
  252. bias: Optional[Tensor] = None,
  253. stride: Union[int, Tuple[int, int, int]] = 1,
  254. padding: Union[int, Tuple[int, int, int]] = 0,
  255. dilation: Union[int, Tuple[int, int, int]] = 1,
  256. groups: int = 1,
  257. conv_mode: str = "cross_correlation",
  258. ) -> Tensor:
  259. """
  260. 3D convolution operation.
  261. Refer to :class:`~.Conv3d` for more information.
  262. :param inp: feature map of the convolution operation.
  263. :param weight: convolution kernel.
  264. :param bias: bias added to the result of convolution (if given).
  265. :param stride: stride of the 3D convolution operation. Default: 1
  266. :param padding: size of the paddings added to the input on both sides of its
  267. spatial dimensions. Only zero-padding is supported. Default: 0
  268. :param dilation: dilation of the 3D convolution operation. Default: 1
  269. :param groups: number of groups into which the input and output channels are divided,
  270. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  271. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  272. and the shape of weight should be ``(groups, out_channel // groups,
  273. in_channels // groups, depth, height, width)``. Default: 1
  274. :param conv_mode: supports "cross_correlation". Default:
  275. "cross_correlation"
  276. :return: output tensor.
  277. """
  278. assert conv_mode.lower() == "cross_correlation"
  279. D, H, W = 0, 1, 2
  280. pad = _triple(padding)
  281. stride = _triple_nonzero(stride)
  282. dilate = _triple_nonzero(dilation)
  283. dtype = dtype_promotion(inp, weight)
  284. if inp.dtype != dtype:
  285. inp = inp.astype(dtype)
  286. if weight.dtype != dtype:
  287. weight = weight.astype(dtype)
  288. sparse_type = "dense" if groups == 1 else "group"
  289. op = builtin.Convolution3D(
  290. pad_d=pad[D],
  291. pad_h=pad[H],
  292. pad_w=pad[W],
  293. stride_d=stride[D],
  294. stride_h=stride[H],
  295. stride_w=stride[W],
  296. dilate_d=dilate[D],
  297. dilate_h=dilate[H],
  298. dilate_w=dilate[W],
  299. strategy=get_execution_strategy(),
  300. mode=conv_mode,
  301. sparse=sparse_type,
  302. )
  303. (output,) = apply(op, inp, weight)
  304. if bias is not None:
  305. output += bias
  306. return output
  307. def conv_transpose2d(
  308. inp: Tensor,
  309. weight: Tensor,
  310. bias: Optional[Tensor] = None,
  311. stride: Union[int, Tuple[int, int]] = 1,
  312. padding: Union[int, Tuple[int, int]] = 0,
  313. dilation: Union[int, Tuple[int, int]] = 1,
  314. groups: int = 1,
  315. conv_mode="cross_correlation",
  316. compute_mode="default",
  317. ) -> Tensor:
  318. """
  319. 2D transposed convolution operation.
  320. Refer to :class:`~.ConvTranspose2d` for more information.
  321. :param inp: feature map of the convolution operation.
  322. :param weight: convolution kernel.
  323. :param bias: bias added to the result of convolution (if given).
  324. :param stride: stride of the 2D convolution operation. Default: 1
  325. :param padding: size of the paddings added to the input on both sides of its
  326. spatial dimensions. Only zero-padding is supported. Default: 0
  327. :param dilation: dilation of the 2D convolution operation. Default: 1
  328. :param groups: number of groups into which the input and output channels are divided,
  329. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  330. ``in_channels`` and ``out_channels`` must be divisible by groups,
  331. and the shape of weight should be ``(groups, in_channels // groups,
  332. out_channels // groups, height, width)``. Default: 1
  333. :type conv_mode: string or :class:`Convolution.Mode`
  334. :param conv_mode: supports "cross_correlation". Default:
  335. "cross_correlation"
  336. :type compute_mode: string or
  337. :class:`Convolution.ComputeMode`
  338. :param 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. :return: output tensor.
  343. """
  344. assert (
  345. conv_mode.lower() == "cross_correlation"
  346. or conv_mode.name == "CROSS_CORRELATION"
  347. )
  348. if amp._enabled:
  349. compute_mode = "float32"
  350. inp, weight, bias = cast_tensors(inp, weight, bias)
  351. else:
  352. dtype = dtype_promotion(inp, weight)
  353. if inp.dtype != dtype:
  354. inp = inp.astype(dtype)
  355. if weight.dtype != dtype:
  356. weight = weight.astype(dtype)
  357. if groups != 1:
  358. raise NotImplementedError("group transposed conv2d is not supported yet.")
  359. stride_h, stride_w = expand_hw(stride)
  360. pad_h, pad_w = expand_hw(padding)
  361. dilate_h, dilate_w = expand_hw(dilation)
  362. op = builtin.ConvolutionBackwardData(
  363. stride_h=stride_h,
  364. stride_w=stride_w,
  365. pad_h=pad_h,
  366. pad_w=pad_w,
  367. dilate_h=dilate_h,
  368. dilate_w=dilate_w,
  369. strategy=get_execution_strategy(),
  370. compute_mode=compute_mode,
  371. )
  372. (output,) = apply(op, weight, inp)
  373. if bias is not None:
  374. output += bias
  375. return output
  376. def deformable_conv2d(
  377. inp: Tensor,
  378. weight: Tensor,
  379. offset: Tensor,
  380. mask: Tensor,
  381. bias: Optional[Tensor] = None,
  382. stride: Union[int, Tuple[int, int]] = 1,
  383. padding: Union[int, Tuple[int, int]] = 0,
  384. dilation: Union[int, Tuple[int, int]] = 1,
  385. groups: int = 1,
  386. conv_mode="cross_correlation",
  387. compute_mode="default",
  388. ) -> Tensor:
  389. """
  390. Deformable Convolution.
  391. :param inp: input feature map.
  392. :param weight: convolution kernel.
  393. :param offset: input offset to kernel, channel of this tensor should match the deformable settings.
  394. :param mask: input mask to kernel, channel of this tensor should match the deformable settings.
  395. :param bias: bias added to the result of convolution (if given).
  396. :param stride: stride of the 2D convolution operation. Default: 1
  397. :param padding: size of the paddings added to the input on both sides of its
  398. spatial dimensions. Only zero-padding is supported. Default: 0
  399. :param dilation: dilation of the 2D convolution operation. Default: 1
  400. :param groups: number of groups into which the input and output channels are divided,
  401. so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  402. ``in_channels`` and ``out_channels`` must be divisible by groups,
  403. and the shape of weight should be ``(groups, out_channel // groups,
  404. in_channels // groups, height, width)``. Default: 1
  405. :type conv_mode: string or :class:`Convolution.Mode`
  406. :param conv_mode: supports "cross_correlation". Default:
  407. "cross_correlation"
  408. :type compute_mode: string or
  409. :class:`Convolution.ComputeMode`
  410. :param compute_mode: when set to "default", no special requirements will be
  411. placed on the precision of intermediate results. When set to "float32",
  412. "float32" would be used for accumulator and intermediate result, but only
  413. effective when input and output are of float16 dtype.
  414. :return: output tensor.
  415. """
  416. assert (
  417. conv_mode.lower() == "cross_correlation"
  418. or conv_mode.name == "CROSS_CORRELATION"
  419. )
  420. if amp._enabled:
  421. compute_mode = "float32"
  422. inp, weight, offset, mask, bias = cast_tensors(inp, weight, offset, mask, bias)
  423. else:
  424. offset = offset.astype("float32")
  425. mask = mask.astype("float32")
  426. stride_h, stride_w = expand_hw(stride)
  427. pad_h, pad_w = expand_hw(padding)
  428. dilate_h, dilate_w = expand_hw(dilation)
  429. sparse_type = "dense" if groups == 1 else "group"
  430. op = builtin.DeformableConv(
  431. stride_h=stride_h,
  432. stride_w=stride_w,
  433. pad_h=pad_h,
  434. pad_w=pad_w,
  435. dilate_h=dilate_h,
  436. dilate_w=dilate_w,
  437. strategy=get_execution_strategy(),
  438. mode=conv_mode,
  439. compute_mode=compute_mode,
  440. sparse=sparse_type,
  441. )
  442. (output,) = apply(op, inp, weight, offset, mask)
  443. if bias is not None:
  444. output += bias
  445. return output
  446. def local_conv2d(
  447. inp: Tensor,
  448. weight: Tensor,
  449. bias: Optional[Tensor] = None,
  450. stride: Union[int, Tuple[int, int]] = 1,
  451. padding: Union[int, Tuple[int, int]] = 0,
  452. dilation: Union[int, Tuple[int, int]] = 1,
  453. conv_mode="cross_correlation",
  454. ):
  455. """Applies spatial 2D convolution over an groupped channeled image with untied kernels."""
  456. assert (
  457. conv_mode.lower() == "cross_correlation"
  458. or conv_mode.name == "CROSS_CORRELATION"
  459. )
  460. stride_h, stride_w = expand_hw(stride)
  461. pad_h, pad_w = expand_hw(padding)
  462. dilate_h, dilate_w = expand_hw(dilation)
  463. dtype = dtype_promotion(inp, weight)
  464. if inp.dtype != dtype:
  465. inp = inp.astype(dtype)
  466. if weight.dtype != dtype:
  467. weight = weight.astype(dtype)
  468. op = builtin.GroupLocal(
  469. stride_h=stride_h,
  470. stride_w=stride_w,
  471. pad_h=pad_h,
  472. pad_w=pad_w,
  473. dilate_h=dilate_h,
  474. dilate_w=dilate_w,
  475. mode=conv_mode,
  476. sparse="dense",
  477. )
  478. (output,) = apply(op, inp, weight)
  479. if bias is not None:
  480. output += bias
  481. return output
  482. def conv_transpose3d(
  483. inp: Tensor,
  484. weight: Tensor,
  485. bias: Optional[Tensor] = None,
  486. stride: Union[int, Tuple[int, int, int]] = 1,
  487. padding: Union[int, Tuple[int, int, int]] = 0,
  488. dilation: Union[int, Tuple[int, int, int]] = 1,
  489. ) -> Tensor:
  490. """
  491. 3D transposed convolution operation. Only support the case that groups = 1
  492. and conv_mode = "cross_correlation".
  493. Refer to :class:`~.ConvTranspose3d` for more information.
  494. :param inp: feature map of the convolution operation.
  495. :param weight: convolution kernel.
  496. weight usually has shape ``(in_channels, out_channels, depth, height, width)``.
  497. :param bias: bias added to the result of convolution (if given).
  498. :param stride: stride of the 3D convolution operation. Default: 1
  499. :param padding: size of the paddings added to the input on all sides of its
  500. spatial dimensions. Only zero-padding is supported. Default: 0
  501. :param dilation: dilation of the 3D convolution operation. Default: 1
  502. :return: output tensor.
  503. """
  504. D, H, W = 0, 1, 2
  505. pad = _triple(padding)
  506. stride = _triple_nonzero(stride)
  507. dilate = _triple_nonzero(dilation)
  508. dtype = dtype_promotion(inp, weight)
  509. if inp.dtype != dtype:
  510. inp = inp.astype(dtype)
  511. if weight.dtype != dtype:
  512. weight = weight.astype(dtype)
  513. op = builtin.Convolution3DBackwardData(
  514. pad_d=pad[D],
  515. pad_h=pad[H],
  516. pad_w=pad[W],
  517. stride_d=stride[D],
  518. stride_h=stride[H],
  519. stride_w=stride[W],
  520. dilate_d=dilate[D],
  521. dilate_h=dilate[H],
  522. dilate_w=dilate[W],
  523. strategy=get_execution_strategy(),
  524. )
  525. (output,) = apply(op, weight, inp)
  526. if bias is not None:
  527. output += bias
  528. return output
  529. def max_pool2d(
  530. inp: Tensor,
  531. kernel_size: Union[int, Tuple[int, int]],
  532. stride: Optional[Union[int, Tuple[int, int]]] = None,
  533. padding: Union[int, Tuple[int, int]] = 0,
  534. ) -> Tensor:
  535. """
  536. Applies a 2D max pooling over an input tensor.
  537. Refer to :class:`~.MaxPool2d` for more information.
  538. :param inp: input tensor.
  539. :param kernel_size: size of the window.
  540. :param stride: stride of the window. If not provided, its value is set to kernel_size.
  541. Default: None
  542. :param padding: implicit zero padding added on both sides. Default: 0
  543. :return: output tensor.
  544. """
  545. if stride is None:
  546. stride = kernel_size
  547. window_h, window_w = _pair_nonzero(kernel_size)
  548. stride_h, stride_w = _pair_nonzero(stride)
  549. padding_h, padding_w = _pair(padding)
  550. op = builtin.Pooling(
  551. window_h=window_h,
  552. window_w=window_w,
  553. stride_h=stride_h,
  554. stride_w=stride_w,
  555. pad_h=padding_h,
  556. pad_w=padding_w,
  557. mode="max",
  558. )
  559. (output,) = apply(op, inp)
  560. return output
  561. def avg_pool2d(
  562. inp: Tensor,
  563. kernel_size: Union[int, Tuple[int, int]],
  564. stride: Optional[Union[int, Tuple[int, int]]] = None,
  565. padding: Union[int, Tuple[int, int]] = 0,
  566. mode: str = "average_count_exclude_padding",
  567. ) -> Tensor:
  568. """
  569. Applies 2D average pooling over an input tensor.
  570. Refer to :class:`~.AvgPool2d` for more information.
  571. :param inp: input tensor.
  572. :param kernel_size: size of the window.
  573. :param stride: stride of the window. If not provided, its value is set to ``kernel_size``.
  574. Default: None
  575. :param padding: implicit zero padding added on both sides. Default: 0
  576. :param mode: whether to count padding values, set to "average" will do counting.
  577. Default: "average_count_exclude_padding"
  578. :return: output tensor.
  579. """
  580. if stride is None:
  581. stride = kernel_size
  582. window_h, window_w = _pair_nonzero(kernel_size)
  583. stride_h, stride_w = _pair_nonzero(stride)
  584. padding_h, padding_w = _pair(padding)
  585. op = builtin.Pooling(
  586. window_h=window_h,
  587. window_w=window_w,
  588. stride_h=stride_h,
  589. stride_w=stride_w,
  590. pad_h=padding_h,
  591. pad_w=padding_w,
  592. mode=mode,
  593. )
  594. (output,) = apply(op, inp)
  595. return output
  596. def adaptive_max_pool2d(
  597. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  598. ) -> Tensor:
  599. """
  600. Applies a 2D max adaptive pooling over an input.
  601. Refer to :class:`~.MaxAdaptivePool2d` for more information.
  602. :param inp: input tensor.
  603. :param oshp: `(OH, OW)` size of the output shape.
  604. :return: output tensor.
  605. """
  606. if isinstance(oshp, int):
  607. oshp = (oshp, oshp)
  608. op = builtin.AdaptivePooling(mode="max", format="NCHW",)
  609. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  610. (output,) = apply(op, inp, oshp)
  611. return output
  612. def adaptive_avg_pool2d(
  613. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  614. ) -> Tensor:
  615. """
  616. Applies a 2D average adaptive pooling over an input.
  617. Refer to :class:`~.AvgAdaptivePool2d` for more information.
  618. :param inp: input tensor.
  619. :param oshp: `(OH, OW)` size of the output shape.
  620. :return: output tensor.
  621. """
  622. if isinstance(oshp, int):
  623. oshp = (oshp, oshp)
  624. op = builtin.AdaptivePooling(mode="average", format="NCHW",)
  625. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  626. (output,) = apply(op, inp, oshp)
  627. return output
  628. def deformable_psroi_pooling(
  629. inp: Tensor,
  630. rois: Tensor,
  631. trans: Tensor,
  632. no_trans: bool,
  633. part_size: int,
  634. pooled_h: int,
  635. pooled_w: int,
  636. sample_per_part: int,
  637. spatial_scale: float,
  638. trans_std: float = 0.1,
  639. ):
  640. """
  641. Deformable PSROI(Position Sensitive Region of Interest) Pooling.
  642. :param inp: input feature map.
  643. :param rois: the rois for feature pooling.
  644. :param trans: input offset to psroi_pooling.
  645. :param no_trans: check the phase of DeformablePSROIPooling. False to the
  646. 1st phase, True to the 2nd phase.
  647. :param part_size: part size.
  648. :param sample_per_part: sample points of each part.
  649. :param pooled_shape: kernel shape of convolution.
  650. :param spatial_scale: the spatial_scale w.r.t input image.
  651. :param trans_std: multiplier used in 2nd phase.
  652. """
  653. op = builtin.DeformablePSROIPooling(
  654. no_trans=no_trans,
  655. part_size=part_size,
  656. pooled_h=pooled_h,
  657. pooled_w=pooled_w,
  658. sample_per_part=sample_per_part,
  659. spatial_scale=spatial_scale,
  660. trans_std=trans_std,
  661. )
  662. output, _ = apply(op, inp, rois, trans)
  663. return output
  664. def hswish(x):
  665. """
  666. Element-wise `x * relu6(x + 3) / 6`.
  667. :param x: input tensor.
  668. :return: computed tensor.
  669. Example:
  670. .. testcode::
  671. import numpy as np
  672. from megengine import tensor
  673. import megengine.functional as F
  674. x = tensor(np.arange(5).astype(np.float32))
  675. out = F.hswish(x)
  676. print(out.numpy().round(decimals=4))
  677. .. testoutput::
  678. [0. 0.6667 1.6667 3. 4. ]
  679. """
  680. return _elwise(x, mode=Elemwise.Mode.H_SWISH)
  681. def sigmoid(x):
  682. """Element-wise `1 / ( 1 + exp( -x ) )`."""
  683. return _elwise(x, mode=Elemwise.Mode.SIGMOID)
  684. def hsigmoid(x):
  685. """Element-wise `relu6(x + 3) / 6`."""
  686. return relu6(x + 3) / 6
  687. def relu(x):
  688. """Element-wise `max(x, 0)`."""
  689. return _elwise(x, mode=Elemwise.Mode.RELU)
  690. def relu6(x):
  691. """Element-wise `min(max(x, 0), 6)`."""
  692. return minimum(maximum(x, 0), 6)
  693. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  694. r"""
  695. Applies the element-wise PReLU function.
  696. Refer to :class:`~.PReLU` for more information.
  697. """
  698. return maximum(inp, 0) + weight * minimum(inp, 0)
  699. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  700. r"""
  701. Applies the element-wise leaky_relu function
  702. Refer to :class:`~.LeakyReLU` for more information.
  703. """
  704. return maximum(inp, 0) + negative_slope * minimum(inp, 0)
  705. def silu(x):
  706. r"""
  707. Applies the element-wise Sigmoid Linear Unit function, i.e. `x * sigmoid(x)`.
  708. """
  709. return _elwise(x, mode=Elemwise.Mode.SILU)
  710. def gelu(x):
  711. r"""
  712. Applies the element-wise function:
  713. .. math::
  714. \text{gelu}(x) = x\Phi(x)
  715. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  716. """
  717. return _elwise(x, mode=Elemwise.Mode.GELU)
  718. def softplus(inp: Tensor) -> Tensor:
  719. r"""
  720. Applies the element-wise function:
  721. .. math::
  722. \text{softplus}(x) = \log(1 + \exp(x))
  723. softplus is a smooth approximation to the ReLU function and can be used
  724. to constrain the output to be always positive.
  725. For numerical stability the implementation follows this transformation:
  726. .. math::
  727. \text{softplus}(x) = \log(1 + \exp(x))
  728. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  729. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  730. :param inp: input tensor.
  731. Examples:
  732. .. testcode::
  733. import numpy as np
  734. from megengine import tensor
  735. import megengine.functional as F
  736. x = tensor(np.arange(-3, 3, dtype=np.float32))
  737. y = F.softplus(x)
  738. print(y.numpy().round(decimals=4))
  739. Outputs:
  740. .. testoutput::
  741. [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
  742. """
  743. return log1p(exp(-abs(inp))) + relu(inp)
  744. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  745. r"""
  746. Applies the :math:`\log(\text{softmax}(x))` function to an n-dimensional
  747. input tensor. The :math:`\text{logsoftmax}(x)` formulation can be simplified as:
  748. .. math::
  749. \text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  750. For numerical stability the implementation follows this transformation:
  751. .. math::
  752. \text{logsoftmax}(x)
  753. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  754. = x - \log (\sum_{i}(\exp (x_{i})))
  755. = x - \text{logsumexp}(x)
  756. :param inp: input tensor.
  757. :param axis: axis along which :math:`\text{logsoftmax}(x)` will be applied.
  758. Examples:
  759. .. testcode::
  760. import numpy as np
  761. from megengine import tensor
  762. import megengine.functional as F
  763. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  764. y = F.logsoftmax(x, axis=1)
  765. print(y.numpy().round(decimals=4))
  766. Outputs:
  767. .. testoutput::
  768. [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
  769. [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
  770. """
  771. return inp - logsumexp(inp, axis, keepdims=True)
  772. def logsigmoid(inp: Tensor) -> Tensor:
  773. r"""
  774. Applies the element-wise function:
  775. .. math::
  776. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  777. = \log(1/(1 + \exp(-x)))
  778. = - \log(1 + \exp(-x))
  779. = - \text{softplus}(-x)
  780. :param inp: input tensor.
  781. Examples:
  782. .. testcode::
  783. import numpy as np
  784. from megengine import tensor
  785. import megengine.functional as F
  786. x = tensor(np.arange(-5, 5, dtype=np.float32))
  787. y = F.logsigmoid(x)
  788. print(y.numpy().round(decimals=4))
  789. Outputs:
  790. .. testoutput::
  791. [-5.0067 -4.0182 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
  792. -0.0181]
  793. """
  794. return -softplus(-inp)
  795. def logsumexp(
  796. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  797. ) -> Tensor:
  798. r"""
  799. Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  800. .. math::
  801. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  802. For numerical stability, the implementation follows this transformation:
  803. .. math::
  804. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  805. = \text{logsumexp}(x)=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  806. where
  807. .. math::
  808. b = \max(x_j)
  809. :param inp: input tensor.
  810. :param axis: axis over which the sum is taken. It could be single axis or list of axes.
  811. :param keepdims: whether to retain :attr:`axis` or not for the output tensor.
  812. Examples:
  813. .. testcode::
  814. import numpy as np
  815. from megengine import tensor
  816. import megengine.functional as F
  817. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  818. y = F.logsumexp(x, axis=1, keepdims=False)
  819. print(y.numpy().round(decimals=4))
  820. Outputs:
  821. .. testoutput::
  822. [-0.5481 4.4519]
  823. """
  824. max_value = max(inp.detach(), axis, keepdims=True)
  825. if keepdims:
  826. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  827. else:
  828. return squeeze(max_value, axis=None) + log(
  829. sum(exp(inp - max_value), axis, keepdims)
  830. )
  831. def _get_softmax_axis(ndim: int) -> int:
  832. if ndim in (0, 1, 3):
  833. return 0
  834. return 1
  835. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  836. r"""
  837. Applies a :math:`\text{softmax}(x)` function. :math:`\text{softmax}(x)` is defined as:
  838. .. math::
  839. \text{softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  840. It is applied to all elements along axis, and rescales elements so that
  841. they stay in the range `[0, 1]` and sum to 1.
  842. See :class:`~megengine.module.activation.Softmax` for more details.
  843. :param inp: input tensor.
  844. :param axis: an axis along which :math:`\text{softmax}(x)` will be applied. By default,
  845. :math:`\text{softmax}(x)` will apply along the highest ranked axis.
  846. Examples:
  847. .. testcode::
  848. import numpy as np
  849. from megengine import tensor
  850. import megengine.functional as F
  851. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  852. out = F.softmax(x)
  853. print(out.numpy().round(decimals=4))
  854. Outputs:
  855. .. testoutput::
  856. [[0.0117 0.0317 0.0861 0.2341 0.6364]
  857. [0.0117 0.0317 0.0861 0.2341 0.6364]]
  858. """
  859. if axis is None:
  860. axis = _get_softmax_axis(len(inp.shape))
  861. offset = inp.max(axis=axis, keepdims=True).detach()
  862. cached = exp(inp - offset)
  863. down = sum(cached, axis=axis, keepdims=True)
  864. return cached / down
  865. def batch_norm(
  866. inp: Tensor,
  867. running_mean: Tensor = None,
  868. running_var: Tensor = None,
  869. weight: Optional[Tensor] = None,
  870. bias: Optional[Tensor] = None,
  871. *,
  872. training: bool = False,
  873. momentum: float = 0.9,
  874. eps: float = 1e-5,
  875. inplace: bool = True,
  876. compute_mode="default"
  877. ):
  878. r"""
  879. Applies batch normalization to the input.
  880. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  881. :param inp: input tensor.
  882. :param running_mean: tensor to store running mean.
  883. :param running_var: tensor to store running variance.
  884. :param weight: scaling tensor in the learnable affine parameters.
  885. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  886. :param bias: bias tensor in the learnable affine parameters.
  887. See :math:`\beta` in :class:`~.BatchNorm2d`.
  888. :param training: a boolean value to indicate whether batch norm is performed
  889. in training mode. Default: False
  890. :param momentum: value used for the ``running_mean`` and ``running_var``
  891. computation.
  892. Default: 0.9
  893. :param eps: a value added to the denominator for numerical stability.
  894. Default: 1e-5
  895. :param inplace: whether to update ``running_mean`` and ``running_var`` inplace or return new tensors
  896. Default: True
  897. :return: output tensor.
  898. """
  899. if inp.ndim != 4:
  900. raise NotImplementedError("batch_norm for ndim != 4")
  901. C = inp.shape[1]
  902. def make_full_if_none(x, value):
  903. if x is None:
  904. (x,) = Const(value, dtype=inp.dtype, device=inp.device)()
  905. shape = astensor1d((1, C, 1, 1), inp, dtype="int32", device=inp.device)
  906. (result,) = apply(builtin.Broadcast(), x, shape)
  907. return result
  908. elif x.ndim == 1:
  909. shape = astensor1d((1, C, 1, 1), inp, dtype="int32", device=inp.device)
  910. (result,) = apply(builtin.Reshape(), x, shape)
  911. return result
  912. return x
  913. has_mean = running_mean is not None
  914. has_var = running_var is not None
  915. if not training:
  916. assert has_mean, "running_mean must be provided in inference mode"
  917. assert has_var, "running_var must be provided in inference mode"
  918. if has_mean and running_mean.ndim != 4:
  919. raise ValueError
  920. if has_var and running_var.ndim != 4:
  921. raise ValueError
  922. if amp._enabled:
  923. inp = inp.astype("float16")
  924. weight, bias, running_mean, running_var = cast_tensors(
  925. weight, bias, running_mean, running_var, promote=True
  926. )
  927. weight = make_full_if_none(weight, 1)
  928. bias = make_full_if_none(bias, 0)
  929. if not training:
  930. op = builtin.BatchNorm(
  931. fwd_mode=BatchNorm.FwdMode.INFERENCE, epsilon=eps, param_dim="dim_1c11"
  932. )
  933. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  934. return ret
  935. else:
  936. op = builtin.BatchNorm(
  937. avg_factor=1 - momentum, epsilon=eps, param_dim="dim_1c11"
  938. )
  939. if has_mean or has_var:
  940. running_mean = make_full_if_none(running_mean, 0)
  941. running_var = make_full_if_none(running_var, 1)
  942. new_mean, new_var, _, _, inp = apply(
  943. op, inp, weight, bias, running_mean, running_var
  944. )
  945. if not has_mean:
  946. new_mean = None
  947. if not has_var:
  948. new_var = None
  949. if inplace:
  950. if has_mean:
  951. running_mean[...] = new_mean
  952. if has_var:
  953. running_var[...] = new_var
  954. return inp
  955. else:
  956. return inp, new_mean, new_var
  957. else:
  958. (_, _, inp,) = apply(op, inp, weight, bias)
  959. return inp
  960. def sync_batch_norm(
  961. inp: Tensor,
  962. running_mean: Tensor,
  963. running_var: Tensor,
  964. weight: Optional[Tensor] = None,
  965. bias: Optional[Tensor] = None,
  966. training: bool = False,
  967. momentum: Union[float, Tensor] = 0.9,
  968. eps: float = 1e-5,
  969. eps_mode="additive",
  970. group=WORLD,
  971. ) -> Tensor:
  972. r"""
  973. Applies synchronized batch normalization to the input.
  974. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  975. :param inp: input tensor.
  976. :param running_mean: tensor to store running mean.
  977. :param running_var: tensor to store running variance.
  978. :param weight: scaling tensor in the learnable affine parameters.
  979. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  980. :param bias: bias tensor in the learnable affine parameters.
  981. See :math:`\beta` in :class:`~.BatchNorm2d`.
  982. :param training: a boolean value to indicate whether batch norm is performed
  983. in traning mode. Default: False
  984. :param momentum: value used for the ``running_mean`` and ``running_var``
  985. computation.
  986. Default: 0.9
  987. :param eps: a value added to the denominator for numerical stability.
  988. Default: 1e-5
  989. :param eps_mode: mode of calculation for eps, "max" or "additive".
  990. Default: "additive"
  991. :param group: communication group, caculate mean and variance between this group.
  992. Default: :obj:`~megengine.distributed.WORLD`
  993. :return: output tensor.
  994. """
  995. assert eps_mode.lower() in {"max", "additive"}, "unknown eps_mode: {}".format(
  996. eps_mode
  997. )
  998. _channels = inp.shape[1]
  999. _ndim = inp.ndim
  1000. _device = inp.device
  1001. _dtype = inp.dtype
  1002. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  1003. _reduce_axis = [0] + [i for i in range(2, _ndim)]
  1004. if training:
  1005. def _sum_on_channel(inp):
  1006. return inp.sum(axis=_reduce_axis, keepdims=True)
  1007. reduce_size = inp.shape[0]
  1008. for i in range(2, _ndim):
  1009. reduce_size = reduce_size * inp.shape[i]
  1010. channel_x1s = _sum_on_channel(inp)
  1011. channel_x2s = _sum_on_channel(inp ** 2)
  1012. if is_distributed():
  1013. # reduce all nodes' data to calculate mean and variance
  1014. reduce_size = broadcast_to(
  1015. Tensor(reduce_size).astype(dtype=_dtype), [1] * _ndim
  1016. )
  1017. stat = concat([reduce_size, channel_x1s, channel_x2s], axis=1)
  1018. stat = all_reduce_sum(stat, group)
  1019. reduce_size = stat[:, :1].reshape(1)
  1020. channel_x1s = stat[:, 1 : 1 + _channels]
  1021. channel_x2s = stat[:, 1 + _channels :]
  1022. channel_mean = channel_x1s / reduce_size
  1023. channel_variance = (
  1024. channel_x1s ** 2 / (-reduce_size * reduce_size) + channel_x2s / reduce_size
  1025. )
  1026. else:
  1027. assert running_var is not None and running_mean is not None
  1028. channel_variance = running_var.reshape(*_param_shape)
  1029. channel_mean = running_mean.reshape(*_param_shape)
  1030. invsqrt_channel_variance = (
  1031. maximum(channel_variance, eps) if eps_mode == "max" else channel_variance + eps
  1032. ) ** -0.5
  1033. if weight is not None:
  1034. weight = weight.reshape(*_param_shape)
  1035. if bias is not None:
  1036. bias = bias.reshape(*_param_shape)
  1037. # outvar = output * weight + bias
  1038. # where output = inp * invsqrt_channel_variance + (
  1039. # -channel_mean * invsqrt_channel_variance
  1040. # )
  1041. # Manually expand output for gopt
  1042. if weight is not None:
  1043. inv_var_wt = invsqrt_channel_variance * weight
  1044. neg_channel_mean = -channel_mean
  1045. if bias is not None:
  1046. outvar = inp * inv_var_wt + (neg_channel_mean * inv_var_wt + bias)
  1047. else:
  1048. outvar = inp * inv_var_wt + neg_channel_mean * inv_var_wt
  1049. else:
  1050. outvar = inp * invsqrt_channel_variance + (
  1051. -channel_mean * invsqrt_channel_variance
  1052. )
  1053. if bias is not None:
  1054. outvar = outvar + bias
  1055. if training and running_var is not None and running_mean is not None:
  1056. running_mean *= momentum
  1057. running_mean += (1 - momentum) * channel_mean
  1058. channel_variance_unbiased = channel_x1s ** 2 / (
  1059. -reduce_size * (reduce_size - 1)
  1060. ) + channel_x2s / (reduce_size - 1)
  1061. running_var *= momentum
  1062. running_var += (1 - momentum) * channel_variance_unbiased
  1063. return outvar
  1064. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1065. """
  1066. Returns a new tensor where each of the elements are randomly set to zero
  1067. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1068. :param inp: input tensor.
  1069. :param drop_prob: probability to drop (set to zero) a single element.
  1070. :param training: the default behavior of ``dropout`` during training is to rescale the output,
  1071. then it can be replaced by an :class:`~.Identity` during inference. Default: True
  1072. :return: the output tensor
  1073. Examples:
  1074. .. testcode::
  1075. import numpy as np
  1076. from megengine import tensor
  1077. import megengine.functional as F
  1078. x = tensor(np.ones(10, dtype=np.float32))
  1079. out = F.dropout(x, 1./3.)
  1080. print(out.numpy())
  1081. Outputs:
  1082. .. testoutput::
  1083. :options: +SKIP
  1084. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1085. """
  1086. assert 0 <= drop_prob < 1
  1087. rv = uniform(size=inp.shape)
  1088. mask = rv > drop_prob
  1089. inp *= mask.astype(inp.dtype)
  1090. if training:
  1091. inp *= 1 / (1 - drop_prob)
  1092. return inp
  1093. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  1094. r"""
  1095. Performs one-hot encoding for the input tensor.
  1096. :param inp: input tensor.
  1097. :param num_classes: number of classes denotes the last dimension of the output tensor.
  1098. :return: output tensor.
  1099. Examples:
  1100. .. testcode::
  1101. import numpy as np
  1102. from megengine import tensor
  1103. import megengine.functional as F
  1104. x = tensor(np.arange(1, 4, dtype=np.int32))
  1105. out = F.one_hot(x, num_classes=4)
  1106. print(out.numpy())
  1107. Outputs:
  1108. .. testoutput::
  1109. [[0 1 0 0]
  1110. [0 0 1 0]
  1111. [0 0 0 1]]
  1112. """
  1113. zeros_tensor = zeros(list(inp.shape) + [num_classes], inp.dtype, inp.device)
  1114. ones_tensor = ones(list(inp.shape) + [1], inp.dtype, inp.device)
  1115. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  1116. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  1117. return result
  1118. def embedding(
  1119. inp: Tensor,
  1120. weight: Tensor,
  1121. padding_idx: Optional[int] = None,
  1122. max_norm: Optional[float] = None,
  1123. norm_type: Optional[float] = None,
  1124. ):
  1125. """
  1126. Applies lookup table for embedding.
  1127. :param inp: tensor with indices.
  1128. :param weight: learnable weights which embeds from.
  1129. :param padding_idx: should be set to None, not supported now.
  1130. :param max_norm: should be set to None, not supported now.
  1131. :param norm_type: should be set to None, not supported now.
  1132. :return: output tensor.
  1133. Refer to :class:`~.Embedding` for more information.
  1134. """
  1135. if padding_idx is not None:
  1136. raise ValueError("Not support padding_idx Now!")
  1137. if max_norm is not None or norm_type is not None:
  1138. raise ValueError("Not support weight normlization Now!")
  1139. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1140. return weight[inp.reshape(-1)].reshape(dest_shp)
  1141. def indexing_one_hot(
  1142. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1143. ) -> Tensor:
  1144. r"""
  1145. One-hot indexing for some axes.
  1146. :param src: input tensor.
  1147. :param index: index tensor.
  1148. :param axis: axis on src for which values in index index. Default: 1
  1149. :param keepdims: whether not to remove the axis in result. Default: False
  1150. :return: output tensor.
  1151. Examples:
  1152. .. testcode::
  1153. import megengine.functional as F
  1154. from megengine import tensor
  1155. src = tensor([[1.0, 2.0]])
  1156. index = tensor([0])
  1157. val = F.indexing_one_hot(src, index)
  1158. print(val.numpy())
  1159. Outputs:
  1160. .. testoutput::
  1161. [1.]
  1162. """
  1163. assert isinstance(src, Tensor), "src must be of Tensor type"
  1164. op = builtin.IndexingOneHot(axis=axis)
  1165. index = convert_single_value(index, dtype="int32", device=src.device)
  1166. (result,) = apply(op, src, index)
  1167. if not keepdims:
  1168. result = squeeze(result, axis)
  1169. return result
  1170. def sliding_window(
  1171. inp: Tensor,
  1172. kernel_size: Union[int, Tuple[int, int]],
  1173. padding: Union[int, Tuple[int, int]] = 0,
  1174. stride: Union[int, Tuple[int, int]] = 1,
  1175. dilation: Union[int, Tuple[int, int]] = 1,
  1176. ) -> Tensor:
  1177. """
  1178. Extracts sliding local blocks from a batched input tensor.
  1179. Refer to :class:`~.SlidingWindow` for more information.
  1180. :param inp: input tensor.
  1181. :param kernel_size: size of the window.
  1182. :param padding: implicit zero padding added on both sides of input. Default: 0
  1183. :param stride: stride of the window. Default: 1
  1184. :param dilation: dilation of the window. Default: 1
  1185. :return: output tensor.
  1186. """
  1187. padding_h, padding_w = _pair(padding)
  1188. stride_h, stride_w = _pair_nonzero(stride)
  1189. dilation_h, dilation_w = _pair_nonzero(dilation)
  1190. window_h, window_w = _pair_nonzero(kernel_size)
  1191. op = builtin.Images2Neibs(
  1192. pad_h=padding_h,
  1193. pad_w=padding_w,
  1194. stride_h=stride_h,
  1195. stride_w=stride_w,
  1196. dilate_h=dilation_h,
  1197. dilate_w=dilation_w,
  1198. window_h=window_h,
  1199. window_w=window_w,
  1200. )
  1201. (output,) = apply(op, inp)
  1202. return output
  1203. def sliding_window_transpose(
  1204. inp: Tensor,
  1205. output_size: Union[int, Tuple[int, int]],
  1206. kernel_size: Union[int, Tuple[int, int]],
  1207. padding: Union[int, Tuple[int, int]] = 0,
  1208. stride: Union[int, Tuple[int, int]] = 1,
  1209. dilation: Union[int, Tuple[int, int]] = 1,
  1210. ) -> Tensor:
  1211. """
  1212. Sum over the sliding windows on the corresponding input location.
  1213. Refer to :class:`~.SlidingWindowTranspose` for more information.
  1214. :param inp: input tensor.
  1215. :param output_size: shape of output tensor.
  1216. :param kernel_size: size of the window.
  1217. :param padding: implicit zero padding added on both sides of input. Default: 0
  1218. :param stride: stride of the window. Default: 1
  1219. :param dilation: dilation of the window. Default: 1
  1220. :return: output tensor.
  1221. """
  1222. output_h, output_w = _pair_nonzero(output_size)
  1223. padding_h, padding_w = _pair(padding)
  1224. stride_h, stride_w = _pair_nonzero(stride)
  1225. dilation_h, dilation_w = _pair_nonzero(dilation)
  1226. window_h, window_w = _pair_nonzero(kernel_size)
  1227. expected_h = (
  1228. output_h + 2 * padding_h - dilation_h * (window_h - 1) - 1
  1229. ) // stride_h + 1
  1230. expected_w = (
  1231. output_w + 2 * padding_w - dilation_w * (window_w - 1) - 1
  1232. ) // stride_w + 1
  1233. assert inp.ndim == 6, "the input dimension of sliding_window_transpose should be 6"
  1234. assert (
  1235. inp.shape[2] == expected_h and inp.shape[3] == expected_w
  1236. ), "the input shape and output size do not match"
  1237. op = builtin.SlidingWindowTranspose(
  1238. out_h=output_h,
  1239. out_w=output_w,
  1240. pad_h=padding_h,
  1241. pad_w=padding_w,
  1242. stride_h=stride_h,
  1243. stride_w=stride_w,
  1244. dilate_h=dilation_h,
  1245. dilate_w=dilation_w,
  1246. window_h=window_h,
  1247. window_w=window_w,
  1248. )
  1249. (output,) = apply(op, inp)
  1250. return output
  1251. interpolate = deprecated_func("1.3", "megengine.functional.vision", "interpolate", True)
  1252. roi_pooling = deprecated_func("1.3", "megengine.functional.vision", "roi_pooling", True)
  1253. roi_align = deprecated_func("1.3", "megengine.functional.vision", "roi_align", True)
  1254. nms = deprecated_func("1.3", "megengine.functional.vision", "nms", True)
  1255. resize = deprecated_func("1.3", "megengine.functional.vision", "resize", True)
  1256. remap = deprecated_func("1.3", "megengine.functional.vision", "remap", True)
  1257. nvof = deprecated_func("1.3", "megengine.functional.vision", "nvof", True)
  1258. warp_affine = deprecated_func("1.3", "megengine.functional.vision", "warp_affine", True)
  1259. warp_perspective = deprecated_func(
  1260. "1.3", "megengine.functional.vision", "warp_perspective", True
  1261. )
  1262. from .quantized import conv_bias_activation # isort:skip
  1263. from .loss import * # isort:skip

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