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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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, Tuple, Union
  11. import megengine._internal as mgb
  12. from megengine._internal import CompGraph, CompNode
  13. from megengine._internal.config import add_extra_vardep
  14. from megengine._internal.opr import add_update
  15. from megengine._internal.opr_param_defs import CollectiveComm as CollParam
  16. from .. import distributed as dist
  17. from ..core import Tensor, wrap_io_tensor
  18. from ..core.graph import _use_default_if_none
  19. from ..distributed.util import get_group_id
  20. from ..jit import barrier, mark_impure
  21. from ..random import uniform
  22. from ..utils.types import _pair, _pair_nonzero
  23. from .debug_param import get_conv_execution_strategy
  24. from .elemwise import exp, log
  25. from .tensor import where
  26. from .utils import _decide_comp_node_and_comp_graph
  27. @wrap_io_tensor
  28. def linear(inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None) -> Tensor:
  29. """Applies a linear transformation to the input.
  30. Refer to :class:`~.module.linear.Linear` for more information.
  31. :param inp: the input tensor with shape `(N, in_features)`.
  32. :param weight: the weight with shape `(out_features, in_features)`.
  33. :param bias: the bias with shape `(out_features,)`.
  34. Default: ``None``
  35. """
  36. orig_shape = inp.shape
  37. inp = inp.reshape(-1, orig_shape[-1])
  38. ret = mgb.opr.matrix_mul(inp, weight, transposeB=True)
  39. ret = ret.reshape(orig_shape[:-1], weight.shape[0])
  40. if bias is not None:
  41. ret += bias.reshape(1, bias.shape[0])
  42. return ret
  43. @wrap_io_tensor
  44. def conv2d(
  45. inp: Tensor,
  46. weight: Tensor,
  47. bias: Optional[Tensor] = None,
  48. stride: Union[int, Tuple[int, int]] = 1,
  49. padding: Union[int, Tuple[int, int]] = 0,
  50. dilation: Union[int, Tuple[int, int]] = 1,
  51. groups: int = 1,
  52. conv_mode="CROSS_CORRELATION",
  53. compute_mode="DEFAULT",
  54. ) -> Tensor:
  55. """2D convolution operation.
  56. Refer to :class:`~.Conv2d` for more information.
  57. :param inp: The feature map of the convolution operation
  58. :param weight: The convolution kernel
  59. :param bias: The bias added to the result of convolution (if given)
  60. :param stride: Stride of the 2D convolution operation. Default: 1
  61. :param padding: Size of the paddings added to the input on both sides of its
  62. spatial dimensions. Only zero-padding is supported. Default: 0
  63. :param dilation: Dilation of the 2D convolution operation. Default: 1
  64. :param groups: number of groups to divide input and output channels into,
  65. so as to perform a "grouped convolution". When ``groups`` is not 1,
  66. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  67. and the shape of weight should be ``(groups, out_channel // groups,
  68. in_channels // groups, height, width)``.
  69. :type conv_mode: string or :class:`mgb.opr_param_defs.Convolution.Mode`
  70. :param conv_mode: Supports 'CROSS_CORRELATION' or 'CONVOLUTION'. Default:
  71. 'CROSS_CORRELATION'.
  72. :type compute_mode: string or
  73. :class:`mgb.opr_param_defs.Convolution.ComputeMode`
  74. :param compute_mode: When set to 'DEFAULT', no special requirements will be
  75. placed on the precision of intermediate results. When set to 'FLOAT32',
  76. Float32 would be used for accumulator and intermediate result, but only
  77. effective when input and output are of Float16 dtype.
  78. """
  79. ph, pw = _pair(padding)
  80. sh, sw = _pair_nonzero(stride)
  81. dh, dw = _pair_nonzero(dilation)
  82. Sparse = mgb.opr_param_defs.Convolution.Sparse
  83. sparse_type = Sparse.DENSE if groups == 1 else Sparse.GROUP
  84. res = mgb.opr.convolution(
  85. inp,
  86. weight,
  87. pad_h=ph,
  88. pad_w=pw,
  89. stride_h=sh,
  90. stride_w=sw,
  91. dilate_h=dh,
  92. dilate_w=dw,
  93. format="NCHW",
  94. strategy=get_conv_execution_strategy(),
  95. mode=conv_mode,
  96. compute_mode=compute_mode,
  97. sparse=sparse_type,
  98. )
  99. if bias is not None:
  100. res += bias
  101. return res
  102. @wrap_io_tensor
  103. def conv_transpose2d(
  104. inp: Tensor,
  105. weight: Tensor,
  106. bias: Optional[Tensor] = None,
  107. stride: Union[int, Tuple[int, int]] = 1,
  108. padding: Union[int, Tuple[int, int]] = 0,
  109. dilation: Union[int, Tuple[int, int]] = 1,
  110. groups: int = 1,
  111. conv_mode="CROSS_CORRELATION",
  112. compute_mode="DEFAULT",
  113. ) -> Tensor:
  114. """2D transposed convolution operation.
  115. Refer to :class:`~.ConvTranspose2d` for more information.
  116. :param inp: The feature map of the convolution operation
  117. :param weight: The convolution kernel
  118. :param bias: The bias added to the result of convolution (if given)
  119. :param stride: Stride of the 2D convolution operation. Default: 1
  120. :param padding: Size of the paddings added to the input on both sides of its
  121. spatial dimensions. Only zero-padding is supported. Default: 0
  122. :param dilation: Dilation of the 2D convolution operation. Default: 1
  123. :param groups: number of groups to divide input and output channels into,
  124. so as to perform a "grouped convolution". When ``groups`` is not 1,
  125. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  126. and the shape of weight should be ``(groups, out_channel // groups,
  127. in_channels // groups, height, width)``. Default: 1
  128. :type conv_mode: string or :class:`mgb.opr_param_defs.Convolution.Mode`
  129. :param conv_mode: Supports 'CROSS_CORRELATION' or 'CONVOLUTION'. Default:
  130. 'CROSS_CORRELATION'.
  131. :type compute_mode: string or
  132. :class:`mgb.opr_param_defs.Convolution.ComputeMode`
  133. :param compute_mode: When set to 'DEFAULT', no special requirements will be
  134. placed on the precision of intermediate results. When set to 'FLOAT32',
  135. Float32 would be used for accumulator and intermediate result, but only
  136. effective when input and output are of Float16 dtype.
  137. """
  138. ph, pw = _pair(padding)
  139. sh, sw = _pair_nonzero(stride)
  140. dh, dw = _pair_nonzero(dilation)
  141. Sparse = mgb.opr_param_defs.Convolution.Sparse
  142. sparse_type = Sparse.DENSE if groups == 1 else Sparse.GROUP
  143. res = mgb.opr.deconvolution(
  144. inp,
  145. weight,
  146. pad_h=ph,
  147. pad_w=pw,
  148. stride_h=sh,
  149. stride_w=sw,
  150. dilate_h=dh,
  151. dilate_w=dw,
  152. format="NCHW",
  153. strategy=get_conv_execution_strategy(),
  154. mode=conv_mode,
  155. compute_mode=compute_mode,
  156. sparse=sparse_type,
  157. )
  158. if bias is not None:
  159. res += bias
  160. return res
  161. @wrap_io_tensor
  162. def local_conv2d(
  163. inp: Tensor,
  164. weight: Tensor,
  165. stride: Union[int, Tuple[int, int]] = 1,
  166. padding: Union[int, Tuple[int, int]] = 0,
  167. dilation: Union[int, Tuple[int, int]] = 1,
  168. conv_mode="CROSS_CORRELATION",
  169. ) -> Tensor:
  170. """Applies spatial 2D convolution over an image with untied kernels.
  171. Refer to :class:`~.LocalConv2d` for more information.
  172. """
  173. ret = mgb.opr.group_local(
  174. inp,
  175. weight,
  176. pad_h=padding[0],
  177. pad_w=padding[1],
  178. stride_h=stride[0],
  179. stride_w=stride[1],
  180. dilate_h=dilation[0],
  181. dilate_w=dilation[1],
  182. format="NCHW",
  183. mode=conv_mode,
  184. )
  185. return ret
  186. @wrap_io_tensor
  187. def max_pool2d(
  188. inp: Tensor,
  189. kernel_size: Union[int, Tuple[int, int]],
  190. stride: Optional[Union[int, Tuple[int, int]]] = None,
  191. padding: Union[int, Tuple[int, int]] = 0,
  192. ) -> Tensor:
  193. """Applies a 2D max pooling over an input.
  194. Refer to :class:`~.MaxPool2d` for more information.
  195. :param inp: The input tensor.
  196. :param kernel_size: The size of the window.
  197. :param stride: The stride of the window. If not provided, its value is set to ``kernel_size``.
  198. Default: None
  199. :param padding: Implicit zero padding to be added on both sides. Default: 0
  200. """
  201. kh, kw = _pair_nonzero(kernel_size)
  202. sh, sw = _pair_nonzero(stride or kernel_size)
  203. ph, pw = _pair(padding)
  204. mode = mgb.opr_param_defs.Pooling.Mode.MAX
  205. return mgb.opr.pooling(
  206. inp,
  207. mode=mode,
  208. format="NCHW",
  209. stride_h=sh,
  210. stride_w=sw,
  211. pad_h=ph,
  212. pad_w=pw,
  213. window_h=kh,
  214. window_w=kw,
  215. )
  216. @wrap_io_tensor
  217. def avg_pool2d(
  218. inp: Tensor,
  219. kernel_size: Union[int, Tuple[int, int]],
  220. stride: Optional[Union[int, Tuple[int, int]]] = None,
  221. padding: Union[int, Tuple[int, int]] = 0,
  222. ) -> Tensor:
  223. """ Applies a 2D average pooling over an input.
  224. Refer to :class:`~.AvgPool2d` for more information.
  225. :param inp: The input tensor.
  226. :param kernel_size: The size of the window.
  227. :param stride: The stride of the window. If not provided, its value is set to ``kernel_size``.
  228. Default: None
  229. :param padding: Implicit zero padding to be added on both sides. Default: 0
  230. """
  231. kh, kw = _pair_nonzero(kernel_size)
  232. sh, sw = _pair_nonzero(stride or kernel_size)
  233. ph, pw = _pair(padding)
  234. mode = mgb.opr_param_defs.Pooling.Mode.AVERAGE
  235. return mgb.opr.pooling(
  236. inp,
  237. mode=mode,
  238. format="NCHW",
  239. stride_h=sh,
  240. stride_w=sw,
  241. pad_h=ph,
  242. pad_w=pw,
  243. window_h=kh,
  244. window_w=kw,
  245. )
  246. @wrap_io_tensor
  247. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  248. r"""
  249. Applies the element-wise PReLU function.
  250. Refer to :class:`~.PReLU` for more information.
  251. """
  252. return mgb.opr.elemwise(inp, 0, mode="MAX") + weight * mgb.opr.elemwise(
  253. inp, 0, mode="MIN"
  254. )
  255. @wrap_io_tensor
  256. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  257. r"""
  258. Applies the element-wise leaky_relu function
  259. Refer to :class:`~.LeakyReLU` for more information.
  260. """
  261. return mgb.opr.elemwise(inp, 0, mode="MAX") + negative_slope * mgb.opr.elemwise(
  262. inp, 0, mode="MIN"
  263. )
  264. @wrap_io_tensor
  265. def softplus(inp: Tensor, beta: float = 1, threshold: float = 20) -> Tensor:
  266. r"""
  267. Performs the elementwise function:
  268. .. math::
  269. \mathsf{softplus}(x) = \log(1+\exp(\beta x)) / \beta.
  270. For numerical stability the identity function is used when :math:`\beta x > \textrm{threshold}`.
  271. """
  272. mask = beta * inp <= threshold
  273. out = log(1 + exp(beta * inp)) / beta
  274. out = where(mask, out, inp)
  275. return out
  276. @wrap_io_tensor
  277. def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor:
  278. r"""
  279. Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
  280. :param inp: The input tensor.
  281. :param start_axis: The start dimension that the sub-tensor to be flattened. Default: 0
  282. :param end_axis: The end dimension that the sub-tensor to be flattened. Default: -1
  283. Examples:
  284. .. testcode::
  285. import numpy as np
  286. from megengine import tensor
  287. import megengine.functional as F
  288. inp_shape = (2, 2, 3, 3)
  289. inp = tensor(
  290. np.arange(36, dtype=np.int32).reshape(inp_shape),
  291. )
  292. oup = F.flatten(inp, 2)
  293. print(inp.numpy().shape)
  294. print(oup.numpy().shape)
  295. Outputs:
  296. .. testoutput::
  297. (2, 2, 3, 3)
  298. (2, 2, 9)
  299. """
  300. target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,)
  301. if end_axis != -1:
  302. target_shape += (inp.shape[end_axis + 1 :],)
  303. return inp.reshape(*target_shape)
  304. def _get_softmax_axis(ndim: int) -> int:
  305. if ndim in (0, 1, 3):
  306. return 0
  307. return 1
  308. @wrap_io_tensor
  309. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  310. r"""
  311. Applies a softmax function. Softmax is defined as:
  312. .. math::
  313. \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  314. It is applied to all elements along axis, and will re-scale them so that
  315. the elements lie in the range `[0, 1]` and sum to 1.
  316. See :class:`~megengine.module.activation.Softmax` for more details.
  317. :param inp: The input tensor.
  318. :param axis: An axis along which softmax will be applied. By default,
  319. softmax will apply along the highest ranked axis.
  320. """
  321. if axis is None:
  322. axis = _get_softmax_axis(len(inp.imm_shape))
  323. offset = mgb.opr.zero_grad(inp.max(axis=axis, keepdims=True))
  324. inp = inp - offset
  325. down = mgb.opr.elem.exp(inp).sum(axis=axis, keepdims=True)
  326. return mgb.opr.elem.exp(inp) / down
  327. @wrap_io_tensor
  328. def batch_norm2d(
  329. inp: Tensor,
  330. running_mean: Tensor,
  331. running_var: Tensor,
  332. weight: Optional[Tensor] = None,
  333. bias: Optional[Tensor] = None,
  334. training: bool = False,
  335. momentum: float = 0.9,
  336. eps: float = 1e-5,
  337. ) -> Tensor:
  338. """Applies batch normalization to the input.
  339. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  340. :param inp: input tensor.
  341. :param running_mean: tensor to store running mean.
  342. :param running_var: tensor to store running variance.
  343. :param weight: scaling tensor in the learnable affine parameters.
  344. See :math:`\gamma` in :class:`~.BatchNorm2d`
  345. :param bias: bias tensor in the learnable affine parameters.
  346. See :math:`\beta` in :class:`~.BatchNorm2d`
  347. :param training: a boolean value to indicate whether batch norm is performed
  348. in traning mode. Default: ``False``
  349. :param momentum: the value used for the ``running_mean`` and ``running_var``
  350. computation.
  351. Default: 0.9
  352. :param eps: a value added to the denominator for numerical stability.
  353. Default: 1e-5.
  354. """
  355. inp = mgb.opr.mark_no_broadcast_elemwise(inp)
  356. _channels = inp.imm_shape[1]
  357. _ndim = len(inp.imm_shape)
  358. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  359. assert _ndim == 4, "only 4D tensor supported"
  360. if weight is not None:
  361. weight = weight.reshape(*_param_shape)
  362. else:
  363. weight = mgb.make_immutable(*_use_default_if_none(None, None), 1.0).broadcast(
  364. *_param_shape
  365. )
  366. if bias is not None:
  367. bias = bias.reshape(*_param_shape)
  368. else:
  369. bias = mgb.make_immutable(*_use_default_if_none(None, None), 0.0).broadcast(
  370. *_param_shape
  371. )
  372. FwdMode = mgb.opr_param_defs.BN.FwdMode
  373. fwdmode = FwdMode.TRAINING if training else FwdMode.INFERENCE
  374. avg_factor = 1 - momentum
  375. if running_mean is not None and running_var is not None:
  376. if training:
  377. inp = barrier(inp)
  378. output = mgb.opr.batch_norm(
  379. inp,
  380. weight,
  381. bias,
  382. running_mean,
  383. running_var,
  384. param_dim="DIM_1C11",
  385. fwd_mode=fwdmode,
  386. epsilon=eps,
  387. avg_factor=avg_factor,
  388. )[-1]
  389. if training:
  390. mark_impure(output)
  391. else:
  392. output = mgb.opr.batch_norm_no_statistic(
  393. inp,
  394. weight,
  395. bias,
  396. param_dim="DIM_1C11",
  397. fwd_mode=fwdmode,
  398. epsilon=eps,
  399. avg_factor=avg_factor,
  400. )[-1]
  401. return output
  402. @wrap_io_tensor
  403. def sync_batch_norm(
  404. input: Tensor,
  405. running_mean: Tensor,
  406. running_var: Tensor,
  407. weight: Optional[Tensor] = None,
  408. bias: Optional[Tensor] = None,
  409. training: bool = False,
  410. momentum: Union[float, Tensor] = 0.9,
  411. eps: float = 1e-5,
  412. eps_mode="ADDITIVE",
  413. ) -> Tensor:
  414. """ Applies synchronized batch normalization to the input.
  415. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  416. :param inp: input tensor.
  417. :param running_mean: tensor to store running mean.
  418. :param running_var: tensor to store running variance.
  419. :param weight: scaling tensor in the learnable affine parameters.
  420. See :math:`\gamma` in :class:`~.BatchNorm2d`
  421. :param bias: bias tensor in the learnable affine parameters.
  422. See :math:`\beta` in :class:`~.BatchNorm2d`
  423. :param training: a boolean value to indicate whether batch norm is performed
  424. in traning mode. Default: ``False``
  425. :param momentum: the value used for the ``running_mean`` and ``running_var``
  426. computation.
  427. Default: 0.9
  428. :param eps: a value added to the denominator for numerical stability.
  429. Default: 1e-5.
  430. """
  431. assert eps_mode in {"MAX", "ADDITIVE"}, "unknown eps_mode: {}".format(eps_mode)
  432. input = mgb.opr.mark_no_broadcast_elemwise(input)
  433. _channels = input.imm_shape[1]
  434. _ndim = len(input.imm_shape)
  435. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  436. if training:
  437. def _sum_on_channel(input):
  438. return mgb.opr.reduce_general([input, _param_shape], mode="sum")
  439. def _allreduce(stat, key):
  440. return dist.helper.collective_comm_symvar(
  441. stat, key, CollParam.Mode.ALL_REDUCE_SUM
  442. )
  443. reduce_size = input.shape[0]
  444. for i in range(2, _ndim):
  445. reduce_size = reduce_size * input.shape[i]
  446. channel_x1s = _sum_on_channel(input)
  447. channel_x2s = _sum_on_channel(input ** 2)
  448. if dist.is_distributed():
  449. # reduce all nodes' data to calculate mean and variance
  450. reduce_size = reduce_size.reshape(*(1,) * _ndim)
  451. stat = mgb.opr.concat([reduce_size, channel_x1s, channel_x2s], axis=1)
  452. stat = _allreduce(stat, key="sync_bn_" + str(get_group_id()))
  453. reduce_size = stat[:, :1].reshape(1)
  454. channel_x1s = stat[:, 1 : 1 + _channels]
  455. channel_x2s = stat[:, 1 + _channels :]
  456. channel_mean = channel_x1s / reduce_size
  457. channel_variance = (
  458. channel_x1s ** 2 / (-reduce_size * reduce_size) + channel_x2s / reduce_size
  459. )
  460. else:
  461. assert running_var is not None and running_mean is not None
  462. channel_variance = running_var.reshape(*_param_shape)
  463. channel_mean = running_mean.reshape(*_param_shape)
  464. invsqrt_channel_variance = (
  465. mgb.opr.elem.max(channel_variance, eps)
  466. if eps_mode == "MAX"
  467. else mgb.opr.elem.add(channel_variance, eps)
  468. ) ** -0.5
  469. if weight is not None:
  470. weight = weight.reshape(*_param_shape)
  471. if bias is not None:
  472. bias = bias.reshape(*_param_shape)
  473. # outvar = output * weight + bias
  474. # where output = input * invsqrt_channel_variance + (
  475. # -channel_mean * invsqrt_channel_variance
  476. # )
  477. # Manually expand output for gopt
  478. if weight is not None:
  479. inv_var_wt = invsqrt_channel_variance * weight
  480. neg_channel_mean = -channel_mean
  481. if bias is not None:
  482. outvar = input * inv_var_wt + (neg_channel_mean * inv_var_wt + bias)
  483. else:
  484. outvar = input * inv_var_wt + neg_channel_mean * inv_var_wt
  485. else:
  486. outvar = input * invsqrt_channel_variance + (
  487. -channel_mean * invsqrt_channel_variance
  488. )
  489. if bias is not None:
  490. outvar = outvar + bias
  491. if training and running_var is not None and running_mean is not None:
  492. _mean_update = add_update(
  493. running_mean, channel_mean, alpha=momentum, beta=1 - momentum,
  494. )
  495. channel_variance_unbiased = channel_x1s ** 2 / (
  496. -reduce_size * (reduce_size - 1)
  497. ) + channel_x2s / (reduce_size - 1)
  498. _variance_update = add_update(
  499. running_var, channel_variance_unbiased, alpha=momentum, beta=1 - momentum
  500. )
  501. for dep in (_mean_update, _variance_update):
  502. add_extra_vardep(outvar, dep)
  503. return outvar
  504. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  505. r"""
  506. Perform one-hot encoding for the input tensor.
  507. :param inp: input tensor
  508. :param num_classes: number of classes denotes the last dimension of the output tensor
  509. Examples:
  510. .. testcode::
  511. import numpy as np
  512. from megengine import tensor
  513. import megengine.functional as F
  514. inp = tensor(np.arange(1, 4, dtype=np.int32))
  515. out = F.one_hot(inp, num_classes=4)
  516. print(out.numpy())
  517. Outputs:
  518. .. testoutput::
  519. [[0 1 0 0]
  520. [0 0 1 0]
  521. [0 0 0 1]]
  522. """
  523. comp_node, comp_graph = _decide_comp_node_and_comp_graph(inp)
  524. zeros = mgb.make_immutable(value=0, comp_node=comp_node, comp_graph=comp_graph)
  525. zeros_symvar = zeros.broadcast(inp.shapeof(), num_classes)
  526. ones = mgb.make_immutable(value=1, comp_node=comp_node, comp_graph=comp_graph)
  527. ones_symvar = ones.broadcast(inp.shapeof(), 1)
  528. return Tensor(
  529. mgb.opr.indexing_set_one_hot(
  530. zeros_symvar, axis=len(inp.shapeof()), index=inp, value=ones_symvar
  531. )
  532. )
  533. @wrap_io_tensor
  534. def warp_perspective(
  535. inp: Tensor,
  536. M: Tensor,
  537. dsize: Union[Tuple[int, int], int, Tensor],
  538. border_mode: str = "REPLICATE",
  539. border_val: float = 0.0,
  540. interp_mode: str = "LINEAR",
  541. ):
  542. r"""
  543. Applies perspective transformation to batched 2D images.
  544. The input images are transformed to the output images by the transformation matrix:
  545. .. math::
  546. \text{output}(n, c, h, w) = \text{input} \left( n, c,
  547. \frac{M_{00}h + M_{01}w + M_{02}}{M_{20}h + M_{21}w + M_{22}},
  548. \frac{M_{10}h + M_{11}w + M_{12}}{M_{20}h + M_{21}w + M_{22}}
  549. \right)
  550. :param inp: input image
  551. :param M: (batch, 3, 3) transformation matrix
  552. :param dsize: (h, w) size of the output image
  553. :param border_mode: pixel extrapolation method. Default: ``"REPLICATE"``
  554. :param border_val: value used in case of a constant border. Default: ``0``
  555. :param interp_mode: interpolation methods. Default: ``"LINEAR"``
  556. Examples:
  557. .. testcode::
  558. import numpy as np
  559. from megengine import tensor
  560. import megengine.functional as F
  561. inp_shape = (1, 1, 4, 4)
  562. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  563. M_shape = (1, 3, 3)
  564. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  565. M = tensor(np.array([[1., 0., 1.],
  566. [0., 1., 1.],
  567. [0., 0., 1.]], dtype=np.float32).reshape(M_shape))
  568. out = F.warp_perspective(inp, M, (2, 2))
  569. print(out.numpy())
  570. Outputs:
  571. .. testoutput::
  572. [[[[ 5. 6.]
  573. [ 9. 10.]]]]
  574. """
  575. return mgb.opr.warp_perspective(
  576. inp,
  577. M,
  578. dsize,
  579. bmode=border_mode,
  580. border_val=border_val,
  581. imode=interp_mode,
  582. format="NCHW",
  583. )
  584. @wrap_io_tensor
  585. def remap(
  586. inp: Tensor,
  587. map_xy: Tensor,
  588. border_mode: str = "REPLICATE",
  589. scalar: float = 0.0,
  590. interp_mode: str = "LINEAR",
  591. ) -> Tensor:
  592. r"""
  593. Applies remap transformation to batched 2D images.
  594. The input images are transformed to the output images by the tensor map_xy.
  595. The output's H and W are same as map_xy's H and W.
  596. :param inp: input image
  597. :param map_xy: (batch, oh, ow, 2) transformation matrix
  598. :param border_mode: pixel extrapolation method. Default: ``"REPLICATE"``
  599. :param scalar: value used in case of a constant border. Default: ``0``
  600. :param interp_mode: interpolation methods. Default: ``"LINEAR"``
  601. Examples:
  602. .. testcode::
  603. import numpy as np
  604. from megengine import tensor
  605. import megengine.functional as F
  606. inp_shape = (1, 1, 4, 4)
  607. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  608. map_xy_shape = (1, 2, 2, 2)
  609. map_xy = tensor(np.array([[[1., 0.],[0., 1.]],
  610. [[0., 1.],[0., 1.]]],
  611. dtype=np.float32).reshape(map_xy_shape))
  612. out = F.remap(inp, map_xy)
  613. print(out.numpy())
  614. Outputs:
  615. .. testoutput::
  616. [[[[1. 4.]
  617. [4. 4.]]]]
  618. """
  619. return mgb.opr.remap(
  620. inp,
  621. map_xy,
  622. border_type=border_mode,
  623. scalar=scalar,
  624. imode=interp_mode,
  625. format="NCHW",
  626. )
  627. @wrap_io_tensor
  628. def eye(
  629. n: int,
  630. m: Optional[int] = None,
  631. *,
  632. dtype=None,
  633. device: Optional[CompNode] = None,
  634. comp_graph: Optional[CompGraph] = None
  635. ) -> Tensor:
  636. """
  637. Returns a 2D tensor with ones on the diagonal and zeros elsewhere.
  638. :param n: The number of rows
  639. :param m: The number of columns. Default: None
  640. :param dtype: The data type. Default: None
  641. :param device: Compute node of the matrix. Default: None
  642. :param comp_graph: Compute graph of the matrix. Default: None
  643. :return: The eye matrix
  644. Examples:
  645. .. testcode::
  646. import numpy as np
  647. import megengine.functional as F
  648. data_shape = (4, 6)
  649. n, m = data_shape
  650. out = F.eye(n, m, dtype=np.float32)
  651. print(out.numpy())
  652. Outputs:
  653. .. testoutput::
  654. [[1. 0. 0. 0. 0. 0.]
  655. [0. 1. 0. 0. 0. 0.]
  656. [0. 0. 1. 0. 0. 0.]
  657. [0. 0. 0. 1. 0. 0.]]
  658. """
  659. device, comp_graph = _use_default_if_none(device, comp_graph)
  660. if m is None:
  661. m = n
  662. return mgb.opr.eye((n, m), dtype=dtype, comp_node=device, comp_graph=comp_graph)
  663. @wrap_io_tensor
  664. def matrix_mul(inp1: Tensor, inp2: Tensor) -> Tensor:
  665. """
  666. Performs a matrix multiplication of the matrices ``inp1`` and ``inp2``
  667. :param inp1: The first matrix to be multiplied (a, b)
  668. :param inp2: The second matrix to be multiplied (b, c)
  669. :return: The output tensor (a, c)
  670. Examples:
  671. .. testcode::
  672. import numpy as np
  673. from megengine import tensor
  674. import megengine.functional as F
  675. shape_1 = (2, 3)
  676. shape_2 = (3, 4)
  677. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  678. data2 = tensor(np.arange(0, 6, dtype=np.float32).reshape(3, 2))
  679. out = F.matrix_mul(data1, data2)
  680. print(out.numpy())
  681. Outputs:
  682. .. testoutput::
  683. [[10. 13.]
  684. [28. 40.]]
  685. """
  686. return mgb.opr.matrix_mul(inp1, inp2)
  687. @wrap_io_tensor
  688. def batched_matrix_mul(inp1: Tensor, inp2: Tensor) -> Tensor:
  689. """
  690. Performs a batched multiplication of th batched matrices ``inp1`` and ``inp2``
  691. :param inp1: The first batch matrix to be multiplied (n, a, b)
  692. :param inp2: The second batch matrix to be multiplied (n, b, c)
  693. :return: The output batch (n, a, c)
  694. Examples:
  695. .. testcode::
  696. import numpy as np
  697. from megengine import tensor
  698. import megengine.functional as F
  699. batch_size = 3
  700. shape_1 = (batch_size, 2, 3)
  701. shape_2 = (batch_size, 3, 4)
  702. data1 = tensor(
  703. np.arange(0, batch_size * 6, dtype=np.float32).reshape(batch_size, 2, 3))
  704. data2 = tensor(
  705. np.arange(0, batch_size * 12, dtype=np.float32).reshape(batch_size, 3, 4))
  706. out = F.batched_matrix_mul(data1, data2)
  707. print(out.numpy())
  708. Outputs:
  709. .. testoutput::
  710. [[[ 20. 23. 26. 29.]
  711. [ 56. 68. 80. 92.]]
  712. [[ 344. 365. 386. 407.]
  713. [ 488. 518. 548. 578.]]
  714. [[1100. 1139. 1178. 1217.]
  715. [1352. 1400. 1448. 1496.]]]
  716. """
  717. return mgb.opr.batched_matrix_mul(inp1, inp2)
  718. @wrap_io_tensor
  719. def interpolate(
  720. inp: Tensor,
  721. size: Optional[Union[int, Tuple[int, int]]] = None,
  722. scale_factor: Optional[Union[float, Tuple[float, float]]] = None,
  723. mode: str = "BILINEAR",
  724. align_corners: bool = None,
  725. ) -> Tensor:
  726. r"""
  727. Down/up samples the input tensor to either the given :attr:`size` or the given
  728. :attr:`scale_factor`
  729. :param inp: input tensor
  730. :param size: size of the output tensor. Default: ``None``
  731. :param scale_factor: scaling factor of the output tensor. Default: ``None``
  732. :param mode: interpolation methods, acceptable values are:
  733. 'BILINEAR', 'LINEAR'. Default: ``BILINEAR``
  734. Examples:
  735. .. testcode::
  736. import numpy as np
  737. from megengine import tensor
  738. import megengine.functional as F
  739. from megengine.test import assertTensorClose
  740. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  741. out = F.interpolate(inp, [4, 4], align_corners=False)
  742. print(out.numpy())
  743. out2 = F.interpolate(inp, scale_factor=2.)
  744. assertTensorClose(out.numpy(), out2.numpy())
  745. Outputs:
  746. .. testoutput::
  747. [[[[1. 1.25 1.75 2. ]
  748. [1.5 1.75 2.25 2.5 ]
  749. [2.5 2.75 3.25 3.5 ]
  750. [3. 3.25 3.75 4. ]]]]
  751. """
  752. mode = mode.upper()
  753. if mode not in ["BILINEAR", "LINEAR"]:
  754. raise ValueError("interpolate only support linear or bilinear mode")
  755. if mode not in ["BILINEAR", "LINEAR"]:
  756. if align_corners is not None:
  757. raise ValueError(
  758. "align_corners option can only be set in the bilinear/linear interpolating mode"
  759. )
  760. else:
  761. if align_corners is None:
  762. align_corners = False
  763. if mode == "LINEAR":
  764. inp = mgb.opr.add_axis(inp, 3)
  765. if len(inp.imm_shape) != 4:
  766. raise ValueError("shape of input tensor must correspond to the operartion mode")
  767. if size is None:
  768. if scale_factor is None:
  769. raise ValueError("scale_factor must not be None when size is None")
  770. if isinstance(scale_factor, (float, int)):
  771. scale_factor = float(scale_factor)
  772. if mode == "LINEAR":
  773. scale_factor = (scale_factor, float(1))
  774. else:
  775. scale_factor = (scale_factor, scale_factor)
  776. else:
  777. if mode == "LINEAR":
  778. raise ValueError(
  779. "under LINEAR mode, scale_factor can only be single value"
  780. )
  781. assert len(scale_factor) == 2, "shape of scale_factor must be equal to (2, )"
  782. assert isinstance(scale_factor[0], float) and isinstance(
  783. scale_factor[1], float
  784. ), "scale_factor must be float type"
  785. dsize = tuple(
  786. mgb.opr.elemwise(inp.shape[i + 2] * scale_factor[i], mode="FLOOR")
  787. for i in range(2)
  788. )
  789. dsize = mgb.opr.concat([dsize[0], dsize[1]], axis=0)
  790. else:
  791. if scale_factor is not None:
  792. raise ValueError("scale_factor must be None when size is provided")
  793. if isinstance(size, int):
  794. size = (size, 1)
  795. else:
  796. if mode == "LINEAR":
  797. raise ValueError("under LINEAR mode, size can only be single value")
  798. dsize = size
  799. oh, ow = dsize[0], dsize[1]
  800. ih, iw = inp.shape[2], inp.shape[3]
  801. if align_corners:
  802. hscale = (ih - 1.0) / (oh - 1.0)
  803. wscale = 1.0 * iw / ow
  804. if mode != "LINEAR":
  805. wscale = (iw - 1.0) / (ow - 1.0)
  806. row0 = mgb.opr.concat([wscale, [0, 0]], axis=0).reshape(1, 3)
  807. row1 = mgb.opr.concat([[0], hscale, [0]], axis=0).reshape(1, 3)
  808. weight = mgb.opr.concat([row0, row1, [[0, 0, 1]]], axis=0).reshape(1, 3, 3)
  809. weight = mgb.opr.broadcast(weight, (inp.shape[0], 3, 3))
  810. else:
  811. hscale = 1.0 * ih / oh
  812. wscale = 1.0 * iw / ow
  813. row0 = mgb.opr.concat([wscale, [0], 0.5 * wscale - 0.5], axis=0).reshape(1, 3)
  814. row1 = mgb.opr.concat([[0], hscale, 0.5 * hscale - 0.5], axis=0).reshape(1, 3)
  815. weight = mgb.opr.concat([row0, row1, [[0, 0, 1]]], axis=0).reshape(1, 3, 3)
  816. weight = mgb.opr.broadcast(weight, (inp.shape[0], 3, 3))
  817. ret = mgb.opr.warp_perspective(inp, weight, dsize, imode="LINEAR", format="NCHW")
  818. if mode == "LINEAR":
  819. ret = mgb.opr.reshape(ret, ret.shape[0:3])
  820. return ret
  821. @wrap_io_tensor
  822. def dropout(inp: Tensor, drop_prob: float, rescale: bool = True) -> Tensor:
  823. """
  824. Returns a new tensor where each of the elements are randomly set to zero
  825. with probability P = ``drop_prob``. Optionally rescale the output tensor.
  826. :param inp: The input tensor
  827. :param drop_prob: The probability to drop (set to zero) a single element
  828. :param rescale: The default behavior of ``dropout`` during training is to rescale the output,
  829. then it can be replaced by an :class:`~.Identity` during inference, default to True.
  830. :return: The output tensor
  831. Examples:
  832. .. testcode::
  833. import numpy as np
  834. import megengine as mge
  835. import megengine.functional as F
  836. from megengine import tensor
  837. data = tensor(np.ones(10, dtype=np.float32))
  838. out = F.dropout(data, 1./3.)
  839. print(out.numpy())
  840. Outputs:
  841. .. testoutput::
  842. :options: +SKIP
  843. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  844. """
  845. assert 0 <= drop_prob < 1
  846. rv = uniform(inp.shape)
  847. mask = rv > drop_prob
  848. inp *= mask.astype(inp.dtype)
  849. if rescale:
  850. inp *= 1 / (1 - drop_prob)
  851. return inp
  852. @wrap_io_tensor
  853. def identity(inp: Tensor) -> Tensor:
  854. """applies an identity transform to the input tensor.
  855. :param inp: The input tensor
  856. """
  857. return mgb.opr.identity(inp)
  858. @wrap_io_tensor
  859. def embedding(
  860. input: Tensor,
  861. weight: Tensor,
  862. padding_idx: Optional[int] = None,
  863. max_norm: Optional[float] = None,
  864. norm_type: Optional[float] = None,
  865. ):
  866. """
  867. Applies lookup table for embedding.
  868. :param input: the tensor with indices.
  869. :param weight: the learnable weights which embedding from.
  870. :param padding_idx: should be set to None, not support now.
  871. :param max_norm: should be set to None, not support now.
  872. :param norm_type: should be set to None, not support now.
  873. Refer to :class:`~.Embedding` for more information.
  874. """
  875. if padding_idx is not None:
  876. raise ValueError("Not support padding_idx Now!")
  877. if max_norm is not None or norm_type is not None:
  878. raise ValueError("Not support weight normlization Now!")
  879. return mgb.opr.advanced_indexing(weight)[input.reshape(-1), :].reshape(
  880. input.shape, weight.shape[-1]
  881. )
  882. @wrap_io_tensor
  883. def roi_pooling(
  884. input: Tensor,
  885. rois: Tensor,
  886. output_shape: Union[int, tuple, list],
  887. mode: str = "max",
  888. scale: float = 1.0,
  889. ) -> Tensor:
  890. """
  891. Apply roi pooling on input feature
  892. :param input: tensor that represents the input feature, (N, C, H, W) images
  893. :param rois: (K, 5) boxes. First column is the index into N. The other 4 columns are xyxy
  894. :param output_shape: (height, width) of output rois feature
  895. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: ``"max"``
  896. :param scale: scale the input boxes by this number. Default: 1.0
  897. :return: (K, C, output_shape[0], output_shape[1]) feature of rois
  898. """
  899. assert mode in ["max", "average"], "only max/average mode is supported"
  900. if isinstance(output_shape, int):
  901. output_shape = (output_shape, output_shape)
  902. return mgb.opr.roi_pooling(
  903. input, rois, output_shape, mode=mode.upper(), scale=scale
  904. )
  905. @wrap_io_tensor
  906. def roi_align(
  907. input: Tensor,
  908. rois: Tensor,
  909. output_shape: Union[int, tuple, list],
  910. mode: str = "average",
  911. spatial_scale: float = 1.0,
  912. sample_points: Union[int, tuple, list] = 2,
  913. aligned: bool = True,
  914. ) -> Tensor:
  915. """
  916. Apply roi align on input feature
  917. :param input: tensor that represents the input feature, (N, C, H, W) images
  918. :param rois: (N, 5) boxes. First column is the index into N. The other 4 columns are xyxy
  919. :param output_shape: (height, width) shape of output rois feature.
  920. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: ``"average"``
  921. :param spatial_scale: scale the input boxes by this number. Default: 1.0
  922. :param sample_points: number of inputs samples to take for each output sample.
  923. 0 to take samples densely. Default: 2
  924. :param aligned: wheather align the input feature, with `aligned=True`,
  925. we first appropriately scale the ROI and then shift it by -0.5. Default: True
  926. """
  927. assert mode in ["max", "average"], "only max/average mode is supported"
  928. if isinstance(output_shape, int):
  929. output_shape = (output_shape, output_shape)
  930. pooled_height, pooled_width = output_shape
  931. if isinstance(sample_points, int):
  932. sample_points = (sample_points, sample_points)
  933. sample_height, sample_width = sample_points
  934. offset = 0.5 if aligned else 0.0
  935. return mgb.opr.roi_align(
  936. input,
  937. rois,
  938. mode=mode.upper(),
  939. spatial_scale=spatial_scale,
  940. offset=offset,
  941. pooled_height=pooled_height,
  942. pooled_width=pooled_width,
  943. sample_height=sample_height,
  944. sample_width=sample_width,
  945. )
  946. @wrap_io_tensor
  947. def assert_equal(
  948. get: Tensor, expect: Tensor, max_err: float = 1e-4, verbose: bool = False
  949. ) -> Tensor:
  950. r"""
  951. Asserts that ``get`` equals to ``expect``, and returns value of ``expect``.
  952. :param get: tensor to be checked.
  953. :param expect: tensor with expected values.
  954. :param max_err: tolerance that two float values are asserted equal. Default: 1e-4
  955. :param verbose: whether to print details if two tensors are not equal. Default: False
  956. Examples:
  957. .. testcode::
  958. import megengine.functional as F
  959. from megengine import tensor
  960. get = tensor([1.0, 2.0])
  961. max_err = 0.1
  962. expect = get + max_err / 2.0
  963. val = F.assert_equal(expect, get, max_err=max_err)
  964. print(val.numpy())
  965. Outputs:
  966. .. testoutput::
  967. [1.05 2.05]
  968. """
  969. return mgb.opr.assert_equal(get, expect, maxerr=max_err, verbose=verbose)
  970. @wrap_io_tensor
  971. def indexing_one_hot(
  972. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  973. ) -> Tensor:
  974. r"""
  975. One-hot indexing for some axis.
  976. :param src: input data tensor.
  977. :param index: index tensor.
  978. :param axis: the axis on src for which values in index index. Default: 1
  979. :param keepdims: whether not to remove the axis in result. Default: ``False``
  980. Examples:
  981. .. testcode::
  982. import megengine.functional as F
  983. from megengine import tensor
  984. src = tensor([[1.0, 2.0]])
  985. index = tensor([0])
  986. val = F.indexing_one_hot(src, index)
  987. print(val.numpy())
  988. .. testoutput::
  989. [1.]
  990. """
  991. return mgb.opr.indexing_one_hot(src, axis, index, keepdims=keepdims)

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