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

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