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 70 kB

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