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

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

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