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

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

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