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

nn.py 64 kB

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