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