You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

nn.py 64 kB

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