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

nn.py 67 kB

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