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

nn.py 66 kB

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