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

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

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