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

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