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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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. @lru_cache(maxsize=None)
  669. def _get_hsigmoid_op(dtype=None, device=None):
  670. @subgraph_fn(
  671. "Hsigmoid",
  672. dtype=dtype,
  673. device=device,
  674. nr_inputs=1,
  675. jit_fusion=True,
  676. custom_grad=True,
  677. )
  678. def hsigmoid(inputs, f, c):
  679. (inp,) = inputs[0:1]
  680. inp = f("+", inp, c(3))
  681. max_0 = f("max", inp, c(0))
  682. min_6 = f("min", max_0, c(6))
  683. oup = f("/", min_6, c(6))
  684. (oup_grad,) = yield (oup,)
  685. inp_grad = f("/", oup_grad, c(6))
  686. inp_grad = f("cond_leq_mov", max_0, c(6), inp_grad)
  687. inp_grad = f("cond_leq_mov", c(0), inp, inp_grad)
  688. yield (inp_grad,)
  689. return hsigmoid
  690. def hsigmoid(x):
  691. r"""Element-wise `relu6(x + 3) / 6`."""
  692. hsigmoid = _get_hsigmoid_op(x.dtype, x.device)
  693. (x,) = hsigmoid(x)
  694. return x
  695. # return relu6(x + 3) / 6
  696. def relu(x):
  697. r"""Element-wise `max(x, 0)`."""
  698. return _elwise(x, mode=Elemwise.Mode.RELU)
  699. @lru_cache(maxsize=None)
  700. def _get_relu6_op(dtype=None, device=None):
  701. @subgraph_fn(
  702. "ReLU6",
  703. dtype=dtype,
  704. device=device,
  705. nr_inputs=1,
  706. jit_fusion=True,
  707. custom_grad=True,
  708. )
  709. def relu6(inputs, f, c):
  710. (inp,) = inputs[0:1]
  711. max_0 = f("max", inp, c(0))
  712. min_6 = f("min", max_0, c(6))
  713. oup = min_6
  714. (oup_grad,) = yield (oup,)
  715. inp_grad = f("cond_leq_mov", max_0, c(6), oup_grad)
  716. inp_grad = f("cond_leq_mov", c(0), inp, inp_grad)
  717. yield (inp_grad,)
  718. return relu6
  719. def relu6(x):
  720. r"""Element-wise `min(max(x, 0), 6)`."""
  721. relu6 = _get_relu6_op(x.dtype, x.device)
  722. (x,) = relu6(x)
  723. return x
  724. @lru_cache(maxsize=None)
  725. def _get_prelu_op(dtype=None, device=None):
  726. @subgraph_fn(
  727. "PReLU",
  728. dtype=dtype,
  729. device=device,
  730. nr_inputs=2,
  731. jit_fusion=True,
  732. custom_grad=True,
  733. )
  734. def prelu(inputs, f, c):
  735. (inp, weight) = inputs[0:2]
  736. max_0 = f("max", inp, c(0))
  737. min_0 = f("min", inp, c(0))
  738. oup = f("fma3", min_0, weight, max_0)
  739. (oup_grad,) = yield (oup,)
  740. inp_grad_0 = f("cond_leq_mov", c(0), inp, oup_grad)
  741. inp_grad_1 = f("*", oup_grad, weight)
  742. inp_grad_1 = f("cond_leq_mov", inp, c(0), inp_grad_1)
  743. inp_grad = f("+", inp_grad_0, inp_grad_1)
  744. weight_grad = f("*", oup_grad, min_0)
  745. yield (inp_grad, weight_grad)
  746. return prelu
  747. def prelu(inp: Tensor, weight: Tensor) -> Tensor:
  748. r"""Element-wise PReLU function.
  749. Refer to :class:`~.PReLU` for more information.
  750. """
  751. prelu = _get_prelu_op(dtype=inp.dtype, device=inp.device)
  752. (oup,) = prelu(inp, broadcast_to(weight, inp.shape))
  753. return oup
  754. @lru_cache(maxsize=None)
  755. def _get_leaky_relu_op(negative_slope, *, dtype=None, device=None):
  756. @subgraph_fn(
  757. "LeakyReLU",
  758. dtype=dtype,
  759. device=device,
  760. nr_inputs=1,
  761. jit_fusion=True,
  762. custom_grad=True,
  763. )
  764. def leakyReLU(inputs, f, c):
  765. (inp,) = inputs[0:1]
  766. max_0 = f("max", inp, c(0))
  767. min_0 = f("min", inp, c(0))
  768. oup = f("+", max_0, f("*", min_0, c(negative_slope)))
  769. (oup_grad,) = yield (oup,)
  770. inp_grad_0 = f("cond_leq_mov", c(0), inp, oup_grad)
  771. inp_grad_1 = f("*", oup_grad, c(negative_slope))
  772. inp_grad_1 = f("cond_leq_mov", inp, c(0), inp_grad_1)
  773. inp_grad = f("+", inp_grad_0, inp_grad_1)
  774. yield (inp_grad,)
  775. return leakyReLU
  776. def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
  777. r"""Element-wise LeakyReLU function
  778. Refer to :class:`~.LeakyReLU` for more information.
  779. """
  780. leakyReLU = _get_leaky_relu_op(negative_slope, dtype=inp.dtype, device=inp.device)
  781. (oup,) = leakyReLU(inp)
  782. return oup
  783. def silu(x):
  784. r"""Applies the element-wise Sigmoid Linear Unit function, i.e. `x * sigmoid(x)`."""
  785. return _elwise(x, mode=Elemwise.Mode.SILU)
  786. def gelu(x):
  787. r"""Applies the element-wise function:
  788. .. math::
  789. \text{gelu}(x) = x\Phi(x)
  790. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  791. """
  792. return _elwise(x, mode=Elemwise.Mode.GELU)
  793. @lru_cache(maxsize=None)
  794. def _get_softplus_op(dtype=None, device=None):
  795. @subgraph_fn(
  796. "Softplus",
  797. dtype=dtype,
  798. device=device,
  799. nr_inputs=1,
  800. jit_fusion=True,
  801. custom_grad=True,
  802. )
  803. def softplus(inputs, f, c):
  804. (inp,) = inputs[0:1]
  805. neg_abs = f("-", f("abs", inp))
  806. exp = f("exp", neg_abs)
  807. oup0 = f("log1p", exp)
  808. oup1 = f("relu", inp)
  809. oup = f("+", oup0, oup1)
  810. (oup_grad,) = yield (oup,)
  811. inp_grad_0 = f("switch_gt0", oup1, oup_grad)
  812. inp_grad_1 = oup_grad
  813. inp_grad_1 = f("/", oup_grad, f("+", exp, c(1)))
  814. inp_grad_1 = f("*", inp_grad_1, exp)
  815. inp_grad_1 = f("-", inp_grad_1)
  816. inp_grad_1 = f("abs_grad", inp, inp_grad_1)
  817. inp_grad = f("+", inp_grad_0, inp_grad_1)
  818. yield (inp_grad,)
  819. return softplus
  820. def softplus(inp: Tensor) -> Tensor:
  821. r"""Applies the element-wise function:
  822. .. math::
  823. \text{softplus}(x) = \log(1 + \exp(x))
  824. softplus is a smooth approximation to the ReLU function and can be used
  825. to constrain the output to be always positive.
  826. For numerical stability the implementation follows this transformation:
  827. .. math::
  828. \text{softplus}(x) = \log(1 + \exp(x))
  829. = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
  830. = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)
  831. Examples:
  832. >>> import numpy as np
  833. >>> x = Tensor(np.arange(-3, 3, dtype=np.float32))
  834. >>> y = F.softplus(x)
  835. >>> y.numpy().round(decimals=4)
  836. array([0.0486, 0.1269, 0.3133, 0.6931, 1.3133, 2.1269], dtype=float32)
  837. """
  838. softplus = _get_softplus_op(inp.dtype, inp.device)
  839. (oup,) = softplus(inp)
  840. return oup
  841. def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
  842. r"""Applies the :math:`\log(\text{softmax}(x))` function to an n-dimensional
  843. input tensor. The :math:`\text{logsoftmax}(x)` formulation can be simplified as:
  844. .. math::
  845. \text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )
  846. For numerical stability the implementation follows this transformation:
  847. .. math::
  848. \text{logsoftmax}(x)
  849. = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
  850. = x - \log (\sum_{i}(\exp (x_{i})))
  851. = x - \text{logsumexp}(x)
  852. Examples:
  853. >>> import numpy as np
  854. >>> x = Tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  855. >>> y = F.logsoftmax(x, axis=1)
  856. >>> y.numpy().round(decimals=4)
  857. array([[-4.4519, -3.4519, -2.4519, -1.4519, -0.4519],
  858. [-4.4519, -3.4519, -2.4519, -1.4519, -0.4519]], dtype=float32)
  859. """
  860. return inp - logsumexp(inp, axis, keepdims=True)
  861. @lru_cache(maxsize=None)
  862. def _get_logsigmoid_op(dtype=None, device=None):
  863. @subgraph_fn(
  864. "LogSigmoid",
  865. dtype=dtype,
  866. device=device,
  867. nr_inputs=1,
  868. jit_fusion=True,
  869. custom_grad=True,
  870. )
  871. def logsigmoid(inputs, f, c):
  872. (inp,) = inputs[0:1]
  873. neg_abs = f("-", f("abs", inp))
  874. exp = f("exp", neg_abs)
  875. oup0 = f("log1p", exp)
  876. oup1 = f("relu", f("-", inp))
  877. oup = f("+", oup0, oup1)
  878. oup = f("-", oup)
  879. (oup_grad,) = yield (oup,)
  880. oup_grad = f("-", oup_grad)
  881. inp_grad_0 = f("switch_gt0", oup1, oup_grad)
  882. inp_grad_0 = f("-", inp_grad_0)
  883. inp_grad_1 = oup_grad
  884. inp_grad_1 = f("/", inp_grad_1, f("+", exp, c(1)))
  885. inp_grad_1 = f("*", inp_grad_1, exp)
  886. inp_grad_1 = f("-", inp_grad_1)
  887. inp_grad_1 = f("abs_grad", inp, inp_grad_1)
  888. inp_grad = f("+", inp_grad_0, inp_grad_1)
  889. yield (inp_grad,)
  890. return logsigmoid
  891. def logsigmoid(inp: Tensor) -> Tensor:
  892. r"""Applies the element-wise function:
  893. .. math::
  894. \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
  895. = \log(1/(1 + \exp(-x)))
  896. = - \log(1 + \exp(-x))
  897. = - \text{softplus}(-x)
  898. Examples:
  899. >>> import numpy as np
  900. >>> x = Tensor(np.arange(-5, 5, dtype=np.float32))
  901. >>> y = F.logsigmoid(x)
  902. >>> y.numpy().round(decimals=4)
  903. array([-5.0067, -4.0182, -3.0486, -2.1269, -1.3133, -0.6931, -0.3133,
  904. -0.1269, -0.0486, -0.0181], dtype=float32)
  905. """
  906. logsigmoid = _get_logsigmoid_op(inp.dtype, inp.device)
  907. (oup,) = logsigmoid(inp)
  908. return oup
  909. def logsumexp(
  910. inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
  911. ) -> Tensor:
  912. r"""Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.
  913. .. math::
  914. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  915. For numerical stability, the implementation follows this transformation:
  916. .. math::
  917. \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
  918. = \text{logsumexp}(x)=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)
  919. where
  920. .. math::
  921. b = \max(x_j)
  922. Examples:
  923. >>> import numpy as np
  924. >>> x = Tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  925. >>> y = F.logsumexp(x, axis=1, keepdims=False)
  926. >>> y.numpy().round(decimals=4)
  927. array([-0.5481, 4.4519], dtype=float32)
  928. """
  929. max_value = max(inp.detach(), axis, keepdims=True)
  930. if keepdims:
  931. return max_value + log(sum(exp(inp - max_value), axis, keepdims))
  932. else:
  933. return squeeze(max_value, axis=None) + log(
  934. sum(exp(inp - max_value), axis, keepdims)
  935. )
  936. def _get_softmax_axis(ndim: int) -> int:
  937. if ndim in (0, 1, 3):
  938. return 0
  939. return 1
  940. def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
  941. r"""Applies a :math:`\text{softmax}(x)` function. :math:`\text{softmax}(x)` is defined as:
  942. .. math::
  943. \text{softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
  944. It is applied to all elements along axis, and rescales elements so that
  945. they stay in the range `[0, 1]` and sum to 1.
  946. See :class:`~.module.Softmax` for more details.
  947. Examples:
  948. >>> import numpy as np
  949. >>> x = Tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
  950. >>> out = F.softmax(x)
  951. >>> out.numpy().round(decimals=4)
  952. array([[0.0117, 0.0317, 0.0861, 0.2341, 0.6364],
  953. [0.0117, 0.0317, 0.0861, 0.2341, 0.6364]], dtype=float32)
  954. """
  955. if axis is None:
  956. axis = _get_softmax_axis(len(inp.shape))
  957. if isinstance(axis, list):
  958. offset = inp.max(axis=axis, keepdims=True).detach()
  959. cached = exp(inp - offset)
  960. down = sum(cached, axis=axis, keepdims=True)
  961. return cached / down
  962. else:
  963. op = builtin.Softmax(axis=axis,)
  964. (output,) = apply(op, inp)
  965. return output
  966. def layer_norm(
  967. inp: Tensor,
  968. normalized_shape: tuple,
  969. affine: bool,
  970. weight: Optional[Tensor] = None,
  971. bias: Optional[Tensor] = None,
  972. eps: float = 1e-5,
  973. ):
  974. r"""Applies layer normalization to the input. Support tensor of any shape as input.
  975. Reference: https://arxiv.org/pdf/1803.08494.pdf.
  976. Args:
  977. inp: input tensor.
  978. normalized_shape: the shape that you want to be normalizated
  979. affine: whether to use weight and bias
  980. weight: must not be None when the affine is true
  981. bias: must not be None when the affine is true
  982. eps: a value added to the denominator for numerical stability. Default: 1e-5
  983. """
  984. if isinstance(normalized_shape, int):
  985. normalized_shape = [normalized_shape]
  986. normalized_dim = len(normalized_shape)
  987. assert normalized_dim > 0
  988. normalized_size = 1
  989. for i in range(normalized_dim):
  990. normalized_size = normalized_size * normalized_shape[i]
  991. op = builtin.LayerNorm(
  992. affine=affine,
  993. eps=eps,
  994. normalized_dim=normalized_dim,
  995. normalized_size=normalized_size,
  996. )
  997. if affine:
  998. assert weight is not None and bias is not None
  999. return apply(op, inp, weight, bias)[0]
  1000. else:
  1001. # assert weight is None and bias is None
  1002. return apply(op, inp)[0]
  1003. def batch_norm(
  1004. inp: Tensor,
  1005. running_mean: Tensor = None,
  1006. running_var: Tensor = None,
  1007. weight: Optional[Tensor] = None,
  1008. bias: Optional[Tensor] = None,
  1009. *,
  1010. training: bool = False,
  1011. momentum: float = 0.9,
  1012. eps: float = 1e-5,
  1013. inplace: bool = True,
  1014. ):
  1015. r"""Applies batch normalization to the input.
  1016. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  1017. Args:
  1018. inp: input tensor.
  1019. running_mean: tensor to store running mean.
  1020. running_var: tensor to store running variance.
  1021. weight: scaling tensor in the learnable affine parameters.
  1022. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  1023. bias: bias tensor in the learnable affine parameters.
  1024. See :math:`\beta` in :class:`~.BatchNorm2d`.
  1025. training: a boolean value to indicate whether batch norm is performed
  1026. in training mode. Default: False
  1027. momentum: value used for the ``running_mean`` and ``running_var``
  1028. computation. Default: 0.9
  1029. eps: a value added to the denominator for numerical stability. Default: 1e-5
  1030. inplace: whether to update ``running_mean`` and ``running_var``
  1031. inplace or return new tensors. Default: True
  1032. """
  1033. def make_full_if_none(x, value):
  1034. x_ndim = None if x is None else x.ndim
  1035. # in general case, x will be returned here directly
  1036. if x_ndim is not None and x_ndim != 1:
  1037. return x
  1038. C = inp.shape[1]
  1039. pshape = (1, C, 1, 1)
  1040. if x is None:
  1041. x = Const(value, inp.dtype, inp.device)
  1042. shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
  1043. (result,) = apply(builtin.Broadcast(), x, shape)
  1044. result.format = inp.format
  1045. return result
  1046. else:
  1047. assert x_ndim == 1
  1048. shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
  1049. (result,) = apply(builtin.Reshape(), x, shape)
  1050. return result
  1051. has_mean = running_mean is not None
  1052. has_var = running_var is not None
  1053. if not training:
  1054. assert has_mean, "running_mean must be provided in inference mode"
  1055. assert has_var, "running_var must be provided in inference mode"
  1056. weight = make_full_if_none(weight, 1)
  1057. bias = make_full_if_none(bias, 0)
  1058. if not training:
  1059. op = builtin.BatchNorm(
  1060. fwd_mode=BatchNorm.FwdMode.INFERENCE, epsilon=eps, param_dim="dim_1c11"
  1061. )
  1062. ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
  1063. return ret
  1064. else:
  1065. op = builtin.BatchNorm(
  1066. avg_factor=1 - momentum, epsilon=eps, param_dim="dim_1c11"
  1067. )
  1068. if has_mean or has_var:
  1069. running_mean = make_full_if_none(running_mean, 0)
  1070. running_var = make_full_if_none(running_var, 1)
  1071. new_mean, new_var, *_, inp = apply(
  1072. op, inp, weight, bias, running_mean, running_var
  1073. )
  1074. if not has_mean:
  1075. new_mean = None
  1076. if not has_var:
  1077. new_var = None
  1078. if inplace:
  1079. if has_mean:
  1080. running_mean[...] = new_mean
  1081. if has_var:
  1082. running_var[...] = new_var
  1083. return inp
  1084. else:
  1085. return inp, new_mean, new_var
  1086. else:
  1087. inp = apply(op, inp, weight, bias)[-1]
  1088. return inp
  1089. @lru_cache(maxsize=None)
  1090. def _get_sync_bn_ops(device, dtype, eps_mode, ndim, channels):
  1091. # fmt: off
  1092. @subgraph("SyncBnStage0", dtype, device, 1)
  1093. def syncbn_stage0(inputs, f, c):
  1094. input = inputs[0]
  1095. reduce_shape = c((1, channels) + (1,) * (ndim - 2), dtype="int32", device=device)
  1096. input_shape = f(GetVarShape(), input)
  1097. input_elems = f(Reduce(mode="product", axis=0), input_shape)
  1098. reduce_elems = f(Reduce(mode="product", axis=0), reduce_shape)
  1099. reduce_size = f("//", input_elems, reduce_elems)
  1100. channel_x1s = f(Reduce(mode="sum"), input, reduce_shape)
  1101. channel_x2s = f(Reduce(mode="sum_sqr"), input, reduce_shape)
  1102. reduce_size_f = f(TypeCvt(dtype=dtype), reduce_size)
  1103. return (reduce_shape, reduce_size_f, channel_x1s, channel_x2s), (False, False, True, True)
  1104. @subgraph("SyncBnStage1", dtype, device, 7)
  1105. def syncbn_stage1(inputs, f, c):
  1106. input, reduce_size, channel_x1s, channel_x2s, eps = inputs[0:5]
  1107. weight, bias = inputs[5:7]
  1108. channel_mean = f("/", channel_x1s, reduce_size)
  1109. channel_var =\
  1110. f("+", f("/", f("**", channel_x1s, c(2)),
  1111. f("-", f("*", reduce_size, reduce_size))),
  1112. f("/", channel_x2s, reduce_size))
  1113. invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
  1114. inv_var_wt = f("*", invsqrt_channel_var, weight)
  1115. neg_channel_mean = f("-", channel_mean)
  1116. outvar =\
  1117. f("fma3", input, inv_var_wt,
  1118. f("+", f("*", neg_channel_mean, inv_var_wt),
  1119. bias))
  1120. return (outvar, channel_mean, channel_var), (True, True, True)
  1121. @subgraph("SyncBnStage1Inference", dtype, device, 6)
  1122. def syncbn_stage1_inference(inputs, f, c):
  1123. input, channel_mean, channel_var, eps = inputs[0:4]
  1124. weight, bias = inputs[4:6]
  1125. invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
  1126. inv_var_wt = f("*", invsqrt_channel_var, weight)
  1127. neg_channel_mean = f("-", channel_mean)
  1128. outvar =\
  1129. f("+", f("*", input, inv_var_wt),
  1130. f("+", f("*", neg_channel_mean, inv_var_wt),
  1131. bias))
  1132. return (outvar,), (True,)
  1133. @subgraph("SyncBnStage2", dtype, device, 7)
  1134. def syncbn_stage2(inputs, f, c):
  1135. running_mean, running_var, momentum = inputs[0:3]
  1136. reduce_size, channel_x1s, channel_x2s, channel_mean = inputs[3:7]
  1137. c1_minus_momentum = f("-", c(1), momentum)
  1138. reduce_size_minus_c1 = f("-", reduce_size, c(1))
  1139. running_mean = f("fma4",
  1140. running_mean, momentum,
  1141. c1_minus_momentum, channel_mean,
  1142. )
  1143. channel_variance_unbiased =\
  1144. f("+", f("/", f("**", channel_x1s, c(2)),
  1145. f("*", f("-", reduce_size),
  1146. reduce_size_minus_c1)),
  1147. f("/", channel_x2s,
  1148. reduce_size_minus_c1))
  1149. running_var = f("fma4",
  1150. running_var, momentum,
  1151. c1_minus_momentum, channel_variance_unbiased
  1152. )
  1153. return (running_mean, running_var), (True, True)
  1154. @subgraph("SyncBnConcatStats", dtype, device, 3)
  1155. def syncbn_concat_stats(inputs, f, c):
  1156. reduce_size, channel_x1s, channel_x2s = inputs[0:3]
  1157. reduce_size = f(builtin.Broadcast(), reduce_size, c([1]*ndim, dtype="int32"))
  1158. stats = f(builtin.Concat(axis=1, comp_node=device), reduce_size, channel_x1s, channel_x2s)
  1159. return (stats,), (True,)
  1160. @subgraph("SyncBnSplitStats", dtype, device, 1)
  1161. def syncbn_split_stats(inputs, f, c):
  1162. stats = inputs[0]
  1163. c_1 = c(1, dtype="int32")
  1164. channel_x1s_end = c(channels+1, dtype="int32")
  1165. def _subtensor(src, axis, begin, end):
  1166. items = (axis, (begin is not None), (end is not None), False, False),
  1167. args = ()
  1168. if begin is not None:
  1169. args += begin,
  1170. if end is not None:
  1171. args += end,
  1172. return f(builtin.Subtensor(items=items), src, *args)
  1173. reduce_size = _subtensor(stats, 1, None, c_1)
  1174. channel_x1s = _subtensor(stats, 1, c_1, channel_x1s_end)
  1175. channel_x2s = _subtensor(stats, 1, channel_x1s_end, None)
  1176. reduce_size = f(builtin.Reshape(), reduce_size, c_1)
  1177. return (reduce_size, channel_x1s, channel_x2s), (False, True, True)
  1178. # fmt: on
  1179. return (
  1180. syncbn_stage0,
  1181. syncbn_stage1,
  1182. syncbn_stage1_inference,
  1183. syncbn_stage2,
  1184. syncbn_concat_stats,
  1185. syncbn_split_stats,
  1186. )
  1187. def sync_batch_norm(
  1188. inp: Tensor,
  1189. running_mean: Tensor,
  1190. running_var: Tensor,
  1191. weight: Optional[Tensor] = None,
  1192. bias: Optional[Tensor] = None,
  1193. training: bool = False,
  1194. momentum: Union[float, Tensor] = 0.9,
  1195. eps: float = 1e-5,
  1196. eps_mode="additive",
  1197. group=WORLD,
  1198. ) -> Tensor:
  1199. r"""Applies synchronized batch normalization to the input.
  1200. Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.
  1201. Args:
  1202. inp: input tensor.
  1203. running_mean: tensor to store running mean.
  1204. running_var: tensor to store running variance.
  1205. weight: scaling tensor in the learnable affine parameters.
  1206. See :math:`\gamma` in :class:`~.BatchNorm2d`.
  1207. bias: bias tensor in the learnable affine parameters.
  1208. See :math:`\beta` in :class:`~.BatchNorm2d`.
  1209. training: a boolean value to indicate whether batch norm is performed
  1210. in traning mode. Default: False
  1211. momentum: value used for the ``running_mean`` and ``running_var``
  1212. computation. Default: 0.9
  1213. eps: a value added to the denominator for numerical stability.
  1214. Default: 1e-5
  1215. eps_mode: mode of calculation for eps, "max" or "additive".
  1216. Default: "additive"
  1217. group: communication group, caculate mean and variance between this group.
  1218. Default: :obj:`~megengine.distributed.WORLD`
  1219. """
  1220. _eps_mode = eps_mode.lower()
  1221. assert _eps_mode in {"max", "additive"}, "unknown eps_mode: {}".format(eps_mode)
  1222. if _eps_mode == "additive" and not (is_distributed() and training):
  1223. return batch_norm(
  1224. inp,
  1225. running_mean,
  1226. running_var,
  1227. weight,
  1228. bias,
  1229. training=training,
  1230. momentum=momentum,
  1231. eps=eps,
  1232. )
  1233. if amp._enabled:
  1234. inp, weight, bias, running_mean, running_var = cast_tensors(
  1235. inp, weight, bias, running_mean, running_var, promote=True
  1236. )
  1237. _channels = make_shape_tuple(inp.shape)[1]
  1238. _ndim = inp.ndim
  1239. _device = inp.device
  1240. _dtype = inp.dtype
  1241. if _ndim != 4:
  1242. raise NotImplementedError("sync_batch_norm for ndim != 4")
  1243. def _make_full_if_none(x, value):
  1244. if x is None:
  1245. x = Const(value, inp.dtype, _device)
  1246. (result,) = apply(builtin.Broadcast(), x, reduce_shape)
  1247. return result
  1248. elif x.ndim == 1:
  1249. (result,) = apply(builtin.Reshape(), x, reduce_shape)
  1250. return result
  1251. return x
  1252. (
  1253. syncbn_stage0,
  1254. syncbn_stage1,
  1255. syncbn_stage1_inference,
  1256. syncbn_stage2,
  1257. syncbn_concat_stats,
  1258. syncbn_split_stats,
  1259. ) = _get_sync_bn_ops(_device, _dtype, eps_mode, _ndim, _channels)
  1260. reduce_shape, reduce_size, channel_x1s, channel_x2s = apply(syncbn_stage0(), inp)
  1261. eps = convert_single_value(eps, dtype=inp.dtype, device=inp.device)
  1262. weight = _make_full_if_none(weight, 1)
  1263. bias = _make_full_if_none(bias, 0)
  1264. if training:
  1265. if is_distributed():
  1266. # reduce all nodes' data to calculate mean and variance
  1267. (stat,) = apply(
  1268. syncbn_concat_stats(), reduce_size, channel_x1s, channel_x2s
  1269. )
  1270. stat = all_reduce_sum(stat, group)
  1271. reduce_size, channel_x1s, channel_x2s = apply(syncbn_split_stats(), stat)
  1272. outvar, channel_mean, *_ = apply(
  1273. syncbn_stage1(),
  1274. inp,
  1275. reduce_size,
  1276. channel_x1s,
  1277. channel_x2s,
  1278. eps,
  1279. weight,
  1280. bias,
  1281. )
  1282. else:
  1283. assert running_var is not None and running_mean is not None
  1284. channel_mean = running_mean
  1285. channel_var = running_var
  1286. outvar, *_ = apply(
  1287. syncbn_stage1_inference(), inp, channel_mean, channel_var, eps, weight, bias
  1288. )
  1289. # outvar = output * weight + bias
  1290. # where output = inp * invsqrt_channel_variance + (
  1291. # -channel_mean * invsqrt_channel_variance
  1292. # )
  1293. # Manually expand output for gopt
  1294. if training and running_var is not None and running_mean is not None:
  1295. momentum = convert_single_value(momentum, dtype=inp.dtype, device=inp.device)
  1296. running_mean[...], running_var[...] = apply(
  1297. syncbn_stage2(),
  1298. running_mean,
  1299. running_var,
  1300. momentum,
  1301. reduce_size,
  1302. channel_x1s,
  1303. channel_x2s,
  1304. channel_mean,
  1305. )
  1306. if amp._enabled:
  1307. outvar = outvar.astype("float16")
  1308. return outvar
  1309. def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
  1310. r"""Returns a new tensor where each of the elements are randomly set to zero
  1311. with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.
  1312. Args:
  1313. inp: input tensor.
  1314. drop_prob: probability to drop (set to zero) a single element.
  1315. training: the default behavior of ``dropout`` during training is to rescale the output,
  1316. then it can be replaced by an :class:`~.module.identify.Identity` during inference. Default: True
  1317. Returns:
  1318. the ouput tensor
  1319. Examples:
  1320. >>> import numpy as np
  1321. >>> data = Tensor(np.ones(10000000, dtype=np.float32))
  1322. >>> out = F.nn.dropout(data, 1.0 / 3.0, training=True)
  1323. >>> assert not out.numpy().all()
  1324. >>> out = F.nn.dropout(data, 1.0 / 3.0, training=False)
  1325. >>> assert out.numpy().all()
  1326. >>> out.numpy()
  1327. array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)
  1328. """
  1329. assert 0 <= drop_prob < 1
  1330. if not training or drop_prob == 0:
  1331. return inp
  1332. # model in training mode, e.g. model.train()
  1333. op = Dropout(drop_prob=drop_prob, seed=_get_global_rng_seed(), handle=0)
  1334. outputs = apply(op, inp)
  1335. return outputs[0]
  1336. def one_hot(inp: Tensor, num_classes: int) -> Tensor:
  1337. r"""Performs one-hot encoding for the input tensor.
  1338. Args:
  1339. inp: input tensor.
  1340. num_classes: number of classes denotes the last dimension of the output tensor.
  1341. Examples:
  1342. >>> import numpy as np
  1343. >>> x = Tensor(np.arange(1, 4, dtype=np.int32))
  1344. >>> F.one_hot(x, num_classes=4)
  1345. Tensor([[0 1 0 0]
  1346. [0 0 1 0]
  1347. [0 0 0 1]], dtype=int32, device=xpux:0)
  1348. """
  1349. zeros_tensor = zeros(
  1350. list(inp.shape) + [num_classes], dtype=inp.dtype, device=inp.device
  1351. )
  1352. ones_tensor = ones(list(inp.shape) + [1], dtype=inp.dtype, device=inp.device)
  1353. op = builtin.IndexingSetOneHot(axis=inp.ndim)
  1354. (result,) = apply(op, zeros_tensor, inp, ones_tensor)
  1355. return result
  1356. def embedding(
  1357. inp: Tensor,
  1358. weight: Tensor,
  1359. padding_idx: Optional[int] = None,
  1360. max_norm: Optional[float] = None,
  1361. norm_type: Optional[float] = None,
  1362. ):
  1363. r"""Applies lookup table for embedding.
  1364. Args:
  1365. inp: tensor with indices.
  1366. weight: learnable weights which embeds from.
  1367. padding_idx: should be set to None, not supported now.
  1368. max_norm: should be set to None, not supported now.
  1369. norm_type: should be set to None, not supported now.
  1370. Refer to :class:`~.module.Embedding` for more information.
  1371. """
  1372. if padding_idx is not None:
  1373. raise ValueError("Not support padding_idx Now!")
  1374. if max_norm is not None or norm_type is not None:
  1375. raise ValueError("Not support weight normlization Now!")
  1376. dest_shp = list(inp.shape) + [weight.shape[-1]]
  1377. return weight[inp.reshape(-1)].reshape(dest_shp)
  1378. def indexing_one_hot(
  1379. src: Tensor, index: Tensor, axis: int = 1, keepdims=False
  1380. ) -> Tensor:
  1381. r"""One-hot indexing for some axes.
  1382. Args:
  1383. src: input tensor.
  1384. index: index tensor.
  1385. axis: axis on src for which values in index index. Default: 1
  1386. keepdims: whether not to remove the axis in result. Default: False
  1387. Examples:
  1388. >>> src = Tensor([[1.0, 2.0]])
  1389. >>> index = Tensor([0])
  1390. >>> val = F.indexing_one_hot(src, index)
  1391. >>> val.numpy()
  1392. array([1.], dtype=float32)
  1393. """
  1394. assert isinstance(src, Tensor), "src must be of Tensor type"
  1395. op = builtin.IndexingOneHot(axis=axis)
  1396. index = convert_single_value(index, dtype="int32", device=src.device)
  1397. (result,) = apply(op, src, index)
  1398. if not keepdims:
  1399. result = squeeze(result, axis)
  1400. return result
  1401. def sliding_window(
  1402. inp: Tensor,
  1403. kernel_size: Union[int, Tuple[int, int]],
  1404. padding: Union[int, Tuple[int, int]] = 0,
  1405. stride: Union[int, Tuple[int, int]] = 1,
  1406. dilation: Union[int, Tuple[int, int]] = 1,
  1407. ) -> Tensor:
  1408. r"""Extracts sliding local blocks from a batched input tensor.
  1409. Refer to :class:`~.module.sliding_window.SlidingWindow` for more information.
  1410. Args:
  1411. inp: input tensor.
  1412. kernel_size: size of the window.
  1413. padding: implicit zero padding added on both sides of input. Default: 0
  1414. stride: stride of the window. Default: 1
  1415. dilation: dilation of the window. Default: 1
  1416. """
  1417. padding_h, padding_w = expand_hw(padding)
  1418. stride_h, stride_w = expand_hw(stride)
  1419. dilation_h, dilation_w = expand_hw(dilation)
  1420. window_h, window_w = expand_hw(kernel_size)
  1421. op = builtin.Images2Neibs(
  1422. pad_h=padding_h,
  1423. pad_w=padding_w,
  1424. stride_h=stride_h,
  1425. stride_w=stride_w,
  1426. dilate_h=dilation_h,
  1427. dilate_w=dilation_w,
  1428. window_h=window_h,
  1429. window_w=window_w,
  1430. )
  1431. (output,) = apply(op, inp)
  1432. return output
  1433. def sliding_window_transpose(
  1434. inp: Tensor,
  1435. output_size: Union[int, Tuple[int, int]],
  1436. kernel_size: Union[int, Tuple[int, int]],
  1437. padding: Union[int, Tuple[int, int]] = 0,
  1438. stride: Union[int, Tuple[int, int]] = 1,
  1439. dilation: Union[int, Tuple[int, int]] = 1,
  1440. ) -> Tensor:
  1441. r"""Sum over the sliding windows on the corresponding input location.
  1442. Refer to :class:`~.module.sliding_window.SlidingWindowTranspose` for more information.
  1443. Args:
  1444. inp: input tensor.
  1445. output_size: shape of output tensor.
  1446. kernel_size: size of the window.
  1447. padding: implicit zero padding added on both sides of input. Default: 0
  1448. stride: stride of the window. Default: 1
  1449. dilation: dilation of the window. Default: 1
  1450. """
  1451. output_h, output_w = expand_hw(output_size)
  1452. padding_h, padding_w = expand_hw(padding)
  1453. stride_h, stride_w = expand_hw(stride)
  1454. dilation_h, dilation_w = expand_hw(dilation)
  1455. window_h, window_w = expand_hw(kernel_size)
  1456. expected_h = (
  1457. output_h + 2 * padding_h - dilation_h * (window_h - 1) - 1
  1458. ) // stride_h + 1
  1459. expected_w = (
  1460. output_w + 2 * padding_w - dilation_w * (window_w - 1) - 1
  1461. ) // stride_w + 1
  1462. assert inp.ndim == 6, "the input dimension of sliding_window_transpose should be 6"
  1463. assert (
  1464. inp.shape[2] == expected_h and inp.shape[3] == expected_w
  1465. ), "the input shape and output size do not match"
  1466. op = builtin.SlidingWindowTranspose(
  1467. out_h=output_h,
  1468. out_w=output_w,
  1469. pad_h=padding_h,
  1470. pad_w=padding_w,
  1471. stride_h=stride_h,
  1472. stride_w=stride_w,
  1473. dilate_h=dilation_h,
  1474. dilate_w=dilation_w,
  1475. window_h=window_h,
  1476. window_w=window_w,
  1477. )
  1478. (output,) = apply(op, inp)
  1479. return output
  1480. def pad(
  1481. src: Tensor,
  1482. pad_width: Tuple[Tuple[int, int], ...],
  1483. mode: str = "constant",
  1484. constant_value: float = 0.0,
  1485. ) -> Tensor:
  1486. r"""Pads the input tensor.
  1487. Args:
  1488. pad_width: A tuple. Each element in the tuple is the tuple of 2-elements,
  1489. the 2 elements represent the padding size on both sides of the current dimension, ``(front_offset, back_offset)``
  1490. mode: One of the following string values. Default: ``'constant'``
  1491. * ``'constant'``: Pads with a constant value.
  1492. * ``'reflect'``: Pads with the edge values of tensor.
  1493. * ``'replicate'``: Pads with the reflection of the tensor mirrored on the first and last values of the tensor along each axis.
  1494. constant_val: Fill value for ``'constant'`` padding. Default: 0
  1495. Examples:
  1496. >>> import numpy as np
  1497. >>> inp = Tensor([[1., 2., 3.],[4., 5., 6.]])
  1498. >>> inp
  1499. Tensor([[1. 2. 3.]
  1500. [4. 5. 6.]], device=xpux:0)
  1501. >>> F.nn.pad(inp, pad_width=((1, 1),), mode="constant")
  1502. Tensor([[0. 0. 0.]
  1503. [1. 2. 3.]
  1504. [4. 5. 6.]
  1505. [0. 0. 0.]], device=xpux:0)
  1506. >>> F.nn.pad(inp, pad_width=((1, 1),), mode="constant", constant_value=9)
  1507. Tensor([[9. 9. 9.]
  1508. [1. 2. 3.]
  1509. [4. 5. 6.]
  1510. [9. 9. 9.]], device=xpux:0)
  1511. >>> F.nn.pad(inp, pad_width=((1, 1), (1, 2)), mode="reflect")
  1512. Tensor([[5. 4. 5. 6. 5. 4.]
  1513. [2. 1. 2. 3. 2. 1.]
  1514. [5. 4. 5. 6. 5. 4.]
  1515. [2. 1. 2. 3. 2. 1.]], device=xpux:0)
  1516. >>> F.nn.pad(inp, pad_width=((1, 1), (1, 2)), mode="replicate")
  1517. Tensor([[1. 1. 2. 3. 3. 3.]
  1518. [1. 1. 2. 3. 3. 3.]
  1519. [4. 4. 5. 6. 6. 6.]
  1520. [4. 4. 5. 6. 6. 6.]], device=xpux:0)
  1521. """
  1522. p_offsets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  1523. assert mode.lower() in ["constant", "edge", "replicate", "reflect"]
  1524. if mode.lower() == "edge":
  1525. mode = "replicate"
  1526. for i in range(0, len(pad_width)):
  1527. p_offsets[i * 2] = pad_width[i][0]
  1528. p_offsets[i * 2 + 1] = pad_width[i][1]
  1529. op = builtin.Padding(
  1530. front_offset_dim0=p_offsets[0],
  1531. front_offset_dim1=p_offsets[2],
  1532. front_offset_dim2=p_offsets[4],
  1533. front_offset_dim3=p_offsets[6],
  1534. front_offset_dim4=p_offsets[8],
  1535. front_offset_dim5=p_offsets[10],
  1536. front_offset_dim6=p_offsets[12],
  1537. back_offset_dim0=p_offsets[1],
  1538. back_offset_dim1=p_offsets[3],
  1539. back_offset_dim2=p_offsets[5],
  1540. back_offset_dim3=p_offsets[7],
  1541. back_offset_dim4=p_offsets[9],
  1542. back_offset_dim5=p_offsets[11],
  1543. back_offset_dim6=p_offsets[13],
  1544. padding_val=constant_value,
  1545. padding_mode=mode.upper(),
  1546. )
  1547. (output,) = apply(op, src)
  1548. return output
  1549. def local_response_norm(
  1550. inp: Tensor,
  1551. kernel_size: int = 5,
  1552. k: float = 2.0,
  1553. alpha: float = 1e-4,
  1554. beta: float = 0.75,
  1555. ) -> Tensor:
  1556. r"""
  1557. Apply local response normalization to the input tensor.
  1558. Args:
  1559. kernel_size: the size of the kernel to apply LRN on.
  1560. k: hyperparameter k. The default vaule is 2.0.
  1561. alpha: hyperparameter alpha. The default value is 1e-4.
  1562. beta: hyperparameter beta. The default value is 0.75.
  1563. Example:
  1564. >>> import numpy as np
  1565. >>> inp = Tensor(np.arange(25, dtype=np.float32).reshape(1,1,5,5))
  1566. >>> GT = np.array([[[[ 0., 0.999925, 1.9994003, 2.9979765, 3.9952066],
  1567. ... [ 4.9906454, 5.983851, 6.974385, 7.961814, 8.945709 ],
  1568. ... [ 9.925651, 10.90122, 11.872011, 12.837625, 13.7976675],
  1569. ... [14.751757, 15.699524, 16.640602, 17.574642, 18.501305 ],
  1570. ... [19.420258, 20.331186, 21.233786, 22.127764, 23.012836 ]]]])
  1571. >>> out = F.local_response_norm(inp, kernel_size=3, k=1.0, alpha=1e-4, beta=0.75)
  1572. >>> np.testing.assert_allclose(GT, out.numpy(), rtol=1e-6, atol=1e-6)
  1573. """
  1574. op = builtin.LRN(n=kernel_size, k=k, alpha=alpha, beta=beta,)
  1575. (output,) = apply(op, inp)
  1576. return output
  1577. @lru_cache(maxsize=None)
  1578. def _get_layerPixelShuffle(device, dtype, dim_order):
  1579. @subgraph("LayerPixelShuffle", dtype, device, 3)
  1580. def layerPixelShuffle(inputs, f, c):
  1581. inp, shape_0, shape_1 = inputs
  1582. inp = f(Reshape(), inp, shape_0)
  1583. inp = f(Dimshuffle(dim_order), inp)
  1584. oup = f(Reshape(), inp, shape_1)
  1585. return (oup,), (True,)
  1586. return layerPixelShuffle
  1587. def layerPixelShuffle_traceable(inp, upscale_factor):
  1588. assert upscale_factor > 0, "upscale_factor should larger than 0"
  1589. assert inp.ndim >= 3, "the input dimension of pixel_shuffle should be larger than 3"
  1590. assert (
  1591. inp.shape[-3] % (upscale_factor ** 2) == 0
  1592. ), "the -3 dimension should be divided by (upscale_factor ** 2)"
  1593. _device = inp.device
  1594. _dtype = inp.dtype
  1595. shape_ori = inp.shape
  1596. high_dim = shape_ori[:-3]
  1597. square = upscale_factor ** 2
  1598. n = 1
  1599. for item in high_dim:
  1600. n *= item
  1601. shape_0 = (
  1602. n,
  1603. int(shape_ori[-3] / square),
  1604. upscale_factor,
  1605. upscale_factor,
  1606. shape_ori[-2],
  1607. shape_ori[-1],
  1608. )
  1609. shape_1 = (
  1610. *high_dim,
  1611. int(shape_ori[-3] / square),
  1612. shape_ori[-2] * upscale_factor,
  1613. shape_ori[-1] * upscale_factor,
  1614. )
  1615. dim_order = (0, 1, 4, 2, 5, 3)
  1616. layerPixelShuffle = _get_layerPixelShuffle(_device, _dtype, dim_order)
  1617. shape_0 = convert_single_value(shape_0, device=inp.device)
  1618. shape_1 = convert_single_value(shape_1, device=inp.device)
  1619. outvar, *_ = apply(layerPixelShuffle(), inp, shape_0, shape_1)
  1620. return outvar
  1621. def pixel_shuffle(inp: Tensor, upscale_factor: int) -> Tensor:
  1622. """
  1623. Rearranges elements in a tensor of shape `(..., C * r^2, H, W)` to a tensor of
  1624. shape `(..., C, H * r, W * r)`, where `r` is an upscale factor, where `...` is
  1625. zero or more batch dimensions.
  1626. :param inp: input tensor.
  1627. :param upscale_factor: upscale factor of pixel_shuffle.
  1628. :return: output tensor.
  1629. """
  1630. return pixel_shuffle_cpp(inp, upscale_factor, layerPixelShuffle_traceable)
  1631. from .quantized import conv_bias_activation # isort:skip
  1632. from .loss import * # isort:skip
  1633. from .metric import * # isort:skip
  1634. from .vision import * # isort:skip