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

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

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