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

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

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