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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # pylint: disable=too-many-lines
  10. from typing import Optional, Sequence, Tuple, Union
  11. from ..core._imperative_rt import CompNode
  12. from ..core._trace_option import use_symbolic_shape
  13. from ..core.ops import builtin
  14. from ..core.ops._internal import param_defs as P
  15. from ..core.ops.builtin import BatchNorm
  16. from ..core.ops.special import Const
  17. from ..core.tensor import megbrain_graph, utils
  18. from ..core.tensor.core import TensorBase, TensorWrapperBase, apply
  19. from ..core.tensor.utils import astensor1d
  20. from ..distributed import WORLD, is_distributed
  21. from ..jit.tracing import is_tracing
  22. from ..random import uniform
  23. from ..tensor import Tensor
  24. from .debug_param import get_conv_execution_strategy
  25. from .distributed import all_reduce_sum
  26. from .elemwise import exp, floor, log, log1p, maximum, minimum, relu
  27. from .math import argsort, max, prod, sum
  28. from .tensor import (
  29. broadcast_to,
  30. concat,
  31. expand_dims,
  32. full,
  33. ones,
  34. reshape,
  35. squeeze,
  36. zeros,
  37. )
  38. from .types import _pair, _pair_nonzero
  39. __all__ = [
  40. "adaptive_avg_pool2d",
  41. "adaptive_max_pool2d",
  42. "avg_pool2d",
  43. "batch_norm",
  44. "conv2d",
  45. "conv_transpose2d",
  46. "dot",
  47. "dropout",
  48. "indexing_one_hot",
  49. "leaky_relu",
  50. "local_conv2d",
  51. "logsigmoid",
  52. "logsumexp",
  53. "logsoftmax",
  54. "matmul",
  55. "max_pool2d",
  56. "one_hot",
  57. "prelu",
  58. "remap",
  59. "softmax",
  60. "softplus",
  61. "svd",
  62. "warp_perspective",
  63. ]
  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:`P.Convolution.Mode`
  112. :param conv_mode: supports "CROSS_CORRELATION" or "CONVOLUTION". Default:
  113. "CROSS_CORRELATION"
  114. :type compute_mode: string or
  115. :class:`P.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 = P.Convolution.Sparse
  128. sparse_type = Sparse.DENSE if groups == 1 else Sparse.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:`P.Convolution.Mode`
  172. :param conv_mode: supports "CROSS_CORRELATION" or "CONVOLUTION". Default:
  173. "CROSS_CORRELATION"
  174. :type compute_mode: string or
  175. :class:`P.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. """
  213. Applies spatial 2D convolution over an groupped channeled image with untied kernels.
  214. """
  215. assert conv_mode == "CROSS_CORRELATION" or conv_mode.name == "CROSS_CORRELATION"
  216. stride_h, stride_w = expand_hw(stride)
  217. pad_h, pad_w = expand_hw(padding)
  218. dilate_h, dilate_w = expand_hw(dilation)
  219. Sparse = P.Convolution.Sparse
  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=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)(inp)
  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. BatchNorm.ParamDim.DIM_1C11, BatchNorm.FwdMode.INFERENCE, eps, 1.0, 1.0, 0.0
  563. )
  564. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  565. return ret
  566. else:
  567. op = builtin.BatchNorm(
  568. BatchNorm.ParamDim.DIM_1C11,
  569. BatchNorm.FwdMode.TRAINING,
  570. eps,
  571. 1.0 - momentum,
  572. 1.0,
  573. 0.0,
  574. )
  575. if has_mean or has_var:
  576. running_mean = make_full_if_none(running_mean, 0)
  577. running_var = make_full_if_none(running_var, 1)
  578. new_mean, new_var, _, _, inp = apply(
  579. op, inp, weight, bias, running_mean, running_var
  580. )
  581. if not has_mean:
  582. new_mean = None
  583. if not has_var:
  584. new_var = None
  585. if inplace:
  586. if has_mean:
  587. running_mean[...] = new_mean
  588. if has_var:
  589. running_var[...] = new_var
  590. return inp
  591. else:
  592. return inp, new_mean, new_var
  593. else:
  594. (_, _, inp,) = apply(op, inp, weight, bias)
  595. return inp
  596. def sync_batch_norm(
  597. inp: Tensor,
  598. running_mean: Tensor,
  599. running_var: Tensor,
  600. weight: Optional[Tensor] = None,
  601. bias: Optional[Tensor] = None,
  602. training: bool = False,
  603. momentum: Union[float, Tensor] = 0.9,
  604. eps: float = 1e-5,
  605. eps_mode="ADDITIVE",
  606. group=WORLD,
  607. ) -> Tensor:
  608. r"""
  609. Applies synchronized batch normalization to the input.
  610. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  611. :param inp: input tensor.
  612. :param running_mean: tensor to store running mean.
  613. :param running_var: tensor to store running variance.
  614. :param weight: scaling tensor in the learnable affine parameters.
  615. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  616. :param bias: bias tensor in the learnable affine parameters.
  617. See :math:`\beta` in :class:`~.BatchNorm2d`.
  618. :param training: a boolean value to indicate whether batch norm is performed
  619. in traning mode. Default: False
  620. :param momentum: value used for the ``running_mean`` and ``running_var``
  621. computation.
  622. Default: 0.9
  623. :param eps: a value added to the denominator for numerical stability.
  624. Default: 1e-5
  625. :return: output tensor.
  626. """
  627. assert eps_mode in {"MAX", "ADDITIVE"}, "unknown eps_mode: {}".format(eps_mode)
  628. _channels = inp.shape[1]
  629. _ndim = inp.ndim
  630. _device = inp.device
  631. _dtype = inp.dtype
  632. _param_shape = (1, _channels) + (1,) * (_ndim - 2)
  633. _reduce_axis = [0] + [i for i in range(2, _ndim)]
  634. if training:
  635. def _sum_on_channel(inp):
  636. return inp.sum(axis=_reduce_axis, keepdims=True)
  637. reduce_size = inp.shape[0]
  638. for i in range(2, _ndim):
  639. reduce_size = reduce_size * inp.shape[i]
  640. channel_x1s = _sum_on_channel(inp)
  641. channel_x2s = _sum_on_channel(inp ** 2)
  642. if is_distributed():
  643. # reduce all nodes' data to calculate mean and variance
  644. reduce_size = broadcast_to(Tensor(reduce_size, dtype=_dtype), [1] * _ndim)
  645. stat = concat(
  646. [reduce_size.astype(_dtype), channel_x1s, channel_x2s], axis=1
  647. )
  648. stat = all_reduce_sum(stat, group)
  649. reduce_size = stat[:, :1].reshape(1)
  650. channel_x1s = stat[:, 1 : 1 + _channels]
  651. channel_x2s = stat[:, 1 + _channels :]
  652. channel_mean = channel_x1s / reduce_size
  653. channel_variance = (
  654. channel_x1s ** 2 / (-reduce_size * reduce_size) + channel_x2s / reduce_size
  655. )
  656. else:
  657. assert running_var is not None and running_mean is not None
  658. channel_variance = running_var.reshape(*_param_shape)
  659. channel_mean = running_mean.reshape(*_param_shape)
  660. invsqrt_channel_variance = (
  661. maximum(channel_variance, eps) if eps_mode == "MAX" else channel_variance + eps
  662. ) ** -0.5
  663. if weight is not None:
  664. weight = weight.reshape(*_param_shape)
  665. if bias is not None:
  666. bias = bias.reshape(*_param_shape)
  667. # outvar = output * weight + bias
  668. # where output = inp * invsqrt_channel_variance + (
  669. # -channel_mean * invsqrt_channel_variance
  670. # )
  671. # Manually expand output for gopt
  672. if weight is not None:
  673. inv_var_wt = invsqrt_channel_variance * weight
  674. neg_channel_mean = -channel_mean
  675. if bias is not None:
  676. outvar = inp * inv_var_wt + (neg_channel_mean * inv_var_wt + bias)
  677. else:
  678. outvar = inp * inv_var_wt + neg_channel_mean * inv_var_wt
  679. else:
  680. outvar = inp * invsqrt_channel_variance + (
  681. -channel_mean * invsqrt_channel_variance
  682. )
  683. if bias is not None:
  684. outvar = outvar + bias
  685. if training and running_var is not None and running_mean is not None:
  686. running_mean *= momentum
  687. running_mean += (1 - momentum) * channel_mean
  688. channel_variance_unbiased = channel_x1s ** 2 / (
  689. -reduce_size * (reduce_size - 1)
  690. ) + channel_x2s / (reduce_size - 1)
  691. running_var *= momentum
  692. running_var += (1 - momentum) * channel_variance_unbiased
  693. return outvar
  694. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  695. r"""
  696. Performs one-hot encoding for the input tensor.
  697. :param inp: input tensor.
  698. :param num_classes: number of classes denotes the last dimension of the output tensor.
  699. :return: output tensor.
  700. Examples:
  701. .. testcode::
  702. import numpy as np
  703. from megengine import tensor
  704. import megengine.functional as F
  705. x = tensor(np.arange(1, 4, dtype=np.int32))
  706. out = F.one_hot(x, num_classes=4)
  707. print(out.numpy())
  708. Outputs:
  709. .. testoutput::
  710. [[0 1 0 0]
  711. [0 0 1 0]
  712. [0 0 0 1]]
  713. """
  714. zeros_tensor = zeros(list(inp.shape) + [num_classes], inp.dtype, inp.device)
  715. ones_tensor = ones(list(inp.shape) + [1], inp.dtype, inp.device)
  716. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  717. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  718. return result
  719. def warp_perspective(
  720. inp: Tensor,
  721. M: Tensor,
  722. dsize: Union[Tuple[int, int], int, Tensor],
  723. border_mode: str = "REPLICATE",
  724. border_val: float = 0.0,
  725. interp_mode: str = "LINEAR",
  726. ) -> Tensor:
  727. r"""
  728. Applies perspective transformation to batched 2D images.
  729. The input images are transformed to the output images by the transformation matrix:
  730. .. math::
  731. \text{output}(n, c, h, w) = \text{input} \left( n, c,
  732. \frac{M_{00}h + M_{01}w + M_{02}}{M_{20}h + M_{21}w + M_{22}},
  733. \frac{M_{10}h + M_{11}w + M_{12}}{M_{20}h + M_{21}w + M_{22}}
  734. \right)
  735. :param inp: input image.
  736. :param M: `(batch, 3, 3)` transformation matrix.
  737. :param dsize: `(h, w)` size of the output image.
  738. :param border_mode: pixel extrapolation method.
  739. Default: "REPLICATE". Currently also support "CONSTANT", "REFLECT",
  740. "REFLECT_101", "WRAP".
  741. :param border_val: value used in case of a constant border. Default: 0
  742. :param interp_mode: interpolation methods.
  743. Default: "LINEAR". Currently only support "LINEAR" mode.
  744. :return: output tensor.
  745. Note:
  746. The transformation matrix is the inverse of that used by `cv2.warpPerspective`.
  747. Examples:
  748. .. testcode::
  749. import numpy as np
  750. from megengine import tensor
  751. import megengine.functional as F
  752. inp_shape = (1, 1, 4, 4)
  753. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  754. M_shape = (1, 3, 3)
  755. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  756. M = tensor(np.array([[1., 0., 1.],
  757. [0., 1., 1.],
  758. [0., 0., 1.]], dtype=np.float32).reshape(M_shape))
  759. out = F.warp_perspective(x, M, (2, 2))
  760. print(out.numpy())
  761. Outputs:
  762. .. testoutput::
  763. [[[[ 5. 6.]
  764. [ 9. 10.]]]]
  765. """
  766. op = builtin.WarpPerspective(
  767. imode=interp_mode, bmode=border_mode, format="NCHW", border_val=border_val
  768. )
  769. inp, M = utils.convert_inputs(inp, M)
  770. dsize = astensor1d(dsize, inp, dtype="int32", device=inp.device)
  771. (result,) = apply(op, inp, M, dsize)
  772. return result
  773. def remap(
  774. inp: Tensor,
  775. map_xy: Tensor,
  776. border_mode: str = "REPLICATE",
  777. scalar: float = 0.0,
  778. interp_mode: str = "LINEAR",
  779. ) -> Tensor:
  780. r"""
  781. Applies remap transformation to batched 2D images.
  782. The input images are transformed to the output images by the tensor map_xy.
  783. The output's H and W are same as map_xy's H and W.
  784. :param inp: input image
  785. :param map_xy: (batch, oh, ow, 2) transformation matrix
  786. :param border_mode: pixel extrapolation method.
  787. Default: "REPLICATE". Currently also support "CONSTANT", "REFLECT",
  788. "REFLECT_101", "WRAP".
  789. :param scalar: value used in case of a constant border. Default: 0
  790. :param interp_mode: interpolation methods.
  791. Default: "LINEAR". Currently only support "LINEAR" mode.
  792. :return: output tensor.
  793. Examples:
  794. .. testcode::
  795. import numpy as np
  796. from megengine import tensor
  797. import megengine.functional as F
  798. inp_shape = (1, 1, 4, 4)
  799. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  800. map_xy_shape = (1, 2, 2, 2)
  801. map_xy = tensor(np.array([[[1., 0.],[0., 1.]],
  802. [[0., 1.],[0., 1.]]],
  803. dtype=np.float32).reshape(map_xy_shape))
  804. out = F.remap(inp, map_xy)
  805. print(out.numpy())
  806. Outputs:
  807. .. testoutput::
  808. [[[[1. 4.]
  809. [4. 4.]]]]
  810. """
  811. op = builtin.Remap(
  812. imode=interp_mode, border_type=border_mode, format="NCHW", scalar=scalar
  813. )
  814. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  815. (result,) = apply(op, inp, map_xy)
  816. return result
  817. def matmul(
  818. inp1: Tensor,
  819. inp2: Tensor,
  820. transpose_a=False,
  821. transpose_b=False,
  822. compute_mode="DEFAULT",
  823. format="DEFAULT",
  824. ) -> Tensor:
  825. """
  826. Performs a matrix multiplication of the matrices ``inp1`` and ``inp2``.
  827. With different inputs dim, this function behaves differently:
  828. - Both 1-D tensor, simply forward to ``dot``.
  829. - Both 2-D tensor, normal matrix multiplication.
  830. - If one input tensor is 1-D, matrix vector multiplication.
  831. - 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
  832. be broadcasted. For example:
  833. - inp1: `(n, k, m)`, inp2: `(n, m, p)`, return: `(n, k, p)`
  834. - inp1: `(n, k, m)`, inp2: `(m, p)`, return: `(n, k, p)`
  835. - inp1: `(n, j, k, m)`, inp2: `(n, j, m, p)`, return: `(n, j, k, p)`
  836. :param inp1: first matrix to be multiplied.
  837. :param inp2: second matrix to be multiplied.
  838. :return: output tensor.
  839. Examples:
  840. .. testcode::
  841. import numpy as np
  842. from megengine import tensor
  843. import megengine.functional as F
  844. data1 = tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  845. data2 = tensor(np.arange(0, 6, dtype=np.float32).reshape(3, 2))
  846. out = F.matmul(data1, data2)
  847. print(out.numpy())
  848. Outputs:
  849. .. testoutput::
  850. [[10. 13.]
  851. [28. 40.]]
  852. """
  853. remove_row, remove_col = False, False
  854. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  855. dim1, dim2 = inp1.ndim, inp2.ndim
  856. # handle dim=1 cases, dot and matrix-vector multiplication
  857. if dim1 == 1 and dim2 == 1:
  858. return dot(inp1, inp2)
  859. # the underlying matmul op requires input dims to be at least 2
  860. if dim1 == 1:
  861. inp1 = expand_dims(inp1, 0)
  862. dim1 = 2
  863. remove_row = True
  864. if dim2 == 1:
  865. inp2 = expand_dims(inp2, 1)
  866. dim2 = 2
  867. remove_col = True
  868. batch_shape = None
  869. shape1 = inp1.shape
  870. shape2 = inp2.shape
  871. maxdim = dim1 if dim1 > dim2 else dim2
  872. if dim1 >= 3 or dim2 >= 3:
  873. if use_symbolic_shape():
  874. if dim1 > dim2:
  875. shape2 = concat([shape1[:-2], shape2[-2:]])
  876. inp2 = broadcast_to(inp2, shape2)
  877. if dim1 < dim2:
  878. shape1 = concat([shape2[:-2], shape1[-2:]])
  879. inp1 = broadcast_to(inp1, shape1)
  880. if maxdim > 3:
  881. batch_shape = shape1[:-2]
  882. # compress inputs to 3d
  883. (inp1,) = apply(
  884. builtin.Reshape(), inp1, concat([prod(shape1[:-2]), shape1[-2:]])
  885. )
  886. (inp2,) = apply(
  887. builtin.Reshape(), inp2, concat([prod(shape2[:-2]), shape2[-2:]])
  888. )
  889. else:
  890. if dim1 > dim2:
  891. shape2 = shape1[:-2] + shape2[-2:]
  892. inp2 = broadcast_to(inp2, shape2)
  893. if dim1 < dim2:
  894. shape1 = shape2[:-2] + shape1[-2:]
  895. inp1 = broadcast_to(inp1, shape1)
  896. if maxdim > 3:
  897. batch_shape = shape1[:-2]
  898. # compress inputs to 3d
  899. inp1 = inp1.reshape((-1, shape1[-2], shape1[-1]))
  900. inp2 = inp2.reshape((-1, shape2[-2], shape2[-1]))
  901. op = builtin.BatchedMatrixMul(
  902. transposeA=transpose_a,
  903. transposeB=transpose_b,
  904. compute_mode=compute_mode,
  905. format=format,
  906. )
  907. else:
  908. op = builtin.MatrixMul(
  909. transposeA=transpose_a,
  910. transposeB=transpose_b,
  911. compute_mode=compute_mode,
  912. format=format,
  913. )
  914. (result,) = apply(op, inp1, inp2)
  915. if maxdim > 3:
  916. if use_symbolic_shape():
  917. (result,) = apply(
  918. builtin.Reshape(), result, concat([batch_shape, result.shape[-2:]])
  919. )
  920. else:
  921. result = result.reshape(batch_shape + result.shape[-2:])
  922. if remove_row:
  923. result = squeeze(result, axis=-2)
  924. if remove_col:
  925. result = squeeze(result, axis=-1)
  926. return result
  927. def dot(inp1: Tensor, inp2: Tensor) -> Tensor:
  928. """
  929. Computes dot-product of two vectors ``inp1`` and ``inp2``.
  930. inputs must be 1-dimensional, scalar input can be automatically broadcasted.
  931. :param inp1: first vector.
  932. :param inp2: second vector.
  933. :return: output value.
  934. Examples:
  935. .. testcode::
  936. import numpy as np
  937. from megengine import tensor
  938. import megengine.functional as F
  939. data1 = tensor(np.arange(0, 6, dtype=np.float32))
  940. data2 = tensor(np.arange(0, 6, dtype=np.float32))
  941. out = F.dot(data1, data2)
  942. print(out.numpy())
  943. Outputs:
  944. .. testoutput::
  945. [55.]
  946. """
  947. op = builtin.Dot()
  948. inp1, inp2 = utils.convert_inputs(inp1, inp2)
  949. (result,) = apply(op, inp1, inp2)
  950. return result
  951. def svd(inp: Tensor, full_matrices=False, compute_uv=True) -> Tensor:
  952. """
  953. Computes the singular value decompositions of input matrix.
  954. :param inp: input matrix, must has shape `[..., M, N]`.
  955. :return: output matrices, `(U, sigma, V)`.
  956. Examples:
  957. .. testcode::
  958. import numpy as np
  959. from megengine import tensor
  960. import megengine.functional as F
  961. x = tensor(np.arange(0, 6, dtype=np.float32).reshape(2,3))
  962. _, y, _ = F.svd(x)
  963. print(y.numpy().round(decimals=3))
  964. Outputs:
  965. .. testoutput::
  966. [7.348 1. ]
  967. """
  968. op = builtin.SVD(full_matrices=full_matrices, compute_uv=compute_uv)
  969. U, sigma, V = apply(op, inp)
  970. return U, sigma, V
  971. def interpolate(
  972. inp: Tensor,
  973. size: Optional[Union[int, Tuple[int, int]]] = None,
  974. scale_factor: Optional[Union[float, Tuple[float, float]]] = None,
  975. mode: str = "BILINEAR",
  976. align_corners: bool = None,
  977. ) -> Tensor:
  978. r"""
  979. Down/up samples the input tensor to either the given size or with the given scale_factor. ``size`` can not coexist with ``scale_factor``.
  980. :param inp: input tensor.
  981. :param size: size of the output tensor. Default: None
  982. :param scale_factor: scaling factor of the output tensor. Default: None
  983. :param mode: interpolation methods, acceptable values are:
  984. "BILINEAR", "LINEAR". Default: "BILINEAR"
  985. :return: output tensor.
  986. Examples:
  987. .. testcode::
  988. import numpy as np
  989. from megengine import tensor
  990. import megengine.functional as F
  991. x = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  992. out = F.nn.interpolate(x, [4, 4], align_corners=False)
  993. print(out.numpy())
  994. out2 = F.nn.interpolate(x, scale_factor=2.)
  995. np.testing.assert_allclose(out.numpy(), out2.numpy())
  996. Outputs:
  997. .. testoutput::
  998. [[[[1. 1.25 1.75 2. ]
  999. [1.5 1.75 2.25 2.5 ]
  1000. [2.5 2.75 3.25 3.5 ]
  1001. [3. 3.25 3.75 4. ]]]]
  1002. """
  1003. mode = mode.upper()
  1004. if mode not in ["BILINEAR", "LINEAR"]:
  1005. raise ValueError("interpolate only support linear or bilinear mode")
  1006. if mode not in ["BILINEAR", "LINEAR"]:
  1007. if align_corners is not None:
  1008. raise ValueError(
  1009. "align_corners option can only be set in the bilinear/linear interpolating mode"
  1010. )
  1011. else:
  1012. if align_corners is None:
  1013. align_corners = False
  1014. if mode == "LINEAR":
  1015. inp = expand_dims(inp, 3)
  1016. if inp.ndim != 4:
  1017. raise ValueError("shape of input tensor must correspond to the operartion mode")
  1018. if size is None:
  1019. if scale_factor is None:
  1020. raise ValueError("scale_factor must not be None when size is None")
  1021. if isinstance(scale_factor, (float, int)):
  1022. scale_factor = float(scale_factor)
  1023. if mode == "LINEAR":
  1024. scale_factor = (scale_factor, float(1))
  1025. else:
  1026. scale_factor = (scale_factor, scale_factor)
  1027. else:
  1028. if mode == "LINEAR":
  1029. raise ValueError(
  1030. "under LINEAR mode, scale_factor can only be single value"
  1031. )
  1032. assert len(scale_factor) == 2, "shape of scale_factor must be equal to (2, )"
  1033. assert isinstance(scale_factor[0], float) and isinstance(
  1034. scale_factor[1], float
  1035. ), "scale_factor must be float type"
  1036. dsize = tuple(
  1037. floor(
  1038. Tensor(
  1039. inp.shape[i + 2] * scale_factor[i],
  1040. dtype="float32",
  1041. device=inp.device,
  1042. )
  1043. )
  1044. for i in range(2)
  1045. )
  1046. dsize = concat([dsize[0], dsize[1]], axis=0)
  1047. else:
  1048. if scale_factor is not None:
  1049. raise ValueError("scale_factor must be None when size is provided")
  1050. if isinstance(size, int):
  1051. size = (size, 1)
  1052. else:
  1053. if mode == "LINEAR":
  1054. raise ValueError("under LINEAR mode, size can only be single value")
  1055. dsize = size
  1056. oh, ow = dsize[0], dsize[1]
  1057. ih, iw = inp.shape[2], inp.shape[3]
  1058. if align_corners:
  1059. hscale = (ih - 1.0) / (oh - 1.0)
  1060. wscale = 1.0 * iw / ow
  1061. if mode != "LINEAR":
  1062. wscale = (iw - 1.0) / (ow - 1.0)
  1063. row0 = concat(
  1064. [wscale, Tensor([0, 0], dtype="float32", device=inp.device)], axis=0
  1065. ).reshape(1, 3)
  1066. row1 = concat(
  1067. [
  1068. Tensor(0, dtype="float32", device=inp.device),
  1069. hscale,
  1070. Tensor(0, dtype="float32", device=inp.device),
  1071. ],
  1072. axis=0,
  1073. ).reshape(1, 3)
  1074. weight = concat(
  1075. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  1076. axis=0,
  1077. ).reshape(1, 3, 3)
  1078. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  1079. else:
  1080. hscale = 1.0 * ih / oh
  1081. wscale = 1.0 * iw / ow
  1082. row0 = concat(
  1083. [wscale, Tensor(0, dtype="float32", device=inp.device), 0.5 * wscale - 0.5],
  1084. axis=0,
  1085. ).reshape(1, 3)
  1086. row1 = concat(
  1087. [Tensor(0, dtype="float32", device=inp.device), hscale, 0.5 * hscale - 0.5],
  1088. axis=0,
  1089. ).reshape(1, 3)
  1090. weight = concat(
  1091. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  1092. axis=0,
  1093. ).reshape(1, 3, 3)
  1094. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  1095. weight = weight.astype("float32")
  1096. ret = warp_perspective(inp, weight, dsize, interp_mode="LINEAR")
  1097. if mode == "LINEAR":
  1098. ret = reshape(ret, ret.shape[0:3])
  1099. return ret
  1100. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1101. """
  1102. Returns a new tensor where each of the elements are randomly set to zero
  1103. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1104. :param inp: input tensor.
  1105. :param drop_prob: probability to drop (set to zero) a single element.
  1106. :param training: the default behavior of ``dropout`` during training is to rescale the output,
  1107. then it can be replaced by an :class:`~.Identity` during inference. Default: True
  1108. :return: the output tensor
  1109. Examples:
  1110. .. testcode::
  1111. import numpy as np
  1112. from megengine import tensor
  1113. import megengine.functional as F
  1114. x = tensor(np.ones(10, dtype=np.float32))
  1115. out = F.dropout(x, 1./3.)
  1116. print(out.numpy())
  1117. Outputs:
  1118. .. testoutput::
  1119. :options: +SKIP
  1120. [1.5 1.5 0. 1.5 1.5 1.5 1.5 1.5 1.5 1.5]
  1121. """
  1122. assert 0 <= drop_prob < 1
  1123. rv = uniform(size=inp.shape)
  1124. mask = rv > drop_prob
  1125. inp *= mask.astype(inp.dtype)
  1126. if training:
  1127. inp *= 1 / (1 - drop_prob)
  1128. return inp
  1129. def embedding(
  1130. inp: Tensor,
  1131. weight: Tensor,
  1132. padding_idx: Optional[int] = None,
  1133. max_norm: Optional[float] = None,
  1134. norm_type: Optional[float] = None,
  1135. ):
  1136. """
  1137. Applies lookup table for embedding.
  1138. :param inp: tensor with indices.
  1139. :param weight: learnable weights which embeds from.
  1140. :param padding_idx: should be set to None, not supported now.
  1141. :param max_norm: should be set to None, not supported now.
  1142. :param norm_type: should be set to None, not supported now.
  1143. :return: output tensor.
  1144. Refer to :class:`~.Embedding` for more information.
  1145. """
  1146. if padding_idx is not None:
  1147. raise ValueError("Not support padding_idx Now!")
  1148. if max_norm is not None or norm_type is not None:
  1149. raise ValueError("Not support weight normlization Now!")
  1150. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1151. return weight[inp.reshape(-1)].reshape(dest_shp)
  1152. def roi_pooling(
  1153. inp: Tensor,
  1154. rois: Tensor,
  1155. output_shape: Union[int, tuple, list],
  1156. mode: str = "max",
  1157. scale: float = 1.0,
  1158. ) -> Tensor:
  1159. """
  1160. Applies roi pooling on input feature.
  1161. :param inp: tensor that represents the input feature, `(N, C, H, W)` images.
  1162. :param rois: `(K, 5)` boxes. First column is the index into N. The other 4 columns are xyxy.
  1163. :param output_shape: `(height, width)` of output rois feature.
  1164. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "max"
  1165. :param scale: scale the input boxes by this number. Default: 1.0
  1166. :return: `(K, C, output_shape[0], output_shape[1])` feature of rois.
  1167. Examples:
  1168. .. testcode::
  1169. import numpy as np
  1170. from megengine import tensor
  1171. import megengine.functional as F
  1172. np.random.seed(42)
  1173. inp = tensor(np.random.randn(1, 1, 128, 128))
  1174. rois = tensor(np.random.random((4, 5)))
  1175. y = F.nn.roi_pooling(inp, rois, (2, 2))
  1176. print(y.numpy()[0].round(decimals=4))
  1177. Outputs:
  1178. .. testoutput::
  1179. [[[-0.1383 -0.1383]
  1180. [-0.5035 -0.5035]]]
  1181. """
  1182. assert mode in ["max", "average"], "only max/average mode is supported"
  1183. if isinstance(output_shape, int):
  1184. output_shape = (output_shape, output_shape)
  1185. op = builtin.ROIPooling(mode=mode, scale=scale)
  1186. inp, rois = utils.convert_inputs(inp, rois)
  1187. result, _ = apply(
  1188. op, inp, rois, Tensor(output_shape, dtype="int32", device=inp.device)
  1189. )
  1190. return result
  1191. def roi_align(
  1192. inp: Tensor,
  1193. rois: Tensor,
  1194. output_shape: Union[int, tuple, list],
  1195. mode: str = "average",
  1196. spatial_scale: float = 1.0,
  1197. sample_points: Union[int, tuple, list] = 2,
  1198. aligned: bool = True,
  1199. ) -> Tensor:
  1200. """
  1201. Applies roi align on input feature.
  1202. :param inp: tensor that represents the input feature, shape is `(N, C, H, W)`.
  1203. :param rois: `(N, 5)` boxes. First column is the box index. The other 4 columns are ``xyxy``.
  1204. :param output_shape: `(height, width)` shape of output rois feature.
  1205. :param mode: "max" or "average", use max/average align just like max/average pooling. Default: "average"
  1206. :param spatial_scale: scale the input boxes by this number. Default: 1.0
  1207. :param sample_points: number of inputs samples to take for each output sample.
  1208. 0 to take samples densely. Default: 2
  1209. :param aligned: wheather to align the input feature, with `aligned=True`,
  1210. we first appropriately scale the ROI and then shift it by -0.5. Default: True
  1211. :return: output tensor.
  1212. Examples:
  1213. .. testcode::
  1214. import numpy as np
  1215. from megengine import tensor
  1216. import megengine.functional as F
  1217. np.random.seed(42)
  1218. inp = tensor(np.random.randn(1, 1, 128, 128))
  1219. rois = tensor(np.random.random((4, 5)))
  1220. y = F.nn.roi_align(inp, rois, (2, 2))
  1221. print(y.numpy()[0].round(decimals=4))
  1222. Outputs:
  1223. .. testoutput::
  1224. [[[0.175 0.175 ]
  1225. [0.1359 0.1359]]]
  1226. """
  1227. assert mode in ["max", "average"], "only max/average mode is supported"
  1228. if isinstance(output_shape, int):
  1229. output_shape = (output_shape, output_shape)
  1230. pooled_height, pooled_width = output_shape
  1231. if isinstance(sample_points, int):
  1232. sample_points = (sample_points, sample_points)
  1233. sample_height, sample_width = sample_points
  1234. offset = 0.5 if aligned else 0.0
  1235. op = builtin.ROIAlign(
  1236. mode=mode,
  1237. format="NCHW",
  1238. spatial_scale=spatial_scale,
  1239. offset=offset,
  1240. pooled_height=pooled_height,
  1241. pooled_width=pooled_width,
  1242. sample_height=sample_height,
  1243. sample_width=sample_width,
  1244. )
  1245. inp, rois = utils.convert_inputs(inp, rois)
  1246. result, *_ = apply(op, inp, rois)
  1247. return result
  1248. def indexing_one_hot(
  1249. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1250. ) -> Tensor:
  1251. r"""
  1252. One-hot indexing for some axes.
  1253. :param src: input tensor.
  1254. :param index: index tensor.
  1255. :param axis: axis on src for which values in index index. Default: 1
  1256. :param keepdims: whether not to remove the axis in result. Default: False
  1257. :return: output tensor.
  1258. Examples:
  1259. .. testcode::
  1260. import megengine.functional as F
  1261. from megengine import tensor
  1262. src = tensor([[1.0, 2.0]])
  1263. index = tensor([0])
  1264. val = F.indexing_one_hot(src, index)
  1265. print(val.numpy())
  1266. Outputs:
  1267. .. testoutput::
  1268. [1.]
  1269. """
  1270. assert isinstance(
  1271. src, (TensorWrapperBase, TensorBase)
  1272. ), "src must be of Tensor type"
  1273. op = builtin.IndexingOneHot(axis=axis)
  1274. index = utils.convert_single_value(index, (src,), dtype="int32", device=src.device)
  1275. (result,) = apply(op, src, index)
  1276. if not keepdims:
  1277. result = squeeze(result, axis)
  1278. return result
  1279. def nms(
  1280. boxes: Tensor, scores: Tensor, iou_thresh: float, max_output: Optional[int] = None
  1281. ) -> Tensor:
  1282. r"""
  1283. Performs non-maximum suppression (NMS) on the boxes according to their intersection-over-union(IoU).
  1284. :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.
  1285. :param iou_thresh: IoU threshold for overlapping.
  1286. :param scores: tensor of shape `(N,)`, the score of boxes.
  1287. :param max_output: the maximum number of boxes to keep; it is optional if this operator is not traced
  1288. otherwise it required to be specified; if it is not specified, all boxes are kept.
  1289. :return: indices of the elements that have been kept by NMS.
  1290. Examples:
  1291. .. testcode::
  1292. import numpy as np
  1293. from megengine import tensor
  1294. import megengine.functional as F
  1295. x = np.zeros((100,4))
  1296. np.random.seed(42)
  1297. x[:,:2] = np.random.rand(100,2)*20
  1298. x[:,2:] = np.random.rand(100,2)*20 + 100
  1299. scores = tensor(np.random.rand(100))
  1300. inp = tensor(x)
  1301. result = F.nn.nms(inp, scores, iou_thresh=0.7)
  1302. print(result.numpy())
  1303. Outputs:
  1304. .. testoutput::
  1305. [75 69]
  1306. """
  1307. assert (
  1308. boxes.ndim == 2 and boxes.shape[1] == 4
  1309. ), "the expected shape of boxes is (N, 4)"
  1310. assert scores.ndim == 1, "the expected shape of scores is (N,)"
  1311. assert (
  1312. boxes.shape[0] == scores.shape[0]
  1313. ), "number of boxes and scores are not matched"
  1314. boxes = boxes.detach()
  1315. scores = scores.detach()
  1316. sorted_idx = argsort(scores, descending=True)
  1317. boxes = boxes[sorted_idx]
  1318. if is_tracing():
  1319. assert (
  1320. max_output is not None and max_output > 0
  1321. ), "max_output should be specified under tracing"
  1322. if max_output is None:
  1323. max_output = boxes.shape[0]
  1324. op = builtin.NMSKeep(iou_thresh, max_output)
  1325. inp = utils.convert_inputs(boxes.reshape(1, -1, 4))
  1326. indices, count = apply(op, *inp)
  1327. indices = indices[0][: count[0]]
  1328. keep_inds = sorted_idx[indices]
  1329. return keep_inds
  1330. def nvof(src: Tensor, precision: int = 1) -> Tensor:
  1331. r"""
  1332. Implements NVIDIA Optical Flow SDK.
  1333. :src shape: input tensor with shape (n, t, h, w, c4).
  1334. :src dtype: uint8.
  1335. :param precision: 0:NV_OF_PERF_LEVEL_SLOW 1:NV_OF_PERF_LEVEL_MEDIUM 2:NV_OF_PERF_LEVEL_FAST.
  1336. :output shape: (n, t-1, h//4, w//4, c2).
  1337. :output dtype: int16.
  1338. .. code-block:: python
  1339. import numpy as np
  1340. from megengine import tensor
  1341. import megengine.functional as F
  1342. x = np.random.random_integers(0, 255, (1,2,224,244,4)).astype("uint8")
  1343. src = tensor(x)
  1344. result = F.nn.nvof(src, precision=1)
  1345. print(result.numpy())
  1346. """
  1347. assert isinstance(src, (Tensor, megbrain_graph.VarNode)), "src must be Tensor type"
  1348. assert src.ndim == 5 and src.shape[4] == 4
  1349. src = src.detach()
  1350. op = builtin.NvOf(precision=precision)
  1351. return apply(op, src)[0]
  1352. from .loss import * # isort:skip
  1353. from .quantized import conv_bias_activation # isort:skip

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