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

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

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