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

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

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