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

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

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