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

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

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