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

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

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

Contributors (1)