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

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