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

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

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