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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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, Sequence, Tuple, Union
  11. from ..core._imperative_rt import CompNode
  12. from ..core.ops import builtin
  13. from ..core.ops._internal import param_defs as P
  14. from ..core.ops.special import Const
  15. from ..core.tensor import megbrain_graph, utils
  16. from ..core.tensor.core import TensorBase, TensorWrapperBase, apply
  17. from ..core.tensor.utils import astensor1d
  18. from ..distributed import WORLD, is_distributed
  19. from ..random import uniform
  20. from ..tensor import Tensor
  21. from .debug_param import get_conv_execution_strategy
  22. from .distributed import all_reduce_sum
  23. from .elemwise import exp, floor, log, log1p, maximum, minimum, relu
  24. from .math import argsort, max, sum
  25. from .tensor import (
  26. broadcast_to,
  27. concat,
  28. expand_dims,
  29. full,
  30. ones,
  31. reshape,
  32. squeeze,
  33. zeros,
  34. )
  35. from .types import _pair, _pair_nonzero
  36. __all__ = [
  37. "adaptive_avg_pool2d",
  38. "adaptive_max_pool2d",
  39. "avg_pool2d",
  40. "batch_norm2d",
  41. "conv2d",
  42. "conv_transpose2d",
  43. "dot",
  44. "dropout",
  45. "indexing_one_hot",
  46. "leaky_relu",
  47. "local_conv2d",
  48. "logsigmoid",
  49. "logsumexp",
  50. "logsoftmax",
  51. "matmul",
  52. "max_pool2d",
  53. "one_hot",
  54. "prelu",
  55. "softmax",
  56. "softplus",
  57. "svd",
  58. "sync_batch_norm",
  59. "warp_perspective",
  60. ]
  61. def expand_hw(x):
  62. # NOTE: >1d array is accepted, as long as 1 <= size <= 2
  63. try:
  64. x = int(x)
  65. return [x, x]
  66. except (TypeError, ValueError):
  67. pass
  68. h, w = x
  69. return int(h), int(w)
  70. def linear(inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None) -> Tensor:
  71. """Applies a linear transformation to the input tensor.
  72. Refer to :class:`~.module.linear.Linear` for more information.
  73. :param inp: input tensor with shape `(N, in_features)`.
  74. :param weight: weight with shape `(out_features, in_features)`.
  75. :param bias: bias with shape `(out_features,)`.
  76. Default: None
  77. """
  78. ret = matmul(inp, weight, transpose_b=True)
  79. if bias is not None:
  80. ret += bias
  81. return ret
  82. def conv2d(
  83. inp: Tensor,
  84. weight: Tensor,
  85. bias: Optional[Tensor] = None,
  86. stride: Union[int, Tuple[int, int]] = 1,
  87. padding: Union[int, Tuple[int, int]] = 0,
  88. dilation: Union[int, Tuple[int, int]] = 1,
  89. groups: int = 1,
  90. conv_mode="CROSS_CORRELATION",
  91. compute_mode="DEFAULT",
  92. ) -> Tensor:
  93. """2D convolution operation.
  94. Refer to :class:`~.Conv2d` for more information.
  95. :param inp: feature map of the convolution operation.
  96. :param weight: convolution kernel.
  97. :param bias: bias added to the result of convolution (if given).
  98. :param stride: stride of the 2D convolution operation. Default: 1
  99. :param padding: size of the paddings added to the input on both sides of its
  100. spatial dimensions. Only zero-padding is supported. Default: 0
  101. :param dilation: dilation of the 2D convolution operation. Default: 1
  102. :param groups: number of groups into which the input and output channels are divided, so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  103. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  104. and the shape of weight should be `(groups, out_channel // groups,
  105. in_channels // groups, height, width)`.
  106. :type conv_mode: string or :class:`P.Convolution.Mode`
  107. :param conv_mode: supports "CROSS_CORRELATION" or "CONVOLUTION". Default:
  108. "CROSS_CORRELATION"
  109. :type compute_mode: string or
  110. :class:`P.Convolution.ComputeMode`
  111. :param compute_mode: when set to "DEFAULT", no special requirements will be
  112. placed on the precision of intermediate results. When set to "FLOAT32",
  113. "Float32" would be used for accumulator and intermediate result, but only
  114. effective when input and output are of Float16 dtype.
  115. :return: output tensor.
  116. """
  117. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  118. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  119. stride_h, stride_w = expand_hw(stride)
  120. pad_h, pad_w = expand_hw(padding)
  121. dilate_h, dilate_w = expand_hw(dilation)
  122. Sparse = P.Convolution.Sparse
  123. sparse_type = Sparse.DENSE if groups == 1 else Sparse.GROUP
  124. op = builtin.Convolution(
  125. stride_h=stride_h,
  126. stride_w=stride_w,
  127. pad_h=pad_h,
  128. pad_w=pad_w,
  129. dilate_h=dilate_h,
  130. dilate_w=dilate_w,
  131. strategy=get_conv_execution_strategy(),
  132. mode=conv_mode,
  133. compute_mode=compute_mode,
  134. sparse=sparse_type,
  135. )
  136. inp, weight = utils.convert_inputs(inp, weight)
  137. (output,) = apply(op, inp, weight)
  138. if bias is not None:
  139. output += bias
  140. return output
  141. def conv_transpose2d(
  142. inp: Tensor,
  143. weight: Tensor,
  144. bias: Optional[Tensor] = None,
  145. stride: Union[int, Tuple[int, int]] = 1,
  146. padding: Union[int, Tuple[int, int]] = 0,
  147. dilation: Union[int, Tuple[int, int]] = 1,
  148. groups: int = 1,
  149. conv_mode="CROSS_CORRELATION",
  150. compute_mode="DEFAULT",
  151. ) -> Tensor:
  152. """2D transposed convolution operation.
  153. Refer to :class:`~.ConvTranspose2d` for more information.
  154. :param inp: feature map of the convolution operation.
  155. :param weight: convolution kernel.
  156. :param bias: bias added to the result of convolution (if given).
  157. :param stride: stride of the 2D convolution operation. Default: 1
  158. :param padding: size of the paddings added to the input on both sides of its
  159. spatial dimensions. Only zero-padding is supported. Default: 0
  160. :param dilation: dilation of the 2D convolution operation. Default: 1
  161. :param groups: number of groups into which the input and output channels are divided, so as to perform a ``grouped convolution``. When ``groups`` is not 1,
  162. ``in_channels`` and ``out_channels`` must be divisible by groups,
  163. and the shape of weight should be `(groups, out_channel // groups,
  164. in_channels // groups, height, width)`. Default: 1
  165. :type conv_mode: string or :class:`P.Convolution.Mode`
  166. :param conv_mode: supports "CROSS_CORRELATION" or "CONVOLUTION". Default:
  167. "CROSS_CORRELATION"
  168. :type compute_mode: string or
  169. :class:`P.Convolution.ComputeMode`
  170. :param compute_mode: when set to "DEFAULT", no special requirements will be
  171. placed on the precision of intermediate results. When set to "FLOAT32",
  172. "Float32" would be used for accumulator and intermediate result, but only
  173. effective when input and output are of Float16 dtype.
  174. :return: output tensor.
  175. """
  176. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  177. assert compute_mode == "DEFAULT" or compute_mode.name == "DEFAULT"
  178. if groups != 1:
  179. raise NotImplementedError("TODO")
  180. stride_h, stride_w = expand_hw(stride)
  181. pad_h, pad_w = expand_hw(padding)
  182. dilate_h, dilate_w = expand_hw(dilation)
  183. op = builtin.ConvolutionBackwardData(
  184. stride_h=stride_h,
  185. stride_w=stride_w,
  186. pad_h=pad_h,
  187. pad_w=pad_w,
  188. dilate_h=dilate_h,
  189. dilate_w=dilate_w,
  190. strategy=get_conv_execution_strategy(),
  191. )
  192. weight, inp = utils.convert_inputs(weight, inp)
  193. (output,) = apply(op, weight, inp)
  194. if bias is not None:
  195. output += bias
  196. return output
  197. def local_conv2d(
  198. inp: Tensor,
  199. weight: Tensor,
  200. bias: Optional[Tensor] = None,
  201. stride: Union[int, Tuple[int, int]] = 1,
  202. padding: Union[int, Tuple[int, int]] = 0,
  203. dilation: Union[int, Tuple[int, int]] = 1,
  204. conv_mode="CROSS_CORRELATION",
  205. ):
  206. """Applies spatial 2D convolution over an groupped channeled image with untied kernels.
  207. """
  208. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  209. stride_h, stride_w = expand_hw(stride)
  210. pad_h, pad_w = expand_hw(padding)
  211. dilate_h, dilate_w = expand_hw(dilation)
  212. Sparse = P.Convolution.Sparse
  213. op = builtin.GroupLocal(
  214. stride_h=stride_h,
  215. stride_w=stride_w,
  216. pad_h=pad_h,
  217. pad_w=pad_w,
  218. dilate_h=dilate_h,
  219. dilate_w=dilate_w,
  220. mode=conv_mode,
  221. compute_mode="DEFAULT",
  222. sparse=Sparse.DENSE,
  223. )
  224. inp, weight = utils.convert_inputs(inp, weight)
  225. (output,) = apply(op, inp, weight)
  226. if bias is not None:
  227. output += bias
  228. return output
  229. def max_pool2d(
  230. inp: Tensor,
  231. kernel_size: Union[int, Tuple[int, int]],
  232. stride: Optional[Union[int, Tuple[int, int]]] = None,
  233. padding: Union[int, Tuple[int, int]] = 0,
  234. ) -> Tensor:
  235. """Applies a 2D max pooling over an input tensor.
  236. Refer to :class:`~.MaxPool2d` for more information.
  237. :param inp: input tensor.
  238. :param kernel_size: size of the window.
  239. :param stride: stride of the window. If not provided, its value is set to kernel_size.
  240. Default: None
  241. :param padding: implicit zero padding added on both sides. Default: 0
  242. :return: output tensor.
  243. """
  244. if stride is None:
  245. stride = kernel_size
  246. window_h, window_w = _pair_nonzero(kernel_size)
  247. stride_h, stride_w = _pair_nonzero(stride)
  248. padding_h, padding_w = _pair(padding)
  249. op = builtin.Pooling(
  250. window_h=window_h,
  251. window_w=window_w,
  252. stride_h=stride_h,
  253. stride_w=stride_w,
  254. pad_h=padding_h,
  255. pad_w=padding_w,
  256. mode="MAX",
  257. )
  258. (output,) = apply(op, inp)
  259. return output
  260. def avg_pool2d(
  261. inp: Tensor,
  262. kernel_size: Union[int, Tuple[int, int]],
  263. stride: Optional[Union[int, Tuple[int, int]]] = None,
  264. padding: Union[int, Tuple[int, int]] = 0,
  265. mode: str = "AVERAGE_COUNT_EXCLUDE_PADDING",
  266. ) -> Tensor:
  267. """Applies 2D average pooling over an input tensor.
  268. Refer to :class:`~.AvgPool2d` for more information.
  269. :param inp: input tensor.
  270. :param kernel_size: size of the window.
  271. :param stride: stride of the window. If not provided, its value is set to ``kernel_size``.
  272. Default: None
  273. :param padding: implicit zero padding added on both sides. Default: 0
  274. :param mode: whether to count padding values. Default: "AVERAGE_COUNT_EXCLUDE_PADDING"
  275. :return: output tensor.
  276. """
  277. if stride is None:
  278. stride = kernel_size
  279. window_h, window_w = _pair_nonzero(kernel_size)
  280. stride_h, stride_w = _pair_nonzero(stride)
  281. padding_h, padding_w = _pair(padding)
  282. op = builtin.Pooling(
  283. window_h=window_h,
  284. window_w=window_w,
  285. stride_h=stride_h,
  286. stride_w=stride_w,
  287. pad_h=padding_h,
  288. pad_w=padding_w,
  289. mode=mode,
  290. )
  291. (output,) = apply(op, inp)
  292. return output
  293. def adaptive_max_pool2d(
  294. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  295. ) -> Tensor:
  296. """Applies a 2D max adaptive pooling over an input.
  297. Refer to :class:`~.MaxAdaptivePool2d` for more information.
  298. :param inp: The input tensor.
  299. :param oshp: (OH, OW) size of the output shape.
  300. :return: output tensor.
  301. """
  302. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  303. if isinstance(oshp, int):
  304. oshp = (oshp, oshp)
  305. op = builtin.AdaptivePooling(mode="MAX", format="NCHW",)
  306. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  307. (output,) = apply(op, inp, oshp)
  308. return output
  309. def adaptive_avg_pool2d(
  310. inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
  311. ) -> Tensor:
  312. """Applies a 2D average adaptive pooling over an input.
  313. Refer to :class:`~.AvgAdaptivePool2d` for more information.
  314. :param inp: The input tensor.
  315. :param oshp: (OH, OW) size of the output shape.
  316. :return: output tensor.
  317. """
  318. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  319. if isinstance(oshp, int):
  320. oshp = (oshp, oshp)
  321. op = builtin.AdaptivePooling(mode="AVERAGE", format="NCHW",)
  322. oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
  323. (output,) = apply(op, inp, oshp)
  324. return output
  325. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  326. r"""
  327. Applies the element-wise PReLU function.
  328. Refer to :class:`~.PReLU` for more information.
  329. """
  330. return maximum(inp, 0) + weight * minimum(inp, 0)
  331. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  332. r"""
  333. Applies the element-wise leaky_relu function
  334. Refer to :class:`~.LeakyReLU` for more information.
  335. """
  336. return maximum(inp, 0) + negative_slope * minimum(inp, 0)
  337. def softplus(inp: Tensor) -> Tensor:
  338. r"""Applies the element-wise function:
  339. .. math::
  340. \text{softplus}(x) = \log(1 + \exp(x))
  341. softplus is a smooth approximation to the ReLU function and can be used
  342. to constrain the output to be always positive.
  343. For numerical stability the implementation follows this transformation:
  344. .. math::
  345. \text{softplus}(x) = \log(1 + \exp(x))
  346. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  347. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  348. :param inp: input tensor.
  349. Examples:
  350. .. testcode::
  351. import numpy as np
  352. from megengine import tensor
  353. import megengine.functional as F
  354. x = tensor(np.arange(-3, 3, dtype=np.float32))
  355. y = F.softplus(x)
  356. print(y.numpy())
  357. Outputs:
  358. .. testoutput::
  359. [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
  360. """
  361. return log1p(exp(-abs(inp))) + relu(inp)
  362. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  363. r"""Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional
  364. input Tensor. The LogSoftmax formulation can be simplified as:
  365. .. math::
  366. \text{LogSoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  367. For numerical stability the implementation follows this transformation:
  368. .. math::
  369. \operatorname{logsoftmax}(x)
  370. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  371. = x - \log (\sum_{i}(\exp (x_{i})))
  372. = x - logsumexp(x)
  373. :param inp: input tensor.
  374. :param axis: axis along which logsoftmax will be applied.
  375. Examples:
  376. .. testcode::
  377. import numpy as np
  378. from megengine import tensor
  379. import megengine.functional as F
  380. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  381. y = F.logsoftmax(x, axis=1)
  382. print(y.numpy())
  383. Outputs:
  384. .. testoutput::
  385. [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
  386. [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
  387. """
  388. return inp - logsumexp(inp, axis, keepdims=True)
  389. def logsigmoid(inp: Tensor) -> Tensor:
  390. r"""Applies the element-wise function:
  391. .. math::
  392. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  393. = \log(1/(1 + exp(-x)))
  394. = - \log(1 + exp(-x))
  395. = - \text{softplus}(-x)
  396. :param inp: input tensor.
  397. Examples:
  398. .. testcode::
  399. import numpy as np
  400. from megengine import tensor
  401. import megengine.functional as F
  402. x = tensor(np.arange(-5, 5, dtype=np.float32))
  403. y = F.logsigmoid(x)
  404. print(y.numpy())
  405. Outputs:
  406. .. testoutput::
  407. [-5.0067 -4.0181 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
  408. -0.0181]
  409. """
  410. return -softplus(-inp)
  411. def logsumexp(
  412. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  413. ) -> Tensor:
  414. r"""
  415. Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  416. .. math::
  417. \operatorname{logsumexp}(\boldsymbol{x})= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  418. For numerical stability, the implementation follows this transformation:
  419. .. math::
  420. \operatorname{logsumexp}(\boldsymbol{x})= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  421. = \operatorname{logsumexp}(\boldsymbol{x})=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  422. where
  423. .. math::
  424. b = \max(x_j)
  425. :param inp: input tensor.
  426. :param axis: axis over which the sum is taken. It could be single axis or list of axes.
  427. :param keepdims: whether to retain :attr:`axis` or not for the output tensor.
  428. Examples:
  429. .. testcode::
  430. import numpy as np
  431. from megengine import tensor
  432. import megengine.functional as F
  433. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  434. y = F.logsumexp(x, axis=1, keepdims=False)
  435. print(y.numpy())
  436. Outputs:
  437. .. testoutput::
  438. [-0.5481 4.4519]
  439. """
  440. max_value = max(inp, axis, keepdims=True)
  441. if keepdims:
  442. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  443. else:
  444. return squeeze(max_value, axis=None) + log(
  445. sum(exp(inp - max_value), axis, keepdims)
  446. )
  447. def _get_softmax_axis(ndim: int) -> int:
  448. if ndim in (0, 1, 3):
  449. return 0
  450. return 1
  451. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  452. r"""
  453. Applies a softmax function. Softmax is defined as:
  454. .. math::
  455. \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  456. It is applied to all elements along axis, and rescales elements so that
  457. they stay in the range `[0, 1]` and sum to 1.
  458. See :class:`~megengine.module.activation.Softmax` for more details.
  459. :param inp: input tensor.
  460. :param axis: an axis along which softmax will be applied. By default,
  461. softmax will apply along the highest ranked axis.
  462. Examples:
  463. .. testcode::
  464. import numpy as np
  465. from megengine import tensor
  466. import megengine.functional as F
  467. x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  468. out = F.softmax(x)
  469. print(out.numpy())
  470. Outputs:
  471. .. testoutput::
  472. [[0.0117 0.0317 0.0861 0.2341 0.6364]
  473. [0.0117 0.0317 0.0861 0.2341 0.6364]]
  474. """
  475. if axis is None:
  476. axis = _get_softmax_axis(len(inp.shape))
  477. offset = inp.max(axis=axis, keepdims=True).detach()
  478. cached = exp(inp - offset)
  479. down = sum(cached, axis=axis, keepdims=True)
  480. return cached / down
  481. def batch_norm2d(
  482. inp: Tensor,
  483. running_mean: Tensor = None,
  484. running_var: Tensor = None,
  485. weight: Optional[Tensor] = None,
  486. bias: Optional[Tensor] = None,
  487. *,
  488. training: bool = False,
  489. momentum: float = 0.9,
  490. eps: float = 1e-5,
  491. inplace: bool = True
  492. ):
  493. r"""Applies batch normalization to the input.
  494. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  495. :param inp: input tensor.
  496. :param running_mean: tensor to store running mean.
  497. :param running_var: tensor to store running variance.
  498. :param weight: scaling tensor in the learnable affine parameters.
  499. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  500. :param bias: bias tensor in the learnable affine parameters.
  501. See :math:`\beta` in :class:`~.BatchNorm2d`.
  502. :param training: a boolean value to indicate whether batch norm is performed
  503. in training mode. Default: False
  504. :param momentum: value used for the ``running_mean`` and ``running_var``
  505. computation.
  506. Default: 0.9
  507. :param eps: a value added to the denominator for numerical stability.
  508. Default: 1e-5
  509. :param inplace: whether to update ``running_mean`` and ``running_var`` inplace or return new tensors
  510. Default: True
  511. :return: output tensor.
  512. """
  513. def full_value(value):
  514. C = inp.shape[1]
  515. (x,) = Const(value, dtype=inp.dtype, device=inp.device)(inp)
  516. return broadcast_to(x, [1, C, 1, 1])
  517. def expand_or_full(x, value):
  518. if x is None:
  519. return full_value(value)
  520. return expand_dims(x, [0, 2, 3])
  521. def make_full_if_none(x, value):
  522. if x is None:
  523. return full(shape=(1, inp.shape[1], 1, 1), value=value)
  524. return x
  525. has_mean = running_mean is not None
  526. has_var = running_var is not None
  527. if not training:
  528. assert has_mean, "running_mean must be provided in inference mode"
  529. assert has_var, "running_var must be provided in inference mode"
  530. if has_mean and running_mean.ndim != 4:
  531. raise ValueError
  532. if has_var and running_var.ndim != 4:
  533. raise ValueError
  534. inp, weight, bias, running_mean, running_var = utils.convert_inputs(
  535. inp, weight, bias, running_mean, running_var
  536. )
  537. weight = expand_or_full(weight, 1)
  538. bias = expand_or_full(bias, 0)
  539. if not training:
  540. op = builtin.BatchNorm(fwd_mode="INFERENCE", epsilon=eps, param_dim="DIM_1C11")
  541. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  542. return ret
  543. else:
  544. op = builtin.BatchNorm(
  545. avg_factor=1 - momentum, epsilon=eps, param_dim="DIM_1C11"
  546. )
  547. if has_mean or has_var:
  548. running_mean = make_full_if_none(running_mean, 0)
  549. running_var = make_full_if_none(running_var, 1)
  550. new_mean, new_var, _, _, inp = apply(
  551. op, inp, weight, bias, running_mean, running_var
  552. )
  553. if not has_mean:
  554. new_mean = None
  555. if not has_var:
  556. new_var = None
  557. if inplace:
  558. if has_mean:
  559. running_mean[...] = new_mean
  560. if has_var:
  561. running_var[...] = new_var
  562. return inp
  563. else:
  564. return inp, new_mean, new_var
  565. else:
  566. _, _, inp, = apply(op, inp, weight, bias)
  567. return inp
  568. def sync_batch_norm(
  569. inp: Tensor,
  570. running_mean: Tensor,
  571. running_var: Tensor,
  572. weight: Optional[Tensor] = None,
  573. bias: Optional[Tensor] = None,
  574. training: bool = False,
  575. momentum: Union[float, Tensor] = 0.9,
  576. eps: float = 1e-5,
  577. eps_mode="ADDITIVE",
  578. group=WORLD,
  579. ) -> Tensor:
  580. r"""Applies synchronized batch normalization to the input.
  581. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  582. :param inp: input tensor.
  583. :param running_mean: tensor to store running mean.
  584. :param running_var: tensor to store running variance.
  585. :param weight: scaling tensor in the learnable affine parameters.
  586. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  587. :param bias: bias tensor in the learnable affine parameters.
  588. See :math:`\beta` in :class:`~.BatchNorm2d`.
  589. :param training: a boolean value to indicate whether batch norm is performed
  590. in traning mode. Default: False
  591. :param momentum: value used for the ``running_mean`` and ``running_var``
  592. computation.
  593. Default: 0.9
  594. :param eps: a value added to the denominator for numerical stability.
  595. Default: 1e-5
  596. :return: output tensor.
  597. """
  598. assert eps_mode in {"MAX", "ADDITIVE"}, "unknown eps_mode: {}".format(eps_mode)
  599. _channels = inp.shape[1]
  600. _ndim = inp.ndim
  601. _device = inp.device
  602. _dtype = inp.dtype
  603. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  604. _reduce_axis = [0] + [i for i in range(2, _ndim)]
  605. if training:
  606. def _sum_on_channel(inp):
  607. return inp.sum(axis=_reduce_axis, keepdims=True)
  608. reduce_size = inp.shape[0]
  609. for i in range(2, _ndim):
  610. reduce_size = reduce_size * inp.shape[i]
  611. channel_x1s = _sum_on_channel(inp)
  612. channel_x2s = _sum_on_channel(inp ** 2)
  613. if is_distributed():
  614. # reduce all nodes' data to calculate mean and variance
  615. reduce_size = broadcast_to(Tensor(reduce_size, dtype=_dtype), [1] * _ndim)
  616. stat = concat(
  617. [reduce_size.astype(_dtype), channel_x1s, channel_x2s], axis=1
  618. )
  619. stat = all_reduce_sum(stat, group)
  620. reduce_size = stat[:, :1].reshape(1)
  621. channel_x1s = stat[:, 1 : 1 + _channels]
  622. channel_x2s = stat[:, 1 + _channels :]
  623. channel_mean = channel_x1s / reduce_size
  624. channel_variance = (
  625. channel_x1s ** 2 / (-reduce_size * reduce_size) + channel_x2s / reduce_size
  626. )
  627. else:
  628. assert running_var is not None and running_mean is not None
  629. channel_variance = running_var.reshape(*_param_shape)
  630. channel_mean = running_mean.reshape(*_param_shape)
  631. invsqrt_channel_variance = (
  632. maximum(channel_variance, eps) if eps_mode == "MAX" else channel_variance + eps
  633. ) ** -0.5
  634. if weight is not None:
  635. weight = weight.reshape(*_param_shape)
  636. if bias is not None:
  637. bias = bias.reshape(*_param_shape)
  638. # outvar = output * weight + bias
  639. # where output = inp * invsqrt_channel_variance + (
  640. # -channel_mean * invsqrt_channel_variance
  641. # )
  642. # Manually expand output for gopt
  643. if weight is not None:
  644. inv_var_wt = invsqrt_channel_variance * weight
  645. neg_channel_mean = -channel_mean
  646. if bias is not None:
  647. outvar = inp * inv_var_wt + (neg_channel_mean * inv_var_wt + bias)
  648. else:
  649. outvar = inp * inv_var_wt + neg_channel_mean * inv_var_wt
  650. else:
  651. outvar = inp * invsqrt_channel_variance + (
  652. -channel_mean * invsqrt_channel_variance
  653. )
  654. if bias is not None:
  655. outvar = outvar + bias
  656. if training and running_var is not None and running_mean is not None:
  657. running_mean *= momentum
  658. running_mean += (1 - momentum) * channel_mean
  659. channel_variance_unbiased = channel_x1s ** 2 / (
  660. -reduce_size * (reduce_size - 1)
  661. ) + channel_x2s / (reduce_size - 1)
  662. running_var *= momentum
  663. running_var += (1 - momentum) * channel_variance_unbiased
  664. return outvar
  665. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  666. r"""Performs one-hot encoding for the input tensor.
  667. :param inp: input tensor.
  668. :param num_classes: number of classes denotes the last dimension of the output tensor.
  669. :return: output tensor.
  670. Examples:
  671. .. testcode::
  672. import numpy as np
  673. from megengine import tensor
  674. import megengine.functional as F
  675. x = tensor(np.arange(1, 4, dtype=np.int32))
  676. out = F.one_hot(x, num_classes=4)
  677. print(out.numpy())
  678. Outputs:
  679. .. testoutput::
  680. [[0 1 0 0]
  681. [0 0 1 0]
  682. [0 0 0 1]]
  683. """
  684. zeros_tensor = zeros(list(inp.shape) + [num_classes], inp.dtype, inp.device)
  685. ones_tensor = ones(list(inp.shape) + [1], inp.dtype, inp.device)
  686. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  687. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  688. return result
  689. def warp_perspective(
  690. inp: Tensor,
  691. M: Tensor,
  692. dsize: Union[Tuple[int, int], int, Tensor],
  693. border_mode: str = "REPLICATE",
  694. border_val: float = 0.0,
  695. interp_mode: str = "LINEAR",
  696. ):
  697. r"""Applies perspective transformation to batched 2D images.
  698. The input images are transformed to the output images by the transformation matrix:
  699. .. math::
  700. \text{output}(n, c, h, w) = \text{input} \left( n, c,
  701. \frac{M_{00}h + M_{01}w + M_{02}}{M_{20}h + M_{21}w + M_{22}},
  702. \frac{M_{10}h + M_{11}w + M_{12}}{M_{20}h + M_{21}w + M_{22}}
  703. \right)
  704. :param inp: input image.
  705. :param M: `(batch, 3, 3)` transformation matrix.
  706. :param dsize: `(h, w)` size of the output image.
  707. :param border_mode: pixel extrapolation method. Default: "REPLICATE"
  708. :param border_val: value used in case of a constant border. Default: 0
  709. :param interp_mode: interpolation methods. Default: "LINEAR"
  710. :return: output tensor.
  711. Note:
  712. The transformation matrix is the inverse of that used by `cv2.warpPerspective`.
  713. Examples:
  714. .. testcode::
  715. import numpy as np
  716. from megengine import tensor
  717. import megengine.functional as F
  718. inp_shape = (1, 1, 4, 4)
  719. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  720. M_shape = (1, 3, 3)
  721. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  722. M = tensor(np.array([[1., 0., 1.],
  723. [0., 1., 1.],
  724. [0., 0., 1.]], dtype=np.float32).reshape(M_shape))
  725. out = F.warp_perspective(x, M, (2, 2))
  726. print(out.numpy())
  727. Outputs:
  728. .. testoutput::
  729. [[[[ 5. 6.]
  730. [ 9. 10.]]]]
  731. """
  732. op = builtin.WarpPerspective(
  733. imode=interp_mode, bmode=border_mode, format="NCHW", border_val=border_val
  734. )
  735. inp, M = utils.convert_inputs(inp, M)
  736. dsize = astensor1d(dsize, inp, dtype="int32", device=inp.device)
  737. (result,) = apply(op, inp, M, dsize)
  738. return result
  739. def matmul(
  740. inp1: Tensor,
  741. inp2: Tensor,
  742. transpose_a=False,
  743. transpose_b=False,
  744. compute_mode="DEFAULT",
  745. format="DEFAULT",
  746. ) -> Tensor:
  747. """
  748. Performs a matrix multiplication of the matrices ``inp1`` and ``inp2``.
  749. With different inputs dim, this function behaves differently:
  750. - Both 1-D tensor, simply forward to ``dot``.
  751. - Both 2-D tensor, normal matrix multiplication.
  752. - If one input tensor is 1-D, matrix vector multiplication.
  753. - If at least one tensor are 3-dimensional or >3-dimensional, the other tensor should have dim >= 2, the batched matrix-matrix is returned, and the tensor with smaller dimension will
  754. be broadcasted. For example:
  755. - inp1: `(n, k, m)`, inp2: `(n, m, p)`, return: `(n, k, p)`
  756. - inp1: `(n, k, m)`, inp2: `(m, p)`, return: `(n, k, p)`
  757. - inp1: `(n, j, k, m)`, inp2: `(n, j, m, p)`, return: `(n, j, k, p)`
  758. :param inp1: first matrix to be multiplied.
  759. :param inp2: second matrix to be multiplied.
  760. :return: output tensor.
  761. Examples:
  762. .. testcode::
  763. import numpy as np
  764. from megengine import tensor
  765. import megengine.functional as F
  766. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  767. data2 = tensor(np.arange(0, 6, dtype=np.float32).reshape(3, 2))
  768. out = F.matmul(data1, data2)
  769. print(out.numpy())
  770. Outputs:
  771. .. testoutput::
  772. [[10. 13.]
  773. [28. 40.]]
  774. """
  775. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  776. dim1, dim2 = inp1.ndim, inp2.ndim
  777. if dim1 == 1 and dim2 == 1:
  778. return dot(inp1, inp2)
  779. shp = None
  780. if dim1 > 3 or dim2 > 3:
  781. shape1, shape2 = list(inp1.shape), list(inp2.shape)
  782. if dim1 != dim2:
  783. if dim1 < dim2:
  784. shape1 = shape2[: dim2 - dim1] + shape1
  785. inp1 = broadcast_to(inp1, shape1)
  786. else:
  787. shape2 = shape1[: dim1 - dim2] + shape2
  788. inp2 = broadcast_to(inp2, shape2)
  789. reshaped_batch_size = 1
  790. for i in shape1[:-2]:
  791. reshaped_batch_size *= i
  792. inp1 = inp1.reshape(*([reshaped_batch_size] + shape1[-2:]))
  793. inp2 = inp2.reshape(*([reshaped_batch_size] + shape2[-2:]))
  794. op = builtin.BatchedMatrixMul(
  795. transposeA=transpose_a,
  796. transposeB=transpose_b,
  797. compute_mode=compute_mode,
  798. format=format,
  799. )
  800. shp = shape1[:-1] + shape2[-1:]
  801. elif dim1 == 3 or dim2 == 3:
  802. if dim2 < 3:
  803. inp2 = broadcast_to(inp2, inp1.shape[:1] + inp2.shape)
  804. elif dim1 < 3:
  805. inp1 = broadcast_to(inp1, inp2.shape[:1] + inp1.shape)
  806. op = builtin.BatchedMatrixMul(
  807. transposeA=transpose_a,
  808. transposeB=transpose_b,
  809. compute_mode=compute_mode,
  810. format=format,
  811. )
  812. else:
  813. if dim1 == 1:
  814. shp = (inp2.shape[1],)
  815. inp1 = expand_dims(inp1, 0)
  816. if dim2 == 1:
  817. shp = (inp1.shape[0],)
  818. inp2 = expand_dims(inp2, 1)
  819. op = builtin.MatrixMul(
  820. transposeA=transpose_a,
  821. transposeB=transpose_b,
  822. compute_mode=compute_mode,
  823. format=format,
  824. )
  825. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  826. (result,) = apply(op, inp1, inp2)
  827. if shp is not None:
  828. result = result.reshape(shp)
  829. return result
  830. def dot(inp1: Tensor, inp2: Tensor) -> Tensor:
  831. """
  832. Computes dot-product of two vectors ``inp1`` and ``inp2``.
  833. inputs must be 1-dimensional, scalar input can be automatically broadcasted.
  834. :param inp1: first vector.
  835. :param inp2: second vector.
  836. :return: output value.
  837. Examples:
  838. .. testcode::
  839. import numpy as np
  840. from megengine import tensor
  841. import megengine.functional as F
  842. data1 = tensor(np.arange(0, 6, dtype=np.float32))
  843. data2 = tensor(np.arange(0, 6, dtype=np.float32))
  844. out = F.dot(data1, data2)
  845. print(out.numpy())
  846. Outputs:
  847. .. testoutput::
  848. [55.]
  849. """
  850. op = builtin.Dot()
  851. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  852. (result,) = apply(op, inp1, inp2)
  853. return result
  854. def svd(inp: Tensor, full_matrices=False, compute_uv=True) -> Tensor:
  855. """
  856. Computes the singular value decompositions of input matrix.
  857. :param inp: input matrix, must has shape `[..., M, N]`.
  858. :return: output matrices, `(U, sigma, V)`.
  859. Examples:
  860. .. testcode::
  861. import numpy as np
  862. from megengine import tensor
  863. import megengine.functional as F
  864. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2,3))
  865. _, y, _ = F.svd(x)
  866. print(y.numpy())
  867. Outputs:
  868. .. testoutput::
  869. [7.3485 1. ]
  870. """
  871. op = builtin.SVD(full_matrices=full_matrices, compute_uv=compute_uv)
  872. U, sigma, V = apply(op, inp)
  873. return U, sigma, V
  874. def interpolate(
  875. inp: Tensor,
  876. size: Optional[Union[int, Tuple[int, int]]] = None,
  877. scale_factor: Optional[Union[float, Tuple[float, float]]] = None,
  878. mode: str = "BILINEAR",
  879. align_corners: bool = None,
  880. ) -> Tensor:
  881. r"""Down/up samples the input tensor to either the given size or with the given scale_factor. ``size`` can not coexist with ``scale_factor``.
  882. :param inp: input tensor.
  883. :param size: size of the output tensor. Default: None
  884. :param scale_factor: scaling factor of the output tensor. Default: None
  885. :param mode: interpolation methods, acceptable values are:
  886. "BILINEAR", "LINEAR". Default: "BILINEAR"
  887. :return: output tensor.
  888. Examples:
  889. .. testcode::
  890. import numpy as np
  891. from megengine import tensor
  892. import megengine.functional as F
  893. x = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  894. out = F.nn.interpolate(x, [4, 4], align_corners=False)
  895. print(out.numpy())
  896. out2 = F.nn.interpolate(x, scale_factor=2.)
  897. np.testing.assert_allclose(out.numpy(), out2.numpy())
  898. Outputs:
  899. .. testoutput::
  900. [[[[1. 1.25 1.75 2. ]
  901. [1.5 1.75 2.25 2.5 ]
  902. [2.5 2.75 3.25 3.5 ]
  903. [3. 3.25 3.75 4. ]]]]
  904. """
  905. mode = mode.upper()
  906. if mode not in ["BILINEAR", "LINEAR"]:
  907. raise ValueError("interpolate only support linear or bilinear mode")
  908. if mode not in ["BILINEAR", "LINEAR"]:
  909. if align_corners is not None:
  910. raise ValueError(
  911. "align_corners option can only be set in the bilinear/linear interpolating mode"
  912. )
  913. else:
  914. if align_corners is None:
  915. align_corners = False
  916. if mode == "LINEAR":
  917. inp = expand_dims(inp, 3)
  918. if inp.ndim != 4:
  919. raise ValueError("shape of input tensor must correspond to the operartion mode")
  920. if size is None:
  921. if scale_factor is None:
  922. raise ValueError("scale_factor must not be None when size is None")
  923. if isinstance(scale_factor, (float, int)):
  924. scale_factor = float(scale_factor)
  925. if mode == "LINEAR":
  926. scale_factor = (scale_factor, float(1))
  927. else:
  928. scale_factor = (scale_factor, scale_factor)
  929. else:
  930. if mode == "LINEAR":
  931. raise ValueError(
  932. "under LINEAR mode, scale_factor can only be single value"
  933. )
  934. assert len(scale_factor) == 2, "shape of scale_factor must be equal to (2, )"
  935. assert isinstance(scale_factor[0], float) and isinstance(
  936. scale_factor[1], float
  937. ), "scale_factor must be float type"
  938. dsize = tuple(
  939. floor(
  940. Tensor(
  941. inp.shape[i + 2] * scale_factor[i],
  942. dtype="float32",
  943. device=inp.device,
  944. )
  945. )
  946. for i in range(2)
  947. )
  948. dsize = concat([dsize[0], dsize[1]], axis=0)
  949. else:
  950. if scale_factor is not None:
  951. raise ValueError("scale_factor must be None when size is provided")
  952. if isinstance(size, int):
  953. size = (size, 1)
  954. else:
  955. if mode == "LINEAR":
  956. raise ValueError("under LINEAR mode, size can only be single value")
  957. dsize = size
  958. oh, ow = dsize[0], dsize[1]
  959. ih, iw = inp.shape[2], inp.shape[3]
  960. if align_corners:
  961. hscale = (ih - 1.0) / (oh - 1.0)
  962. wscale = 1.0 * iw / ow
  963. if mode != "LINEAR":
  964. wscale = (iw - 1.0) / (ow - 1.0)
  965. row0 = concat(
  966. [wscale, Tensor([0, 0], dtype="float32", device=inp.device)], axis=0
  967. ).reshape(1, 3)
  968. row1 = concat(
  969. [
  970. Tensor(0, dtype="float32", device=inp.device),
  971. hscale,
  972. Tensor(0, dtype="float32", device=inp.device),
  973. ],
  974. axis=0,
  975. ).reshape(1, 3)
  976. weight = concat(
  977. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  978. axis=0,
  979. ).reshape(1, 3, 3)
  980. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  981. else:
  982. hscale = 1.0 * ih / oh
  983. wscale = 1.0 * iw / ow
  984. row0 = concat(
  985. [wscale, Tensor(0, dtype="float32", device=inp.device), 0.5 * wscale - 0.5],
  986. axis=0,
  987. ).reshape(1, 3)
  988. row1 = concat(
  989. [Tensor(0, dtype="float32", device=inp.device), hscale, 0.5 * hscale - 0.5],
  990. axis=0,
  991. ).reshape(1, 3)
  992. weight = concat(
  993. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  994. axis=0,
  995. ).reshape(1, 3, 3)
  996. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  997. weight = weight.astype("float32")
  998. ret = warp_perspective(inp, weight, dsize, interp_mode="LINEAR")
  999. if mode == "LINEAR":
  1000. ret = reshape(ret, ret.shape[0:3])
  1001. return ret
  1002. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1003. """Returns a new tensor where each of the elements are randomly set to zero
  1004. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1005. :param inp: input tensor.
  1006. :param drop_prob: probability to drop (set to zero) a single element.
  1007. :param training: the default behavior of ``dropout`` during training is to rescale the output,
  1008. then it can be replaced by an :class:`~.Identity` during inference. Default: True
  1009. :return: the output tensor
  1010. Examples:
  1011. .. testcode::
  1012. import numpy as np
  1013. from megengine import tensor
  1014. import megengine.functional as F
  1015. x = tensor(np.ones(10, dtype=np.float32))
  1016. out = F.dropout(x, 1./3.)
  1017. print(out.numpy())
  1018. Outputs:
  1019. .. testoutput::
  1020. :options: +SKIP
  1021. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1022. """
  1023. assert 0 <= drop_prob < 1
  1024. rv = uniform(size=inp.shape)
  1025. mask = rv > drop_prob
  1026. inp *= mask.astype(inp.dtype)
  1027. if training:
  1028. inp *= 1 / (1 - drop_prob)
  1029. return inp
  1030. def embedding(
  1031. inp: Tensor,
  1032. weight: Tensor,
  1033. padding_idx: Optional[int] = None,
  1034. max_norm: Optional[float] = None,
  1035. norm_type: Optional[float] = None,
  1036. ):
  1037. """Applies lookup table for embedding.
  1038. :param inp: tensor with indices.
  1039. :param weight: learnable weights which embeds from.
  1040. :param padding_idx: should be set to None, not supported now.
  1041. :param max_norm: should be set to None, not supported now.
  1042. :param norm_type: should be set to None, not supported now.
  1043. :return: output tensor.
  1044. Refer to :class:`~.Embedding` for more information.
  1045. """
  1046. if padding_idx is not None:
  1047. raise ValueError("Not support padding_idx Now!")
  1048. if max_norm is not None or norm_type is not None:
  1049. raise ValueError("Not support weight normlization Now!")
  1050. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1051. return weight[inp.reshape(-1)].reshape(dest_shp)
  1052. def roi_pooling(
  1053. inp: Tensor,
  1054. rois: Tensor,
  1055. output_shape: Union[int, tuple, list],
  1056. mode: str = "max",
  1057. scale: float = 1.0,
  1058. ) -> Tensor:
  1059. """Applies roi pooling on input feature.
  1060. :param inp: tensor that represents the input feature, `(N, C, H, W)` images.
  1061. :param rois: `(K, 5)` boxes. First column is the index into N. The other 4 columns are xyxy.
  1062. :param output_shape: `(height, width)` of output rois feature.
  1063. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "max"
  1064. :param scale: scale the input boxes by this number. Default: 1.0
  1065. :return: `(K, C, output_shape[0], output_shape[1])` feature of rois.
  1066. Examples:
  1067. .. testcode::
  1068. import numpy as np
  1069. from megengine import tensor
  1070. import megengine.functional as F
  1071. np.random.seed(42)
  1072. inp = tensor(np.random.randn(1, 1, 128, 128))
  1073. rois = tensor(np.random.random((4, 5)))
  1074. y = F.nn.roi_pooling(inp, rois, (2, 2))
  1075. print(y.numpy()[0])
  1076. Outputs:
  1077. .. testoutput::
  1078. [[[-0.1383 -0.1383]
  1079. [-0.5035 -0.5035]]]
  1080. """
  1081. assert mode in ["max", "average"], "only max/average mode is supported"
  1082. if isinstance(output_shape, int):
  1083. output_shape = (output_shape, output_shape)
  1084. op = builtin.ROIPooling(mode=mode, scale=scale)
  1085. inp, rois = utils.convert_inputs(inp, rois)
  1086. result, _ = apply(
  1087. op, inp, rois, Tensor(output_shape, dtype="int32", device=inp.device)
  1088. )
  1089. return result
  1090. def roi_align(
  1091. inp: Tensor,
  1092. rois: Tensor,
  1093. output_shape: Union[int, tuple, list],
  1094. mode: str = "average",
  1095. spatial_scale: float = 1.0,
  1096. sample_points: Union[int, tuple, list] = 2,
  1097. aligned: bool = True,
  1098. ) -> Tensor:
  1099. """Applies roi align on input feature.
  1100. :param inp: tensor that represents the input feature, shape is `(N, C, H, W)`.
  1101. :param rois: `(N, 5)` boxes. First column is the box index. The other 4 columns are ``xyxy``.
  1102. :param output_shape: `(height, width)` shape of output rois feature.
  1103. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "average"
  1104. :param spatial_scale: scale the input boxes by this number. Default: 1.0
  1105. :param sample_points: number of inputs samples to take for each output sample.
  1106. 0 to take samples densely. Default: 2
  1107. :param aligned: wheather to align the input feature, with `aligned=True`,
  1108. we first appropriately scale the ROI and then shift it by -0.5. Default: True
  1109. :return: output tensor.
  1110. Examples:
  1111. .. testcode::
  1112. import numpy as np
  1113. from megengine import tensor
  1114. import megengine.functional as F
  1115. np.random.seed(42)
  1116. inp = tensor(np.random.randn(1, 1, 128, 128))
  1117. rois = tensor(np.random.random((4, 5)))
  1118. y = F.nn.roi_align(inp, rois, (2, 2))
  1119. print(y.numpy()[0])
  1120. Outputs:
  1121. .. testoutput::
  1122. [[[0.175 0.175 ]
  1123. [0.1359 0.1359]]]
  1124. """
  1125. assert mode in ["max", "average"], "only max/average mode is supported"
  1126. if isinstance(output_shape, int):
  1127. output_shape = (output_shape, output_shape)
  1128. pooled_height, pooled_width = output_shape
  1129. if isinstance(sample_points, int):
  1130. sample_points = (sample_points, sample_points)
  1131. sample_height, sample_width = sample_points
  1132. offset = 0.5 if aligned else 0.0
  1133. op = builtin.ROIAlign(
  1134. mode=mode,
  1135. format="NCHW",
  1136. spatial_scale=spatial_scale,
  1137. offset=offset,
  1138. pooled_height=pooled_height,
  1139. pooled_width=pooled_width,
  1140. sample_height=sample_height,
  1141. sample_width=sample_width,
  1142. )
  1143. inp, rois = utils.convert_inputs(inp, rois)
  1144. result, *_ = apply(op, inp, rois)
  1145. return result
  1146. def indexing_one_hot(
  1147. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1148. ) -> Tensor:
  1149. r"""One-hot indexing for some axes.
  1150. :param src: input tensor.
  1151. :param index: index tensor.
  1152. :param axis: axis on src for which values in index index. Default: 1
  1153. :param keepdims: whether not to remove the axis in result. Default: False
  1154. :return: output tensor.
  1155. Examples:
  1156. .. testcode::
  1157. import megengine.functional as F
  1158. from megengine import tensor
  1159. src = tensor([[1.0, 2.0]])
  1160. index = tensor([0])
  1161. val = F.indexing_one_hot(src, index)
  1162. print(val.numpy())
  1163. Outputs:
  1164. .. testoutput::
  1165. [1.]
  1166. """
  1167. assert isinstance(
  1168. src, (TensorWrapperBase, TensorBase)
  1169. ), "src must be of Tensor type"
  1170. op = builtin.IndexingOneHot(axis=axis)
  1171. index = utils.convert_single_value(index, (src,), dtype="int32", device=src.device)
  1172. (result,) = apply(op, src, index)
  1173. if not keepdims:
  1174. result = squeeze(result, axis)
  1175. return result
  1176. def nms(boxes: Tensor, scores: Tensor, iou_thresh: float) -> Tensor:
  1177. r"""
  1178. Performs non-maximum suppression (NMS) on the boxes according to their intersection-over-union(IoU).
  1179. :param boxes: tensor of shape `(N, 4)`; the boxes to perform nms on; each box is expected to be in `(x1, y1, x2, y2)` format.
  1180. :param iou_thresh: IoU threshold for overlapping.
  1181. :param scores: tensor of shape `(N,)`, the score of boxes.
  1182. :return: indices of the elements that have been kept by NMS.
  1183. Examples:
  1184. .. testcode::
  1185. import numpy as np
  1186. from megengine import tensor
  1187. import megengine.functional as F
  1188. x = np.zeros((100,4))
  1189. np.random.seed(42)
  1190. x[:,:2] = np.random.rand(100,2)*20
  1191. x[:,2:] = np.random.rand(100,2)*20 + 100
  1192. scores = tensor(np.random.rand(100))
  1193. inp = tensor(x)
  1194. result = F.nn.nms(inp, scores, iou_thresh=0.7)
  1195. print(result.numpy())
  1196. Outputs:
  1197. .. testoutput::
  1198. [75 69]
  1199. """
  1200. assert (
  1201. boxes.ndim == 2 and boxes.shape[1] == 4
  1202. ), "the expected shape of boxes is (N, 4)"
  1203. assert scores.ndim == 1, "the expected shape of scores is (N,)"
  1204. assert (
  1205. boxes.shape[0] == scores.shape[0]
  1206. ), "number of boxes and scores are not matched"
  1207. boxes = boxes.detach()
  1208. scores = scores.detach()
  1209. sorted_idx = argsort(scores, descending=True)
  1210. boxes = boxes[sorted_idx]
  1211. max_output = boxes.shape[0]
  1212. op = builtin.NMSKeep(iou_thresh, max_output)
  1213. inp = utils.convert_inputs(boxes.reshape(1, -1, 4))
  1214. indices, count = apply(op, *inp)
  1215. indices = indices[0][: count.item()]
  1216. keep_inds = sorted_idx[indices]
  1217. return keep_inds
  1218. from .loss import * # isort:skip
  1219. from .quantized import conv_bias_activation # isort:skip

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