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

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

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