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

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

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