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

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