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

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

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