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

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