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

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