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

nn.py 49 kB

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

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