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

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

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