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

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

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