You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

nn.py 50 kB

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

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