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

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

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

Contributors (1)