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.

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

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