common.py 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import inspect
  15. import warnings
  16. from functools import reduce
  17. import numpy as np
  18. import paddle
  19. from paddle.base import core, unique_name
  20. from paddle.base.data_feeder import check_dtype
  21. from paddle.base.framework import (
  22. Program,
  23. Variable,
  24. default_main_program,
  25. in_dygraph_mode,
  26. in_dynamic_or_pir_mode,
  27. in_pir_mode,
  28. name_scope,
  29. program_guard,
  30. static_only,
  31. )
  32. from paddle.base.param_attr import ParamAttr
  33. from paddle.base.wrapped_decorator import signature_safe_contextmanager
  34. from paddle.common_ops_import import (
  35. LayerHelper,
  36. check_type,
  37. check_variable_and_dtype,
  38. )
  39. from paddle.nn.initializer import Constant, Normal
  40. __all__ = []
  41. @static_only
  42. def fc(
  43. x,
  44. size,
  45. num_flatten_dims=1,
  46. weight_attr=None,
  47. bias_attr=None,
  48. activation=None,
  49. name=None,
  50. ):
  51. r"""
  52. Fully-Connected layer can take a tensor or a list of tensor as its inputs.
  53. It creates a 2-D weight tensor for each input tensor, which represents its
  54. weight matrix from each input unit to each output unit. The fully connected
  55. layer multiplies each input tensor with its corresponding weight to produce
  56. an output tensor with shape :math:`[batch\_size, *, size]` , where :math:`*`
  57. means any number of additional dimensions. If a list of tensor is given,
  58. the results of multiple output tensors with shape :math:`[batch\_size, *, size]`
  59. will be summed up. If :attr:`bias_attr` is not False, a 1-D bias tensor will
  60. be created and added to the output. Finally, if :attr:`activation` is not None,
  61. it will be applied to the output as well.
  62. For a single input tensor :math:`X` , the equation is:
  63. .. math::
  64. Out = Act({XW + b})
  65. For a list of input tensor, the equation is:
  66. .. math::
  67. Out = Act({\sum_{i=0}^{N-1}X_iW_i + b})
  68. where:
  69. * :math:`N`: The number of the input tensors. :math:`N` equals to :math:`len(X)` if :math:`X` is list of tensor.
  70. * :math:`X_i`: The i-th input tensor.
  71. * :math:`W_i`: The i-th weight matrix corresponding i-th input tensor.
  72. * :math:`b`: The bias created by this layer (if needed).
  73. * :math:`Act`: The activation function.
  74. * :math:`Out`: The output tensor.
  75. .. code-block:: text
  76. # Case 1, input is a single tensor:
  77. x.data = [[[0.1, 0.2],
  78. [0.3, 0.4]]]
  79. x.shape = (1, 2, 2) # 1 is batch_size
  80. out = paddle.static.nn.fc(x=x, size=1, num_flatten_dims=2)
  81. # Get the output:
  82. out.data = [[0.83234344], [0.34936576]]
  83. out.shape = (1, 2, 1)
  84. # Case 2, input is a list of tensor:
  85. x0.data = [[[0.1, 0.2],
  86. [0.3, 0.4]]]
  87. x0.shape = (1, 2, 2) # 1 is batch_size
  88. x1.data = [[[0.1, 0.2, 0.3]]]
  89. x1.shape = (1, 1, 3)
  90. out = paddle.static.nn.fc(x=[x0, x1], size=2)
  91. # Get the output:
  92. out.data = [[0.18669507, 0.1893476]]
  93. out.shape = (1, 2)
  94. Args:
  95. x (Tensor|list[Tensor]|tuple[Tensor]): A tensor or a list/tuple of tensors. The number of dimensions
  96. of each tensor is at least 2. The data type should be float16, float32 or float64.
  97. size (int): The number of output units in this layer, which also means the feature
  98. size of output tensor.
  99. num_flatten_dims (int, optional): The fc layer can accept an input tensor with more than
  100. two dimensions. If this happens, the multi-dimensional tensor will first be flattened
  101. into a 2-D matrix. The parameter :attr:`num_flatten_dims` determines how the input
  102. tensor is flattened: the first :math:`num\_flatten\_dims` (inclusive, index starts from 1)
  103. dimensions will be flatten to form the first dimension of the final matrix (height of
  104. the matrix), and the rest :math:`rank(x) - num\_flatten\_dims` dimensions are
  105. flattened to form the second dimension of the final matrix (width of the matrix).
  106. For example, assuming that :attr:`x` is a 5-dimensional tensor with a shape
  107. :math:`[2, 3, 4, 5, 6]` , and :attr:`num_flatten_dims` = 3.
  108. Then, the flattened matrix will have a shape :math:`[2 * 3 * 4, 5 * 6] = [24, 30]` .
  109. Default: 1.
  110. weight_attr (ParamAttr, optional): The attribute for the learnable weight.
  111. The default value is None, and the weight will be initialized to zero.
  112. For detailed information, please refer to :attr:`paddle.ParamAttr`.
  113. Warning, if x is a list of tensor, weight_attr should also be a list of same length.
  114. bias_attr (ParamAttr|bool, optional): The attribute of the learnable bias.
  115. If it is set to False, no bias will be added to the output.
  116. If it is set to None or one kind of ParamAttr, a bias parameter will
  117. be created according to ParamAttr. For detailed information, please refer
  118. to :attr:`paddle.ParamAttr`. The default value is None and the bias will be
  119. initialized to zero.
  120. activation (str, optional): Activation to be applied to the output of
  121. this layer, such as tanh, softmax, sigmoid, relu. For more information,
  122. please refer to :ref:`api_guide_activations_en` . Default: None.
  123. name (str, optional): The default value is None. Normally there is no need for user to set
  124. it. For more information, please refer to :ref:`api_guide_Name` .
  125. Returns:
  126. Tensor, its shape is :math:`[batch\_size, *, size]` , and the data type is same with input.
  127. Examples:
  128. .. code-block:: python
  129. >>> import paddle
  130. >>> paddle.enable_static()
  131. >>> # When input is a single tensor
  132. >>> x = paddle.static.data(name="x", shape=[1, 2, 2], dtype="float32")
  133. >>> out = paddle.static.nn.fc(
  134. ... x=x,
  135. ... size=1,
  136. ... num_flatten_dims=2,
  137. ... weight_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=0.5)),
  138. ... bias_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0)))
  139. >>> print(out)
  140. var fc_0.tmp_1 : LOD_TENSOR.shape(1, 2, 1).dtype(float32).stop_gradient(False)
  141. >>> # When input is multiple tensors
  142. >>> x0 = paddle.static.data(name="x0", shape=[1, 2, 2], dtype="float32")
  143. >>> x1 = paddle.static.data(name="x1", shape=[1, 1, 3], dtype="float32")
  144. >>> out = paddle.static.nn.fc(
  145. ... x=[x0, x1],
  146. ... size=2,
  147. ... weight_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=0.5)),
  148. ... bias_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0)))
  149. >>> print(out)
  150. var fc_1.tmp_3 : LOD_TENSOR.shape(1, 2).dtype(float32).stop_gradient(False)
  151. """
  152. def fc_base(
  153. input,
  154. size,
  155. num_flatten_dims=1,
  156. param_attr=None,
  157. bias_attr=None,
  158. act=None,
  159. name=None,
  160. ):
  161. helper = LayerHelper("fc", **locals())
  162. check_type(
  163. input, 'input', (list, tuple, Variable, paddle.pir.Value), 'fc'
  164. )
  165. if isinstance(input, (list, tuple)):
  166. for i, input_x in enumerate(input):
  167. check_type(
  168. input_x,
  169. 'input[' + str(i) + ']',
  170. (Variable, paddle.pir.Value),
  171. 'fc',
  172. )
  173. dtype = helper.input_dtype()
  174. check_dtype(
  175. dtype, 'input', ['float16', 'uint16', 'float32', 'float64'], 'fc'
  176. )
  177. mul_results = []
  178. for input_var, param_attr in helper.iter_inputs_and_params():
  179. input_shape = input_var.shape
  180. if num_flatten_dims == -1:
  181. num_flatten_dims = len(input_shape) - 1
  182. param_shape = [
  183. reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1)
  184. ] + [size]
  185. w = helper.create_parameter(
  186. attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False
  187. )
  188. if in_pir_mode():
  189. if len(input_var.shape) > 2:
  190. new_shape = (
  191. input_var.shape[0],
  192. np.prod(input_var.shape[1:]),
  193. )
  194. input_var = paddle.reshape(input_var, new_shape)
  195. tmp = paddle.matmul(input_var, w)
  196. else:
  197. tmp = helper.create_variable_for_type_inference(dtype)
  198. helper.append_op(
  199. type="mul",
  200. inputs={"X": input_var, "Y": w},
  201. outputs={"Out": tmp},
  202. attrs={
  203. "x_num_col_dims": num_flatten_dims,
  204. "y_num_col_dims": 1,
  205. },
  206. )
  207. mul_results.append(tmp)
  208. if len(mul_results) == 1:
  209. pre_bias = mul_results[0]
  210. elif in_pir_mode():
  211. pre_bias = paddle.add_n(mul_results)
  212. else:
  213. pre_bias = helper.create_variable_for_type_inference(dtype)
  214. helper.append_op(
  215. type="sum",
  216. inputs={"X": mul_results},
  217. outputs={"Out": pre_bias},
  218. attrs={},
  219. )
  220. # add bias
  221. pre_activation = helper.append_bias_op(
  222. pre_bias, dim_start=num_flatten_dims
  223. )
  224. # add activation
  225. return helper.append_activation(pre_activation)
  226. return fc_base(
  227. input=x,
  228. size=size,
  229. num_flatten_dims=num_flatten_dims,
  230. param_attr=weight_attr,
  231. bias_attr=bias_attr,
  232. act=activation,
  233. name=name,
  234. )
  235. def instance_norm(
  236. input, epsilon=1e-05, param_attr=None, bias_attr=None, name=None
  237. ):
  238. r"""
  239. **Instance Normalization Layer**
  240. Can be used as a normalizer function for convolution or fully_connected operations.
  241. The required data format for this layer is one of the following:
  242. DataLayout: NCHW `[batch, in_channels, in_height, in_width]`
  243. Refer to `Instance Normalization: The Missing Ingredient for
  244. Fast Stylization <https://arxiv.org/pdf/1607.08022.pdf>`_
  245. for more details.
  246. :math:`input` is the input features over a mini-batch.
  247. .. math::
  248. \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//
  249. \ mean\ of\ one\ feature\ map\ in\ mini-batch \\
  250. \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i -
  251. \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\
  252. \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{
  253. \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
  254. y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
  255. Note:
  256. `H` means height of feature map, `W` means width of feature map.
  257. Args:
  258. input(Tensor): The rank of input tensor can be 2, 3, 4, 5.
  259. The data type is float32 or float64.
  260. epsilon(float, Default 1e-05): A value added to the denominator for
  261. numerical stability. Default is 1e-5.
  262. param_attr(ParamAttr|None|bool, optional): The parameter attribute for Parameter `scale`
  263. of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm
  264. will create ParamAttr as param_attr, the name of scale can be set in ParamAttr.
  265. If the Initializer of the param_attr is not set, the parameter is initialized
  266. with Xavier. If the param_attr is set to False, instance_norm will not create param_attr.
  267. Default: None.
  268. bias_attr(ParamAttr|None|bool, optional): The parameter attribute for the bias of instance_norm.
  269. If it is set to None or one attribute of ParamAttr, instance_norm
  270. will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr.
  271. If the Initializer of the bias_attr is not set, the bias is initialized zero.
  272. If the bias_attr is set to False, instance_norm will not create bias_attr.
  273. Default: None.
  274. name(string, Default None): A name for this layer(optional). If set None, the layer
  275. will be named automatically.
  276. Returns:
  277. A Tensor which is the result after applying instance normalization on the input,
  278. has same shape and data type with input.
  279. Examples:
  280. .. code-block:: python
  281. >>> import paddle
  282. >>> paddle.enable_static()
  283. >>> x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32')
  284. >>> hidden1 = paddle.static.nn.fc(x, size=200)
  285. >>> hidden2 = paddle.static.nn.instance_norm(hidden1)
  286. """
  287. check_variable_and_dtype(
  288. input,
  289. 'input',
  290. ['uint16', 'float16', 'float32', 'float64'],
  291. 'instance_norm',
  292. )
  293. if param_attr is False:
  294. assert (
  295. bias_attr is False
  296. ), "param_attr and bias_attr must be set to False at the same time in instance_norm"
  297. helper = LayerHelper('instance_norm', **locals())
  298. dtype = helper.input_dtype()
  299. # use fp32 for in parameter
  300. if dtype == paddle.float16:
  301. dtype = paddle.float32
  302. input_shape = input.shape
  303. if len(input.shape) < 2 or len(input.shape) > 5:
  304. raise ValueError(
  305. f'expected 2D or 3D or 4D or 5D input (got {len(input.shape)}D input, input shape is: {input_shape})'
  306. )
  307. channel_num = input_shape[1]
  308. param_shape = [channel_num]
  309. if param_attr and bias_attr:
  310. # create parameter
  311. scale = helper.create_parameter(
  312. attr=helper.param_attr,
  313. shape=param_shape,
  314. dtype=dtype,
  315. default_initializer=Constant(1.0),
  316. )
  317. bias = helper.create_parameter(
  318. attr=helper.bias_attr,
  319. shape=param_shape,
  320. dtype=dtype,
  321. is_bias=True,
  322. default_initializer=Constant(0.0),
  323. )
  324. # create output
  325. saved_mean = helper.create_variable_for_type_inference(
  326. dtype=dtype, stop_gradient=True
  327. )
  328. saved_variance = helper.create_variable_for_type_inference(
  329. dtype=dtype, stop_gradient=True
  330. )
  331. instance_norm_out = helper.create_variable_for_type_inference(dtype)
  332. inputs = {"X": input}
  333. if param_attr and bias_attr:
  334. inputs["Scale"] = scale
  335. inputs["Bias"] = bias
  336. helper.append_op(
  337. type="instance_norm",
  338. inputs=inputs,
  339. outputs={
  340. "Y": instance_norm_out,
  341. "SavedMean": saved_mean,
  342. "SavedVariance": saved_variance,
  343. },
  344. attrs={
  345. "epsilon": epsilon,
  346. },
  347. )
  348. return instance_norm_out
  349. @static_only
  350. def continuous_value_model(input, cvm, use_cvm=True):
  351. r"""
  352. **continuous_value_model layers**
  353. Now, this OP is used in CTR project to remove or dispose show and click value in :attr:`input`.
  354. :attr:`input` is an embedding vector including show and click value, whose shape is :math:`[N, D]` (N is batch size. D is `2 + embedding dim` ).
  355. Show and click at first two dims of embedding vector D.
  356. If :attr:`use_cvm` is True, it will calculate :math:`log(show)` and :math:`log(click)` , and output shape is :math:`[N, D]` .
  357. If :attr:`use_cvm` is False, it will remove show and click from :attr:`input` , and output shape is :math:`[N, D - 2]` .
  358. :attr:`cvm` is show_click info, whose shape is :math:`[N, 2]` .
  359. Args:
  360. input (Variable): The input variable. A 2-D LoDTensor with shape :math:`[N, D]` , where N is the batch size, D is `2 + the embedding dim` . `lod level = 1` .
  361. A Tensor with type float32, float64.
  362. cvm (Variable): Show and click variable. A 2-D Tensor with shape :math:`[N, 2]` , where N is the batch size, 2 is show and click.
  363. A Tensor with type float32, float64.
  364. use_cvm (bool): Use show_click or not. if use, the output dim is the same as input.
  365. if not use, the output dim is `input dim - 2` (remove show and click)
  366. Returns:
  367. Variable: A 2-D LodTensor with shape :math:`[N, M]` . if :attr:`use_cvm` = True, M is equal to input dim D. if False, M is equal to `D - 2`. \
  368. A Tensor with same type as input.
  369. Examples:
  370. .. code-block:: python
  371. >>> import paddle
  372. >>> paddle.enable_static()
  373. >>> input = paddle.static.data(name="input", shape=[64, 1], dtype="int64")
  374. >>> label = paddle.static.data(name="label", shape=[64, 1], dtype="int64")
  375. >>> w0 = paddle.full(shape=(100, 1), fill_value=2).astype(paddle.float32)
  376. >>> embed = paddle.nn.functional.embedding(input, w0)
  377. >>> ones = paddle.full_like(label, 1, dtype="int64")
  378. >>> show_clk = paddle.cast(paddle.concat([ones, label], axis=1), dtype='float32')
  379. >>> show_clk.stop_gradient = True
  380. >>> input_with_cvm = paddle.static.nn.continuous_value_model(embed[:, 0], show_clk, True)
  381. """
  382. helper = LayerHelper('cvm', **locals())
  383. out = helper.create_variable(dtype=input.dtype)
  384. check_variable_and_dtype(
  385. input, 'input', ['float16', 'float32', 'float64'], 'cvm'
  386. )
  387. helper.append_op(
  388. type='cvm',
  389. inputs={'X': [input], 'CVM': [cvm]},
  390. outputs={'Y': [out]},
  391. attrs={"use_cvm": use_cvm},
  392. )
  393. return out
  394. @static_only
  395. def data_norm(
  396. input,
  397. act=None,
  398. epsilon=1e-05,
  399. param_attr=None,
  400. data_layout='NCHW',
  401. in_place=False,
  402. name=None,
  403. moving_mean_name=None,
  404. moving_variance_name=None,
  405. do_model_average_for_mean_and_var=True,
  406. slot_dim=-1,
  407. sync_stats=False,
  408. summary_decay_rate=0.9999999,
  409. enable_scale_and_shift=False,
  410. ):
  411. r"""
  412. **Data Normalization Layer**
  413. This op can be used as a normalizer function for conv2d and fully_connected operations.
  414. The required data format for this layer is one of the following:
  415. 1. NHWC `[batch, in_height, in_width, in_channels]`
  416. 2. NCHW `[batch, in_channels, in_height, in_width]`
  417. :math:`input` is the input features over a mini-batch.
  418. .. math::
  419. \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//
  420. \ mini-batch\ mean \\
  421. \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i -
  422. \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\
  423. \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{
  424. \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
  425. y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
  426. Args:
  427. input (Tensor): The input Tensor.
  428. act (str, optional): Activation type, linear|relu|prelu|... Default: None.
  429. epsilon(float, optional): Whether to add small values into the variance during calculations
  430. to prevent division by zero. Default: 1e-05.
  431. param_attr (ParamAttr, optional): The parameter attribute for Parameter `scale`. Default: None.
  432. data_layout (str, optional): Specify the data format of the input, and the data format of the output
  433. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  434. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  435. `[batch_size, input_channels, input_height, input_width]`. Default: `"NCHW"`.
  436. in_place (bool, optional): Make the input and output of batch norm reuse memory. Default: False.
  437. name (str, optional): A name for this layer (optional). If set None, the layer
  438. will be named automatically. Default: None.
  439. moving_mean_name (str, optional): The name of moving_mean which store the global Mean. Default: None.
  440. moving_variance_name (str, optional): The name of the moving_variance which store the global Variance. Default: None.
  441. do_model_average_for_mean_and_var (bool, optional): Whether parameter mean and variance
  442. should do model average when model average is enabled. Default: True.
  443. slot_dim (int, optional): The embedding dimension of one slot. Slot is a set of one specific feature. In pslib mode,
  444. we distinguish feature ids by slot and pull their embeddings from parameter server (pslib). The first
  445. place of the embedding is the historical show number (occurrence time of this feature id with a label 0).
  446. If the input of this op is concated by slot-wise embeddings, and the show number is zero when this slot
  447. is new or empty, the normalization result may be impractical. To avoid this, we add slot_dim to locate
  448. the show number and judge if the show number is zero. If so, we choose to skip normalization on this
  449. embedding. Default: -1.
  450. sync_stats (bool, optional): When running with multiple GPU cards, using allreduce to sync the
  451. summary messages. Default: False.
  452. summary_decay_rate (float, optional): The decay rate when updating summary. Default: 0.9999999.
  453. enable_scale_and_shift (bool, optional): do scale&shift after normalization. Default: False.
  454. Returns:
  455. Tensor: A tensor which is the result after applying data normalization on the input.
  456. Examples:
  457. .. code-block:: python
  458. >>> import paddle
  459. >>> paddle.enable_static()
  460. >>> x = paddle.randn(shape=[32, 100])
  461. >>> hidden2 = paddle.static.nn.data_norm(input=x)
  462. """
  463. helper = LayerHelper('data_norm', **locals())
  464. dtype = helper.input_dtype()
  465. input_shape = input.shape
  466. if len(input_shape) < 2:
  467. raise ValueError(
  468. f"The shape pf Input < 2 (got {len(input_shape)}D input, input shape is: {input_shape})"
  469. )
  470. if data_layout == 'NCHW':
  471. channel_num = input_shape[1]
  472. else:
  473. if data_layout == 'NHWC':
  474. channel_num = input_shape[-1]
  475. else:
  476. raise ValueError("unsupported data layout:" + data_layout)
  477. param_shape = [channel_num]
  478. batch_size_default = 1e4
  479. batch_sum_default = 0.0
  480. batch_square_sum_default = 1e4
  481. scale_w_default = 1.0
  482. bias_default = 0.0
  483. if param_attr and isinstance(param_attr, dict):
  484. batch_size_default = param_attr.get("batch_size", 1e4)
  485. batch_sum_default = param_attr.get("batch_sum", 0.0)
  486. batch_square_sum_default = param_attr.get("batch_square", 1e4)
  487. if enable_scale_and_shift:
  488. scale_w_default = param_attr.get("scale_w", 1.0)
  489. bias_default = param_attr.get("bias", 0.0)
  490. # create scale and shift(bias) when enable_scale_and_shift is True
  491. if name is None:
  492. name = "dn"
  493. if enable_scale_and_shift:
  494. scale_w = helper.create_parameter(
  495. attr=ParamAttr(
  496. name=name + '.scale_w',
  497. initializer=Constant(value=float(scale_w_default)),
  498. trainable=True,
  499. ),
  500. shape=param_shape,
  501. dtype=input.dtype,
  502. )
  503. bias = helper.create_parameter(
  504. attr=ParamAttr(
  505. name=name + '.bias',
  506. initializer=Constant(value=float(bias_default)),
  507. trainable=True,
  508. ),
  509. shape=param_shape,
  510. dtype=input.dtype,
  511. )
  512. # create parameter
  513. batch_size = helper.create_parameter(
  514. attr=ParamAttr(
  515. name=name + '.batch_size',
  516. initializer=Constant(value=float(batch_size_default)),
  517. trainable=True,
  518. ),
  519. shape=param_shape,
  520. dtype=input.dtype,
  521. )
  522. batch_sum = helper.create_parameter(
  523. attr=ParamAttr(
  524. name=name + '.batch_sum',
  525. initializer=Constant(value=float(batch_sum_default)),
  526. trainable=True,
  527. ),
  528. shape=param_shape,
  529. dtype=input.dtype,
  530. )
  531. batch_square_sum = helper.create_parameter(
  532. attr=ParamAttr(
  533. name=name + '.batch_square_sum',
  534. initializer=Constant(value=float(batch_square_sum_default)),
  535. trainable=True,
  536. ),
  537. shape=param_shape,
  538. dtype=input.dtype,
  539. )
  540. means = helper.create_variable(dtype=dtype, stop_gradient=True)
  541. scales = helper.create_variable(dtype=dtype, stop_gradient=True)
  542. data_norm_out = input if in_place else helper.create_variable(dtype=dtype)
  543. inputs = {
  544. "X": input,
  545. "BatchSize": batch_size,
  546. "BatchSum": batch_sum,
  547. "BatchSquareSum": batch_square_sum,
  548. }
  549. attrs = {
  550. "epsilon": epsilon,
  551. "data_layout": data_layout,
  552. "sync_stats": sync_stats,
  553. "summary_decay_rate": summary_decay_rate,
  554. }
  555. if slot_dim > 0:
  556. attrs["slot_dim"] = slot_dim
  557. if enable_scale_and_shift:
  558. attrs["enable_scale_and_shift"] = enable_scale_and_shift
  559. if enable_scale_and_shift:
  560. inputs["scale_w"] = scale_w
  561. inputs["bias"] = bias
  562. helper.append_op(
  563. type="data_norm",
  564. inputs=inputs,
  565. outputs={
  566. "Y": data_norm_out,
  567. "Means": means,
  568. "Scales": scales,
  569. "BatchSize": batch_size,
  570. "BatchSum": batch_sum,
  571. "BatchSquareSum": batch_square_sum,
  572. },
  573. attrs=attrs,
  574. )
  575. return helper.append_activation(data_norm_out)
  576. def group_norm(
  577. input,
  578. groups,
  579. epsilon=1e-05,
  580. param_attr=None,
  581. bias_attr=None,
  582. act=None,
  583. data_layout='NCHW',
  584. name=None,
  585. ):
  586. """
  587. **Group Normalization Layer**
  588. Refer to `Group Normalization <https://arxiv.org/abs/1803.08494>`_ .
  589. Parameters:
  590. input(Tensor): Tensor with dimension greater than 1, the data type is float32 or float64.
  591. groups(int): The number of groups that divided from channels, the data type
  592. is int32.
  593. epsilon(float, optional): The small value added to the variance to prevent
  594. division by zero, the data type is float32. Default: 1e-05.
  595. param_attr(ParamAttr|bool, optional): ParamAttr object that specifies weight parameter
  596. attribute. If a bool type, only False is supported, which means there is no weight parameter.
  597. Default: None, the default weight parameter attribute is used. For more information, please
  598. refer to :ref:`api_guide_ParamAttr` .
  599. bias_attr(ParamAttr|bool, optional): ParamAttr object that specifies bias parameter
  600. attribute. If a bool type, only False is supported, which means there is no bias parameter.
  601. Default: None, the default bias parameter attribute is used. For more information, please
  602. refer to :ref:`api_guide_ParamAttr` .
  603. act(str, optional): Activation to be applied to the output of group normalization.
  604. data_layout(str, optional): Specify the data format of the input, and the data format of the output
  605. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  606. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  607. `[batch_size, input_channels, *]`.
  608. name (str, optional): The default value is None. Normally there is no need for user to set this
  609. property. For more information, please refer to :ref:`api_guide_Name` .
  610. Returns:
  611. Tensor: A Tensor has same data type and data format with `input`.
  612. Examples:
  613. .. code-block:: python
  614. >>> import paddle
  615. >>> paddle.enable_static()
  616. >>> data = paddle.static.data(name='data', shape=[2, 8, 32, 32], dtype='float32')
  617. >>> x = paddle.static.nn.group_norm(input=data, groups=4)
  618. >>> print(x.shape)
  619. (2, 8, 32, 32)
  620. """
  621. helper = LayerHelper('group_norm', **locals())
  622. dtype = helper.input_dtype()
  623. check_variable_and_dtype(
  624. input,
  625. 'input',
  626. ['float16', 'uint16', 'float32', 'float64'],
  627. 'group_norm',
  628. )
  629. # create input and parameters
  630. inputs = {'X': input}
  631. input_shape = input.shape
  632. if len(input_shape) < 2:
  633. raise ValueError(
  634. f"The dimensions of Op(static.nn.group_norm)'s input should be more than 1. But received {len(input_shape)}"
  635. )
  636. if data_layout != 'NCHW' and data_layout != 'NHWC':
  637. raise ValueError(
  638. "Param(data_layout) of Op(static.nn.group_norm) got wrong value: received "
  639. + data_layout
  640. + " but only NCHW or NHWC supported."
  641. )
  642. channel_num = input_shape[1] if data_layout == 'NCHW' else input_shape[-1]
  643. param_shape = [channel_num]
  644. if param_attr:
  645. scale = helper.create_parameter(
  646. attr=helper.param_attr,
  647. shape=param_shape,
  648. dtype=dtype,
  649. default_initializer=Constant(1.0),
  650. )
  651. inputs['Scale'] = scale
  652. if bias_attr:
  653. bias = helper.create_parameter(
  654. attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True
  655. )
  656. inputs['Bias'] = bias
  657. # create output
  658. mean_out = helper.create_variable(dtype=dtype, stop_gradient=True)
  659. variance_out = helper.create_variable(dtype=dtype, stop_gradient=True)
  660. group_norm_out = helper.create_variable(dtype=dtype)
  661. helper.append_op(
  662. type="group_norm",
  663. inputs=inputs,
  664. outputs={
  665. "Y": group_norm_out,
  666. "Mean": mean_out,
  667. "Variance": variance_out,
  668. },
  669. attrs={
  670. "epsilon": epsilon,
  671. "groups": groups,
  672. "data_layout": data_layout,
  673. },
  674. )
  675. return helper.append_activation(group_norm_out)
  676. def conv2d(
  677. input,
  678. num_filters,
  679. filter_size,
  680. stride=1,
  681. padding=0,
  682. dilation=1,
  683. groups=None,
  684. param_attr=None,
  685. bias_attr=None,
  686. use_cudnn=True,
  687. act=None,
  688. name=None,
  689. data_format="NCHW",
  690. ):
  691. r"""
  692. The convolution2D layer calculates the output based on the input, filter
  693. and strides, paddings, dilations, groups parameters. Input and
  694. Output are in NCHW or NHWC format, where N is batch size, C is the number of
  695. channels, H is the height of the feature, and W is the width of the feature.
  696. Filter is in MCHW format, where M is the number of output image channels,
  697. C is the number of input image channels, H is the height of the filter,
  698. and W is the width of the filter. If the groups is greater than 1,
  699. C will equal the number of input image channels divided by the groups.
  700. Please refer to UFLDL's `convolution
  701. <http://ufldl.stanford.edu/tutorial/supervised/FeatureExtractionUsingConvolution/>`_
  702. for more details.
  703. If bias attribution and activation type are provided, bias is added to the
  704. output of the convolution, and the corresponding activation function is
  705. applied to the final result.
  706. For each input :math:`X`, the equation is:
  707. .. math::
  708. Out = \sigma (W \\ast X + b)
  709. Where:
  710. * :math:`X`: Input value, a tensor with NCHW or NHWC format.
  711. * :math:`W`: Filter value, a tensor with MCHW format.
  712. * :math:`\\ast`: Convolution operation.
  713. * :math:`b`: Bias value, a 2-D tensor with shape [M, 1].
  714. * :math:`\\sigma`: Activation function.
  715. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  716. Example:
  717. - Input:
  718. Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
  719. Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)`
  720. - Output:
  721. Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
  722. Where
  723. .. math::
  724. H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\
  725. W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1
  726. Args:
  727. input (Tensor): The input is 4-D Tensor with shape [N, C, H, W], the data type
  728. of input is float16 or float32 or float64.
  729. num_filters(int): The number of filter. It is as same as the output
  730. image channel.
  731. filter_size (int|tuple): The filter size. If filter_size
  732. is a tuple, it must contain two integers, (filter_size_height,
  733. filter_size_width). Otherwise, filter_size_height = filter_size_width =\
  734. filter_size.
  735. stride (int|tuple, optional): The stride size. It means the stride in convolution.
  736. If stride is a tuple, it must contain two integers, (stride_height, stride_width).
  737. Otherwise, stride_height = stride_width = stride. Default: stride = 1.
  738. padding (string|int|list|tuple, optional): The padding size. It means the number of zero-paddings
  739. on both sides for each dimension.If `padding` is a string, either 'VALID' or
  740. 'SAME' which is the padding algorithm. If padding size is a tuple or list,
  741. it could be in three forms: `[pad_height, pad_width]` or
  742. `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when
  743. `data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0],
  744. [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
  745. when `data_format` is `"NHWC"`, `pool_padding` can be in the form
  746. `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
  747. Default: padding = 0.
  748. dilation (int|tuple, optional): The dilation size. It means the spacing between the kernel
  749. points. If dilation is a tuple, it must contain two integers, (dilation_height,
  750. dilation_width). Otherwise, dilation_height = dilation_width = dilation.
  751. Default: dilation = 1.
  752. groups (int, optional): The groups number of the Conv2d Layer. According to grouped
  753. convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  754. the first half of the filters is only connected to the first half
  755. of the input channels, while the second half of the filters is only
  756. connected to the second half of the input channels. Default: groups=1.
  757. param_attr (ParamAttr|None, optional): The parameter attribute for learnable parameters/weights
  758. of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
  759. will create ParamAttr as param_attr. If the Initializer of the param_attr
  760. is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
  761. and the :math:`std` is :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
  762. bias_attr (ParamAttr|bool|None, optional): The parameter attribute for the bias of conv2d.
  763. If it is set to False, no bias will be added to the output units.
  764. If it is set to None or one attribute of ParamAttr, conv2d
  765. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  766. is not set, the bias is initialized zero. Default: None.
  767. use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
  768. library is installed. Default: True
  769. act (str, optional): Activation type, if it is set to None, activation is not appended.
  770. Default: None
  771. name(str|None, optional): For detailed information, please refer
  772. to :ref:`api_guide_Name`. Usually name is no need to set and
  773. None by default.
  774. data_format (str, optional): Specify the data format of the input, and the data format of the output
  775. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  776. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  777. `[batch_size, input_channels, input_height, input_width]`.
  778. Returns:
  779. A Tensor representing the conv2d, whose data type is the
  780. same with input. If act is None, the tensor storing the convolution
  781. result, and if act is not None, the tensor storing convolution
  782. and non-linearity activation result.
  783. Examples:
  784. .. code-block:: python
  785. >>> import paddle
  786. >>> paddle.enable_static()
  787. >>> data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32')
  788. >>> conv2d = paddle.static.nn.conv2d(input=data, num_filters=2, filter_size=3, act="relu")
  789. >>> print(conv2d.shape)
  790. (-1, 2, 30, 30)
  791. """
  792. check_variable_and_dtype(
  793. input, 'input', ['uint16', 'float16', 'float32', 'float64'], 'conv2d'
  794. )
  795. if len(input.shape) != 4:
  796. raise ValueError(
  797. "Input size should be 4, " f"but received {len(input.shape)}"
  798. )
  799. num_channels = input.shape[1]
  800. if not isinstance(use_cudnn, bool):
  801. raise ValueError(
  802. "Attr(use_cudnn) should be True or False. Received "
  803. "Attr(use_cudnn): %s. " % str(use_cudnn)
  804. )
  805. if data_format not in ["NCHW", "NHWC"]:
  806. raise ValueError(
  807. "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
  808. "Attr(data_format): %s." % str(data_format)
  809. )
  810. channel_last = data_format == "NHWC"
  811. num_channels = input.shape[3] if channel_last else input.shape[1]
  812. if num_channels < 0:
  813. raise ValueError(
  814. f"The channel dimension of the input({str(input.shape)}) should be defined. "
  815. f"Received: {str(num_channels)}."
  816. )
  817. assert param_attr is not False, "param_attr should not be False here."
  818. if groups is None:
  819. num_filter_channels = num_channels
  820. elif groups <= 0:
  821. raise ValueError(
  822. "the groups of input must be greater than 0, "
  823. f"but received the groups of input is {groups}"
  824. )
  825. else:
  826. if num_channels % groups != 0:
  827. raise ValueError(
  828. "the channel of input must be divisible by groups,"
  829. f"received: the channel of input is {num_channels}, the shape of input is {input.shape}"
  830. f", the groups is {groups}"
  831. )
  832. num_filter_channels = num_channels // groups
  833. l_type = 'conv2d'
  834. if (
  835. num_channels == groups
  836. and num_filters % num_channels == 0
  837. and not use_cudnn
  838. ):
  839. l_type = 'depthwise_conv2d'
  840. if (
  841. num_channels == groups
  842. and num_filters % num_channels == 0
  843. and core.is_compiled_with_rocm()
  844. ):
  845. l_type = 'depthwise_conv2d'
  846. helper = LayerHelper(l_type, **locals())
  847. dtype = helper.input_dtype()
  848. filter_size = paddle.utils.convert_to_list(filter_size, 2, 'filter_size')
  849. stride = paddle.utils.convert_to_list(stride, 2, 'stride')
  850. dilation = paddle.utils.convert_to_list(dilation, 2, 'dilation')
  851. # padding
  852. def _update_padding(padding, data_format):
  853. if isinstance(padding, (list, tuple)) and len(padding) == 4:
  854. if isinstance(padding[0], (list, tuple)) and (
  855. data_format == "NCHW"
  856. ):
  857. if not (padding[0] == [0, 0] and padding[1] == [0, 0]):
  858. raise ValueError(
  859. "Non-zero padding(%s) in the batch or channel dimensions "
  860. "is not supported." % str(padding)
  861. )
  862. padding = padding[2:4]
  863. padding = [ele for a_list in padding for ele in a_list]
  864. elif isinstance(padding[0], (list, tuple)) and (
  865. data_format == "NHWC"
  866. ):
  867. if not (padding[0] == [0, 0] and padding[3] == [0, 0]):
  868. raise ValueError(
  869. "Non-zero padding(%s) in the batch or channel dimensions "
  870. "is not supported." % str(padding)
  871. )
  872. padding = padding[1:3]
  873. padding = [ele for a_list in padding for ele in a_list]
  874. padding = paddle.utils.convert_to_list(padding, 4, 'padding')
  875. if paddle.utils._is_symmetric_padding(padding, 2):
  876. padding = [padding[0], padding[2]]
  877. else:
  878. padding = paddle.utils.convert_to_list(padding, 2, 'padding')
  879. return padding
  880. padding_algorithm = "EXPLICIT"
  881. if isinstance(padding, str):
  882. padding = padding.upper()
  883. if padding not in ["SAME", "VALID"]:
  884. raise ValueError(
  885. "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'."
  886. % str(padding)
  887. )
  888. if padding == "VALID":
  889. padding_algorithm = "VALID"
  890. padding = [0, 0]
  891. elif padding == "SAME":
  892. padding_algorithm = "SAME"
  893. padding = [0, 0]
  894. padding = _update_padding(padding, data_format)
  895. filter_shape = [num_filters, int(num_filter_channels)] + filter_size
  896. def _get_default_param_initializer():
  897. filter_elem_num = filter_size[0] * filter_size[1] * num_channels
  898. if filter_elem_num <= 0:
  899. raise ValueError(
  900. "Invalid filter number, excepted number is larger than 0, but"
  901. f" received {filter_elem_num}, please check the input shape and "
  902. "filter size."
  903. )
  904. std = (2.0 / filter_elem_num) ** 0.5
  905. return Normal(0.0, std)
  906. filter_param = helper.create_parameter(
  907. attr=helper.param_attr,
  908. shape=filter_shape,
  909. dtype=dtype,
  910. default_initializer=_get_default_param_initializer(),
  911. )
  912. pre_bias = helper.create_variable_for_type_inference(dtype)
  913. if (
  914. core.is_compiled_with_cuda()
  915. and paddle.base.get_flags("FLAGS_conv2d_disable_cudnn")[
  916. "FLAGS_conv2d_disable_cudnn"
  917. ]
  918. ):
  919. use_cudnn = False
  920. helper.append_op(
  921. type=l_type,
  922. inputs={
  923. 'Input': input,
  924. 'Filter': filter_param,
  925. },
  926. outputs={"Output": pre_bias},
  927. attrs={
  928. 'strides': stride,
  929. 'paddings': padding,
  930. 'dilations': dilation,
  931. 'groups': groups,
  932. 'use_cudnn': use_cudnn,
  933. 'fuse_relu_before_depthwise_conv': False,
  934. "padding_algorithm": padding_algorithm,
  935. "data_format": data_format,
  936. },
  937. )
  938. if data_format == 'NCHW':
  939. pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
  940. else:
  941. pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4)
  942. return helper.append_activation(pre_act)
  943. def conv3d(
  944. input,
  945. num_filters,
  946. filter_size,
  947. stride=1,
  948. padding=0,
  949. dilation=1,
  950. groups=None,
  951. param_attr=None,
  952. bias_attr=None,
  953. use_cudnn=True,
  954. act=None,
  955. name=None,
  956. data_format="NCDHW",
  957. ):
  958. r"""
  959. The convolution3D layer calculates the output based on the input, filter
  960. and strides, paddings, dilations, groups parameters. Input(Input) and
  961. Output(Output) are in NCDHW or NDHWC format. Where N is batch size C is the number of
  962. channels, D is the depth of the feature, H is the height of the feature,
  963. and W is the width of the feature. Convolution3D is similar with Convolution2D
  964. but adds one dimension(depth). If bias attribution and activation type are
  965. provided, bias is added to the output of the convolution, and the
  966. corresponding activation function is applied to the final result.
  967. For each input :math:`X`, the equation is:
  968. .. math::
  969. Out = \sigma (W \ast X + b)
  970. In the above equation:
  971. * :math:`X`: Input value, a tensor with NCDHW or NDHWC format.
  972. * :math:`W`: Filter value, a tensor with MCDHW format.
  973. * :math:`\ast`: Convolution operation.
  974. * :math:`b`: Bias value, a 2-D tensor with shape [M, 1].
  975. * :math:`\sigma`: Activation function.
  976. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  977. Example:
  978. - Input:
  979. Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`
  980. Filter shape: :math:`(C_{out}, C_{in}, D_f, H_f, W_f)`
  981. - Output:
  982. Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})`
  983. Where
  984. .. math::
  985. D_{out}&= \frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (D_f - 1) + 1))}{strides[0]} + 1 \\
  986. H_{out}&= \frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (H_f - 1) + 1))}{strides[1]} + 1 \\
  987. W_{out}&= \frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (W_f - 1) + 1))}{strides[2]} + 1
  988. Args:
  989. input (Tensor): The input is 5-D Tensor with shape [N, C, D, H, W], the data
  990. type of input is float16 or float32 or float64.
  991. num_filters(int): The number of filter. It is as same as the output
  992. image channel.
  993. filter_size (int|tuple): The filter size. If filter_size is a tuple,
  994. it must contain three integers, (filter_size_depth, filter_size_height,
  995. filter_size_width). Otherwise, filter_size_depth = filter_size_height = \
  996. filter_size_width = filter_size.
  997. stride (int|tuple): The stride size. It means the stride in convolution. If stride is a
  998. tuple, it must contain three integers, (stride_depth, stride_height, stride_width).
  999. Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1.
  1000. padding (string|int|list|tuple): The padding size. It means the number of zero-paddings
  1001. on both sides for each dimension. If `padding` is a string, either 'VALID' or
  1002. 'SAME' which is the padding algorithm. If padding size is a tuple or list,
  1003. it could be in three forms: `[pad_depth, pad_height, pad_width]` or
  1004. `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`,
  1005. and when `data_format` is `"NCDHW"`, `pool_padding` can be in the form
  1006. `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
  1007. when `data_format` is `"NDHWC"`, `pool_padding` can be in the form
  1008. `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
  1009. Default: padding = 0.
  1010. dilation (int|tuple): The dilation size. It means the spacing between the kernel points.
  1011. If dilation is a tuple, it must contain three integers, (dilation_depth, dilation_height,
  1012. dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation.
  1013. Default: dilation = 1.
  1014. groups (int): The groups number of the Conv3d Layer. According to grouped
  1015. convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  1016. the first half of the filters is only connected to the first half
  1017. of the input channels, while the second half of the filters is only
  1018. connected to the second half of the input channels. Default: groups=1
  1019. param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights
  1020. of conv3d. If it is set to None or one attribute of ParamAttr, conv3d
  1021. will create ParamAttr as param_attr. If it is set to None, the parameter
  1022. is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is
  1023. :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
  1024. bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv3d.
  1025. If it is set to False, no bias will be added to the output units.
  1026. If it is set to None or one attribute of ParamAttr, conv3d
  1027. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  1028. is not set, the bias is initialized zero. Default: None.
  1029. use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn
  1030. library is installed. Default: True
  1031. act (str): Activation type, if it is set to None, activation is not appended.
  1032. Default: None.
  1033. name(str|None): For detailed information, please refer
  1034. to :ref:`api_guide_Name`. Usually name is no need to set and
  1035. None by default.
  1036. data_format (str, optional): Specify the data format of the input, and the data format of the output
  1037. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  1038. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  1039. `[batch_size, input_channels, input_height, input_width]`.
  1040. Returns:
  1041. A Tensor representing the conv3d, whose data type is
  1042. the same with input. If act is None, the tensor variable storing the
  1043. convolution result, and if act is not None, the tensor variable storing
  1044. convolution and non-linearity activation result.
  1045. Examples:
  1046. .. code-block:: python
  1047. >>> import paddle
  1048. >>> import numpy as np
  1049. >>> np.random.seed(1107)
  1050. >>> paddle.seed(1107)
  1051. >>> paddle.enable_static()
  1052. >>> data = paddle.static.data(name='data', shape=[None, 3, 12, 32, 32], dtype='float32')
  1053. >>> param_attr = paddle.framework.ParamAttr(name='conv3d.weight', initializer=paddle.nn.initializer.XavierNormal(), learning_rate=0.001)
  1054. >>> res = paddle.static.nn.conv3d(input=data, num_filters=2, filter_size=3, act="relu", param_attr=param_attr)
  1055. >>> place = paddle.CPUPlace()
  1056. >>> exe = paddle.static.Executor(place)
  1057. >>> exe.run(paddle.static.default_startup_program())
  1058. >>> x = np.random.rand(1, 3, 12, 32, 32).astype("float32")
  1059. >>> output, = exe.run(feed={"data": x}, fetch_list=[res])
  1060. >>> print(output.shape)
  1061. (1, 2, 10, 30, 30)
  1062. """
  1063. l_type = 'conv3d'
  1064. assert param_attr is not False, "param_attr should not be False here."
  1065. helper = LayerHelper(l_type, **locals())
  1066. dtype = helper.input_dtype()
  1067. if not isinstance(use_cudnn, bool):
  1068. raise ValueError(
  1069. "Attr(use_cudnn) should be True or False. Received "
  1070. "Attr(use_cudnn): %s. " % str(use_cudnn)
  1071. )
  1072. if data_format not in ["NCDHW", "NDHWC"]:
  1073. raise ValueError(
  1074. "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
  1075. "Attr(data_format): %s." % str(data_format)
  1076. )
  1077. channel_last = data_format == "NDHWC"
  1078. if len(input.shape) != 5:
  1079. raise ValueError(
  1080. f"Input should be 5D tensor, but received input with the shape of {input.shape}"
  1081. )
  1082. num_channels = input.shape[4] if channel_last else input.shape[1]
  1083. if num_channels < 0:
  1084. raise ValueError(
  1085. f"The channel dimension of the input({str(input.shape)}) should be defined. "
  1086. f"Received: {str(num_channels)}."
  1087. )
  1088. if groups is None:
  1089. num_filter_channels = num_channels
  1090. elif groups <= 0:
  1091. raise ValueError(
  1092. f"the groups of conv3d should be greater than 0. Received groups: {groups}"
  1093. )
  1094. else:
  1095. if num_channels % groups != 0:
  1096. raise ValueError(
  1097. "The number of input channels must be divisible by Attr(groups). "
  1098. f"Received: number of channels({str(num_channels)}), groups({str(groups)})."
  1099. )
  1100. num_filter_channels = num_channels // groups
  1101. filter_size = paddle.utils.convert_to_list(filter_size, 3, 'filter_size')
  1102. stride = paddle.utils.convert_to_list(stride, 3, 'stride')
  1103. dilation = paddle.utils.convert_to_list(dilation, 3, 'dilation')
  1104. def _update_padding(padding, data_format):
  1105. if isinstance(padding, (list, tuple)) and len(padding) == 5:
  1106. if isinstance(padding[0], (list, tuple)) and (
  1107. data_format == "NCDHW"
  1108. ):
  1109. if not (padding[0] == [0, 0] and padding[1] == [0, 0]):
  1110. raise ValueError(
  1111. "Non-zero padding(%s) in the batch or channel dimensions "
  1112. "is not supported." % str(padding)
  1113. )
  1114. padding = padding[2:5]
  1115. padding = [ele for a_list in padding for ele in a_list]
  1116. elif isinstance(padding[0], (list, tuple)) and (
  1117. data_format == "NDHWC"
  1118. ):
  1119. if not (padding[0] == [0, 0] and padding[4] == [0, 0]):
  1120. raise ValueError(
  1121. "Non-zero padding(%s) in the batch or channel dimensions "
  1122. "is not supported." % str(padding)
  1123. )
  1124. padding = padding[1:4]
  1125. padding = [ele for a_list in padding for ele in a_list]
  1126. padding = paddle.utils.convert_to_list(padding, 6, 'padding')
  1127. if paddle.utils._is_symmetric_padding(padding, 3):
  1128. padding = [padding[0], padding[2], padding[4]]
  1129. elif isinstance(padding, (list, tuple)) and len(padding) == 6:
  1130. padding = paddle.utils.convert_to_list(padding, 6, 'padding')
  1131. if paddle.utils._is_symmetric_padding(padding, 3):
  1132. padding = [padding[0], padding[2], padding[4]]
  1133. else:
  1134. padding = paddle.utils.convert_to_list(padding, 3, 'padding')
  1135. return padding
  1136. padding_algorithm = "EXPLICIT"
  1137. if isinstance(padding, str):
  1138. padding = padding.upper()
  1139. if padding not in ["SAME", "VALID"]:
  1140. raise ValueError(
  1141. "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'."
  1142. % str(padding)
  1143. )
  1144. if padding == "VALID":
  1145. padding_algorithm = "VALID"
  1146. padding = [0, 0, 0]
  1147. elif padding == "SAME":
  1148. padding_algorithm = "SAME"
  1149. padding = [0, 0, 0]
  1150. padding = _update_padding(padding, data_format)
  1151. input_shape = input.shape
  1152. filter_shape = [num_filters, num_filter_channels] + filter_size
  1153. def _get_default_param_initializer():
  1154. filter_elem_num = (
  1155. filter_size[0] * filter_size[1] * filter_size[2] * num_channels
  1156. )
  1157. if filter_elem_num <= 0:
  1158. raise ValueError(
  1159. "Invalid filter number, excepted number is larger than 0, but"
  1160. f" received {filter_elem_num}, please check the input shape and "
  1161. "filter size."
  1162. )
  1163. std = (2.0 / filter_elem_num) ** 0.5
  1164. return Normal(0.0, std)
  1165. filter_param = helper.create_parameter(
  1166. attr=helper.param_attr,
  1167. shape=filter_shape,
  1168. dtype=dtype,
  1169. default_initializer=_get_default_param_initializer(),
  1170. )
  1171. pre_bias = helper.create_variable_for_type_inference(dtype)
  1172. helper.append_op(
  1173. type=l_type,
  1174. inputs={
  1175. 'Input': input,
  1176. 'Filter': filter_param,
  1177. },
  1178. outputs={"Output": pre_bias},
  1179. attrs={
  1180. 'strides': stride,
  1181. 'paddings': padding,
  1182. 'dilations': dilation,
  1183. 'groups': groups,
  1184. 'use_cudnn': use_cudnn,
  1185. "padding_algorithm": padding_algorithm,
  1186. "data_format": data_format,
  1187. },
  1188. )
  1189. if data_format == 'NCDHW':
  1190. pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
  1191. else:
  1192. pre_act = helper.append_bias_op(pre_bias, dim_start=4, dim_end=5)
  1193. return helper.append_activation(pre_act)
  1194. def conv2d_transpose(
  1195. input,
  1196. num_filters,
  1197. output_size=None,
  1198. filter_size=None,
  1199. padding=0,
  1200. stride=1,
  1201. dilation=1,
  1202. groups=None,
  1203. param_attr=None,
  1204. bias_attr=None,
  1205. use_cudnn=True,
  1206. act=None,
  1207. name=None,
  1208. data_format='NCHW',
  1209. ):
  1210. r"""
  1211. The convolution2D transpose layer calculates the output based on the input,
  1212. filter, and dilations, strides, paddings. Input(Input) and output(Output)
  1213. are in NCHW or NHWC format. Where N is batch size, C is the number of channels,
  1214. H is the height of the feature, and W is the width of the feature.
  1215. Parameters(dilations, strides, paddings) are two elements. These two elements
  1216. represent height and width, respectively. The details of convolution transpose
  1217. layer, please refer to the following explanation and references
  1218. `therein <https://arxiv.org/pdf/1603.07285.pdf>`_.
  1219. If bias attribution and activation type are provided, bias is added to
  1220. the output of the convolution, and the corresponding activation function
  1221. is applied to the final result.
  1222. For each input :math:`X`, the equation is:
  1223. .. math::
  1224. Out = \sigma (W \ast X + b)
  1225. Where:
  1226. * :math:`X`: Input value, a 4-D Tensor with NCHW or NHWC format.
  1227. * :math:`W`: Filter value, a 4-D Tensor with MCHW format.
  1228. * :math:`\ast`: Convolution operation.
  1229. * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1].
  1230. * :math:`\sigma`: Activation function.
  1231. * :math:`Out`: Output value, a 4-D Tensor with data format 'NCHW' or 'NHWC', the shape of :math:`Out` and :math:`X` may be different.
  1232. Example:
  1233. - Input:
  1234. Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
  1235. Filter shape: :math:`(C_{in}, C_{out}, H_f, W_f)`
  1236. - Output:
  1237. Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
  1238. Where
  1239. .. math::
  1240. H^\prime_{out} &= (H_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (H_f - 1) + 1 \\
  1241. W^\prime_{out} &= (W_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (W_f - 1) + 1 \\
  1242. H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] ] \\
  1243. W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] ]
  1244. If `padding` = `"SAME"`:
  1245. .. math::
  1246. H^\prime_{out} &= \frac{(H_{in} + stride[0] - 1)}{stride[0]} \\
  1247. W^\prime_{out} &= \frac{(H_{in} + stride[1] - 1)}{stride[1]}
  1248. If `padding` = `"VALID"`:
  1249. .. math::
  1250. H^\prime_{out} &= (H_{in} - 1) * strides[0] + dilations[0] * (H_f - 1) + 1 \\
  1251. W^\prime_{out} &= (W_{in} − 1) * strides[1] + dilations[1] * (W_f − 1) + 1
  1252. If output_size is None, :math:`H_{out} = H^\prime_{out}, W_{out} = W^\prime_{out}`;
  1253. else, the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}`
  1254. and :math:`H^\prime_{out} + strides[0]`, and the :math:`W_{out}` of the output size must
  1255. between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[1]`,
  1256. Since transposed convolution can be treated as the inverse of convolution, and according to the input-output formula for convolution,
  1257. different sized input feature layers may correspond to the same sized output feature layer,
  1258. the size of the output feature layer for a fixed sized input feature layer is not unique to transposed convolution
  1259. If `output_size` is specified, `conv2d_transpose` can compute the kernel size automatically.
  1260. Args:
  1261. input(Tensor): 4-D Tensor with [N, C, H, W] or [N, H, W, C] format where N is the batch_size,
  1262. C is the input_channels, H is the input_height and W is the input_width.
  1263. Its data type is float32 or float64.
  1264. num_filters(int): The number of the filter. It is as same as the output
  1265. image channel.
  1266. output_size(int|tuple, optional): The output image size. If output size is a
  1267. tuple, it must contain two integers, (image_height, image_width). None if use
  1268. filter_size, padding, and stride to calculate output_size.
  1269. If output_size and filter_size are specified at the same time, They
  1270. should follow the formula above. Default: None. output_size and filter_size
  1271. should not be None at the same time.
  1272. filter_size(int|tuple, optional): The filter size. If filter_size is a tuple,
  1273. it must contain two integers, (filter_size_height, filter_size_width).
  1274. Otherwise, filter_size_height = filter_size_width = filter_size. None if
  1275. use output size to calculate filter_size. Default: None. filter_size and
  1276. output_size should not be None at the same time.
  1277. padding(str|int|list|tuple, optional): The padding size. It means the number of zero-paddings
  1278. on both sides for each dimension. If `padding` is a string, either 'VALID' or
  1279. 'SAME' which is the padding algorithm. If `padding` is a tuple or list,
  1280. it could be in three forms:
  1281. (1) Contains 4 binary groups: when `data_format` is `"NCHW"`, `padding` can be in the form
  1282. `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
  1283. when `data_format` is `"NHWC"`, `padding` can be in the form
  1284. `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
  1285. (2) Contains 4 integer values:`[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`
  1286. (3) Contains 2 integer values:`[pad_height, pad_width]`, in this case, `padding_height_top = padding_height_bottom = padding_height`,
  1287. `padding_width_left = padding_width_right = padding_width`. If an integer, `padding_height = padding_width = padding`. Default: padding = 0.
  1288. stride(int|tuple, optional): The stride size. It means the stride in transposed convolution.
  1289. If stride is a tuple, it must contain two integers, (stride_height, stride_width).
  1290. Otherwise, stride_height = stride_width = stride. Default: stride = 1.
  1291. dilation(int|tuple, optional): The dilation size. It means the spacing between the kernel points.
  1292. If dilation is a tuple, it must contain two integers, (dilation_height, dilation_width).
  1293. Otherwise, dilation_height = dilation_width = dilation. Default: dilation = 1.
  1294. groups(int, optional): The groups number of the Conv2d transpose layer. Inspired by
  1295. grouped convolution in Alex Krizhevsky's Deep CNN paper, in which
  1296. when group=2, the first half of the filters is only connected to the
  1297. first half of the input channels, while the second half of the
  1298. filters is only connected to the second half of the input channels.
  1299. Default: groups = 1.
  1300. param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights
  1301. of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose
  1302. will create ParamAttr as param_attr. If the Initializer of the param_attr
  1303. is not set, the parameter is initialized with Xavier. Default: None.
  1304. bias_attr (ParamAttr|bool, optional): Specifies the object for the bias parameter attribute.
  1305. The default value is None, which means that the default bias parameter attribute is used.
  1306. For detailed information, please refer to :ref:`api_paddle_ParamAttr`.
  1307. The default bias initialisation for the conv2d_transpose operator is 0.0.
  1308. use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
  1309. library is installed. Default: True.
  1310. act (str, optional): Activation type, if it is set to None, activation is not appended.
  1311. Default: None.
  1312. name(str, optional): For detailed information, please refer
  1313. to :ref:`api_guide_Name`. Usually name is no need to set and
  1314. None by default.
  1315. data_format (str, optional): Specify the data format of the input, and the data format of the output
  1316. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  1317. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  1318. `[batch_size, input_channels, input_height, input_width]`.
  1319. Returns:
  1320. A Tensor representing the conv2d_transpose, whose
  1321. data type is the same with input and shape is (num_batches, channels, out_h,
  1322. out_w) or (num_batches, out_h, out_w, channels). If act is None, the tensor
  1323. storing the transposed convolution result, and if act is not None, the
  1324. tensor storing transposed convolution and non-linearity activation
  1325. result.
  1326. Raises:
  1327. ValueError: If the type of `use_cudnn` is not bool.
  1328. ValueError: If `data_format` is not "NCHW" or "NHWC".
  1329. ValueError: If `padding` is a string, but not "SAME" or "VALID".
  1330. ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0
  1331. or the element corresponding to the input's channel is not 0.
  1332. ValueError: If `output_size` and filter_size are None at the same time.
  1333. ShapeError: If the input is not 4-D Tensor.
  1334. ShapeError: If the input's dimension size and filter's dimension size not equal.
  1335. ShapeError: If the dimension size of input minus the size of `stride` is not 2.
  1336. ShapeError: If the number of input channels is not equal to filter's channels.
  1337. ShapeError: If the size of `output_size` is not equal to that of `stride`.
  1338. Examples:
  1339. .. code-block:: python
  1340. >>> import paddle
  1341. >>> paddle.enable_static()
  1342. >>> data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32')
  1343. >>> conv2d_transpose = paddle.static.nn.conv2d_transpose(input=data, num_filters=2, filter_size=3)
  1344. >>> print(conv2d_transpose.shape)
  1345. (-1, 2, 34, 34)
  1346. """
  1347. assert (
  1348. param_attr is not False
  1349. ), "param_attr should not be False in conv2d_transpose."
  1350. if len(input.shape) != 4:
  1351. raise ValueError(
  1352. "Input size should be 4, " f"but received {len(input.shape)}"
  1353. )
  1354. if num_filters == 0:
  1355. raise ValueError("num of filters should not be 0.")
  1356. if data_format not in ['NCHW', 'NHWC']:
  1357. raise ValueError(
  1358. "Attr(data_format) of Op(paddle.static.nn.layers.conv2d_transpose) got wrong value: received "
  1359. + data_format
  1360. + " but only NCHW or NHWC supported."
  1361. )
  1362. input_channel = input.shape[1] if data_format == 'NCHW' else input.shape[-1]
  1363. op_type = 'conv2d_transpose'
  1364. if (
  1365. input_channel == groups
  1366. and num_filters == input_channel
  1367. and not use_cudnn
  1368. ):
  1369. op_type = 'depthwise_conv2d_transpose'
  1370. helper = LayerHelper(op_type, **locals())
  1371. if not isinstance(input, Variable):
  1372. raise TypeError("Input of conv2d_transpose must be Tensor")
  1373. stride = paddle.utils.convert_to_list(stride, 2, 'stride')
  1374. dilation = paddle.utils.convert_to_list(dilation, 2, 'dilation')
  1375. if not isinstance(use_cudnn, bool):
  1376. raise ValueError("use_cudnn should be True or False")
  1377. def _update_padding(padding, data_format):
  1378. if isinstance(padding, (list, tuple)) and len(padding) == 4:
  1379. if isinstance(padding[0], (list, tuple)) and (
  1380. data_format == "NCHW"
  1381. ):
  1382. if not (padding[0] == [0, 0] and padding[1] == [0, 0]):
  1383. raise ValueError(
  1384. "Non-zero padding(%s) in the batch or channel dimensions "
  1385. "is not supported." % str(padding)
  1386. )
  1387. padding = padding[2:4]
  1388. padding = [ele for a_list in padding for ele in a_list]
  1389. elif isinstance(padding[0], (list, tuple)) and (
  1390. data_format == "NHWC"
  1391. ):
  1392. if not (padding[0] == [0, 0] and padding[3] == [0, 0]):
  1393. raise ValueError(
  1394. "Non-zero padding(%s) in the batch or channel dimensions "
  1395. "is not supported." % str(padding)
  1396. )
  1397. padding = padding[1:3]
  1398. padding = [ele for a_list in padding for ele in a_list]
  1399. padding = paddle.utils.convert_to_list(padding, 4, 'padding')
  1400. else:
  1401. padding = paddle.utils.convert_to_list(padding, 2, 'padding')
  1402. padding = [padding[0], padding[0], padding[1], padding[1]]
  1403. return padding
  1404. padding_algorithm = "EXPLICIT"
  1405. if isinstance(padding, str):
  1406. padding = padding.upper()
  1407. if padding not in ["SAME", "VALID"]:
  1408. raise ValueError(
  1409. "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'."
  1410. % str(padding)
  1411. )
  1412. if padding == "VALID":
  1413. padding_algorithm = "VALID"
  1414. padding = [0, 0, 0, 0]
  1415. elif padding == "SAME":
  1416. padding_algorithm = "SAME"
  1417. padding = [0, 0, 0, 0]
  1418. padding = _update_padding(padding, data_format)
  1419. if output_size is None:
  1420. output_size = []
  1421. elif isinstance(output_size, (list, tuple)):
  1422. if paddle.utils._contain_var(output_size):
  1423. output_size = paddle.utils._convert_to_tensor_list(output_size)
  1424. else:
  1425. output_size = paddle.utils.convert_to_list(
  1426. output_size, 2, 'output_size'
  1427. )
  1428. elif isinstance(output_size, int):
  1429. output_size = paddle.utils.convert_to_list(
  1430. output_size, 2, 'output_size'
  1431. )
  1432. elif isinstance(output_size, Variable):
  1433. check_dtype(
  1434. output_size.dtype,
  1435. 'output_size',
  1436. ['int32', 'int64'],
  1437. 'conv2d_transpose',
  1438. )
  1439. if len(output_size.shape) == 1 and (
  1440. output_size.shape[0] == 1 or output_size.shape[0] == 2
  1441. ):
  1442. if output_size.shape[0] == 1:
  1443. output_size = [output_size, output_size]
  1444. else:
  1445. raise ValueError("output_size must contain one or two integers.")
  1446. else:
  1447. raise ValueError(
  1448. "output_size should be int, list[int] or tuple[int] or Tensor"
  1449. )
  1450. if filter_size is None:
  1451. if output_size == []:
  1452. raise ValueError("output_size must be set when filter_size is None")
  1453. if not in_dygraph_mode():
  1454. if isinstance(output_size, Variable) or paddle.utils._contain_var(
  1455. output_size
  1456. ):
  1457. raise ValueError(
  1458. "filter_size should not be None when output_size is Tensor or contain Tensor in static graph mode."
  1459. )
  1460. else:
  1461. output_size = paddle.utils.convert_shape_to_list(output_size)
  1462. if len(output_size) == 1:
  1463. output_size = paddle.utils.convert_to_list(
  1464. output_size[0], 2, 'output_size'
  1465. )
  1466. h_in = input.shape[2] if data_format == 'NCHW' else input.shape[1]
  1467. w_in = input.shape[3] if data_format == 'NCHW' else input.shape[2]
  1468. filter_size_h = (
  1469. output_size[0]
  1470. - (h_in - 1) * stride[0]
  1471. + padding[0]
  1472. + padding[1]
  1473. - 1
  1474. ) // dilation[0] + 1
  1475. filter_size_w = (
  1476. output_size[1]
  1477. - (w_in - 1) * stride[1]
  1478. + padding[2]
  1479. + padding[3]
  1480. - 1
  1481. ) // dilation[1] + 1
  1482. filter_size = [filter_size_h, filter_size_w]
  1483. else:
  1484. filter_size = paddle.utils.convert_to_list(
  1485. filter_size, 2, 'conv2d_transpose.filter_size'
  1486. )
  1487. if len(padding) == 4 and paddle.utils._is_symmetric_padding(padding, 2):
  1488. padding = [padding[0], padding[2]]
  1489. if groups is None:
  1490. groups = 1
  1491. elif groups <= 0:
  1492. raise ValueError(
  1493. "the groups of input must be greater than 0, "
  1494. f"but received the groups of input is {groups}"
  1495. )
  1496. filter_shape = [input_channel, num_filters // groups] + filter_size
  1497. img_filter = helper.create_parameter(
  1498. dtype=input.dtype, shape=filter_shape, attr=helper.param_attr
  1499. )
  1500. pre_bias = helper.create_variable_for_type_inference(dtype=input.dtype)
  1501. helper.append_op(
  1502. type=op_type,
  1503. inputs={'Input': [input], 'Filter': [img_filter]},
  1504. outputs={'Output': pre_bias},
  1505. attrs={
  1506. 'output_size': output_size,
  1507. 'strides': stride,
  1508. 'paddings': padding,
  1509. 'padding_algorithm': padding_algorithm,
  1510. 'dilations': dilation,
  1511. 'groups': groups,
  1512. 'use_cudnn': use_cudnn,
  1513. 'data_format': data_format,
  1514. },
  1515. )
  1516. if data_format == 'NCHW':
  1517. pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
  1518. else:
  1519. pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4)
  1520. out = helper.append_activation(pre_act)
  1521. return out
  1522. def conv3d_transpose(
  1523. input,
  1524. num_filters,
  1525. output_size=None,
  1526. filter_size=None,
  1527. padding=0,
  1528. stride=1,
  1529. dilation=1,
  1530. groups=None,
  1531. param_attr=None,
  1532. bias_attr=None,
  1533. use_cudnn=True,
  1534. act=None,
  1535. name=None,
  1536. data_format='NCDHW',
  1537. ):
  1538. r"""
  1539. The convolution3D transpose layer calculates the output based on the input,
  1540. filter, and dilations, strides, paddings. Input(Input) and output(Output)
  1541. are in NCDHW or NDHWC format. Where N is batch size, C is the number of channels,
  1542. D is the depth of the feature, H is the height of the feature, and W
  1543. is the width of the feature. Parameters(dilations, strides, paddings) are
  1544. two elements. These two elements represent height and width, respectively.
  1545. The details of convolution transpose layer, please refer to the following
  1546. explanation and references `therein <https://arxiv.org/pdf/1603.07285.pdf>`_.
  1547. If bias attribution and activation type are provided, bias is added to
  1548. the output of the convolution, and the corresponding activation function
  1549. is applied to the final result.
  1550. For each input :math:`X`, the equation is:
  1551. .. math::
  1552. Out = \sigma (W \ast X + b)
  1553. In the above equation:
  1554. * :math:`X`: Input value, a Tensor with NCDHW or NDHWC format.
  1555. * :math:`W`: Filter value, a Tensor with MCDHW format.
  1556. * :math:`\ast`: Convolution operation.
  1557. * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1].
  1558. * :math:`\sigma`: Activation function.
  1559. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  1560. Example:
  1561. - Input:
  1562. Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`
  1563. Filter shape: :math:`(C_{in}, C_{out}, D_f, H_f, W_f)`
  1564. - Output:
  1565. Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})`
  1566. Where
  1567. .. math::
  1568. D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (D_f - 1) + 1 \\
  1569. H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (H_f - 1) + 1 \\
  1570. W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (W_f - 1) + 1 \\
  1571. D_{out} &\in [ D^\prime_{out}, D^\prime_{out} + strides[0] ] \\
  1572. H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[1] ] \\
  1573. W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[2] ]
  1574. If `padding` = `"SAME"`:
  1575. .. math::
  1576. D^\prime_{out} &= \frac{(D_{in} + stride[0] - 1)}{stride[0]} \\
  1577. H^\prime_{out} &= \frac{(H_{in} + stride[1] - 1)}{stride[1]} \\
  1578. W^\prime_{out} &= \frac{(H_{in} + stride[2] - 1)}{stride[2]}
  1579. If `padding` = `"VALID"`:
  1580. .. math::
  1581. D^\prime_{out} &= (D_{in} - 1) * strides[0] + dilations[0] * (D_f - 1) + 1 \\
  1582. H^\prime_{out} &= (H_{in} - 1) * strides[1] + dilations[1] * (H_f - 1) + 1 \\
  1583. W^\prime_{out} &= (W_{in} − 1) * strides[2] + dilations[2] * (W_f − 1) + 1
  1584. If `output_size` is None, :math:`D_{out} = D^\prime_{out}, :math:`H_{out} = \
  1585. H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the specified `output_size_depth` (the depth of the output feature layer) :math:`D_{out}`
  1586. must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`(not including :math:`D^\prime_{out} + strides[0]`),
  1587. the specified `output_size_height` (the height of the output feature layer) :math:`H_{out}` must between :math:`H^\prime_{out}`
  1588. and :math:`H^\prime_{out} + strides[1]`(not including :math:`H^\prime_{out} + strides[1]`),
  1589. and the specified `output_size_width` (the width of the output feature layer) :math:`W_{out}` must
  1590. between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`(not including :math:`W^\prime_{out} + strides[2]`).
  1591. Since transposed convolution can be treated as the inverse of convolution,
  1592. and since different sized input feature layers may correspond to the same sized output feature layer according to the input-output formula for convolution,
  1593. the size of the output feature layer for a fixed sized input feature layer is not unique to transposed convolution.
  1594. If `output_size` is specified, `conv3d_transpose` can compute the kernel size automatically.
  1595. Args:
  1596. input(Tensor): The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C], the data type
  1597. of input is float32 or float64.
  1598. num_filters(int): The number of the filter. It is as same as the output
  1599. image channel.
  1600. output_size(int|tuple, optional): The output image size. If output size is a
  1601. tuple, it must contain three integers, (image_depth, image_height, image_width). This
  1602. parameter only works when filter_size is None. If output_size and filter_size are
  1603. specified at the same time, They should follow the formula above. Default: None.
  1604. Output_size and filter_size should not be None at the same time.
  1605. filter_size(int|tuple, optional): The filter size. If filter_size is a tuple,
  1606. it must contain three integers, (filter_size_depth, filter_size_height,
  1607. filter_size_width). Otherwise, filter_size_depth = filter_size_height = \
  1608. filter_size_width = filter_size. None if use output size to
  1609. calculate filter_size. Default: None. filter_size and output_size should not be
  1610. None at the same time.
  1611. padding(int|list|str|tuple, optional): The padding size. The padding argument effectively
  1612. adds `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a string,
  1613. either 'VALID' or 'SAME' supported, which is the padding algorithm. If `padding`
  1614. is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or
  1615. `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`,
  1616. and when `data_format` is `'NCDHW'`, `padding` can be in the form
  1617. `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
  1618. when `data_format` is `'NDHWC'`, `padding` can be in the form
  1619. `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
  1620. Default: padding = 0.
  1621. stride(int|tuple, optional): The stride size. It means the stride in transposed convolution.
  1622. If stride is a tuple, it must contain three integers, (stride_depth, stride_height,
  1623. stride_width). Otherwise, stride_depth = stride_height = stride_width = stride.
  1624. Default: stride = 1.
  1625. dilation(int|tuple, optional): The dilation size. It means the spacing between the kernel points.
  1626. If dilation is a tuple, it must contain three integers, (dilation_depth, dilation_height,
  1627. dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation.
  1628. Default: dilation = 1.
  1629. groups(int, optional): The groups number of the Conv3d transpose layer. Inspired by
  1630. grouped convolution in Alex Krizhevsky's Deep CNN paper, in which
  1631. when group=2, the first half of the filters is only connected to the
  1632. first half of the input channels, while the second half of the
  1633. filters is only connected to the second half of the input channels.
  1634. Default: groups=1
  1635. param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights
  1636. of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose
  1637. will create ParamAttr as param_attr. If the Initializer of the param_attr
  1638. is not set, the parameter is initialized with Xavier. Default: None.
  1639. bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose.
  1640. If it is set to False, no bias will be added to the output units.
  1641. If it is set to None or one attribute of ParamAttr, conv3d_transpose
  1642. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  1643. is not set, the bias is initialized zero. Default: None.
  1644. use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
  1645. library is installed. Default: True
  1646. act (str, optional): Activation type, if it is set to None, activation is not appended.
  1647. Default: None.
  1648. name(str, optional): For detailed information, please refer
  1649. to :ref:`api_guide_Name`. Usually name is no need to set and
  1650. None by default.
  1651. data_format (str, optional): Specify the data format of the input, and the data format of the output
  1652. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  1653. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  1654. `[batch_size, input_channels, input_height, input_width]`.
  1655. Returns:
  1656. A Tensor representing the conv3d_transpose, whose data
  1657. type is the same with input and shape is (num_batches, channels, out_d, out_h,
  1658. out_w) or (num_batches, out_d, out_h, out_w, channels). If act is None, the tensor
  1659. variable storing the transposed convolution result, and if act is not None, the tensor
  1660. variable storing transposed convolution and non-linearity activation result.
  1661. Examples:
  1662. .. code-block:: python
  1663. >>> import paddle
  1664. >>> import numpy as np
  1665. >>> paddle.seed(1107)
  1666. >>> np.random.seed(1107)
  1667. >>> paddle.enable_static()
  1668. >>> data = paddle.static.data(name='data', shape=[None, 3, 12, 32, 32], dtype='float32')
  1669. >>> param_attr = paddle.framework.ParamAttr(name='conv3d.weight', initializer=paddle.nn.initializer.XavierNormal(), learning_rate=0.001)
  1670. >>> res = paddle.static.nn.conv3d_transpose(input=data, num_filters=2, filter_size=3, act="relu", param_attr=param_attr)
  1671. >>> place = paddle.CPUPlace()
  1672. >>> exe = paddle.static.Executor(place)
  1673. >>> exe.run(paddle.static.default_startup_program())
  1674. >>> x = np.random.rand(1, 3, 12, 32, 32).astype("float32")
  1675. >>> output = exe.run(feed={"data": x}, fetch_list=[res.mean()])
  1676. >>> print(output)
  1677. [array(0.5148856, dtype=float32)]
  1678. """
  1679. assert (
  1680. param_attr is not False
  1681. ), "param_attr should not be False in conv3d_transpose."
  1682. if data_format not in ['NCDHW', 'NDHWC']:
  1683. raise ValueError(
  1684. "Param(data_format) of Op(paddle.static.nn.conv3d_transpose) got wrong value: received "
  1685. + data_format
  1686. + " but only NCDHW or NDHWC supported."
  1687. )
  1688. l_type = "conv3d_transpose"
  1689. helper = LayerHelper(l_type, **locals())
  1690. if not isinstance(input, Variable):
  1691. raise TypeError("Input of conv3d_transpose must be Tensor")
  1692. if len(input.shape) != 5:
  1693. raise ValueError(
  1694. f"Input should be 5D tensor, but received input with the shape of {input.shape}"
  1695. )
  1696. input_channel = (
  1697. input.shape[1] if data_format == 'NCDHW' else input.shape[-1]
  1698. )
  1699. stride = paddle.utils.convert_to_list(stride, 3, 'stride')
  1700. dilation = paddle.utils.convert_to_list(dilation, 3, 'dilation')
  1701. if not isinstance(use_cudnn, bool):
  1702. raise ValueError("use_cudnn should be True or False")
  1703. def _update_padding(padding, data_format):
  1704. if isinstance(padding, (list, tuple)) and len(padding) == 5:
  1705. if isinstance(padding[0], (list, tuple)) and (
  1706. data_format == "NCDHW"
  1707. ):
  1708. if not (padding[0] == [0, 0] and padding[1] == [0, 0]):
  1709. raise ValueError(
  1710. "Non-zero padding(%s) in the batch or channel dimensions "
  1711. "is not supported." % str(padding)
  1712. )
  1713. padding = padding[2:5]
  1714. padding = [ele for a_list in padding for ele in a_list]
  1715. elif isinstance(padding[0], (list, tuple)) and (
  1716. data_format == "NDHWC"
  1717. ):
  1718. if not (padding[0] == [0, 0] and padding[4] == [0, 0]):
  1719. raise ValueError(
  1720. "Non-zero padding(%s) in the batch or channel dimensions "
  1721. "is not supported." % str(padding)
  1722. )
  1723. padding = padding[1:4]
  1724. padding = [ele for a_list in padding for ele in a_list]
  1725. padding = paddle.utils.convert_to_list(padding, 6, 'padding')
  1726. elif isinstance(padding, (list, tuple)) and len(padding) == 6:
  1727. padding = paddle.utils.convert_to_list(padding, 6, 'padding')
  1728. else:
  1729. padding = paddle.utils.convert_to_list(padding, 3, 'padding')
  1730. padding = [
  1731. padding[0],
  1732. padding[0],
  1733. padding[1],
  1734. padding[1],
  1735. padding[2],
  1736. padding[2],
  1737. ]
  1738. return padding
  1739. padding_algorithm = "EXPLICIT"
  1740. if isinstance(padding, str):
  1741. padding = padding.upper()
  1742. if padding not in ["SAME", "VALID"]:
  1743. raise ValueError(
  1744. "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'."
  1745. % str(padding)
  1746. )
  1747. if padding == "VALID":
  1748. padding_algorithm = "VALID"
  1749. padding = [0, 0, 0, 0, 0, 0]
  1750. elif padding == "SAME":
  1751. padding_algorithm = "SAME"
  1752. padding = [0, 0, 0, 0, 0, 0]
  1753. padding = _update_padding(padding, data_format)
  1754. if filter_size is None:
  1755. if output_size is None:
  1756. raise ValueError("output_size must be set when filter_size is None")
  1757. if isinstance(output_size, int):
  1758. output_size = [output_size, output_size, output_size]
  1759. d_in = input.shape[2] if data_format == 'NCDHW' else input.shape[1]
  1760. h_in = input.shape[3] if data_format == 'NCDHW' else input.shape[2]
  1761. w_in = input.shape[4] if data_format == 'NCDHW' else input.shape[3]
  1762. filter_size_d = (
  1763. output_size[0]
  1764. - (d_in - 1) * stride[0]
  1765. + padding[0]
  1766. + padding[1]
  1767. - 1
  1768. ) // dilation[0] + 1
  1769. filter_size_h = (
  1770. output_size[1]
  1771. - (h_in - 1) * stride[1]
  1772. + padding[2]
  1773. + padding[3]
  1774. - 1
  1775. ) // dilation[1] + 1
  1776. filter_size_w = (
  1777. output_size[2]
  1778. - (w_in - 1) * stride[2]
  1779. + padding[4]
  1780. + padding[5]
  1781. - 1
  1782. ) // dilation[2] + 1
  1783. filter_size = [filter_size_d, filter_size_h, filter_size_w]
  1784. else:
  1785. filter_size = paddle.utils.convert_to_list(
  1786. filter_size, 3, 'conv3d_transpose.filter_size'
  1787. )
  1788. if len(padding) == 6 and paddle.utils._is_symmetric_padding(padding, 3):
  1789. padding = [padding[0], padding[2], padding[4]]
  1790. if output_size is None:
  1791. output_size = []
  1792. elif isinstance(output_size, (list, tuple, int)):
  1793. output_size = paddle.utils.convert_to_list(
  1794. output_size, 3, 'output_size'
  1795. )
  1796. else:
  1797. raise ValueError("output_size should be int, list[int] or tuple[int]")
  1798. groups = 1 if groups is None else groups
  1799. if groups <= 0:
  1800. raise ValueError(
  1801. f"the groups of conv3d_transpose should be greater than 0. Received groups: {groups}"
  1802. )
  1803. if num_filters % groups != 0:
  1804. raise ValueError(
  1805. "Attr(num_filters) must be divisible by groups,"
  1806. f"Received: Attr(num_filters) is {num_filters}, the groups is {groups}"
  1807. )
  1808. filter_shape = [input_channel, num_filters // groups] + filter_size
  1809. img_filter = helper.create_parameter(
  1810. dtype=input.dtype, shape=filter_shape, attr=helper.param_attr
  1811. )
  1812. if data_format == 'NCDHW':
  1813. data_format = 'NCHW'
  1814. if data_format == 'NDHWC':
  1815. data_format = 'NHWC'
  1816. pre_bias = helper.create_variable_for_type_inference(dtype=input.dtype)
  1817. helper.append_op(
  1818. type=l_type,
  1819. inputs={'Input': [input], 'Filter': [img_filter]},
  1820. outputs={'Output': pre_bias},
  1821. attrs={
  1822. 'output_size': output_size,
  1823. 'strides': stride,
  1824. 'paddings': padding,
  1825. 'padding_algorithm': padding_algorithm,
  1826. 'dilations': dilation,
  1827. 'groups': groups,
  1828. 'use_cudnn': use_cudnn,
  1829. 'data_format': data_format,
  1830. },
  1831. )
  1832. if data_format == 'NCHW':
  1833. pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
  1834. else:
  1835. pre_act = helper.append_bias_op(pre_bias, dim_start=4, dim_end=5)
  1836. out = helper.append_activation(pre_act)
  1837. return out
  1838. def deformable_conv(
  1839. input,
  1840. offset,
  1841. mask,
  1842. num_filters,
  1843. filter_size,
  1844. stride=1,
  1845. padding=0,
  1846. dilation=1,
  1847. groups=None,
  1848. deformable_groups=None,
  1849. im2col_step=None,
  1850. param_attr=None,
  1851. bias_attr=None,
  1852. modulated=True,
  1853. name=None,
  1854. ):
  1855. r"""
  1856. **Deformable Convolution op**
  1857. Compute 2-D deformable convolution on 4-D input.
  1858. Given input image x, output feature map y, the deformable convolution operation can be expressed as follow:
  1859. Deformable Convolution v2:
  1860. .. math::
  1861. y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k}
  1862. Deformable Convolution v1:
  1863. .. math::
  1864. y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)}
  1865. Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location,
  1866. Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results
  1867. <https://arxiv.org/abs/1811.11168v2>`_ and `Deformable Convolutional Networks <https://arxiv.org/abs/1703.06211>`_.
  1868. Example:
  1869. - Input:
  1870. Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
  1871. Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)`
  1872. Offset shape: :math:`(N, 2 * deformable\_groups * H_f * H_w, H_{in}, W_{in})`
  1873. Mask shape: :math:`(N, deformable\_groups * H_f * H_w, H_{in}, W_{in})`
  1874. - Output:
  1875. Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
  1876. Where
  1877. .. math::
  1878. H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\
  1879. W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1
  1880. Args:
  1881. input (Tensor): The input image with [N, C, H, W] format. A Tensor with type
  1882. float32, float64.
  1883. offset (Tensor): The input coordinate offset of deformable convolution layer.
  1884. A Tensor with type float32, float64.
  1885. Mask (Tensor, Optional): The input mask of deformable convolution layer.
  1886. A Tensor with type float32, float64. It should be None when you use
  1887. deformable convolution v1.
  1888. num_filters(int): The number of filter. It is as same as the output
  1889. image channel.
  1890. filter_size (int|tuple): The filter size. If filter_size is a tuple,
  1891. it must contain two integers, (filter_size_H, filter_size_W).
  1892. Otherwise, the filter will be a square.
  1893. stride (int|tuple): The stride size. If stride is a tuple, it must
  1894. contain two integers, (stride_H, stride_W). Otherwise, the
  1895. stride_H = stride_W = stride. Default: stride = 1.
  1896. padding (int|tuple): The padding size. If padding is a tuple, it must
  1897. contain two integers, (padding_H, padding_W). Otherwise, the
  1898. padding_H = padding_W = padding. Default: padding = 0.
  1899. dilation (int|tuple): The dilation size. If dilation is a tuple, it must
  1900. contain two integers, (dilation_H, dilation_W). Otherwise, the
  1901. dilation_H = dilation_W = dilation. Default: dilation = 1.
  1902. groups (int): The groups number of the deformable conv layer. According to
  1903. grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  1904. the first half of the filters is only connected to the first half
  1905. of the input channels, while the second half of the filters is only
  1906. connected to the second half of the input channels. Default: groups=1.
  1907. deformable_groups (int): The number of deformable group partitions.
  1908. Default: deformable_groups = 1.
  1909. im2col_step (int): Maximum number of images per im2col computation;
  1910. The total batch size should be devisable by this value or smaller
  1911. than this value; if you face out of memory problem, you can try
  1912. to use a smaller value here.
  1913. Default: im2col_step = 64.
  1914. param_attr (ParamAttr, Optional): The parameter attribute for learnable parameters/weights
  1915. of deformable conv. If it is set to None or one attribute of ParamAttr,
  1916. deformable conv will create ParamAttr as param_attr.
  1917. If the Initializer of the param_attr is not set, the parameter is
  1918. initialized with :math:`Normal(0.0, std)`, and the
  1919. :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
  1920. bias_attr (ParamAttr|bool, Optional): The parameter attribute for the bias of
  1921. deformable conv layer. If it is set to False, no bias will be added
  1922. to the output units. If it is set to None or one attribute of ParamAttr, conv2d
  1923. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  1924. is not set, the bias is initialized zero. Default: None.
  1925. modulated (bool): Make sure which version should be used between v1 and v2, where v2 is \
  1926. used while True. Default: True.
  1927. name(str, Optional): For details, please refer to :ref:`api_guide_Name`.
  1928. Generally, no setting is required. Default: None.
  1929. Returns:
  1930. Tensor: The tensor variable storing the deformable convolution \
  1931. result. A Tensor with type float32, float64.
  1932. Examples:
  1933. .. code-block:: python
  1934. >>> # deformable conv v2:
  1935. >>> import paddle
  1936. >>> paddle.enable_static()
  1937. >>> C_in, H_in, W_in = 3, 32, 32
  1938. >>> filter_size, deformable_groups = 3, 1
  1939. >>> data = paddle.static.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32')
  1940. >>> offset = paddle.static.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32')
  1941. >>> mask = paddle.static.data(name='mask', shape=[None, deformable_groups*filter_size**2, H_in, W_in], dtype='float32')
  1942. >>> out = paddle.static.nn.common.deformable_conv(input=data, offset=offset, mask=mask,
  1943. ... num_filters=2, filter_size=filter_size, padding=1, modulated=True)
  1944. >>> # deformable conv v1:
  1945. >>> import paddle
  1946. >>> C_in, H_in, W_in = 3, 32, 32
  1947. >>> filter_size, deformable_groups = 3, 1
  1948. >>> data = paddle.static.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32')
  1949. >>> offset = paddle.static.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32')
  1950. >>> out = paddle.static.nn.common.deformable_conv(input=data, offset=offset, mask=None,
  1951. ... num_filters=2, filter_size=filter_size, padding=1, modulated=False)
  1952. """
  1953. check_variable_and_dtype(
  1954. input, "input", ['float32', 'float64'], 'deformable_conv'
  1955. )
  1956. check_variable_and_dtype(
  1957. offset, "offset", ['float32', 'float64'], 'deformable_conv'
  1958. )
  1959. check_type(
  1960. mask, 'mask', (paddle.static.Variable, type(None)), 'deformable_conv'
  1961. )
  1962. if input.ndim != 4:
  1963. raise ValueError(
  1964. f'The input should be of [N, C, H, W] format, but received {input.shape}'
  1965. )
  1966. num_channels = input.shape[1]
  1967. assert param_attr is not False, "param_attr should not be False here."
  1968. helper = LayerHelper('deformable_conv', **locals())
  1969. dtype = helper.input_dtype()
  1970. if not isinstance(input, paddle.static.Variable):
  1971. raise TypeError("Input of deformable_conv must be Tensor")
  1972. if not isinstance(offset, paddle.static.Variable):
  1973. raise TypeError("Input Offset of deformable_conv must be Tensor")
  1974. if groups is None:
  1975. num_filter_channels = num_channels
  1976. else:
  1977. if groups == 0:
  1978. raise ValueError("groups should not be 0.")
  1979. if num_channels % groups != 0:
  1980. raise ValueError("num_channels must be divisible by groups.")
  1981. num_filter_channels = num_channels // groups
  1982. filter_size = paddle.utils.convert_to_list(filter_size, 2, 'filter_size')
  1983. stride = paddle.utils.convert_to_list(stride, 2, 'stride')
  1984. padding = paddle.utils.convert_to_list(padding, 2, 'padding')
  1985. dilation = paddle.utils.convert_to_list(dilation, 2, 'dilation')
  1986. input_shape = input.shape
  1987. filter_shape = [num_filters, int(num_filter_channels)] + filter_size
  1988. def _get_default_param_initializer():
  1989. filter_elem_num = filter_size[0] * filter_size[1] * num_channels
  1990. if filter_elem_num <= 0:
  1991. raise ValueError(
  1992. "Invalid filter number, excepted number is larger than 0, but"
  1993. f" received {filter_elem_num}, please check the input shape and "
  1994. "filter size."
  1995. )
  1996. std = (2.0 / filter_elem_num) ** 0.5
  1997. return paddle.nn.initializer.normal.Normal(0.0, std)
  1998. filter_param = helper.create_parameter(
  1999. attr=helper.param_attr,
  2000. shape=filter_shape,
  2001. dtype=dtype,
  2002. default_initializer=_get_default_param_initializer(),
  2003. )
  2004. pre_bias = helper.create_variable_for_type_inference(dtype)
  2005. if modulated:
  2006. helper.append_op(
  2007. type='deformable_conv',
  2008. inputs={
  2009. 'Input': input,
  2010. 'Filter': filter_param,
  2011. 'Offset': offset,
  2012. 'Mask': mask,
  2013. },
  2014. outputs={"Output": pre_bias},
  2015. attrs={
  2016. 'strides': stride,
  2017. 'paddings': padding,
  2018. 'dilations': dilation,
  2019. 'groups': groups,
  2020. 'deformable_groups': deformable_groups,
  2021. 'im2col_step': im2col_step,
  2022. },
  2023. )
  2024. else:
  2025. helper.append_op(
  2026. type='deformable_conv_v1',
  2027. inputs={
  2028. 'Input': input,
  2029. 'Filter': filter_param,
  2030. 'Offset': offset,
  2031. },
  2032. outputs={"Output": pre_bias},
  2033. attrs={
  2034. 'strides': stride,
  2035. 'paddings': padding,
  2036. 'dilations': dilation,
  2037. 'groups': groups,
  2038. 'deformable_groups': deformable_groups,
  2039. 'im2col_step': im2col_step,
  2040. },
  2041. )
  2042. output = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
  2043. return output
  2044. @static_only
  2045. def deform_conv2d(
  2046. x,
  2047. offset,
  2048. mask,
  2049. num_filters,
  2050. filter_size,
  2051. stride=1,
  2052. padding=0,
  2053. dilation=1,
  2054. groups=1,
  2055. deformable_groups=1,
  2056. im2col_step=1,
  2057. weight_attr=None,
  2058. bias_attr=None,
  2059. name=None,
  2060. ):
  2061. r"""
  2062. Compute 2-D deformable convolution on 4-D input.
  2063. Given input image x, output feature map y, the deformable convolution operation can be expressed as follow:
  2064. Deformable Convolution v2:
  2065. .. math::
  2066. y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k}
  2067. Deformable Convolution v1:
  2068. .. math::
  2069. y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)}
  2070. Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location,
  2071. Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results
  2072. <https://arxiv.org/abs/1811.11168v2>`_ and `Deformable Convolutional Networks <https://arxiv.org/abs/1703.06211>`_.
  2073. Example:
  2074. - Input:
  2075. X shape: :math:`(N, C_{in}, H_{in}, W_{in})`
  2076. Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)`
  2077. Offset shape: :math:`(N, 2 * deformable\_groups * H_f * H_w, H_{in}, W_{in})`
  2078. Mask shape: :math:`(N, deformable\_groups * H_f * H_w, H_{in}, W_{in})`
  2079. - Output:
  2080. Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
  2081. Where
  2082. .. math::
  2083. H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\
  2084. W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1
  2085. Args:
  2086. x (Tensor): The input image with [N, C, H, W] format. A Tensor with type
  2087. float32, float64.
  2088. offset (Tensor): The input coordinate offset of deformable convolution layer.
  2089. A Tensor with type float32, float64.
  2090. mask (Tensor): The input mask of deformable convolution layer.
  2091. A Tensor with type float32, float64. It should be None when you use
  2092. deformable convolution v1.
  2093. num_filters(int): The number of filter. It is as same as the output
  2094. image channel.
  2095. filter_size (int|list|tuple): The filter size. If filter_size is a list/tuple,
  2096. it must contain two integers, (filter_size_H, filter_size_W).
  2097. Otherwise, the filter will be a square.
  2098. stride (int|list|tuple, Optional): The stride size. If stride is a list/tuple, it must
  2099. contain two integers, (stride_H, stride_W). Otherwise, the
  2100. stride_H = stride_W = stride. Default: stride = 1.
  2101. padding (int|list|tuple, Optional): The padding size. If padding is a list/tuple, it must
  2102. contain two integers, (padding_H, padding_W). Otherwise, the
  2103. padding_H = padding_W = padding. Default: padding = 0.
  2104. dilation (int|list|tuple, Optional): The dilation size. If dilation is a list/tuple, it must
  2105. contain two integers, (dilation_H, dilation_W). Otherwise, the
  2106. dilation_H = dilation_W = dilation. Default: dilation = 1.
  2107. groups (int, Optional): The groups number of the deformable conv layer. According to
  2108. grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  2109. the first half of the filters is only connected to the first half
  2110. of the input channels, while the second half of the filters is only
  2111. connected to the second half of the input channels. Default: groups=1.
  2112. deformable_groups (int, Optional): The number of deformable group partitions.
  2113. Default: deformable_groups = 1.
  2114. im2col_step (int, Optional): Maximum number of images per im2col computation;
  2115. The total batch size should be devisable by this value or smaller
  2116. than this value; if you face out of memory problem, you can try
  2117. to use a smaller value here.
  2118. Default: im2col_step = 1.
  2119. weight_attr (ParamAttr, Optional): The parameter attribute for learnable parameters/weights
  2120. of deformable conv. If it is set to None or one attribute of ParamAttr,
  2121. deformable conv will create ParamAttr as weight_attr.
  2122. If the Initializer of the weight_attr is not set, the parameter is
  2123. initialized with :math:`Normal(0.0, std)`, and the
  2124. :math:`std` is :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
  2125. bias_attr (ParamAttr|bool, Optional): The parameter attribute for the bias of
  2126. deformable conv layer. If it is set to False, no bias will be added
  2127. to the output units. If it is set to None or one attribute of ParamAttr, conv2d
  2128. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  2129. is not set, the bias is initialized zero. Default: None.
  2130. name(str, Optional): For details, please refer to :ref:`api_guide_Name`.
  2131. Generally, no setting is required. Default: None.
  2132. Returns:
  2133. Tensor: The tensor storing the deformable convolution result. A Tensor with type float32, float64.
  2134. Examples:
  2135. .. code-block:: python
  2136. >>> # deformable conv v2:
  2137. >>> import paddle
  2138. >>> paddle.enable_static()
  2139. >>> C_in, H_in, W_in = 3, 32, 32
  2140. >>> filter_size, deformable_groups = 3, 1
  2141. >>> data = paddle.static.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32')
  2142. >>> offset = paddle.static.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32')
  2143. >>> mask = paddle.static.data(name='mask', shape=[None, deformable_groups*filter_size**2, H_in, W_in], dtype='float32')
  2144. >>> out = paddle.static.nn.deform_conv2d(x=data, offset=offset, mask=mask,
  2145. ... num_filters=2, filter_size=filter_size, padding=1)
  2146. >>> # deformable conv v1:
  2147. >>> import paddle
  2148. >>> paddle.enable_static()
  2149. >>> C_in, H_in, W_in = 3, 32, 32
  2150. >>> filter_size, deformable_groups = 3, 1
  2151. >>> data = paddle.static.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32')
  2152. >>> offset = paddle.static.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32')
  2153. >>> out = paddle.static.nn.deform_conv2d(x=data, offset=offset, mask=None,
  2154. ... num_filters=2, filter_size=filter_size, padding=1)
  2155. """
  2156. if mask is None:
  2157. return deformable_conv(
  2158. input=x,
  2159. offset=offset,
  2160. mask=mask,
  2161. num_filters=num_filters,
  2162. filter_size=filter_size,
  2163. stride=stride,
  2164. padding=padding,
  2165. dilation=dilation,
  2166. groups=groups,
  2167. deformable_groups=deformable_groups,
  2168. im2col_step=im2col_step,
  2169. param_attr=weight_attr,
  2170. bias_attr=bias_attr,
  2171. modulated=False,
  2172. name=name,
  2173. )
  2174. else:
  2175. return deformable_conv(
  2176. input=x,
  2177. offset=offset,
  2178. mask=mask,
  2179. num_filters=num_filters,
  2180. filter_size=filter_size,
  2181. stride=stride,
  2182. padding=padding,
  2183. dilation=dilation,
  2184. groups=groups,
  2185. deformable_groups=deformable_groups,
  2186. im2col_step=im2col_step,
  2187. param_attr=weight_attr,
  2188. bias_attr=bias_attr,
  2189. modulated=True,
  2190. name=name,
  2191. )
  2192. def bilinear_tensor_product(
  2193. x, y, size, act=None, name=None, param_attr=None, bias_attr=None
  2194. ):
  2195. r"""
  2196. This layer performs bilinear tensor product on two inputs.
  2197. .. math::
  2198. out_{i} = x * W_{i} * {y^\mathrm{T}}, i=0,1,...,size-1
  2199. In this formula:
  2200. - :math:`x`: the first input contains M elements, shape is [batch_size, M].
  2201. - :math:`y`: the second input contains N elements, shape is [batch_size, N].
  2202. - :math:`W_{i}`: the i-th learned weight, shape is [M, N].
  2203. - :math:`out_{i}`: the i-th element of out, shape is [batch_size, size].
  2204. - :math:`y^\mathrm{T}`: the transpose of :math:`y_{2}`.
  2205. Args:
  2206. x (Tensor): 2-D input tensor with shape [batch_size, M]. Data type
  2207. is float32 or float64.
  2208. y (Tensor): 2-D input tensor with shape [batch_size, N]. Data type
  2209. should be same as **x**.
  2210. size (int): The dimension of this layer.
  2211. act (str|None): Activation to be applied to the output of this layer. Default None.
  2212. name(str|None): For detailed information, please refer to
  2213. :ref:`api_guide_Name` . Usually name is no need to set and None by default.
  2214. param_attr (ParamAttr|None): To specify the weight parameter attribute.
  2215. Default: None, which means the default weight parameter property is
  2216. used. See usage for details in :ref:`api_paddle_ParamAttr` .
  2217. bias_attr (ParamAttr|None): To specify the bias parameter attribute.
  2218. Default: None, which means the default bias parameter property is
  2219. used. See usage for details in :ref:`api_paddle_ParamAttr` .
  2220. Returns:
  2221. Tensor, A 2-D Tensor of shape [batch_size, size]. Data type is the same as input **x**.
  2222. Examples:
  2223. .. code-block:: python
  2224. >>> import paddle
  2225. >>> paddle.enable_static()
  2226. >>> x = paddle.static.data("t1", shape=[-1, 5], dtype="float32")
  2227. >>> y = paddle.static.data("t2", shape=[-1, 4], dtype="float32")
  2228. >>> tensor = paddle.static.nn.bilinear_tensor_product(x, y, size=1000)
  2229. """
  2230. helper = LayerHelper('bilinear_tensor_product', **locals())
  2231. dtype = helper.input_dtype('x')
  2232. if len(x.shape) != 2 or len(y.shape) != 2:
  2233. raise ValueError(
  2234. f"Input x and y should be 2D tensor, but received x with the shape of {x.shape}, y with the shape of {y.shape}"
  2235. )
  2236. param_shape = [size, x.shape[1], y.shape[1]]
  2237. w = helper.create_parameter(
  2238. attr=helper.param_attr, shape=param_shape, dtype=dtype, is_bias=False
  2239. )
  2240. out = helper.create_variable_for_type_inference(dtype=dtype)
  2241. inputs = {"X": x, "Y": y, "Weight": w}
  2242. if helper.bias_attr:
  2243. bias_size = [1, size]
  2244. bias = helper.create_parameter(
  2245. attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True
  2246. )
  2247. inputs["Bias"] = bias
  2248. helper.append_op(
  2249. type="bilinear_tensor_product", inputs=inputs, outputs={"Out": out}
  2250. )
  2251. # add activation
  2252. return helper.append_activation(out)
  2253. def batch_norm(
  2254. input,
  2255. act=None,
  2256. is_test=False,
  2257. momentum=0.9,
  2258. epsilon=1e-05,
  2259. param_attr=None,
  2260. bias_attr=None,
  2261. data_layout='NCHW',
  2262. in_place=False,
  2263. name=None,
  2264. moving_mean_name=None,
  2265. moving_variance_name=None,
  2266. do_model_average_for_mean_and_var=True,
  2267. use_global_stats=False,
  2268. ):
  2269. r"""
  2270. **Batch Normalization Layer**
  2271. Can be used as a normalizer function for convolution or fully_connected operations.
  2272. The required data format for this layer is one of the following:
  2273. 1. NHWC `[batch, in_height, in_width, in_channels]`
  2274. 2. NCHW `[batch, in_channels, in_height, in_width]`
  2275. Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing
  2276. Internal Covariate Shift <https://arxiv.org/pdf/1502.03167.pdf>`_
  2277. for more details.
  2278. :math:`input` is the input features over a mini-batch.
  2279. .. math::
  2280. \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//
  2281. \ mini-batch\ mean \\
  2282. \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i -
  2283. \mu_{\\beta})^2 \qquad &//\ mini-batch\ variance \\
  2284. \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{
  2285. \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
  2286. y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
  2287. moving\_mean = moving\_mean * momentum + mini-batch\_mean * (1. - momentum) \\
  2288. moving\_var = moving\_var * momentum + mini-batch\_var * (1. - momentum)
  2289. moving_mean is global mean and moving_var is global variance.
  2290. When use_global_stats = True, the :math:`\\mu_{\\beta}`
  2291. and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch.
  2292. They are global (or running) statistics. (It usually got from the
  2293. pre-trained model.)
  2294. The training and testing (or inference) have the same behavior:
  2295. .. math::
  2296. \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{
  2297. \sigma_{\beta}^{2} + \epsilon}} \\
  2298. y_i &\gets \gamma \hat{x_i} + \beta
  2299. Note:
  2300. if build_strategy.sync_batch_norm=True, the batch_norm in network will use
  2301. sync_batch_norm automatically.
  2302. `is_test = True` can only be used in test program and inference program, `is_test` CANNOT be set to True in train program, if you want to use global status from pre_train model in train program, please set `use_global_stats = True`.
  2303. Args:
  2304. input(Tensor): The rank of input Tensor can be 2, 3, 4, 5. The data type
  2305. is float16 or float32 or float64.
  2306. act(string, Default None): Activation type, linear|relu|prelu|...
  2307. is_test (bool, Default False): A flag indicating whether it is in
  2308. test phrase or not.
  2309. momentum(float|Tensor, Default 0.9): The value used for the moving_mean and
  2310. moving_var computation. This should be a float number or a 0-D Tensor with
  2311. shape [] and data type as float32. The updated formula is:
  2312. :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)`
  2313. :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)`
  2314. Default is 0.9.
  2315. epsilon(float, Default 1e-05): A value added to the denominator for
  2316. numerical stability. Default is 1e-5.
  2317. param_attr(ParamAttr|None): The parameter attribute for Parameter `scale`
  2318. of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
  2319. will create ParamAttr as param_attr, the name of scale can be set in ParamAttr.
  2320. If the Initializer of the param_attr is not set, the parameter is initialized
  2321. with Xavier. Default: None.
  2322. bias_attr(ParamAttr|None): The parameter attribute for the bias of batch_norm.
  2323. If it is set to None or one attribute of ParamAttr, batch_norm
  2324. will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr.
  2325. If the Initializer of the bias_attr is not set, the bias is initialized zero.
  2326. Default: None.
  2327. data_layout (str, optional): Specify the data format of the input, and the data format of the output
  2328. will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
  2329. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  2330. `[batch_size, input_channels, input_height, input_width]`.
  2331. in_place(bool, Default False): Make the input and output of batch norm reuse memory.
  2332. name(str|None): For detailed information, please refer to :ref:`api_guide_Name`.
  2333. Usually name is no need to set and None by default.
  2334. moving_mean_name(str, Default None): The name of moving_mean which store the global Mean. If it
  2335. is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm
  2336. will save global mean with the string.
  2337. moving_variance_name(str, Default None): The name of the moving_variance which store the global Variance.
  2338. If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm
  2339. will save global variance with the string.
  2340. do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance should do model
  2341. average when model average is enabled.
  2342. use_global_stats(bool, Default False): Whether to use global mean and
  2343. variance. In inference or test mode, set use_global_stats to true
  2344. or is_test to true, and the behavior is equivalent.
  2345. In train mode, when setting use_global_stats True, the global mean
  2346. and variance are also used during train period.
  2347. Returns:
  2348. A Tensor which is the result after applying batch normalization on the input,
  2349. has same shape and data type with input.
  2350. Examples:
  2351. .. code-block:: python
  2352. >>> import paddle
  2353. >>> paddle.enable_static()
  2354. >>> x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32')
  2355. >>> hidden1 = paddle.static.nn.fc(x=x, size=200)
  2356. >>> print(hidden1.shape)
  2357. (3, 200)
  2358. >>> hidden2 = paddle.static.nn.batch_norm(input=hidden1)
  2359. >>> print(hidden2.shape)
  2360. (3, 200)
  2361. """
  2362. assert (
  2363. bias_attr is not False
  2364. ), "bias_attr should not be False in batch_norm."
  2365. helper = LayerHelper('batch_norm', **locals())
  2366. check_variable_and_dtype(
  2367. input,
  2368. 'input',
  2369. ['uint16', 'float16', 'float32', 'float64'],
  2370. 'batch_norm',
  2371. )
  2372. dtype = helper.input_dtype()
  2373. # use fp32 for bn parameter
  2374. if dtype == paddle.float16 or dtype == paddle.bfloat16:
  2375. dtype = paddle.float32
  2376. input_shape = input.shape
  2377. if len(input.shape) < 2 or len(input.shape) > 5:
  2378. raise ValueError(
  2379. f'expected 2D or 3D or 4D or 5D input (got {len(input.shape)}D input, input shape is: {input_shape})'
  2380. )
  2381. if data_layout == 'NCHW':
  2382. channel_num = input_shape[1]
  2383. else:
  2384. if data_layout == 'NHWC':
  2385. channel_num = input_shape[-1]
  2386. else:
  2387. raise ValueError("unsupported data layout:" + data_layout)
  2388. param_shape = [channel_num]
  2389. # create parameter
  2390. scale = helper.create_parameter(
  2391. attr=helper.param_attr,
  2392. shape=param_shape,
  2393. dtype=dtype,
  2394. default_initializer=paddle.nn.initializer.Constant(1.0),
  2395. )
  2396. bias = helper.create_parameter(
  2397. attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True
  2398. )
  2399. mean = helper.create_parameter(
  2400. attr=paddle.ParamAttr(
  2401. name=moving_mean_name,
  2402. initializer=paddle.nn.initializer.Constant(0.0),
  2403. trainable=False,
  2404. do_model_average=do_model_average_for_mean_and_var,
  2405. ),
  2406. shape=param_shape,
  2407. dtype=dtype,
  2408. )
  2409. mean.stop_gradient = True
  2410. variance = helper.create_parameter(
  2411. attr=paddle.ParamAttr(
  2412. name=moving_variance_name,
  2413. initializer=paddle.nn.initializer.Constant(1.0),
  2414. trainable=False,
  2415. do_model_average=do_model_average_for_mean_and_var,
  2416. ),
  2417. shape=param_shape,
  2418. dtype=dtype,
  2419. )
  2420. variance.stop_gradient = True
  2421. # create output
  2422. # mean and mean_out share the same memory
  2423. mean_out = mean
  2424. # variance and variance_out share the same memory
  2425. variance_out = variance
  2426. if in_dygraph_mode():
  2427. inputs_has_MomentumTensor = False
  2428. attrs_has_momentum = False
  2429. tmp_tensor_type = core.eager.Tensor
  2430. if isinstance(momentum, tmp_tensor_type):
  2431. inputs_has_MomentumTensor = True
  2432. else:
  2433. attrs_has_momentum = True
  2434. attrs_ = ()
  2435. if attrs_has_momentum:
  2436. attrs_ = (
  2437. 'momentum',
  2438. momentum,
  2439. 'epsilon',
  2440. epsilon,
  2441. 'is_test',
  2442. is_test,
  2443. 'data_layout',
  2444. data_layout,
  2445. 'fuse_with_relu',
  2446. False,
  2447. 'use_global_stats',
  2448. use_global_stats,
  2449. )
  2450. else:
  2451. attrs_ = (
  2452. 'epsilon',
  2453. epsilon,
  2454. 'is_test',
  2455. is_test,
  2456. 'data_layout',
  2457. data_layout,
  2458. 'fuse_with_relu',
  2459. False,
  2460. 'use_global_stats',
  2461. use_global_stats,
  2462. )
  2463. if inputs_has_MomentumTensor:
  2464. batch_norm_out, _, _, _, _, _ = paddle._legacy_C_ops.batch_norm(
  2465. input,
  2466. scale,
  2467. bias,
  2468. mean,
  2469. variance,
  2470. momentum,
  2471. mean_out,
  2472. variance_out,
  2473. *attrs_,
  2474. )
  2475. else:
  2476. batch_norm_out, _, _, _, _, _ = paddle._legacy_C_ops.batch_norm(
  2477. input,
  2478. scale,
  2479. bias,
  2480. mean,
  2481. variance,
  2482. None,
  2483. mean_out,
  2484. variance_out,
  2485. *attrs_,
  2486. )
  2487. return paddle.base.dygraph_utils._append_activation_in_dygraph(
  2488. batch_norm_out, act=act
  2489. )
  2490. saved_mean = helper.create_variable_for_type_inference(
  2491. dtype=dtype, stop_gradient=True
  2492. )
  2493. saved_variance = helper.create_variable_for_type_inference(
  2494. dtype=dtype, stop_gradient=True
  2495. )
  2496. reserve_space = None
  2497. if not is_test:
  2498. reserve_space = helper.create_variable_for_type_inference(
  2499. dtype=helper.input_dtype(), stop_gradient=True
  2500. )
  2501. batch_norm_out = (
  2502. input if in_place else helper.create_variable_for_type_inference(dtype)
  2503. )
  2504. inputs = {
  2505. "X": input,
  2506. "Scale": scale,
  2507. "Bias": bias,
  2508. "Mean": mean,
  2509. "Variance": variance,
  2510. "MeanOut": mean_out,
  2511. "VarianceOut": variance_out,
  2512. }
  2513. attrs = {
  2514. "epsilon": epsilon,
  2515. "is_test": is_test,
  2516. "data_layout": data_layout,
  2517. "fuse_with_relu": False,
  2518. "use_global_stats": use_global_stats,
  2519. }
  2520. if isinstance(momentum, paddle.static.Variable):
  2521. inputs['MomemtumTensor'] = momentum
  2522. else:
  2523. attrs['momentum'] = momentum
  2524. outputs = {
  2525. "Y": batch_norm_out,
  2526. "MeanOut": mean_out,
  2527. "VarianceOut": variance_out,
  2528. "SavedMean": saved_mean,
  2529. "SavedVariance": saved_variance,
  2530. }
  2531. if reserve_space is not None:
  2532. outputs["ReserveSpace"] = reserve_space
  2533. helper.append_op(
  2534. type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs
  2535. )
  2536. return helper.append_activation(batch_norm_out)
  2537. @static_only
  2538. def prelu(x, mode, param_attr=None, data_format="NCHW", name=None):
  2539. r"""
  2540. prelu activation.
  2541. .. math::
  2542. prelu(x) = max(0, x) + \alpha * min(0, x)
  2543. There are three modes for the activation:
  2544. .. code-block:: text
  2545. all: All elements share same alpha.
  2546. channel: Elements in same channel share same alpha.
  2547. element: All elements do not share alpha. Each element has its own alpha.
  2548. Parameters:
  2549. x (Tensor): The input Tensor or LoDTensor with data type float32.
  2550. mode (str): The mode for weight sharing.
  2551. param_attr (ParamAttr|None, optional): The parameter attribute for the learnable \
  2552. weight (alpha), it can be create by ParamAttr. None by default. \
  2553. For detailed information, please refer to :ref:`api_paddle_ParamAttr`.
  2554. data_format(str, optional): Data format that specifies the layout of input.
  2555. It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW".
  2556. name (str, optional): Name for the operation (optional, default is None). \
  2557. For more information, please refer to :ref:`api_guide_Name`.
  2558. Returns:
  2559. Tensor: A tensor with the same shape and data type as x.
  2560. Examples:
  2561. .. code-block:: python
  2562. >>> import paddle
  2563. >>> paddle.enable_static()
  2564. >>> x = paddle.static.data(name="x", shape=[None, 5, 10, 10], dtype="float32")
  2565. >>> mode = 'channel'
  2566. >>> output = paddle.static.nn.prelu(
  2567. ... x,mode,param_attr=paddle.ParamAttr(name='alpha'))
  2568. """
  2569. check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'prelu')
  2570. helper = LayerHelper('prelu', **locals())
  2571. if mode not in ['all', 'channel', 'element']:
  2572. raise ValueError('mode should be one of all, channel, element.')
  2573. alpha_shape = [1]
  2574. if mode == 'channel':
  2575. true_data_format = [
  2576. 'NC',
  2577. 'NCL',
  2578. 'NCHW',
  2579. 'NCDHW',
  2580. 'NLC',
  2581. 'NHWC',
  2582. 'NDHWC',
  2583. ]
  2584. if data_format not in true_data_format:
  2585. raise ValueError(
  2586. "data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', "
  2587. f"'NLC', 'NHWC', 'NDHWC' but receive {data_format}"
  2588. )
  2589. data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC'
  2590. assert (
  2591. len(x.shape) >= 2
  2592. ), "The size of input shape should be equal or larger than 2 in prelu() when mode is 'channel'"
  2593. # NOTE(zhiqiu): The alpha_shape should be [1, channel] + [1] * len(x.shape[2:]).
  2594. # To be consistent with Prelu, it is simplified.
  2595. # NOTE(zhiqiu): Revert shape to [1, channel, 1, 1] for compatibility with saved model of old version.
  2596. # NOTE(GuoxiaWang): support NHWC data format
  2597. if data_format == 'NHWC':
  2598. alpha_shape = [1, 1, 1, x.shape[-1]]
  2599. else:
  2600. alpha_shape = [1, x.shape[1], 1, 1]
  2601. elif mode == 'element':
  2602. assert (
  2603. len(x.shape) >= 1
  2604. ), "The size of input shape should be equal or larger than 1 in prelu() when mode is 'element'"
  2605. alpha_shape = [1] + list(x.shape)[1:]
  2606. dtype = helper.input_dtype(input_param_name='x')
  2607. alpha = helper.create_parameter(
  2608. attr=helper.param_attr,
  2609. shape=alpha_shape,
  2610. dtype=dtype,
  2611. is_bias=False,
  2612. default_initializer=paddle.nn.initializer.Constant(0.25),
  2613. )
  2614. out = helper.create_variable_for_type_inference(dtype)
  2615. helper.append_op(
  2616. type="prelu",
  2617. inputs={"X": x, 'Alpha': alpha},
  2618. attrs={"mode": mode, "data_format": data_format},
  2619. outputs={"Out": out},
  2620. )
  2621. return out
  2622. class PyFuncRegistry:
  2623. _register_funcs = []
  2624. def __init__(self, func):
  2625. if func is None or not callable(func):
  2626. raise TypeError('func must be a Python function')
  2627. self._func = func
  2628. # find named args using reflection
  2629. args = inspect.getfullargspec(self._func)
  2630. if len(args[0]) == 0 and args[1] is None and args[2] is None:
  2631. # Function with no inputs
  2632. self._named_args = None
  2633. else:
  2634. self._named_args = args[0]
  2635. self._id = core._append_python_callable_object_and_return_id(self)
  2636. '''
  2637. Why record self here?
  2638. 1. For debug usage. Users can call
  2639. :code:`py_func.registered_func(idx)` method
  2640. to find the registered function corresponding
  2641. to :code:`idx`.
  2642. 2. For increasing reference count of self.
  2643. It seems that to release Python object
  2644. whose reference count is 1 would cause
  2645. segmentation fault error in C++ side.
  2646. May be lack of Python GC in C++ side?
  2647. '''
  2648. PyFuncRegistry._register_funcs.append(self)
  2649. @classmethod
  2650. def registered_func(cls, idx):
  2651. return cls._register_funcs[idx]._func
  2652. @classmethod
  2653. def registered_func_num(cls):
  2654. return len(cls._register_funcs)
  2655. @property
  2656. def id(self):
  2657. return self._id
  2658. def __call__(self, *args):
  2659. if self._named_args is None:
  2660. func_ret = self._func()
  2661. else:
  2662. kwargs = {}
  2663. idx = 0
  2664. for arg in self._named_args:
  2665. kwargs[arg] = args[idx]
  2666. idx += 1
  2667. func_ret = self._func(*args[idx:], **kwargs)
  2668. if not isinstance(func_ret, (list, tuple)):
  2669. func_ret = (func_ret,)
  2670. ret = []
  2671. for each_ret in func_ret:
  2672. if each_ret is None or isinstance(each_ret, core.LoDTensor):
  2673. ret.append(each_ret)
  2674. continue
  2675. if not isinstance(each_ret, np.ndarray):
  2676. each_ret = np.array(each_ret)
  2677. tensor = core.LoDTensor()
  2678. tensor.set(each_ret, core.CPUPlace())
  2679. ret.append(tensor)
  2680. return tuple(ret)
  2681. @static_only
  2682. def py_func(func, x, out, backward_func=None, skip_vars_in_backward_input=None):
  2683. """
  2684. This is used to register customized Python OP to Paddle. The design
  2685. principe of py_func is that Tensor and numpy array can be converted to each
  2686. other easily. So you can use Python and numpy API to register a python OP.
  2687. The forward function of the registered OP is ``func`` and the backward function
  2688. of that is ``backward_func``. Paddle will call ``func`` at forward runtime and
  2689. call ``backward_func`` at backward runtime(if ``backward_func`` is not None).
  2690. ``x`` is the input of ``func``, whose type must be Tensor; ``out`` is
  2691. the output of ``func``, whose type can be either Tensor or numpy array.
  2692. The input of the backward function ``backward_func`` is ``x``, ``out`` and
  2693. the gradient of ``out``. If ``out`` have no gradient, the relevant input of
  2694. ``backward_func`` is None. If ``x`` do not have a gradient, the user should
  2695. return None in ``backward_func``.
  2696. The data type and shape of ``out`` should also be set correctly before this
  2697. API is called, and the data type and shape of the gradient of ``out`` and
  2698. ``x`` will be inferred automatically.
  2699. This API can also be used to debug the neural network by setting the ``func``
  2700. as a function that only print variables.
  2701. Args:
  2702. func (callable): The forward function of the registered OP. When the network
  2703. is running, the forward output ``out`` will be calculated according to this
  2704. function and the forward input ``x``. In ``func`` , it's suggested that we
  2705. actively convert Tensor into a numpy array, so that we can use Python and
  2706. numpy API arbitrarily. If not, some operations of numpy may not be compatible.
  2707. x (Tensor|tuple(Tensor)|list[Tensor]): The input of the forward function ``func``.
  2708. It can be Tensor|tuple(Tensor)|list[Tensor]. In addition, Multiple Tensor
  2709. should be passed in the form of tuple(Tensor) or list[Tensor].
  2710. out (T|tuple(T)|list[T]): The output of the forward function ``func``, it can be
  2711. T|tuple(T)|list[T], where T can be either Tensor or numpy array. Since Paddle
  2712. cannot automatically infer the shape and type of ``out``, you must create
  2713. ``out`` in advance.
  2714. backward_func (callable, optional): The backward function of the registered OP.
  2715. Its default value is None, which means there is no reverse calculation. If
  2716. it is not None, ``backward_func`` is called to calculate the gradient of
  2717. ``x`` when the network is at backward runtime.
  2718. skip_vars_in_backward_input (Tensor, optional): It's used to limit the input
  2719. list of ``backward_func``, and it can be Tensor|tuple(Tensor)|list[Tensor].
  2720. It must belong to either ``x`` or ``out``. The default value is None, which means
  2721. that no tensors need to be removed from ``x`` and ``out``. If it is not None,
  2722. these tensors will not be the input of ``backward_func``. This parameter is only
  2723. useful when ``backward_func`` is not None.
  2724. Returns:
  2725. Tensor|tuple(Tensor)|list[Tensor], The output ``out`` of the forward function ``func``.
  2726. Examples:
  2727. .. code-block:: python
  2728. :name: code-example1
  2729. >>> import paddle
  2730. >>> import numpy as np
  2731. >>> np.random.seed(1107)
  2732. >>> paddle.seed(1107)
  2733. >>> paddle.enable_static()
  2734. >>> # Creates a forward function, Tensor can be input directly without
  2735. >>> # being converted into numpy array.
  2736. >>> def tanh(x):
  2737. ... return np.tanh(x)
  2738. >>> # Skip x in backward function and return the gradient of x
  2739. >>> # Tensor must be actively converted to numpy array, otherwise,
  2740. >>> # operations such as +/- can't be used.
  2741. >>> def tanh_grad(y, dy):
  2742. ... return np.array(dy) * (1 - np.square(np.array(y)))
  2743. >>> # Creates a forward function for debugging running networks(print value)
  2744. >>> def debug_func(x):
  2745. ... # print(x)
  2746. ... pass
  2747. >>> def create_tmp_var(name, dtype, shape):
  2748. ... return paddle.static.default_main_program().current_block().create_var(
  2749. ... name=name, dtype=dtype, shape=shape)
  2750. >>> def simple_net(img, label):
  2751. ... hidden = img
  2752. ... for idx in range(4):
  2753. ... hidden = paddle.static.nn.fc(hidden, size=200)
  2754. ... new_hidden = create_tmp_var(name='hidden_{}'.format(idx),
  2755. ... dtype=hidden.dtype, shape=hidden.shape)
  2756. ... # User-defined forward and backward
  2757. ... hidden = paddle.static.py_func(func=tanh, x=hidden,
  2758. ... out=new_hidden, backward_func=tanh_grad,
  2759. ... skip_vars_in_backward_input=hidden)
  2760. ... # User-defined debug functions that print out the input Tensor
  2761. ... paddle.static.py_func(func=debug_func, x=hidden, out=None)
  2762. ... prediction = paddle.static.nn.fc(hidden, size=10, activation='softmax')
  2763. ... ce_loss = paddle.nn.loss.CrossEntropyLoss()
  2764. ... return ce_loss(prediction, label)
  2765. >>> x = paddle.static.data(name='x', shape=[1,4], dtype='float32')
  2766. >>> y = paddle.static.data(name='y', shape=[1], dtype='int64')
  2767. >>> res = simple_net(x, y)
  2768. >>> exe = paddle.static.Executor(paddle.CPUPlace())
  2769. >>> exe.run(paddle.static.default_startup_program())
  2770. >>> input1 = np.random.random(size=[1,4]).astype('float32')
  2771. >>> input2 = np.random.randint(1, 10, size=[1], dtype='int64')
  2772. >>> out = exe.run(paddle.static.default_main_program(),
  2773. ... feed={'x':input1, 'y':input2},
  2774. ... fetch_list=[res.name])
  2775. >>> print(out[0].shape)
  2776. ()
  2777. .. code-block:: python
  2778. :name: code-example2
  2779. >>> # This example shows how to turn Tensor into numpy array and
  2780. >>> # use numpy API to register an Python OP
  2781. >>> import paddle
  2782. >>> import numpy as np
  2783. >>> np.random.seed(1107)
  2784. >>> paddle.seed(1107)
  2785. >>> paddle.enable_static()
  2786. >>> def element_wise_add(x, y):
  2787. ... # Tensor must be actively converted to numpy array, otherwise,
  2788. ... # numpy.shape can't be used.
  2789. ... x = np.array(x)
  2790. ... y = np.array(y)
  2791. ... if x.shape != y.shape:
  2792. ... raise AssertionError("the shape of inputs must be the same!")
  2793. ... result = np.zeros(x.shape, dtype='int32')
  2794. ... for i in range(len(x)):
  2795. ... for j in range(len(x[0])):
  2796. ... result[i][j] = x[i][j] + y[i][j]
  2797. ... return result
  2798. >>> def create_tmp_var(name, dtype, shape):
  2799. ... return paddle.static.default_main_program().current_block().create_var(
  2800. ... name=name, dtype=dtype, shape=shape)
  2801. >>> def py_func_demo():
  2802. ... start_program = paddle.static.default_startup_program()
  2803. ... main_program = paddle.static.default_main_program()
  2804. ... # Input of the forward function
  2805. ... x = paddle.static.data(name='x', shape=[2, 3], dtype='int32')
  2806. ... y = paddle.static.data(name='y', shape=[2, 3], dtype='int32')
  2807. ... # Output of the forward function, name/dtype/shape must be specified
  2808. ... output = create_tmp_var('output','int32', [3, 1])
  2809. ... # Multiple Tensor should be passed in the form of tuple(Tensor) or list[Tensor]
  2810. ... paddle.static.py_func(func=element_wise_add, x=[x, y], out=output)
  2811. ... exe=paddle.static.Executor(paddle.CPUPlace())
  2812. ... exe.run(start_program)
  2813. ... # Feed numpy array to main_program
  2814. ... input1 = np.random.randint(1, 10, size=[2, 3], dtype='int32')
  2815. ... input2 = np.random.randint(1, 10, size=[2, 3], dtype='int32')
  2816. ... out = exe.run(main_program,
  2817. ... feed={'x':input1, 'y':input2},
  2818. ... fetch_list=[output.name])
  2819. ... print("{0} + {1} = {2}".format(input1, input2, out))
  2820. >>> py_func_demo()
  2821. >>> # [[1 5 4] + [[3 7 7] = [array([[ 4, 12, 11]
  2822. >>> # [9 4 8]] [2 3 9]] [11, 7, 17]], dtype=int32)]
  2823. """
  2824. helper = LayerHelper('py_func', **locals())
  2825. check_type(x, 'X', (list, tuple, Variable, type(None)), 'py_func')
  2826. if x is None:
  2827. x = []
  2828. elif isinstance(x, Variable):
  2829. x = [x]
  2830. elif isinstance(x, tuple):
  2831. x = list(x)
  2832. elif not isinstance(x, (list, tuple, Variable)):
  2833. raise TypeError('Input must be Tensor/list(Tensor)/tuple(Tensor)')
  2834. check_type(out, 'Out', (list, tuple, Variable, type(None)), 'py_func')
  2835. if out is None:
  2836. out_list = []
  2837. elif isinstance(out, Variable):
  2838. out_list = [out]
  2839. elif isinstance(out, tuple):
  2840. out_list = list(out)
  2841. elif isinstance(out, list):
  2842. out_list = out
  2843. else:
  2844. raise TypeError('Output must be Tensor/list(Tensor)/tuple(Tensor)')
  2845. fwd_func_id = PyFuncRegistry(func).id
  2846. bwd_func_id = (
  2847. PyFuncRegistry(backward_func).id if backward_func is not None else -1
  2848. )
  2849. for each_out in out_list:
  2850. if len(each_out.shape) == 0:
  2851. raise ValueError(
  2852. 'Output shapes of py_func should be provided by users manually'
  2853. )
  2854. backward_skip_vars = set()
  2855. if backward_func is not None and skip_vars_in_backward_input is not None:
  2856. if isinstance(skip_vars_in_backward_input, Variable):
  2857. skip_vars_in_backward_input = [skip_vars_in_backward_input]
  2858. fwd_in_out = [v.name for v in x]
  2859. fwd_in_out.extend([v.name for v in out_list])
  2860. fwd_in_out = set(fwd_in_out)
  2861. backward_skip_vars = set()
  2862. for v in skip_vars_in_backward_input:
  2863. if v.name not in fwd_in_out:
  2864. raise ValueError(
  2865. f'Tensor {v.name} is not found in forward inputs and outputs'
  2866. )
  2867. backward_skip_vars.add(v.name)
  2868. helper.append_op(
  2869. type='py_func',
  2870. inputs={'X': x},
  2871. outputs={'Out': out_list},
  2872. attrs={
  2873. 'forward_callable_id': fwd_func_id,
  2874. 'backward_callable_id': bwd_func_id,
  2875. 'backward_skip_vars': list(backward_skip_vars),
  2876. },
  2877. )
  2878. return out
  2879. def row_conv(input, future_context_size, param_attr=None, act=None):
  2880. r"""
  2881. :api_attr: Static Graph
  2882. The row convolution is called lookahead convolution. It was
  2883. introduced in the following paper for DeepSpeech2:
  2884. http://www.cs.cmu.edu/~dyogatam/papers/wang+etal.iclrworkshop2016.pdf
  2885. The main motivation is that a bidirectional RNN, useful in DeepSpeech
  2886. like speech models, learns representation for a sequence by performing a
  2887. forward and a backward pass through the entire sequence. However, unlike
  2888. unidirectional RNNs, bidirectional RNNs are challenging to deploy in an online
  2889. and low-latency setting. The lookahead convolution incorporates information
  2890. from future subsequences in a computationally efficient manner to improve
  2891. unidirectional recurrent neural networks. The row convolution is
  2892. different from the 1D sequence convolution, and is computed as follows:
  2893. Given an input sequence :math:`X` of length :math:`t` and input dimension :math:`D`,
  2894. and a filter (:math:`W`) of size :math:`context \times D`,
  2895. the output sequence is convolved as:
  2896. .. math::
  2897. Out_{i} = \sum_{j=i}^{i + context - 1} X_{j} \cdot W_{j-i}
  2898. In the above equation:
  2899. * :math:`Out_{i}`: The i-th row of output variable with shape [1, D].
  2900. * :math:`context`: Future context size.
  2901. * :math:`X_{j}`: The j-th row of input variable with shape [1, D].
  2902. * :math:`W_{j-i}`: The (j-i)-th row of parameters with shape [1, D].
  2903. More details about row_conv please refer to
  2904. the design document
  2905. https://github.com/PaddlePaddle/Paddle/issues/2228#issuecomment-303903645 .
  2906. Args:
  2907. input (Tensor): The input is a Tensor, the shape of Tensor input has shape
  2908. (B x T x N), B is batch size.
  2909. future_context_size (int): Future context size. Please note, the shape
  2910. of convolution kernel is [future_context_size + 1, D].
  2911. param_attr (ParamAttr): Attributes of parameters, including
  2912. name, initializer etc.
  2913. act (str): Non-linear activation to be applied to output Tensor.
  2914. Returns:
  2915. Tensor: The output is a Tensor, which has same type and same shape as input.
  2916. Examples:
  2917. .. code-block:: python
  2918. >>> # for LodTensor inputs
  2919. >>> import paddle
  2920. >>> paddle.enable_static()
  2921. >>> x = paddle.static.data(name='x', shape=[9, 16],
  2922. ... dtype='float32', lod_level=1)
  2923. >>> out_x = paddle.static.nn.row_conv(input=x, future_context_size=2)
  2924. >>> # for Tensor inputs
  2925. >>> y = paddle.static.data(name='y', shape=[9, 4, 16], dtype='float32')
  2926. >>> out_y = paddle.static.nn.row_conv(input=y, future_context_size=2)
  2927. """
  2928. helper = LayerHelper('row_conv', **locals())
  2929. check_variable_and_dtype(input, 'input', ['float32'], 'row_conv')
  2930. dtype = helper.input_dtype()
  2931. filter_shape = [future_context_size + 1, input.shape[-1]]
  2932. filter_param = helper.create_parameter(
  2933. attr=helper.param_attr, shape=filter_shape, dtype=dtype
  2934. )
  2935. out = helper.create_variable_for_type_inference(dtype)
  2936. helper.append_op(
  2937. type='row_conv',
  2938. inputs={'X': [input], 'Filter': [filter_param]},
  2939. outputs={'Out': [out]},
  2940. )
  2941. return helper.append_activation(out)
  2942. def spectral_norm(weight, dim=0, power_iters=1, eps=1e-12, name=None):
  2943. r"""
  2944. :api_attr: Static Graph
  2945. **Spectral Normalization Layer**
  2946. This operation calculates the spectral normalization value of weight parameters of
  2947. fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D
  2948. Parameters. Output tensor will be in same shape with input tensor.
  2949. Calculations are showed as follows.
  2950. Step 1:
  2951. Generate vector U in shape of [H], and V in shape of [W].
  2952. While H is the :attr:`dim` th dimension of the input weights,
  2953. and W is the product result of remaining dimensions.
  2954. Step 2:
  2955. :attr:`power_iters` should be a positive integer, do following
  2956. calculations with U and V for :attr:`power_iters` rounds. Calculations
  2957. as follows:
  2958. .. math::
  2959. \mathbf{v} := \\frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2}
  2960. \mathbf{u} := \\frac{\mathbf{W}^{T} \mathbf{v}}{\|\mathbf{W}^{T} \mathbf{v}\|_2}
  2961. Step 3:
  2962. Calculate :math:`\sigma(\mathbf{W})` and normalize weight values.
  2963. .. math::
  2964. \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v}
  2965. \mathbf{W} = \\frac{\mathbf{W}}{\sigma(\mathbf{W})}
  2966. Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ .
  2967. Args:
  2968. weight(Tensor): The input weight tensor of spectral_norm operator,
  2969. This can be a 2-D, 3-D, 4-D, 5-D tensor which is the
  2970. weights of fc, conv1d, conv2d, conv3d layer.
  2971. The data type is float32 or float64.
  2972. dim(int): The index of dimension which should be permuted
  2973. to the first before reshaping Input(Weight) to
  2974. matrix, it should be set as 0 if Input(Weight) is
  2975. the weight of fc layer, and should be set as 1 if
  2976. Input(Weight) is the weight of conv layer, default 0.
  2977. power_iters(int): number of power iterations to calculate spectral norm, default 1.
  2978. eps(float): epsilon for numerical stability in calculating norms, it will be added to
  2979. the denominator to avoid divide zero. Default 1e-12.
  2980. name(str, optional): For detailed information, please refer
  2981. to :ref:`api_guide_Name`. Usually name is no need to set and
  2982. None by default.
  2983. Returns:
  2984. Tensor: A tensor of weight parameters after spectral normalization.
  2985. The data type and shape is same as input tensor.
  2986. Examples:
  2987. .. code-block:: python
  2988. >>> import paddle
  2989. >>> paddle.enable_static()
  2990. >>> weight = paddle.static.data(name='weight', shape=[2, 8, 32, 32], dtype='float32')
  2991. >>> x = paddle.static.nn.spectral_norm(weight=weight, dim=1, power_iters=2)
  2992. >>> print(x.shape)
  2993. (2, 8, 32, 32)
  2994. """
  2995. helper = LayerHelper('spectral_norm', **locals())
  2996. check_variable_and_dtype(
  2997. weight, 'weight', ['float32', 'float64'], 'spectral_norm'
  2998. )
  2999. check_type(dim, 'dim', int, 'spectral_norm')
  3000. check_type(power_iters, 'power_iters', int, 'spectral_norm')
  3001. check_type(eps, 'eps', float, 'spectral_norm')
  3002. dtype = weight.dtype
  3003. # create input and parameters
  3004. input_shape = weight.shape
  3005. assert weight.numel() > 0, "Any dimension of input cannot be equal to 0."
  3006. if dim not in [0, 1]:
  3007. raise ValueError(
  3008. f"The input `dim` must be 0 (if weight in fc) or 1 (if weight in conv), but received dim={dim}"
  3009. )
  3010. h = input_shape[dim]
  3011. w = np.prod(input_shape) // h
  3012. u = helper.create_parameter(
  3013. attr=ParamAttr(),
  3014. shape=[h],
  3015. dtype=dtype,
  3016. default_initializer=Normal(0.0, 1.0),
  3017. )
  3018. u.stop_gradient = True
  3019. v = helper.create_parameter(
  3020. attr=ParamAttr(),
  3021. shape=[w],
  3022. dtype=dtype,
  3023. default_initializer=Normal(0.0, 1.0),
  3024. )
  3025. v.stop_gradient = True
  3026. if in_dynamic_or_pir_mode():
  3027. return paddle._C_ops.spectral_norm(weight, u, v, dim, power_iters, eps)
  3028. inputs = {'Weight': weight}
  3029. inputs['U'] = u
  3030. inputs['V'] = v
  3031. # create output
  3032. out = helper.create_variable(dtype=dtype)
  3033. helper.append_op(
  3034. type="spectral_norm",
  3035. inputs=inputs,
  3036. outputs={
  3037. "Out": out,
  3038. },
  3039. attrs={
  3040. "dim": dim,
  3041. "power_iters": power_iters,
  3042. "eps": eps,
  3043. },
  3044. )
  3045. return out
  3046. # For debug usage
  3047. py_func.registered_func = PyFuncRegistry.registered_func
  3048. py_func.registered_func_num = PyFuncRegistry.registered_func_num
  3049. def layer_norm(
  3050. input,
  3051. scale=True,
  3052. shift=True,
  3053. begin_norm_axis=1,
  3054. epsilon=1e-05,
  3055. param_attr=None,
  3056. bias_attr=None,
  3057. act=None,
  3058. name=None,
  3059. ):
  3060. r"""
  3061. **Layer Normalization Layer**
  3062. The API implements the function of the Layer Normalization Layer and can be applied to mini-batch input data.
  3063. Refer to `Layer Normalization <https://arxiv.org/pdf/1607.06450v1.pdf>`_
  3064. The formula is as follows:
  3065. .. math::
  3066. \mu & = \frac{1}{H}\sum_{i=1}^{H} x_i
  3067. \sigma & = \sqrt{\frac{1}{H}\sum_{i=1}^{H}{(x_i - \mu)^2} + \epsilon}
  3068. y & = f(\frac{g}{\sigma}(x - \mu) + b)
  3069. - :math:`x`: the vector representation of the summed inputs to the neurons in that layer.
  3070. - :math:`H`: the number of hidden units in a layers
  3071. - :math:`\\epsilon`: the small value added to the variance to prevent division by zero.
  3072. - :math:`g`: the trainable scale parameter.
  3073. - :math:`b`: the trainable bias parameter.
  3074. Args:
  3075. input(Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64.
  3076. scale(bool, optional): Whether to learn the adaptive gain :math:`g` after
  3077. normalization. Default: True.
  3078. shift(bool, optional): Whether to learn the adaptive bias :math:`b` after
  3079. normalization. Default: True.
  3080. begin_norm_axis(int, optional): The normalization will be performed along
  3081. dimensions from :attr:`begin_norm_axis` to :attr:`rank(input)`.
  3082. Default: 1.
  3083. epsilon(float, optional): The small value added to the variance to prevent
  3084. division by zero. Default: 1e-05.
  3085. param_attr(ParamAttr, optional): The parameter attribute for the learnable
  3086. gain :math:`g`. If :attr:`scale` is False, :attr:`param_attr` is
  3087. omitted. If :attr:`scale` is True and :attr:`param_attr` is None,
  3088. a default :code:`ParamAttr` would be added as scale. The
  3089. :attr:`param_attr` is initialized as 1 if it is added. Default: None.
  3090. bias_attr(ParamAttr, optional): The parameter attribute for the learnable
  3091. bias :math:`b`. If :attr:`shift` is False, :attr:`bias_attr` is
  3092. omitted. If :attr:`shift` is True and :attr:`param_attr` is None,
  3093. a default :code:`ParamAttr` would be added as bias. The
  3094. :attr:`bias_attr` is initialized as 0 if it is added. Default: None.
  3095. act(str, optional): Activation to be applied to the output of layer normalization.
  3096. Default: None.
  3097. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` .
  3098. Returns:
  3099. Tensor: ``Tensor`` indicating the normalized result, the data type is the same as ``input`` , and the return dimension is the same as ``input`` .
  3100. Examples:
  3101. .. code-block:: python
  3102. >>> import paddle
  3103. >>> paddle.enable_static()
  3104. >>> x = paddle.static.data(name='x', shape=[8, 32, 32], dtype='float32')
  3105. >>> output = paddle.static.nn.layer_norm(input=x, begin_norm_axis=1)
  3106. >>> print(output.shape)
  3107. (8, 32, 32)
  3108. """
  3109. assert (
  3110. in_dygraph_mode() is not True
  3111. ), "please use LayerNorm instead of layer_norm in dygraph mode!"
  3112. helper = LayerHelper('layer_norm', **locals())
  3113. check_variable_and_dtype(
  3114. input, 'input', ['float32', 'float64'], 'layer_norm'
  3115. )
  3116. dtype = helper.input_dtype()
  3117. # create input and parameters
  3118. inputs = {'X': input}
  3119. input_shape = input.shape
  3120. param_shape = [reduce(lambda x, y: x * y, input_shape[begin_norm_axis:], 1)]
  3121. if scale:
  3122. assert (
  3123. param_attr is not False
  3124. ), "param_attr should not be False when using scale."
  3125. scale = helper.create_parameter(
  3126. attr=helper.param_attr,
  3127. shape=param_shape,
  3128. dtype=dtype,
  3129. default_initializer=Constant(1.0),
  3130. )
  3131. inputs['Scale'] = scale
  3132. else:
  3133. if param_attr:
  3134. warnings.warn("param_attr is only available with scale is True.")
  3135. if shift:
  3136. assert (
  3137. bias_attr is not False
  3138. ), "bias_attr should not be False when using shift."
  3139. bias = helper.create_parameter(
  3140. attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True
  3141. )
  3142. inputs['Bias'] = bias
  3143. else:
  3144. if bias_attr:
  3145. warnings.warn("bias_attr is only available with shift is True.")
  3146. # create output
  3147. mean_out = helper.create_variable_for_type_inference(
  3148. dtype=dtype, stop_gradient=True
  3149. )
  3150. variance_out = helper.create_variable_for_type_inference(
  3151. dtype=dtype, stop_gradient=True
  3152. )
  3153. layer_norm_out = helper.create_variable_for_type_inference(dtype)
  3154. helper.append_op(
  3155. type="layer_norm",
  3156. inputs=inputs,
  3157. outputs={
  3158. "Y": layer_norm_out,
  3159. "Mean": mean_out,
  3160. "Variance": variance_out,
  3161. },
  3162. attrs={"epsilon": epsilon, "begin_norm_axis": begin_norm_axis},
  3163. )
  3164. return helper.append_activation(layer_norm_out)
  3165. @static_only
  3166. def embedding(
  3167. input,
  3168. size,
  3169. is_sparse=False,
  3170. is_distributed=False,
  3171. padding_idx=None,
  3172. param_attr=None,
  3173. dtype='float32',
  3174. ):
  3175. r"""
  3176. :api_attr: Static Graph
  3177. The operator is used to lookup embeddings vector of ids provided by :attr:`input` .
  3178. It automatically constructs a 2D embedding matrix based on the
  3179. input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` .
  3180. The shape of output Tensor is generated by appending an emb_size dimension to the
  3181. last dimension of the input Tensor shape.
  3182. **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` ,
  3183. otherwise the program will throw an exception and exit.
  3184. .. code-block:: text
  3185. Case 1:
  3186. input is a Tensor. padding_idx = -1
  3187. input.data = [[1, 3], [2, 4], [4, 127]]
  3188. input.shape = [3, 2]
  3189. Given size = [128, 16]
  3190. output is a Tensor:
  3191. out.shape = [3, 2, 16]
  3192. out.data = [[[0.129435295, 0.244512452, ..., 0.436322452],
  3193. [0.345421456, 0.524563927, ..., 0.144534654]],
  3194. [[0.345249859, 0.124939536, ..., 0.194353745],
  3195. [0.945345345, 0.435394634, ..., 0.435345365]],
  3196. [[0.945345345, 0.435394634, ..., 0.435345365],
  3197. [0.0, 0.0, ..., 0.0 ]]] # padding data
  3198. The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127
  3199. It will pad all-zero data when ids is 127.
  3200. Case 2:
  3201. input is a LoDTensor with 1-level LoD. padding_idx = 0
  3202. input.lod = [[2, 3]]
  3203. input.data = [[1], [3], [2], [4], [0]]
  3204. input.shape = [5, 1]
  3205. Given size = [128, 16]
  3206. output is a LoDTensor:
  3207. out.lod = [[2, 3]]
  3208. out.shape = [5, 1, 16]
  3209. out.data = [[[0.129435295, 0.244512452, ..., 0.436322452]],
  3210. [[0.345421456, 0.524563927, ..., 0.144534654]],
  3211. [[0.345249859, 0.124939536, ..., 0.194353745]],
  3212. [[0.945345345, 0.435394634, ..., 0.435345365]],
  3213. [[0.0, 0.0, ..., 0.0 ]]] # padding data
  3214. It will pad all-zero data when ids is 0.
  3215. Args:
  3216. input(Tensor): A Tensor or LoDTensor with type int64, which contains the id information.
  3217. The value of the input id should satisfy :math:`0<= id < size[0]` .
  3218. size(tuple|list): The shape of lookup table parameter. It should have two elements which
  3219. indicates the size of the dictionary of embeddings and the size of each embedding vector respectively.
  3220. is_sparse(bool): The flag indicating whether to use sparse update. This parameter only
  3221. affects the performance of the backwards gradient update. It is recommended to set
  3222. True because sparse update is faster. But some optimizer does not support sparse update
  3223. In these case, is_sparse must be False. Default: False.
  3224. is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used
  3225. in multi-machine distributed CPU training. Default: False.
  3226. padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size).
  3227. If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
  3228. to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup
  3229. encounters :math:`padding\_idx` in id. And the padding data will not be updated while training.
  3230. If set None, it makes no effect to output. Default: None.
  3231. param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the
  3232. default weight parameter property is used. In addition,
  3233. user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
  3234. The local word vector needs to be transformed into numpy format, and the shape of local word
  3235. vector should be consistent with :attr:`size` .
  3236. dtype(str): It refers to the data type of output Tensor.
  3237. It must be float32 or float64. Default: float32.
  3238. Returns:
  3239. Tensor: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .
  3240. Static Examples:
  3241. .. code-block:: python
  3242. >>> import paddle
  3243. >>> import numpy as np
  3244. >>> paddle.enable_static()
  3245. >>> x = paddle.static.data(name="x", shape = [2, 4], dtype=np.int64)
  3246. >>> output = paddle.static.nn.embedding(x, (10, 3),
  3247. ... param_attr=paddle.nn.initializer.Constant(value=1.0))
  3248. >>> m_output=paddle.mean(output)
  3249. >>> place = paddle.CPUPlace()
  3250. >>> exe = paddle.static.Executor(place)
  3251. >>> exe.run(paddle.static.default_startup_program())
  3252. >>> x = np.array([[7, 2, 4, 5],[4, 3, 2, 9]], dtype=np.int64)
  3253. >>> out, = exe.run(paddle.static.default_main_program(), feed={'x':x}, fetch_list=[output])
  3254. >>> print(out)
  3255. [[[1. 1. 1.]
  3256. [1. 1. 1.]
  3257. [1. 1. 1.]
  3258. [1. 1. 1.]]
  3259. [[1. 1. 1.]
  3260. [1. 1. 1.]
  3261. [1. 1. 1.]
  3262. [1. 1. 1.]]]
  3263. """
  3264. helper = LayerHelper('embedding', **locals())
  3265. check_variable_and_dtype(input, 'input', ['int64'], 'embedding')
  3266. check_dtype(
  3267. dtype,
  3268. 'dtype',
  3269. ['float16', 'float32', 'float64', 'uint16'],
  3270. 'embedding',
  3271. )
  3272. remote_prefetch = is_sparse and (not is_distributed)
  3273. if remote_prefetch:
  3274. assert is_sparse is True and is_distributed is False
  3275. w = helper.create_parameter(
  3276. attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False
  3277. )
  3278. tmp = helper.create_variable_for_type_inference(dtype)
  3279. padding_idx = (
  3280. -1
  3281. if padding_idx is None
  3282. else padding_idx
  3283. if padding_idx >= 0
  3284. else (size[0] + padding_idx)
  3285. )
  3286. helper.append_op(
  3287. type='lookup_table_v2',
  3288. inputs={'Ids': input, 'W': w},
  3289. outputs={'Out': tmp},
  3290. attrs={
  3291. 'is_sparse': is_sparse,
  3292. 'is_distributed': is_distributed,
  3293. 'remote_prefetch': remote_prefetch,
  3294. 'padding_idx': padding_idx,
  3295. },
  3296. )
  3297. return tmp
  3298. def sparse_embedding(
  3299. input,
  3300. size,
  3301. padding_idx=None,
  3302. is_test=False,
  3303. entry=None,
  3304. table_class="MemorySparseTable",
  3305. param_attr=None,
  3306. dtype='float32',
  3307. slot=None,
  3308. ):
  3309. r"""
  3310. :api_attr: Static Graph
  3311. The OP is used as the operator of the Embedding Lookup layer in the large-scale
  3312. sparse training of the parameter server mode, instead of using the paddle.nn.functional.embedding.
  3313. The operator is used to lookup embeddings vector of ids provided by :attr:`input` .
  3314. It automatically constructs a 2D embedding matrix based on the input :attr:`size`
  3315. (vocab_size, emb_size) and :attr:`dtype` .
  3316. The shape of output Tensor is generated by appending an emb_size dimension to the
  3317. last dimension of the input Tensor shape.
  3318. **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , otherwise
  3319. the program will throw an exception and exit.
  3320. .. code-block:: text
  3321. Case 1:
  3322. input is a Tensor. padding_idx = -1
  3323. input.data = [[1, 3], [2, 4], [4, 127]]
  3324. input.shape = [3, 2]
  3325. Given size = [128, 16]
  3326. output is a Tensor:
  3327. out.shape = [3, 2, 16]
  3328. out.data = [[[0.129435295, 0.244512452, ..., 0.436322452],
  3329. [0.345421456, 0.524563927, ..., 0.144534654]],
  3330. [[0.345249859, 0.124939536, ..., 0.194353745],
  3331. [0.945345345, 0.435394634, ..., 0.435345365]],
  3332. [[0.945345345, 0.435394634, ..., 0.435345365],
  3333. [0.0, 0.0, ..., 0.0 ]]] # padding data
  3334. The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127
  3335. It will pad all-zero data when ids is 127.
  3336. Case 2:
  3337. input is a LoDTensor with 1-level LoD. padding_idx = 0
  3338. input.lod = [[2, 3]]
  3339. input.data = [[1], [3], [2], [4], [0]]
  3340. input.shape = [5, 1]
  3341. Given size = [128, 16]
  3342. output is a LoDTensor:
  3343. out.lod = [[2, 3]]
  3344. out.shape = [5, 1, 16]
  3345. out.data = [[[0.129435295, 0.244512452, ..., 0.436322452]],
  3346. [[0.345421456, 0.524563927, ..., 0.144534654]],
  3347. [[0.345249859, 0.124939536, ..., 0.194353745]],
  3348. [[0.945345345, 0.435394634, ..., 0.435345365]],
  3349. [[0.0, 0.0, ..., 0.0 ]]] # padding data
  3350. It will pad all-zero data when ids is 0.
  3351. Args:
  3352. input(Tensor): A Tensor or LoDTensor with type int64, which contains the id
  3353. information. The value of the input id should satisfy :math:`0<= id < size[0]` .
  3354. size(tuple|list): The shape of lookup table parameter (vocab_size, emb_size). It
  3355. should have two elements which indicates the size of the dictionary of embeddings
  3356. and the size of each embedding vector respectively. The initial parameter size
  3357. is 0 in the large-scale sparse scenario, which will gradually expand with the
  3358. training. So if vocab_size is temporarily useless, its value can be any integer.
  3359. The emb_size is the dimensional configuration of the word embedding weight parameter.
  3360. padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-vocab_size, vocab_size).
  3361. If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
  3362. to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever
  3363. lookup encounters :math:`padding\_idx` in id. And the padding data will not be updated
  3364. while training. If set None, it makes no effect to output. Default: None.
  3365. is_test(bool, optional): Training or prediction mode. In prediction mode (is_test=False),
  3366. the output is not initialized and created, and it is filled with 0 and returned. Default: False.
  3367. entry(str, optional): Entry config with parameter server whose value is ProbabilityEntry,
  3368. CountFilterEntry or None. Default: None.
  3369. table_class(str, optional): The type of the sparse table. The value can be CommonSparseTable
  3370. or SSDSparseTable. The default is CommonSparseTable.
  3371. param_attr(ParamAttr, optional): To specify the weight parameter property. Default: None, which means the
  3372. default weight parameter property is used. In addition, user-defined or pre-trained word
  3373. vectors can be loaded with the :attr:`param_attr` parameter. The local word vector needs
  3374. to be transformed into numpy format, and the shape of local word vector should be consistent
  3375. with :attr:`size` .
  3376. dtype(str): It refers to the data type of output Tensor. It must be float32 or
  3377. float64. Default: float32.
  3378. Returns:
  3379. Tensor: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .
  3380. Examples:
  3381. .. code-block:: python
  3382. >>> import paddle
  3383. >>> paddle.enable_static()
  3384. >>> sparse_feature_dim = 1024
  3385. >>> embedding_size = 64
  3386. >>> # Only when the feature appear more than 10 times or more will be participated in the training.
  3387. >>> entry = paddle.distributed.CountFilterEntry(10)
  3388. >>> input = paddle.static.data(name='ins', shape=[1], dtype='int64')
  3389. >>> emb = paddle.static.nn.sparse_embedding(
  3390. ... input=input,
  3391. ... size=[sparse_feature_dim, embedding_size],
  3392. ... is_test=False,
  3393. ... entry=entry,
  3394. ... param_attr=paddle.ParamAttr(name="SparseFeatFactors",
  3395. ... initializer=paddle.nn.initializer.Uniform()))
  3396. """
  3397. helper = LayerHelper('sparse_embedding', **locals())
  3398. check_variable_and_dtype(
  3399. input, 'input', ['int64'], 'paddle.incubate.layers.sparse_embedding'
  3400. )
  3401. check_dtype(
  3402. dtype,
  3403. 'dtype',
  3404. ['float32', 'float64'],
  3405. 'paddle.static.nn.sparse_embedding',
  3406. )
  3407. if input.size == 0:
  3408. raise ValueError("input size should not be 0")
  3409. w = helper.create_parameter(
  3410. attr=helper.param_attr,
  3411. shape=size,
  3412. type=core.VarDesc.VarType.SELECTED_ROWS,
  3413. dtype=dtype,
  3414. is_bias=False,
  3415. )
  3416. tmp = helper.create_variable_for_type_inference(dtype)
  3417. padding_idx = (
  3418. -1
  3419. if padding_idx is None
  3420. else padding_idx
  3421. if padding_idx >= 0
  3422. else (size[0] + padding_idx)
  3423. )
  3424. if table_class not in [
  3425. "CommonSparseTable",
  3426. "SSDSparseTable",
  3427. "MemorySparseTable",
  3428. ]:
  3429. raise ValueError(
  3430. "table_class must be in [CommonSparseTable, SSDSparseTable, MemorySparseTable]"
  3431. )
  3432. entry_str = "none"
  3433. if entry is not None:
  3434. if entry.__class__.__name__ not in [
  3435. "ProbabilityEntry",
  3436. "CountFilterEntry",
  3437. "ShowClickEntry",
  3438. ]:
  3439. raise ValueError(
  3440. "entry must be instance in [paddle.distributed.ProbabilityEntry, paddle.distributed.CountFilterEntry, paddle.distributed.ShowClickEntry]"
  3441. )
  3442. entry_str = entry._to_attr()
  3443. if slot is None:
  3444. slot = 0
  3445. helper.append_op(
  3446. type='lookup_table',
  3447. inputs={'Ids': input, 'W': w},
  3448. outputs={'Out': tmp},
  3449. attrs={
  3450. 'padding_idx': padding_idx,
  3451. 'is_sparse': True,
  3452. 'is_distributed': True,
  3453. 'remote_prefetch': True,
  3454. 'is_test': is_test,
  3455. 'entry': entry_str,
  3456. 'table_class': table_class,
  3457. 'slot': slot,
  3458. },
  3459. )
  3460. return tmp
  3461. class ExponentialMovingAverage:
  3462. r"""
  3463. Compute the moving average of parameters with exponential decay.
  3464. Given a parameter :math:`\\theta`, its exponential moving average (EMA)
  3465. will be
  3466. .. math::
  3467. \text{EMA}_0 & = 0
  3468. \text{EMA}_t & = \text{decay} * \text{EMA}_{t-1} + (1 - \text{decay}) * \theta_t
  3469. The average results calculated by **update()** method will be saved in
  3470. temporary variables which are created and maintained by the object, and can
  3471. be applied to parameters of current model by calling **apply()** method. And
  3472. the **restore()** method is used to restore the parameters.
  3473. **Bias correction**. All EMAs are initialized to :math:`0` and hence they will be
  3474. zero biased, which can be corrected by divided by a factor
  3475. :math:`(1 - \text{decay}^t)` , i.e., the actual EMAs applied to parameters
  3476. when calling **apply()** method would be
  3477. .. math::
  3478. \widehat{\text{EMA}}_t = \frac{\text{EMA}_t}{1 - \text{decay}^t}
  3479. **Decay rate scheduling**. A large decay rate very close to 1 would result
  3480. in that the averages move very slowly. And a better strategy is to set a
  3481. relative smaller decay rate in the very beginning. The argument **thres_steps**
  3482. allows users to pass a Variable to schedule the decay rate, in this case,
  3483. the actual decay rate becomes
  3484. .. math::
  3485. \min(\text{decay}, \frac{1 + \text{thres_steps}}{10 + \text{thres_steps}})
  3486. Usually **thres_steps** can be the global training steps.
  3487. Args:
  3488. decay (float, optional): The exponential decay rate, usually close to 1, such as 0.999, 0.9999, ... . Default 0.999.
  3489. thres_steps (Variable|None, optional): If not `None`, schedule the decay rate. Default None.
  3490. name (str|None, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default.
  3491. Examples:
  3492. .. code-block:: python
  3493. >>> import numpy
  3494. >>> import paddle
  3495. >>> import paddle.static as static
  3496. >>> from paddle.static import ExponentialMovingAverage
  3497. >>> paddle.enable_static()
  3498. >>> data = static.data(name='x', shape=[-1, 5], dtype='float32')
  3499. >>> hidden = static.nn.fc(x=data, size=10)
  3500. >>> cost = paddle.mean(hidden)
  3501. >>> test_program = static.default_main_program().clone(for_test=True)
  3502. >>> optimizer = paddle.optimizer.Adam(learning_rate=0.001)
  3503. >>> optimizer.minimize(cost)
  3504. >>> ema = ExponentialMovingAverage(0.999)
  3505. >>> ema.update()
  3506. >>> place = paddle.CPUPlace()
  3507. >>> exe = static.Executor(place)
  3508. >>> exe.run(static.default_startup_program())
  3509. >>> for pass_id in range(3):
  3510. ... for batch_id in range(6):
  3511. ... data = numpy.random.random(size=(10, 5)).astype('float32')
  3512. ... exe.run(program=static.default_main_program(),
  3513. ... feed={'x': data},
  3514. ... fetch_list=[cost.name])
  3515. ... # usage 1
  3516. ... with ema.apply(exe):
  3517. ... data = numpy.random.random(size=(10, 5)).astype('float32')
  3518. ... exe.run(program=test_program,
  3519. ... feed={'x': data},
  3520. ... fetch_list=[hidden.name])
  3521. ... # usage 2
  3522. ... with ema.apply(exe, need_restore=False):
  3523. ... data = numpy.random.random(size=(10, 5)).astype('float32')
  3524. ... exe.run(program=test_program,
  3525. ... feed={'x': data},
  3526. ... fetch_list=[hidden.name])
  3527. ... ema.restore(exe)
  3528. """
  3529. def __init__(self, decay=0.999, thres_steps=None, name=None):
  3530. if in_dygraph_mode():
  3531. raise Exception(
  3532. "In dygraph, don't support ExponentialMovingAverage."
  3533. )
  3534. self._decay = decay
  3535. self._thres_steps = thres_steps
  3536. self._name = name if name is not None else ''
  3537. self._decay_var = self._get_ema_decay()
  3538. self._step_counter_name = "@EMA_STEP_COUNTER@"
  3539. self._params_tmps = []
  3540. for param in default_main_program().global_block().all_parameters():
  3541. if param.do_model_average:
  3542. tmp = param.block.create_var(
  3543. name=unique_name.generate(
  3544. ".".join([self._name + param.name, 'ema_tmp'])
  3545. ),
  3546. dtype=param.dtype,
  3547. persistable=False,
  3548. stop_gradient=True,
  3549. )
  3550. self._params_tmps.append((param, tmp))
  3551. self._ema_vars = {}
  3552. for param, tmp in self._params_tmps:
  3553. with param.block.program._optimized_guard([param, tmp]), name_scope(
  3554. 'moving_average'
  3555. ):
  3556. self._ema_vars[param.name] = self._create_ema_vars(param)
  3557. self.apply_program = Program()
  3558. block = self.apply_program.global_block()
  3559. with program_guard(main_program=self.apply_program):
  3560. decay_pow, global_step = self._get_decay_pow(block)
  3561. for param, tmp in self._params_tmps:
  3562. param = block._clone_variable(param)
  3563. tmp = block._clone_variable(tmp)
  3564. ema = block._clone_variable(self._ema_vars[param.name])
  3565. paddle.assign(param, output=tmp)
  3566. # bias correction
  3567. param_val = paddle.static.nn.cond(
  3568. global_step > 0,
  3569. lambda: ema / (1.0 - decay_pow),
  3570. lambda: ema,
  3571. )
  3572. paddle.assign(param_val, output=param)
  3573. self.restore_program = Program()
  3574. block = self.restore_program.global_block()
  3575. with program_guard(main_program=self.restore_program):
  3576. for param, tmp in self._params_tmps:
  3577. tmp = block._clone_variable(tmp)
  3578. param = block._clone_variable(param)
  3579. paddle.assign(tmp, output=param)
  3580. def _get_ema_decay(self):
  3581. with default_main_program()._lr_schedule_guard():
  3582. decay_var = paddle.static.create_global_var(
  3583. shape=[1],
  3584. value=self._decay,
  3585. dtype='float32',
  3586. persistable=True,
  3587. name="scheduled_ema_decay_rate",
  3588. )
  3589. if self._thres_steps is not None:
  3590. decay_t = (self._thres_steps + 1.0) / (self._thres_steps + 10.0)
  3591. decay_val = paddle.static.nn.cond(
  3592. decay_t < self._decay,
  3593. lambda: decay_t,
  3594. lambda: np.array([self._decay], dtype=np.float32),
  3595. )
  3596. paddle.assign(decay_val, decay_var)
  3597. return decay_var
  3598. def _get_decay_pow(self, block):
  3599. global_step = paddle.static.create_global_var(
  3600. name=self._step_counter_name,
  3601. shape=[1],
  3602. value=0,
  3603. dtype='int64',
  3604. persistable=True,
  3605. )
  3606. global_step = paddle.cast(global_step, "float32")
  3607. decay_var = block._clone_variable(self._decay_var)
  3608. decay_pow_acc = paddle.pow(decay_var, global_step)
  3609. return decay_pow_acc, global_step
  3610. def _create_ema_vars(self, param):
  3611. param_ema = paddle.static.create_global_var(
  3612. name=unique_name.generate(self._name + param.name + '_ema'),
  3613. shape=param.shape,
  3614. value=0.0,
  3615. dtype=param.dtype,
  3616. persistable=True,
  3617. )
  3618. return param_ema
  3619. def update(self):
  3620. """
  3621. Update Exponential Moving Average. Should only call this method in
  3622. train program.
  3623. """
  3624. global_step = paddle.optimizer.lr.autoincreased_step_counter(
  3625. counter_name=self._step_counter_name
  3626. )
  3627. param_master_emas = []
  3628. for param, tmp in self._params_tmps:
  3629. with param.block.program._optimized_guard([param, tmp]), name_scope(
  3630. 'moving_average'
  3631. ):
  3632. param_ema = self._ema_vars[param.name]
  3633. if param.name + '.master' in self._ema_vars:
  3634. master_ema = self._ema_vars[param.name + '.master']
  3635. param_master_emas.append([param_ema, master_ema])
  3636. else:
  3637. ema_t = param_ema * self._decay_var + param * (
  3638. 1 - self._decay_var
  3639. )
  3640. paddle.assign(ema_t, output=param_ema)
  3641. # for fp16 params
  3642. for param_ema, master_ema in param_master_emas:
  3643. default_main_program().global_block().append_op(
  3644. type="cast",
  3645. inputs={"X": master_ema},
  3646. outputs={"Out": param_ema},
  3647. attrs={
  3648. "in_dtype": master_ema.dtype,
  3649. "out_dtype": param_ema.dtype,
  3650. },
  3651. )
  3652. @signature_safe_contextmanager
  3653. def apply(self, executor, need_restore=True):
  3654. """
  3655. Apply moving average to parameters for evaluation.
  3656. Args:
  3657. executor (Executor): The Executor to execute applying.
  3658. need_restore (bool, optional): Whether to restore parameters after
  3659. applying. Default True.
  3660. """
  3661. executor.run(self.apply_program)
  3662. try:
  3663. yield
  3664. finally:
  3665. if need_restore:
  3666. self.restore(executor)
  3667. def restore(self, executor):
  3668. """Restore parameters.
  3669. Args:
  3670. executor (Executor): The Executor to execute restoring.
  3671. """
  3672. executor.run(self.restore_program)