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

nn.py 48 kB

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

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